@evandu/super-pi 0.1.280 → 0.1.281
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/.super-pi-client-sources.json +9 -7
- package/dist/client/assets/{CodeMirrorEditor-D-UuYizz.js → CodeMirrorEditor-xxJP_tVy.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-Bt1n2la-.js → GitDiffEditor-X8eCsha9.js} +1 -1
- package/dist/client/assets/index-DaKloC7K.css +1 -0
- package/dist/client/assets/{index-rWE1xu-t.js → index-sWsdT0fC.js} +24 -24
- package/dist/client/index.html +2 -2
- package/dist/server/application/provider-service.d.ts +27 -11
- package/dist/server/application/provider-service.js +78 -10
- package/dist/server/application/rsi-service.d.ts +2 -0
- package/dist/server/application/rsi-service.js +78 -10
- package/dist/server/http-server.js +23 -0
- package/dist/server/index.js +4 -0
- package/dist/server/model-discovery.d.ts +44 -0
- package/dist/server/model-discovery.js +139 -0
- package/dist/server/pi-session.d.ts +25 -2
- package/dist/server/pi-session.js +30 -1
- package/dist/server/provider-proxy.d.ts +2 -0
- package/dist/server/provider-proxy.js +1 -1
- package/dist/server/providers.d.ts +6 -0
- package/dist/server/providers.js +76 -10
- package/dist/server/runtime.d.ts +2 -0
- package/dist/server/runtime.js +1 -0
- package/dist/shared/group-chat.d.ts +2 -0
- package/dist/shared/model-discovery.d.ts +15 -0
- package/dist/shared/model-discovery.js +1 -0
- package/dist/shared/tab-layout.d.ts +12 -0
- package/dist/shared/tab-layout.js +28 -0
- package/package.json +5 -1
- package/dist/client/assets/index-B5TLGyEw.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-J6XWqRpB.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-D978o95T.js","assets/dist-B3-a6uF0.js","assets/dist-Cus6_oaF.js","assets/dist-Dc1MBGAG.js","assets/dist-BXAOrsjq.js","assets/dist-Cx00EZKR.js","assets/dist-moiMRpw_.js","assets/dist-Dds-qLxY.js","assets/dist-AW5lyI3I.js","assets/dist-BGxkyh6e.js","assets/dist-CKF2Jksy.js","assets/dist-BV64A9Ji.js","assets/dist-Dvb0SqcK.js","assets/dist-D71y2EI1.js","assets/dist-DeD9copn.js","assets/dist-QzbOCAU6.js","assets/dist-DuvGReu-.js","assets/dist-BRVQKlcp.js","assets/dist-BJxfd7yb.js","assets/CodeMirrorEditor-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-J6XWqRpB.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-D978o95T.js","assets/dist-B3-a6uF0.js","assets/dist-Cus6_oaF.js","assets/dist-Dc1MBGAG.js","assets/dist-BXAOrsjq.js","assets/dist-Cx00EZKR.js","assets/dist-moiMRpw_.js","assets/dist-Dds-qLxY.js","assets/dist-AW5lyI3I.js","assets/dist-BGxkyh6e.js","assets/dist-CKF2Jksy.js","assets/dist-BV64A9Ji.js","assets/dist-Dvb0SqcK.js","assets/dist-D71y2EI1.js","assets/dist-DeD9copn.js","assets/dist-QzbOCAU6.js","assets/dist-DuvGReu-.js","assets/dist-BRVQKlcp.js","assets/dist-BJxfd7yb.js","assets/CodeMirrorEditor-xxJP_tVy.js","assets/GitDiffEditor-X8eCsha9.js","assets/GitDiffEditor-DP0DQ9Y5.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as e,t}from"./rolldown-runtime-XKyaHtl9.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function x(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var S=x.prototype=new b;S.constructor=x,_(S,y.prototype),S.isPureReactComponent=!0;var C=Array.isArray;function w(){}var T={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function D(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function O(e,t){return D(e.type,t,e.props)}function k(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function A(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var j=/\/+/g;function ee(e,t){return typeof e==`object`&&e&&e.key!=null?A(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(w,w):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function te(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,te(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ee(e,0):a,C(o)?(i=``,c!=null&&(i=c.replace(j,`$&/`)+`/`),te(o,r,i,``,function(e){return e})):o!=null&&(k(o)&&(o=O(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(j,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(C(e))for(var u=0;u<e.length;u++)a=e[u],s=l+ee(a,u),c+=te(a,r,i,s,o);else if(u=h(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+ee(a,u++),c+=te(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return te(M(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function N(e,t,n){if(e==null)return e;var r=[],i=0;return te(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ne(e){if(e._status===-1){var t=e._result,n=t();n.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t,n.status===void 0&&(n.status=`fulfilled`,n.value=t))},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t,n.status===void 0&&(n.status=`rejected`,n.reason=t))}),e._status===-1&&(e._status=0,e._result=n)}if(e._status===1)return e._result.default;throw e._result}var re=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)};function ie(e){var t=T.T,n={};n.types=t===null?null:t.types,T.T=n;try{var r=e(),i=T.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(w,re)}catch(e){re(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}}function ae(e){var t=T.T;if(t!==null){var n=t.types;n===null?t.types=[e]:n.indexOf(e)===-1&&n.push(e)}else ie(ae.bind(null,e))}var oe={map:N,forEach:function(e,t,n){N(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return N(e,function(){t++}),t},toArray:function(e){return N(e,function(e){return e})||[]},only:function(e){if(!k(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=oe,e.Component=y,e.Fragment=r,e.Profiler=a,e.PureComponent=x,e.StrictMode=i,e.Suspense=l,e.ViewTransition=p,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return T.H.useMemoCache(e)}},e.addTransitionType=ae,e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=_({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!E.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return D(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)E.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return D(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=k,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ne}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=ie,e.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},e.use=function(e){return T.H.use(e)},e.useActionState=function(e,t,n){return T.H.useActionState(e,t,n)},e.useCallback=function(e,t){return T.H.useCallback(e,t)},e.useContext=function(e){return T.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return T.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return T.H.useEffect(e,t)},e.useEffectEvent=function(e){return T.H.useEffectEvent(e)},e.useId=function(){return T.H.useId()},e.useImperativeHandle=function(e,t,n){return T.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return T.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return T.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return T.H.useMemo(e,t)},e.useOptimistic=function(e,t){return T.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return T.H.useReducer(e,t,n)},e.useRef=function(e){return T.H.useRef(e)},e.useState=function(e){return T.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return T.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return T.H.useTransition()},e.version=`19.3.1`})),r=t(((e,t)=>{t.exports=n()})),i=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-T<w)}function D(){if(g=!1,S){var t=e.unstable_now();T=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),a=t(((e,t)=>{t.exports=i()})),o=t((e=>{var t=r();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function i(){}var a={d:{f:i,r:function(){throw Error(n(522))},D:i,C:i,L:i,m:i,X:i,S:i,M:i},p:0,findDOMNode:null},o=Symbol.for(`react.portal`),s=Symbol.for(`react.recoverable`),c=Symbol.for(`react.optimistic_key`);function l(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:r==null?null:r===c?c:``+r,children:e,containerInfo:t,implementation:n}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function d(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,e.browser=function(e){return{$$typeof:s,_reason:e}},e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return l(e,t,null,r)},e.flushSync=function(e){var t=u.T,n=a.p;try{if(u.T=null,a.p=2,e)return e()}finally{u.T=t,a.p=n,a.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,a.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&a.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=d(n,t.crossOrigin),i=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?a.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:i,fetchPriority:o}):n===`script`&&a.d.X(e,{crossOrigin:r,integrity:i,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`){if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=d(t.as,t.crossOrigin);a.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0})}}else t??a.d.M(e)}},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=d(n,t.crossOrigin);a.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`){if(t){var n=d(t.as,t.crossOrigin);a.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0})}else a.d.m(e)}},e.requestFormReset=function(e){a.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return u.H.useFormState(e,t,n)},e.useFormStatus=function(){return u.H.useHostTransitionStatus()},e.version=`19.3.1`})),s=t(((e,t)=>{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=o()})),c=t((e=>{var t=a(),n=r(),i=s();function o(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function c(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function l(e){for(var t=e,n=t;n&&!n.alternate;)t=n,t.flags&4098&&(e=t.return),n=t.return;for(;t.return;)t=t.return;return t.tag===3?e:null}function u(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function d(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function f(e){if(l(e)!==e)throw Error(o(188))}function p(e){var t=e.alternate;if(!t){if(t=l(e),t===null)throw Error(o(188));return t===e?e:null}for(var n=e,r=t;;){var i=n.return;if(i===null)break;var a=i.alternate;if(a===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===a.child){for(a=i.child;a;){if(a===n)return f(i),e;if(a===r)return f(i),t;a=a.sibling}throw Error(o(188))}if(n.return!==r.return)n=i,r=a;else{for(var s=!1,c=i.child;c;){if(c===n){s=!0,n=i,r=a;break}if(c===r){s=!0,r=i,n=a;break}c=c.sibling}if(!s){for(c=a.child;c;){if(c===n){s=!0,n=a,r=i;break}if(c===r){s=!0,r=a,n=i;break}c=c.sibling}if(!s)throw Error(o(189))}}if(n.alternate!==r)throw Error(o(190))}if(n.tag!==3)throw Error(o(188));return n.stateNode.current===n?e:t}function m(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=m(e),t!==null)return t;e=e.sibling}return null}function h(e,t,n,r,i,a){for(;e!==null;){if((e.tag===5||e.tag===27||e.tag===6)&&n(e,r,i,a)||(e.tag!==22||e.memoizedState===null)&&(t||e.tag!==5&&e.tag!==27)&&h(e.child,t,n,r,i,a))return!0;e=e.sibling}return!1}function g(e){for(e=e.return;e!==null;){if(e.tag===3||e.tag===5||e.tag===27)return e;e=e.return}return null}function _(e){var t=!1;for(e=e.return;e!==null&&(e.tag===4&&(t=!0),e.tag!==3&&e.tag!==5&&e.tag!==27);)e=e.return;return t}function v(e){var t=[null,null],n=g(e);return n===null||y(t,e,n.child,{foundSelf:!1}),t}function y(e,t,n,r){for(;n!==null;){if(n===t)r.foundSelf=!0;else if(n.tag===5||n.tag===27||n.tag===6){if(r.foundSelf)return e[1]=n,!0;e[0]=n}else if((n.tag!==22||n.memoizedState===null)&&y(e,t,n.child,r))return!0;n=n.sibling}return!1}function b(e){switch(e.tag){case 5:case 27:case 6:return e.stateNode;case 3:return e.stateNode.containerInfo;default:throw Error(o(559))}}var x=null,S=null;function C(e,t,n){return e===n||e===t&&(x=e,!0)}function w(e,t,n){return e===n?(S=e,!1):e===t&&(S!==null&&(x=e),!0)}function T(e){if(e===null)return null;do e=e===null?null:e.return;while(e&&e.tag!==5&&e.tag!==27&&e.tag!==3);return e||null}function E(e,t,n){for(var r=0,i=e;i;i=n(i))r++;i=0;for(var a=t;a;a=n(a))i++;for(;0<r-i;)e=n(e),r--;for(;0<i-r;)t=n(t),i--;for(;r--;){if(e===t||t!==null&&e===t.alternate)return e;e=n(e),t=n(t)}return null}var D=Object.assign,O=Symbol.for(`react.element`),k=Symbol.for(`react.transitional.element`),A=Symbol.for(`react.portal`),j=Symbol.for(`react.fragment`),ee=Symbol.for(`react.strict_mode`),M=Symbol.for(`react.profiler`),te=Symbol.for(`react.consumer`),N=Symbol.for(`react.context`),ne=Symbol.for(`react.forward_ref`),re=Symbol.for(`react.suspense`),ie=Symbol.for(`react.suspense_list`),ae=Symbol.for(`react.memo`),oe=Symbol.for(`react.lazy`),se=Symbol.for(`react.activity`),ce=Symbol.for(`react.legacy_hidden`),le=Symbol.for(`react.memo_cache_sentinel`),ue=Symbol.for(`react.view_transition`),de=Symbol.for(`react.recoverable`),fe=Symbol.iterator;function pe(e){return typeof e!=`object`||!e?null:(e=fe&&e[fe]||e[`@@iterator`],typeof e==`function`?e:null)}var me=Symbol.for(`react.client.reference`);function he(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===me?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case j:return`Fragment`;case M:return`Profiler`;case ee:return`StrictMode`;case re:return`Suspense`;case ie:return`SuspenseList`;case se:return`Activity`;case ue:return`ViewTransition`}if(typeof e==`object`)switch(e.$$typeof){case A:return`Portal`;case N:return e.displayName||`Context`;case te:return(e._context.displayName||`Context`)+`.Consumer`;case ne:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case ae:return t=e.displayName||null,t===null?he(e.type)||`Memo`:t;case oe:t=e._payload,e=e._init;try{return he(e(t))}catch{}}return null}var ge=Array.isArray,P=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,_e=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ve={pending:!1,data:null,method:null,action:null},ye=[],be=-1;function xe(e){return{current:e}}function Se(e){0>be||(e.current=ye[be],ye[be]=null,be--)}function Ce(e,t){be++,ye[be]=e.current,e.current=t}var we=xe(null),Te=xe(null),Ee=xe(null),De=xe(null);function Oe(e,t){switch(Ce(Ee,t),Ce(Te,e),Ce(we,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?fp(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=fp(t),e=pp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Se(we),Ce(we,e)}function ke(){Se(we),Se(Te),Se(Ee)}function Ae(e){var t=e.memoizedState;t!==null&&(lh._currentValue=t.memoizedState,Ce(De,e)),t=we.current;var n=pp(t,e.type);t!==n&&(Ce(Te,e),Ce(we,n))}function je(e){Te.current===e&&(Se(we),Se(Te)),De.current===e&&(Se(De),lh._currentValue=ve)}var Me,Ne;function Pe(e){if(Me===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Me=t&&t[1]||``,Ne=-1<e.stack.indexOf(`
|
|
3
3
|
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
|
4
4
|
`+Me+e+Ne}var Fe=!1;function Ie(e,t){if(!e||Fe)return``;Fe=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
|
|
@@ -284,10 +284,10 @@ ${h}.`);break;case m:switch(t){case`xml`:break;case``:e.fail(`the default namesp
|
|
|
284
284
|
`&&(s+=1),n.length===500&&s<e.length-1))return{rows:n,clipped:!0}}else i+=c}return(i||r.length)&&(r.length<50?r.push(i):o=!0,n.push(r)),{rows:n,clipped:o}}function Df({workspaceId:e,cwd:t,path:n,name:r,kind:i,content:a,source:o,version:s,sourceRequest:c,external:l,navigation:d,assetTicket:f,onReload:p}){let[m,h]=(0,u.useState)(c!==void 0),[g,_]=(0,u.useState)(),[v,y]=(0,u.useState)(!1),b=(r,i)=>f?Tf(r,e,t,f,i):wf(r,e,t,n,i),x=b(`asset`,{v:s}),S=b(`asset`,{download:`1`}),C=b(`document`);(0,u.useEffect)(()=>{c!==void 0&&h(!0)},[c]),(0,u.useEffect)(()=>{y(!1)},[x]),(0,u.useEffect)(()=>{if(i!==`document`)return;let e=new AbortController;return Ne(C,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok)throw Error(t.error??`无法读取文档。`);_(t)}).catch(t=>{e.signal.aborted||_({error:String(t.message??t)})}),()=>e.abort()},[C,i,s]);let w=(0,u.useMemo)(()=>i===`table`&&!m?Ef(a,/\.tsv$/i.test(n)?` `:`,`):void 0,[i,a,n,m]);return(0,F.jsxs)(`section`,{className:`workspace-file-preview`,"aria-label":`预览 ${r}`,"data-workspace-file-preview":i,"data-file-readonly":f?`1`:void 0,children:[(0,F.jsxs)(`div`,{className:`workspace-file-preview-head`,children:[d,(0,F.jsxs)(`div`,{className:`workspace-file-preview-actions`,children:[f&&(0,F.jsx)(`span`,{children:`外部文件 · 只读`}),f&&p&&(0,F.jsx)(`button`,{type:`button`,onClick:p,children:`重新读取`}),o&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>h(e=>!e),children:m?`查看表格`:f?`查看原文`:`编辑原文`}),(0,F.jsxs)(`a`,{href:S,download:r,children:[(0,F.jsx)(yf,{name:`download`}),`下载`]})]})]}),l&&!m&&(0,F.jsx)(`p`,{role:`status`,children:o?`磁盘上的文件已变化,请打开原文查看。`:`磁盘上的文件已移走或无法读取。`}),m?o:v?(0,F.jsx)(`p`,{role:`status`,children:`预览无法打开,可以下载文件。`}):(0,F.jsxs)(F.Fragment,{children:[i===`download`&&(0,F.jsx)(`p`,{children:`此文件可以下载。`}),i===`presentation`&&(f?(0,F.jsx)(`p`,{children:`外部演示稿可通过上方按钮下载。`}):(0,F.jsx)(Cf,{workspaceId:e,cwd:t,path:n,version:s})),i===`image`&&(0,F.jsx)(`img`,{src:x,alt:r,onError:()=>y(!0)}),i===`pdf`&&(0,F.jsx)(`iframe`,{src:x,title:r}),i===`audio`&&(0,F.jsx)(`audio`,{src:x,controls:!0,preload:`metadata`,onError:()=>y(!0)}),i===`video`&&(0,F.jsx)(`video`,{src:x,controls:!0,preload:`metadata`,onError:()=>y(!0)}),i===`document`&&(g?.error?(0,F.jsx)(`p`,{role:`alert`,children:g.error}):g?(0,F.jsxs)(F.Fragment,{children:[g.warnings?.map(e=>(0,F.jsx)(`p`,{children:e},e)),(0,F.jsx)(`pre`,{children:g.text||`此文档没有可显示的文字。`})]}):(0,F.jsx)(`p`,{children:`正在读取文档…`})),w&&(w.rows.length?(0,F.jsx)(`div`,{className:`workspace-file-table`,children:(0,F.jsx)(`table`,{children:(0,F.jsx)(`tbody`,{children:w.rows.map((e,t)=>(0,F.jsxs)(`tr`,{children:[(0,F.jsx)(`th`,{scope:`row`,children:t+1}),e.map((e,t)=>(0,F.jsx)(`td`,{children:e},t))]},t))})})}):(0,F.jsx)(`p`,{children:`文件为空。`})),w?.clipped&&(0,F.jsx)(`p`,{className:`workspace-file-preview-limit`,children:`表格超出预览范围。完整内容可在原文中查看。`})]})]})}var Of={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,pdf:`application/pdf`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,m4a:`audio/mp4`,mp4:`video/mp4`,webm:`video/webm`,ogv:`video/ogg`};function kf(e){return/\.([^./]+)$/.exec(e)?.[1].toLowerCase()??``}function Af(e){let t=kf(e);return Object.hasOwn(Of,t)?Of[t]:void 0}function jf(e){let t=Af(e);if(t===`application/pdf`)return`pdf`;if(t?.startsWith(`image/`))return`image`;if(t?.startsWith(`audio/`))return`audio`;if(t?.startsWith(`video/`))return`video`;if(/\.(csv|tsv)$/i.test(e))return`table`;if(/\.docx$/i.test(e))return`document`;if(/\.pptx$/i.test(e))return`presentation`}var Mf=e=>e.slice(0,Math.max(0,e.lastIndexOf(`/`))),Nf=(e,t)=>!t||e===t||e.startsWith(`${t}/`),Pf=e=>e.split(`/`).at(-1)??e;function Ff(e){if(!(e instanceof Element))return;let t=e.closest(`[data-file-dir], [data-file-entry], [data-file-hit]`);if(!t)return;let n=t.dataset.fileDir??t.dataset.fileEntry??t.dataset.fileHit;if(n!==void 0)return{path:n,directory:t.dataset.fileDir!==void 0,linked:t.dataset.linked===`true`||t.dataset.fileOutside!==void 0}}function If({title:e,cancel:t,children:n}){let r=(0,u.useRef)(null);return(0,u.useEffect)(()=>{let e=r.current,t=document.activeElement;return e?.showModal(),()=>{e?.close(),t?.isConnected&&t.focus()}},[]),(0,F.jsx)(`dialog`,{ref:r,className:`file-explorer-dialog`,"aria-label":e,onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`file-explorer-dialog-body`,children:[(0,F.jsx)(`h2`,{children:e}),n]})})}function Lf({target:e,label:t,initial:n,busy:r,error:i,depth:a,submit:o,close:s}){let c=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let t=c.current;if(!t)return;t.focus();let r=n.lastIndexOf(`.`);t.setSelectionRange(0,!e.directory&&r>0?r:n.length)},[n,e.directory]),(0,F.jsxs)(`form`,{className:`file-inline-edit`,"data-file-inline-edit":e.path,"aria-label":t,style:{paddingInlineStart:23+a*15},onSubmit:o,onKeyDown:e=>{e.key===`Escape`&&!r&&(e.preventDefault(),e.stopPropagation(),s())},children:[(0,F.jsxs)(`div`,{className:`file-inline-row`,children:[(0,F.jsx)(Fr,{path:e.path,category:e.directory?`folder`:void 0}),(0,F.jsx)(`input`,{ref:c,name:`name`,required:!0,defaultValue:n,placeholder:t,"aria-label":t,"aria-invalid":!!i,readOnly:r,autoComplete:`off`,spellCheck:!1}),(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`submit`,title:t,"aria-label":t,disabled:r,children:(0,F.jsx)(yf,{name:`right`})}),(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,onClick:s,disabled:r,title:`取消`,"aria-label":`取消`,children:(0,F.jsx)(yf,{name:`close`})})]}),i&&(0,F.jsx)(`p`,{className:`file-inline-error`,role:`alert`,children:i})]})}function Rf({files:e,source:t,scopeName:n}){let[r,i]=(0,u.useState)(Mf(t.path)),a=e.listings[r],o=e.loadDirectory;(0,u.useEffect)(()=>{a||o(r)},[r,a,o]);let s=a&&`entries`in a?a.entries.filter(e=>e.kind===`directory`&&!e.symlink&&!(t.directory&&Nf(e.path,t.path))):[];return(0,F.jsxs)(`div`,{className:`file-move-picker`,children:[(0,F.jsx)(`input`,{type:`hidden`,name:`parent`,value:r}),(0,F.jsxs)(`div`,{className:`file-move-location`,children:[(0,F.jsx)(`button`,{type:`button`,disabled:!r,"aria-label":`上一级`,onClick:()=>i(Mf(r)),children:`↑`}),(0,F.jsx)(`span`,{title:r||n,children:r||n})]}),(0,F.jsx)(`ul`,{"aria-label":`目标文件夹`,children:s.map(e=>(0,F.jsx)(`li`,{children:(0,F.jsxs)(`button`,{type:`button`,onClick:()=>i(e.path),children:[(0,F.jsx)(Fr,{category:`folder`}),(0,F.jsx)(`span`,{children:e.name}),(0,F.jsx)(yf,{name:`right`})]})},e.path))}),!s.length&&(0,F.jsx)(`p`,{children:a?`error`in a?a.error.message:`此处没有子文件夹。`:`正在读取文件夹…`})]})}function zf({workspaceId:e,scopeName:t,cwd:n,files:r,onOpen:i,onReference:a,onMoved:o,onSearchFolder:s}){let[c,l]=(0,u.useState)(),[d,f]=(0,u.useState)(),[p,m]=(0,u.useState)(),[h,g]=(0,u.useState)(!1),[_,v]=(0,u.useState)(``),[y,b]=(0,u.useState)(),x=(0,u.useRef)(null),S=(0,u.useRef)(``),C=(0,u.useRef)(void 0),w=(0,u.useRef)(void 0);(0,u.useEffect)(()=>{let e={controller:new AbortController};return w.current=e,l(void 0),f(void 0),m(void 0),b(void 0),g(!1),v(``),()=>{e.controller.abort(),w.current===e&&(w.current=void 0)}},[e,n]);let T=(t,r=``,i)=>wf(t,e??``,n,r,i);async function E(e,t){let n=await Ne(e,{...t,signal:w.current?.controller.signal}),r=await n.json();if(!n.ok)throw Error(r.error??`操作失败(${n.status})`);return r}function D(e,t){c?.anchor.origin===t.origin&&c.target.path===e.path?l(void 0):l({target:e,anchor:t})}function O(e){l(void 0),e&&c?.anchor.origin.isConnected&&c.anchor.origin.focus({preventScroll:!0})}function k(e,t,n,i){C.current=i??c?.anchor.origin??(document.activeElement instanceof HTMLElement?document.activeElement:void 0),l(void 0),v(``),f({action:e,target:t,move:n}),e===`create-file`||e===`create-directory`?t.path?r.revealPath(`${t.path}/`):r.setQuery(``):e===`move`&&!n&&r.revealPath(t.path)}function A(){f(void 0);let e=C.current;requestAnimationFrame(()=>{e?.isConnected&&e.offsetParent?e.focus({preventScroll:!0}):d?.target.path&&r.locatePath(d.target.path,d.target.directory)})}async function j(t){let a=w.current;g(!0),v(``);try{let s=await E(T(`tree`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(w.current!==a)return;if(s.previousPath&&s.previousPath!==s.path?(r.movePath(s.previousPath,s.path,s.text),o?.(s.previousPath,s.path)):s.removed||r.revealPath(s.path),r.invalidateTree(e??``,[s.path,...s.previousPath?[s.previousPath]:[]].map(e=>n?`${n}/${e}`:e)),s.removed){for(let e of r.open)Nf(e.path,s.path)&&!e.dirty&&r.closeFile(e.path);r.locatePath(Mf(s.path),!0)}f(void 0),t.action===`restore`&&m(e=>e?.filter(e=>e.id!==t.id)),t.action===`create-file`&&s.text!==!1&&i({path:s.path,name:Pf(s.path),text:!0},!0),t.action!==`restore`&&!s.removed&&r.locatePath(s.path,!!s.directory),r.setNotice(s.removed?`已移到回收站:${s.path}`:t.action===`restore`?`已恢复:${s.path}`:``)}catch(e){if(w.current===a){let t=e instanceof Error?e.message:String(e);v(t),d||r.setNotice(t)}}finally{w.current===a&&g(!1)}}function ee(e){if(e.preventDefault(),!d||h)return;let{action:t,target:n}=d;if((t===`move`||t===`trash`)&&Object.entries(r.saves).some(([e,t])=>Nf(e,n.path)&&t.state===`saving`)){v(`文件正在保存,等保存结束后再操作。`);return}if(t===`trash`&&r.open.some(e=>e.dirty&&Nf(e.path,n.path))){v(`这里有未保存的草稿,请先保存。`);return}let i=new FormData(e.currentTarget),a=String(i.get(`name`)??Pf(n.path));if(t===`move`&&!n.directory&&kf(n.path)!==kf(a)&&r.open.some(e=>e.path===n.path&&e.dirty)){v(`更换文件扩展名之前,请先保存草稿。`);return}let o=String(i.get(`parent`)??(t===`move`?Mf(n.path):n.path));d.move&&o===Mf(n.path)?v(`请选择另一个文件夹。`):j({action:t,path:n.path,parent:o,name:a})}async function M(){let e=w.current;l(void 0),v(``);try{let t=await E(T(`tree`));w.current===e&&m(t.entries)}catch(t){w.current===e&&r.setNotice(String(t.message))}}function te(e){S.current=e,O(!0),x.current?.click()}async function N(t,i,a){let o=w.current;if(!e||!o||!i.length||h)return;g(!0),v(``),b(void 0);let s=[],c=[],l=[];try{for(let e of i){if(o!==w.current)return;try{let n=a?.find(t=>t.file===e)?.etag;if(!a){let n=await E(T(`upload-check`,t,{name:e.name}));if(n.exists){!n.replaceable||!n.meta?c.push(`${e.name}:同名目录或链接`):s.push({file:e,etag:n.meta.etag});continue}}let r=await E(T(`upload`,t,{name:e.name}),{method:`POST`,headers:{"content-type":`application/octet-stream`,...n?{"if-match":n}:{}},body:e});l.push(r.path)}catch(t){c.push(`${e.name}:${t.message}`)}}if(w.current!==o)return;l[0]&&r.revealPath(l[0]),l.length&&r.invalidateTree(e,l.map(e=>n?`${n}/${e}`:e)),s.length&&b({parent:t,items:s}),r.setNotice([l.length?`已上传 ${l.length} 个文件`:``,...c].filter(Boolean).join(`。`))}finally{w.current===o&&g(!1)}}function ne(e,t){l(void 0),a?.(e||`.`,t)}function re(e){O(!0),Bd(e||`.`).then(t=>r.setNotice(t?`已复制相对路径。`:`相对路径:${e||`.`}`))}let ie=d?.action===`create-file`?`新建文件`:d?.action===`create-directory`?`新建文件夹`:d?.action===`trash`?`移到回收站`:d?.move?`移动到文件夹`:`重命名`,ae={path:``,directory:!0},oe=d?.action===`create-file`||d?.action===`create-directory`,se=d?.action===`move`&&!d.move,ce=(e,t,n)=>!d||d.target.path!==e||(t===`child`?!oe:!se)?null:(0,F.jsx)(Lf,{target:{...d.target,directory:oe?d.action===`create-directory`:d.target.directory},label:ie,initial:se?Pf(e):``,busy:h,error:_,depth:n,submit:ee,close:A},`${d.action}:${e}`),le=(e,t)=>{h||e.linked||e.directory&&Nf(t,e.path)||t===Mf(e.path)||(Object.entries(r.saves).some(([t,n])=>Nf(t,e.path)&&n.state===`saving`)?r.setNotice(`文件正在保存,等保存结束后再移动。`):j({action:`move`,path:e.path,parent:t,name:Pf(e.path)}))},ue=(0,F.jsxs)(`div`,{className:`file-explorer-toolbar`,role:`group`,"aria-label":`文件操作`,children:[(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-explorer-command":`new-file`,title:`新建文件`,"aria-label":`新建文件`,onClick:e=>k(`create-file`,ae,!1,e.currentTarget),disabled:!e||h,children:(0,F.jsx)(yf,{name:`file`})}),(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-explorer-command":`new-directory`,title:`新建文件夹`,"aria-label":`新建文件夹`,onClick:e=>k(`create-directory`,ae,!1,e.currentTarget),disabled:!e||h,children:(0,F.jsx)(yf,{name:`folder`})}),(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-file-refresh":`1`,title:`刷新目录`,"aria-label":`刷新目录`,onClick:r.refreshTree,disabled:!e,children:(0,F.jsx)(yf,{name:`refresh`})}),(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-file-collapse-all":`1`,title:`折叠所有文件夹`,"aria-label":`折叠所有文件夹`,onClick:r.collapseDirectories,disabled:!r.expanded.size,children:(0,F.jsx)(yf,{name:`collapse`})}),(0,F.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-explorer-command":`root-menu`,"aria-haspopup":`menu`,"aria-expanded":c?.target.path===``,onClick:e=>D(ae,bf(e.currentTarget)),title:`更多文件操作`,"aria-label":`更多文件操作`,disabled:!e||h,children:(0,F.jsx)(yf,{name:`more`})})]}),de=(e,t,n,r,i)=>(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,className:`file-context-item`,"data-explorer-command":r,onClick:n,children:[(0,F.jsx)(yf,{name:t}),(0,F.jsx)(`span`,{children:e}),i&&(0,F.jsx)(`kbd`,{children:i})]});return{controls:(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`input`,{ref:x,type:`file`,multiple:!0,hidden:!0,"aria-label":`上传工作区文件`,onChange:e=>{let t=Array.from(e.currentTarget.files??[]);e.currentTarget.value=``,N(S.current,t)}}),c&&(0,F.jsxs)(xf,{label:c.target.path||t,anchor:c.anchor,close:O,children:[c.target.directory&&!c.target.linked&&(0,F.jsxs)(F.Fragment,{children:[s&&de(`在此文件夹中搜索`,`search`,()=>{let e=c.target.path;O(!1),s(e)},`search-folder`),de(`新建文件`,`file`,()=>k(`create-file`,c.target),`new-file`),de(`新建文件夹`,`folder`,()=>k(`create-directory`,c.target),`new-directory`),de(`上传到此处`,`upload`,()=>te(c.target.path),`upload`),(0,F.jsx)(`div`,{role:`separator`})]}),c.target.path&&!c.target.linked&&(0,F.jsxs)(F.Fragment,{children:[de(`重命名`,`rename`,()=>k(`move`,c.target),`rename`,`F2`),de(`移动到文件夹`,`move`,()=>k(`move`,c.target,!0),`move`),(0,F.jsx)(`div`,{role:`separator`})]}),!c.target.linked&&a&&de(`引用到会话`,`reference`,()=>ne(c.target.path,c.target.directory),`reference`),de(`复制相对路径`,`copy`,()=>re(c.target.path)),!c.target.directory&&!c.target.linked&&(0,F.jsxs)(`a`,{role:`menuitem`,tabIndex:-1,className:`file-context-item`,href:T(`asset`,c.target.path,{download:`1`}),download:Pf(c.target.path),onClick:()=>O(!0),children:[(0,F.jsx)(yf,{name:`download`}),(0,F.jsx)(`span`,{children:`下载`})]}),!c.target.path&&de(`打开回收站`,`trash`,()=>void M(),`trash-list`),!!c.target.path&&!c.target.linked&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{role:`separator`}),de(`移到回收站`,`trash`,()=>k(`trash`,c.target),`trash`,`Delete`)]})]}),d&&!oe&&!se&&(0,F.jsx)(If,{title:ie,cancel:()=>{h||A()},children:(0,F.jsxs)(`form`,{onSubmit:ee,className:`file-explorer-form`,children:[d.action===`trash`?(0,F.jsxs)(`p`,{children:[`将「`,d.target.path,`」移到回收站?`]}):(0,F.jsx)(Rf,{files:r,source:d.target,scopeName:t}),_&&(0,F.jsx)(`p`,{role:`alert`,children:_}),(0,F.jsxs)(`div`,{className:`file-explorer-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,disabled:h,onClick:A,children:`取消`}),(0,F.jsx)(`button`,{type:`submit`,disabled:h,children:d.move?`移动到此处`:ie})]})]})}),p&&(0,F.jsxs)(If,{title:`回收站`,cancel:()=>{h||m(void 0)},children:[_&&(0,F.jsx)(`p`,{role:`alert`,children:_}),p.length?(0,F.jsx)(`ul`,{className:`file-explorer-trash`,children:p.map(e=>(0,F.jsxs)(`li`,{children:[(0,F.jsx)(`span`,{children:e.path}),(0,F.jsx)(`button`,{type:`button`,"data-explorer-restore":e.path,disabled:h,onClick:()=>void j({action:`restore`,id:e.id}),children:`还原`})]},e.id))}):(0,F.jsx)(`p`,{children:`回收站为空。`}),(0,F.jsx)(`button`,{type:`button`,disabled:h,onClick:()=>m(void 0),children:`关闭`})]}),y&&(0,F.jsxs)(If,{title:`同名文件`,cancel:()=>b(void 0),children:[(0,F.jsx)(`p`,{children:`以下文件已经存在。替换前会再次检查磁盘版本。`}),(0,F.jsx)(`ul`,{children:y.items.map(e=>(0,F.jsx)(`li`,{children:e.file.name},e.file.name))}),(0,F.jsxs)(`div`,{className:`file-explorer-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,onClick:()=>{r.setNotice(`已跳过 ${y.items.length} 个同名文件。`),b(void 0)},children:`跳过`}),(0,F.jsx)(`button`,{type:`button`,"data-file-replace-upload":`1`,onClick:()=>void N(y.parent,y.items.map(e=>e.file),y.items),children:`替换`})]})]})]}),toolbar:ue,inline:ce,editing:oe||se,busy:h,openMenu:D,showAction:k,upload:N,moveTo:le}}var Bf=[{id:`path`,label:`文件名 / 路径`,shortcut:`Ctrl+P`},{id:`content`,label:`文件内容`,shortcut:`Ctrl+Shift+F`},{id:`session`,label:`会话消息`}];function Vf({mode:e,query:t,onClose:n,onMode:r,children:i,presentation:a}){let o=e===`path`?{"data-quick-open":`1`}:e===`content`?{"data-content-search":`1`}:{"data-session-search":`1`},s=(0,F.jsx)(`div`,{className:`workbench-search-modes`,role:`group`,"aria-label":`搜索范围`,children:Bf.map(n=>(0,F.jsx)(`button`,{type:`button`,"data-workbench-search-mode":n.id,"aria-pressed":n.id===e,title:n.shortcut,onClick:()=>{n.id!==e&&r(n.id,t)},children:n.label},n.id))});return a===`sidebar`?(0,F.jsxs)(`div`,{className:`workbench-search-embedded`,...o,children:[s,i]}):(0,F.jsx)(`div`,{className:`quick-open-backdrop`,...o,role:`presentation`,onMouseDown:n,children:(0,F.jsxs)(`div`,{className:e===`path`?`quick-open`:`quick-open content-search`,role:`dialog`,"aria-modal":`true`,"aria-label":Bf.find(t=>t.id===e)?.label,onMouseDown:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Escape`&&!e.nativeEvent.isComposing&&(e.preventDefault(),n())},children:[s,i]})})}function Hf({workspaceId:e,initialQuery:t=``,onClose:n,onMode:r,onOpen:i,presentation:a}){let[o,s]=(0,u.useState)(t),[c,l]=(0,u.useState)(),[d,f]=(0,u.useState)(``),[p,m]=(0,u.useState)(0),[h,g]=(0,u.useState)(!1),_=(0,u.useRef)(null),v=(0,u.useRef)(null);return(0,u.useEffect)(()=>{_.current?.focus()},[]),(0,u.useEffect)(()=>{v.current?.scrollIntoView({block:`nearest`})},[p]),(0,u.useEffect)(()=>{let t=o.trim();if(l(void 0),m(0),f(``),g(!1),!e||!t)return;if(t.length>256){f(`搜索词不能超过 256 个字符。`);return}let n=new AbortController;g(!0);let r=setTimeout(()=>{Ne(`/api/session-search?${new URLSearchParams({workspaceId:e,q:t})}`,{signal:n.signal}).then(async e=>{if(!e.ok)throw Error(`会话搜索没有完成。`);return await e.json()}).then(e=>{n.signal.aborted||l(e)}).catch(e=>{n.signal.aborted||f(Or(e,`会话搜索没有完成。`))}).finally(()=>{n.signal.aborted||g(!1)})},180);return()=>{clearTimeout(r),n.abort()}},[o,e]),(0,F.jsxs)(Vf,{mode:`session`,query:o,onMode:r,onClose:n,presentation:a,children:[(0,F.jsx)(`input`,{ref:_,className:`quick-open-input`,"data-session-search-input":!0,value:o,"aria-label":`搜索会话消息`,placeholder:`输入要在会话消息中查找的文字`,onChange:e=>s(e.target.value),onKeyDown:e=>{if(!e.nativeEvent.isComposing&&(e.key===`ArrowDown`&&(e.preventDefault(),m(e=>Math.min(e+1,Math.max(0,(c?.hits.length??0)-1)))),e.key===`ArrowUp`&&(e.preventDefault(),m(e=>Math.max(0,e-1))),e.key===`Enter`)){e.preventDefault();let t=c?.hits[p];t&&i(t)}}}),(0,F.jsx)(`p`,{className:`quick-open-status`,role:`status`,"data-session-search-status":!0,children:d||(h?`搜索中…`:e?c?c.truncated?`显示前 60 条命中`:`${c.hits.length} 条命中`:`当前工作区的未归档会话 · 用户和 Agent 消息`:`请选择工作区`)}),(0,F.jsx)(`ul`,{className:`quick-open-results content-search-results`,"aria-label":`会话搜索结果`,children:c?.hits.map((e,t)=>(0,F.jsx)(`li`,{children:(0,F.jsxs)(`button`,{ref:t===p?v:void 0,type:`button`,"data-session-search-result":e.messageId,className:`quick-open-result content-search-result${p===t?` quick-open-result-active`:``}`,onMouseEnter:()=>m(t),onClick:()=>i(e),children:[(0,F.jsxs)(`span`,{children:[e.title,` · `,e.role===`user`?`用户`:`Agent`]}),(0,F.jsxs)(`small`,{children:[e.before,(0,F.jsx)(`mark`,{children:e.match}),e.after]})]})},`${e.conversationId}:${e.messageId}`))})]})}var Uf=class extends u.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[SuperPi ErrorBoundary captured error]:`,e,t)}reset=()=>{this.setState({error:null})};render(){let{error:e}=this.state;return e?this.props.fallback?this.props.fallback(e,this.reset):(0,F.jsxs)(`div`,{className:`error-boundary-card`,"data-error-boundary":`1`,children:[(0,F.jsxs)(`div`,{className:`error-boundary-head`,children:[(0,F.jsx)(`span`,{className:`error-boundary-icon`,"aria-hidden":`true`,children:`⚠️`}),(0,F.jsx)(`strong`,{children:`视图渲染遇到异常`})]}),(0,F.jsx)(`p`,{className:`error-boundary-msg`,children:e.message||`未知组件错误`}),(0,F.jsx)(`button`,{type:`button`,className:`error-boundary-retry`,onClick:this.reset,children:`重试`})]}):this.props.children}};function Wf(){}Wf.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={}),this.options=n;var i=this;function a(e){return r?(setTimeout(function(){r(void 0,e)},0),!0):e}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0);if(f[0].oldPos+1>=s&&p+1>=o)return a([{value:this.join(t),count:t.length}]);var m=-1/0,h=1/0;function g(){for(var n=Math.max(m,-c);n<=Math.min(h,c);n+=2){var r=void 0,l=f[n-1],u=f[n+1];l&&(f[n-1]=void 0);var d=!1;if(u){var g=u.oldPos-n;d=u&&0<=g&&g<o}var _=l&&l.oldPos+1<s;if(!d&&!_)f[n]=void 0;else{if(r=!_||d&&l.oldPos+1<u.oldPos?i.addToPath(u,!0,void 0,0):i.addToPath(l,void 0,!0,1),p=i.extractCommon(r,t,e,n),r.oldPos+1>=s&&p+1>=o)return a(Gf(i,r.lastComponent,t,e,i.useLongestToken));f[n]=r,r.oldPos+1>=s&&(h=Math.min(h,n-1)),p+1>=o&&(m=Math.max(m,n+1))}}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:i}}},extractCommon:function(e,t,n,r){for(var i=t.length,a=n.length,o=e.oldPos,s=o-r,c=0;s+1<i&&o+1<a&&this.equals(t[s+1],n[o+1]);)s++,o++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=o,s},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return e.split(``)},join:function(e){return e.join(``)}};function Gf(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(!d.removed){if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}else if(d.value=e.join(r.slice(u,u+d.count)),u+=d.count,s&&a[s-1].added){var p=a[s-1];a[s-1]=a[s],a[s]=p}}var m=a[c-1];return c>1&&typeof m.value==`string`&&(m.added||m.removed)&&e.equals(``,m.value)&&(a[c-2].value+=m.value,a.pop()),a}new Wf;var Kf=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,qf=/\S/,Jf=new Wf;Jf.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!qf.test(e)&&!qf.test(t)},Jf.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&Kf.test(t[n])&&Kf.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var Yf=new Wf;Yf.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
285
285
|
`));var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var i=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=i:(this.options.ignoreWhitespace&&(i=i.trim()),t.push(i))}return t};function Xf(e,t,n){return Yf.diff(e,t,n)}var Zf=new Wf;Zf.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var Qf=new Wf;Qf.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function $f(e){"@babel/helpers - typeof";return $f=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},$f(e)}var ep=Object.prototype.toString,tp=new Wf;tp.useLongestToken=!0,tp.tokenize=Yf.tokenize,tp.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(np(e,null,null,i),i,` `)},tp.equals=function(e,t){return Wf.prototype.equals.call(tp,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`))};function np(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));for(var a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(ep.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=np(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),$f(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)e.hasOwnProperty(c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=np(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var rp=new Wf;rp.tokenize=function(e){return e.slice()},rp.join=rp.removeEmpty=function(e){return e};function ip(e,t){let n=Xf(e??``,t??``),r=[],i=0,a=0,o=1,s=1;for(let e of n){let t=e.value.split(`
|
|
286
286
|
`),n=t.length>0&&t[t.length-1]===``;n&&t.pop();for(let c=0;c<t.length;c+=1){let l=t[c],u=c===t.length-1&&!n;e.added?(r.push({kind:`added`,text:l,newLine:s,noNewline:u}),s+=1,i+=1):e.removed?(r.push({kind:`removed`,text:l,oldLine:o,noNewline:u}),o+=1,a+=1):(r.push({kind:`same`,text:l,oldLine:o,newLine:s,noNewline:u}),o+=1,s+=1)}}return{lines:r,added:i,removed:a,identical:i===0&&a===0}}function ap(e,t=3){let n=new Set;e.lines.forEach((r,i)=>{if(r.kind!==`same`)for(let r=-t;r<=t;r+=1){let t=i+r;t>=0&&t<e.lines.length&&n.add(t)}});let r=[],i=0,a=!1;return e.lines.forEach((e,t)=>{n.has(t)?(a&&=(r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),!1),r.push(e)):a||(a=!0,i+=1)}),a&&r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),{lines:r,folded:i}}var op=`super-pi.outbox.v1.`,sp=e=>op+JSON.stringify([e.conversationId,e.clientId]);function cp(){try{let e=[];for(let t of Object.keys(window.localStorage).filter(e=>e.startsWith(op)))try{let n=JSON.parse(window.localStorage.getItem(t)??`null`),r=n?.send;r?.type===`message.send`&&typeof r.conversationId==`string`&&/^message_[0-9a-f-]{36}$/.test(r.clientId)&&typeof r.content==`string`&&t===sp(r)&&e.push(n)}catch{}return e.sort((e,t)=>e.queuedAt-t.queuedAt).map(e=>e.send)}catch{return[]}}function lp(e){try{return window.localStorage.setItem(sp(e),JSON.stringify({queuedAt:Date.now(),send:e})),!0}catch{return!1}}function up(e,t){try{window.localStorage.removeItem(sp({conversationId:e,clientId:t}))}catch{}}function dp(e){return m(h(e.conversationId).server,e.clientId)}function fp(e,t,n){let r=e.conversations.find(e=>e.id===t.conversationId),i=dp(t);if(!r||r.messages.some(e=>e.id===i))return e;let a=r.status===`running`||r.status===`waiting`;return{...e,conversations:e.conversations.map(e=>e===r?{...e,...a?{}:{status:`waiting`,updatedAt:n},messages:[...e.messages,{id:i,role:`user`,content:t.content,createdAt:n,...t.images?.length?{images:t.images}:{},...t.attachments?.length?{attachments:t.attachments}:{},...a?{delivery:`waiting`}:{}}]}:e)}}function pp(e,t){try{return JSON.parse(Pn(e)??`null`)??t}catch{return t}}function mp(e,t){try{return Fn(e,JSON.stringify(t)),!0}catch{return!1}}var hp=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.name=`BlameApiError`,this.status=e,this.body=t}},gp=class extends Error{constructor(){super(`Blame 请求已取消`),this.name=`BlameCancelledError`}},_p=(e,t,n=``)=>`/api/git?workspaceId=${encodeURIComponent(e)}&op=blame&path=${encodeURIComponent(t)}${n?`&cwd=${encodeURIComponent(n)}`:``}`;async function vp(e,t,n={}){if(n.signal?.aborted)throw new gp;let r=n.timeoutMs??15e3,i=new AbortController,a=!1,o=setTimeout(()=>{a=!0,i.abort()},r),s=()=>i.abort();n.signal?.addEventListener(`abort`,s,{once:!0});try{let r=await Ne(_p(e,t,n.cwd),{signal:i.signal}),a;try{a=await r.json()}catch{a=void 0}if(!r.ok){let e=a??{};throw new hp(r.status,{error:e.error||`HTTP ${r.status}`,...e.code?{code:e.code}:{}})}return a}catch(e){throw n.signal?.aborted?new gp:a?new hp(408,{error:`请求超时:${Math.round(r/1e3)} 秒内服务端没有响应`,code:`timeout`}):e}finally{clearTimeout(o),n.signal?.removeEventListener(`abort`,s)}}var yp=`\0`,bp=(e,t,n)=>[e,t,n??``].join(yp),xp=24,Sp=new Map;function Cp(e){let t=Sp.get(e);if(t)return Sp.delete(e),Sp.set(e,t),t}function wp(e,t){for(Sp.delete(e),Sp.set(e,t);Sp.size>xp;){let e=Sp.keys().next();if(e.done)break;Sp.delete(e.value)}}var Tp={untracked:`这个文件尚未被 Git 跟踪`,binary:`二进制文件不支持 Blame`,too_large:`文件过大,未显示 Blame`,no_head:`仓库还没有提交`,not_in_revision:`这个版本里没有这个文件`},Ep=`此工作区不是 Git 仓库`;function Dp(e){return e&&Tp[e]?{code:e,text:Tp[e]}:{code:`unsupported`,text:`这个文件暂时不能显示 Blame`}}function Op(e){return e instanceof hp&&e.body.code===`not_a_repo`?{state:`unsupported`,note:{code:`not_a_repo`,text:Ep}}:{state:`error`,note:{code:`error`,text:`读取 Blame 失败:${e instanceof Error&&e.message?e.message:`未知错误`}`}}}var kp=`${yp}uncommitted`;function Ap(e){let t=new Map,n=0;for(let r of e.lines)t.has(r.line)||t.set(r.line,r),r.line>n&&(n=r.line);let r=[],i=null,a=0;for(let e=1;e<=n;e+=1){let n=t.get(e);if(!n){r.push({line:e,kind:`missing`,data:null}),i=null,a=e;continue}let o=n.isUncommitted?kp:n.commit??`${yp}none`,s=o===i&&e===a+1?`continuation`:n.isUncommitted?`uncommitted`:`commit`;r.push({line:e,kind:s,data:n}),i=o,a=e}if(e.truncated)for(let t=n+1;t<=e.totalLines;t+=1)r.push({line:t,kind:`truncated`,data:null});return r}function jp(e){let t=0;for(let n of e.lines)n.line>t&&(t=n.line);return t}function Mp(e){switch(e.kind){case`commit`:{let t=e.data,n=t?.shortCommit??t?.commit?.slice(0,8)??`?`,r=t?.author?.trim();return r?`${n} · ${r}`:n}case`continuation`:return`│`;case`uncommitted`:return`● 未提交`;case`missing`:return`?`;case`truncated`:return`…`;default:return``}}function Np(e){if(e.kind===`uncommitted`||e.data?.isUncommitted)return[`未提交`,`这行尚不属于任何 Git 提交`];if(e.kind===`missing`)return[`没有 Blame 信息`,`这一行没有对应的提交记录`];if(e.kind===`truncated`)return[`Blame 数据已截断`,`文件太长,只显示了前面一部分的提交信息`];let t=e.data;if(!t)return[`没有 Blame 信息`];let n=t.shortCommit??t.commit?.slice(0,8)??`未知提交`,r=t.author?.trim()||`未知作者`;return[n,t.authorEmail?`${r} <${t.authorEmail}>`:r,Pp(t.date),t.summary?.trim()||`(没有提交摘要)`]}function Pp(e){if(!e)return`不详`;let t=new Date(e);if(!Number.isFinite(t.getTime()))return e;let n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Fp(e){if(e.length===0)return 0;let t=1;for(let n=0;n<e.length;n+=1)e.charCodeAt(n)===10&&(t+=1);return e.charCodeAt(e.length-1)===10&&--t,t}function Ip(e,t,n=!1){return!t||!t.supported?!1:n||Fp(e)!==t.totalLines}var Lp=new WeakMap;function Rp(e){let t=Lp.get(e);if(t)return t;let n={response:e,models:Ap(e),covered:jp(e)};return Lp.set(e,n),n}function zp(e,t){if(!e||t<1)return null;let n=e.models[t-1];return n&&n.line===t?n:null}var Bp=`a1b2c3d · Author`;async function Vp(){let[e,t]=await Promise.all([vn(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([2,1])),vn(()=>import(`./dist-B3-a6uF0.js`).then(e=>e.s),__vite__mapDeps([3,1,2]))]),n=e.StateEffect.define(),r=e.StateField.define({create:()=>null,update:(e,t)=>{for(let e of t.effects)if(e.is(n))return e.value;return e}}),i=e.StateEffect.define(),a=e.StateField.define({create:()=>null,update:(e,t)=>{for(let e of t.effects)if(e.is(i))return e.value;return e}}),o=t.GutterMarker;class s extends o{model;constructor(e){super(),this.model=e}eq(e){let t=e.model;return t?t.line===this.model.line&&t.kind===this.model.kind&&t.data?.commit===this.model.data?.commit&&t.data?.summary===this.model.data?.summary&&t.data?.author===this.model.data?.author:!1}toDOM(){let e=document.createElement(`span`);e.className=`cm-blame-marker cm-blame-${this.model.kind}`,e.setAttribute(`data-file-blame-line`,String(this.model.line)),e.setAttribute(`data-file-blame-kind`,this.model.kind),this.model.data?.commit&&e.setAttribute(`data-file-blame-commit`,this.model.data.commit);let t=Np(this.model);return e.setAttribute(`title`,t.join(`
|
|
287
|
-
`)),e.setAttribute(`aria-label`,t.join(` · `)),e.textContent=Mp(this.model),e}}class c extends o{eq(){return!0}toDOM(){let e=document.createElement(`span`);return e.className=`cm-blame-marker cm-blame-spacer`,e.textContent=Bp,e}}let l=t.gutter({class:`cm-blame-gutter`,initialSpacer:()=>new c,lineMarker:(e,t)=>{let n=e.state.field(r);if(!n)return null;let i=e.state.doc.lineAt(t.from).number,a=zp(n,i);return new s(a??{line:i,kind:`missing`,data:null})},lineMarkerChange:e=>e.startState.field(r)!==e.state.field(r)}),u=t.ViewPlugin.fromClass(class{line=null;editorView;constructor(e){this.editorView=e,this.editorView.dom.addEventListener(`mousemove`,this.onMove),this.editorView.dom.addEventListener(`mouseleave`,this.onLeave)}destroy(){this.editorView.dom.removeEventListener(`mousemove`,this.onMove),this.editorView.dom.removeEventListener(`mouseleave`,this.onLeave)}update(e){e.startState.field(r)!==e.state.field(r)&&this.line!==null&&(this.line=null,this.editorView.dispatch({effects:i.of(null)}))}onMove=e=>{let t=this.lineAt(e);if(t===this.line)return;if(this.line=t,t===null){this.editorView.dispatch({effects:i.of(null)});return}let n=zp(this.editorView.state.field(r),t);if(!n){this.editorView.dispatch({effects:i.of(null)});return}let a=this.editorView.state.doc,o=a.line(Math.min(t,a.lines));this.editorView.dispatch({effects:i.of({pos:o.from,above:!0,create:()=>({dom:Hp(n)})})})};onLeave=()=>{this.line=null,this.editorView.dispatch({effects:i.of(null)})};lineAt(e){let t=e.target,n=t?.closest?.(`[data-file-blame-line]`);if(n){let e=Number(n.getAttribute(`data-file-blame-line`));return Number.isInteger(e)&&e>0?e:null}if(t?.closest?.(`.cm-blame-gutter`))return null;let r=this.editorView.posAtCoords({x:e.clientX,y:e.clientY});return r==null?null:this.editorView.state.doc.lineAt(r).number}});return{field:r,setBlame:n,base:[r,a,t.showTooltip.from(a),u],gutter:l}}function Hp(e){let t=document.createElement(`div`);t.className=`cm-blame-tooltip`,t.setAttribute(`data-file-blame-tooltip`,`1`),t.setAttribute(`data-file-blame-kind`,e.kind),e.data?.commit&&t.setAttribute(`data-file-blame-commit`,e.data.commit);for(let n of Np(e)){let e=document.createElement(`div`);e.className=`cm-blame-tooltip-row`,e.textContent=n,t.appendChild(e)}return t}function Up(e,t){let n=(0,u.useRef)(null),r=(0,u.useRef)(void 0);return(0,u.useLayoutEffect)(()=>{let e=r.current;r.current=void 0;let i=n.current;if(!i||!e)return;let a=i.querySelectorAll(t)[e.index];a&&(i.scrollTop+=a.getBoundingClientRect().top-i.getBoundingClientRect().top-e.offset)},[e,t]),{scrollBox:n,capture:()=>{let e=n.current;if(!e)return;let i=e.getBoundingClientRect().top,a;e.querySelectorAll(t).forEach((e,t)=>{let n=e.getBoundingClientRect().top-i;(!a||Math.abs(n)<Math.abs(a.offset))&&(a={index:t,offset:n})}),r.current=a}}}var Wp=`super-pi.diff-layout.v1`,Gp=`super-pi-diff-layout`;function Kp(){try{return localStorage.getItem(Wp)===`split`}catch{return!1}}function qp(e){let t=t=>{(t.key===Wp||t.key===null)&&e()};return window.addEventListener(Gp,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(Gp,e),window.removeEventListener(`storage`,t)}}var Jp;function Yp(){return Jp??Kp()}function Xp(){return[(0,u.useSyncExternalStore)(qp,Yp,()=>!1),e=>{Jp=e;try{localStorage.setItem(Wp,e?`split`:`inline`),Jp=void 0}catch{}window.dispatchEvent(new Event(Gp))}]}var Zp=4e3,Qp=(0,u.lazy)(()=>vn(()=>import(`./CodeMirrorEditor-D-UuYizz.js`).then(e=>({default:e.CodeMirrorEditor})),__vite__mapDeps([21,1]))),$p=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},em=15e3,tm=e=>new $p(408,{error:`请求超时:${em/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function nm(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),em);try{let r=t?.signal?AbortSignal.any([t.signal,n.signal]):n.signal,i=await Ne(e,{...t,signal:r}),a;try{a=await i.json()}catch{a=void 0}if(!i.ok)throw new $p(i.status,a??{error:`HTTP ${i.status}`});return a}catch(t){throw n.signal.aborted?tm(e):t}finally{clearTimeout(r)}}var rm=e=>e instanceof $p?e:new $p(0,{error:e instanceof Error?e.message:`读取失败`}),im=e=>encodeURIComponent(e),am=e=>e?`&cwd=${im(e)}`:``,om=(e,t,n)=>`/api/files?workspaceId=${im(e)}&path=${im(t)}${am(n)}`,sm=`//workspace/`,cm=e=>e.startsWith(sm)?e.slice(12):void 0,lm=(e,t,n)=>{let r=cm(t);return`/api/file?workspaceId=${im(e)}&path=${im(r??t)}${am(r?``:n)}`},um=(e,t,n)=>lm(e,t,n)+`&meta=1`,dm=(e,t,n)=>`/api/files?workspaceId=${im(e)}&q=${im(t)}${am(n)}`;async function fm(e,t,n){let r=t.current;if(!r)return t.current=nm(e+`&refresh=1`,{cache:`no-store`}),t.current;if(await r.catch(()=>{}),n())return nm(e,{cache:`no-store`})}function pm(e){let t=e.trim();if(/^(["']).*\1$/u.test(t)&&(t=t.slice(1,-1)),!/^file:\/\//iu.test(t))return t;try{let e=new URL(t);return e.hostname||e.search||e.hash?t:decodeURIComponent(e.pathname).replace(/^\/(?=[a-z]:[\\/])/iu,``)}catch{return t}}function mm(e){return{path:e,name:e.split(/[\\/]/).at(-1)||e,text:null,openLink:!0}}function hm(e){let t=pm(e);if(/^(?:\/|[a-z]:[\\/]|\\\\)/iu.test(t))return mm(t)}function gm(e){return pm(e).replaceAll(`\\`,`/`).replace(/^\.\//u,``)}async function _m(e,t,n){if(n.openLink){let r=await nm(`/api/files/open?workspaceId=${im(e)}${am(t)}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:n.path})}),{path:i,name:a,text:o,ticket:s,content:c,meta:l}=r,u=jf(r.targetName??i),d=o===!1&&u===`table`?`download`:u??(o===!1?`download`:void 0);return{path:i,name:a,content:c??``,etag:l.etag,dirty:!1,view:d,assetTicket:s}}let{path:r,name:i,text:a}=n,o=jf(r);if(a===!1&&!o)throw Error(`此文件可通过文件操作菜单下载。`);if(o&&o!==`table`)return{path:r,name:i,content:``,etag:(await nm(um(e,r,t))).etag,dirty:!1,view:o};try{let n=await nm(lm(e,r,t));return{path:cm(r)?r:n.path,name:i,content:n.content,etag:n.meta.etag,dirty:!1,view:o}}catch(n){if(!(n instanceof $p)||![413,415].includes(n.status))throw n;return{path:r,name:i,content:``,etag:(await nm(um(e,r,t))).etag,dirty:!1,view:`download`}}}var vm=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function ym({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:d,depth:f,linked:p,presentation:m}){let h=r[t],g=i.has(t);(0,u.useEffect)(()=>{g&&h===void 0&&o(t)},[g,t,h,o]);let _=m.inline(t,`entry`,f),v=m.inline(t,`child`,f+1);return(0,F.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-linked":p,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,F.jsxs)(`div`,{className:`file-explorer-row`,"data-file-drop-target":m.dropPath===t?`1`:void 0,hidden:!!_,style:{"--file-depth":f},children:[(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":g,tabIndex:-1,draggable:!p,title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:(0,F.jsx)(yf,{name:g?`down`:`right`})}),(0,F.jsx)(Fr,{category:g?`folder-open`:`folder`}),(0,F.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,F.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),(0,F.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,tabIndex:-1,"aria-haspopup":`menu`,"aria-label":`${n} 的文件操作`,children:(0,F.jsx)(yf,{name:`more`})})]}),_,g&&(0,F.jsxs)(`ul`,{className:`file-children`,children:[v&&(0,F.jsx)(`li`,{children:v}),h===void 0?(0,F.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in h?(0,F.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,title:kr(h.error.message),children:Or(h.error.message,`这个目录读取失败。`)}):h.entries.length===0?(0,F.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,F.jsxs)(F.Fragment,{children:[h.truncated&&(0,F.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),h.entries.map(t=>t.kind===`directory`?(0,F.jsx)(ym,{workspaceId:e,entryPath:t.path,name:t.name,linked:t.symlink,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:d,depth:f+1,presentation:m},t.path):(0,F.jsx)(bm,{entry:t,depth:f+1,openPaths:s,changedPaths:l,onOpen:d,presentation:m},t.path))]})]})]})}function bm({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i,presentation:a}){let o={"--file-depth":t};if(e.kind===`symlink`&&!e.openLink)return(0,F.jsx)(`li`,{className:`file-node file-explorer-row`,"data-file-entry":e.path,"data-file-outside":e.path,style:o,children:(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 的目标目录在当前工作区之外,或目标文件不可用`,tabIndex:-1,children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,F.jsx)(`span`,{className:`file-name`,children:e.name}),(0,F.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let s=n.has(e.path),c=r.has(e.path),l=jf(e.path),u=!!(e.outside&&e.openLink||e.text||l),d=a.currentPath===e.path,f=a.inline(e.path,`entry`,t);return(0,F.jsxs)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-linked":e.symlink,"data-file-outside":e.outside?e.path:void 0,"data-file-row-open":s?`1`:`0`,"data-file-row-changed":c?`1`:`0`,children:[(0,F.jsxs)(`div`,{className:`file-explorer-row`,"data-file-current":d?`1`:void 0,hidden:!!f,style:o,children:[(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,"aria-disabled":!u||void 0,title:u?e.path:`${e.name} 可以通过文件操作菜单下载`,tabIndex:-1,"aria-current":d?`true`:void 0,draggable:!e.symlink,onClick:t=>{u&&i(e.openLink&&!e.outside?{...e,openLink:void 0}:e,t.detail>1)},children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,F.jsx)(Fr,{path:e.path}),(0,F.jsx)(`span`,{className:`file-name`,children:e.name}),s&&(0,F.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),c&&(0,F.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),e.document&&(0,F.jsx)(`span`,{className:`file-badge`,"data-file-document":`1`,"aria-label":`文档文件`,children:`文档`}),e.outside&&(0,F.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`}),!u&&!e.document&&(0,F.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]}),!e.outside&&(0,F.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,"aria-haspopup":`menu`,tabIndex:-1,"aria-label":`${e.name} 的文件操作`,children:(0,F.jsx)(yf,{name:`more`})})]}),f]})}function xm({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c,workspaceId:l,cwd:d=``,navigation:f,embedded:p=!1,onPosition:m,languageOverride:h}){let[g,_]=(0,u.useState)(!0),v=(0,u.useRef)(null),[y,b]=(0,u.useState)({}),[x,S]=(0,u.useState)(null),C=(0,u.useRef)(0),w=!!e.assetTicket,T=!w&&y[e.path]===!0&&!!l,E=l?d?`${l}:${d}`:l:``;(0,u.useEffect)(()=>{let t=++C.current;if(!T||!l){S(null);return}let n=new AbortController,i=bp(E,e.path,e.etag),a=r?void 0:Cp(i);if(a){S({state:a.supported?`ready`:`unsupported`,response:a,path:e.path,workspaceId:E,note:a.supported?null:Dp(a.reason)});return}S({state:`loading`,response:null,path:e.path,workspaceId:E,note:null});let o=cm(e.path);return vp(l,o??e.path,{signal:n.signal,cwd:o?``:d}).then(n=>{t===C.current&&(r||wp(i,n),S({state:n.supported?`ready`:`unsupported`,response:n,path:e.path,workspaceId:E,note:n.supported?null:Dp(n.reason)}))}).catch(n=>{if(t!==C.current||n instanceof gp)return;let r=Op(n);S({state:r.state,response:null,path:e.path,workspaceId:E,note:r.note})}),()=>{n.abort()}},[T,l,d,E,e.path,e.etag,r]);let D=x&&x.path===e.path&&x.workspaceId===E?x:null,O=T?D?.state??`loading`:`off`,k=O===`ready`&&Ip(e.content,D?.response??null,e.dirty||r),A=[];D?.note&&A.push(D.note),O===`ready`&&D?.response?.truncated&&A.push({code:`truncated`,text:`Blame 数据已截断,只显示了前面一部分(共 ${D.response.totalLines} 行)`}),k&&A.push({code:`stale`,text:`内容已改动,Blame 对应的是磁盘上的版本`});let j=O===`loading`?`⌛ Blame`:O===`ready`?`✓ Blame`:O===`off`?`Blame`:`! Blame`;(0,u.useEffect)(()=>{i&&_(!1)},[e.path,i]),(0,u.useEffect)(()=>{let e=v.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
|
|
287
|
+
`)),e.setAttribute(`aria-label`,t.join(` · `)),e.textContent=Mp(this.model),e}}class c extends o{eq(){return!0}toDOM(){let e=document.createElement(`span`);return e.className=`cm-blame-marker cm-blame-spacer`,e.textContent=Bp,e}}let l=t.gutter({class:`cm-blame-gutter`,initialSpacer:()=>new c,lineMarker:(e,t)=>{let n=e.state.field(r);if(!n)return null;let i=e.state.doc.lineAt(t.from).number,a=zp(n,i);return new s(a??{line:i,kind:`missing`,data:null})},lineMarkerChange:e=>e.startState.field(r)!==e.state.field(r)}),u=t.ViewPlugin.fromClass(class{line=null;editorView;constructor(e){this.editorView=e,this.editorView.dom.addEventListener(`mousemove`,this.onMove),this.editorView.dom.addEventListener(`mouseleave`,this.onLeave)}destroy(){this.editorView.dom.removeEventListener(`mousemove`,this.onMove),this.editorView.dom.removeEventListener(`mouseleave`,this.onLeave)}update(e){e.startState.field(r)!==e.state.field(r)&&this.line!==null&&(this.line=null,this.editorView.dispatch({effects:i.of(null)}))}onMove=e=>{let t=this.lineAt(e);if(t===this.line)return;if(this.line=t,t===null){this.editorView.dispatch({effects:i.of(null)});return}let n=zp(this.editorView.state.field(r),t);if(!n){this.editorView.dispatch({effects:i.of(null)});return}let a=this.editorView.state.doc,o=a.line(Math.min(t,a.lines));this.editorView.dispatch({effects:i.of({pos:o.from,above:!0,create:()=>({dom:Hp(n)})})})};onLeave=()=>{this.line=null,this.editorView.dispatch({effects:i.of(null)})};lineAt(e){let t=e.target,n=t?.closest?.(`[data-file-blame-line]`);if(n){let e=Number(n.getAttribute(`data-file-blame-line`));return Number.isInteger(e)&&e>0?e:null}if(t?.closest?.(`.cm-blame-gutter`))return null;let r=this.editorView.posAtCoords({x:e.clientX,y:e.clientY});return r==null?null:this.editorView.state.doc.lineAt(r).number}});return{field:r,setBlame:n,base:[r,a,t.showTooltip.from(a),u],gutter:l}}function Hp(e){let t=document.createElement(`div`);t.className=`cm-blame-tooltip`,t.setAttribute(`data-file-blame-tooltip`,`1`),t.setAttribute(`data-file-blame-kind`,e.kind),e.data?.commit&&t.setAttribute(`data-file-blame-commit`,e.data.commit);for(let n of Np(e)){let e=document.createElement(`div`);e.className=`cm-blame-tooltip-row`,e.textContent=n,t.appendChild(e)}return t}function Up(e,t){let n=(0,u.useRef)(null),r=(0,u.useRef)(void 0);return(0,u.useLayoutEffect)(()=>{let e=r.current;r.current=void 0;let i=n.current;if(!i||!e)return;let a=i.querySelectorAll(t)[e.index];a&&(i.scrollTop+=a.getBoundingClientRect().top-i.getBoundingClientRect().top-e.offset)},[e,t]),{scrollBox:n,capture:()=>{let e=n.current;if(!e)return;let i=e.getBoundingClientRect().top,a;e.querySelectorAll(t).forEach((e,t)=>{let n=e.getBoundingClientRect().top-i;(!a||Math.abs(n)<Math.abs(a.offset))&&(a={index:t,offset:n})}),r.current=a}}}var Wp=`super-pi.diff-layout.v1`,Gp=`super-pi-diff-layout`;function Kp(){try{return localStorage.getItem(Wp)===`split`}catch{return!1}}function qp(e){let t=t=>{(t.key===Wp||t.key===null)&&e()};return window.addEventListener(Gp,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(Gp,e),window.removeEventListener(`storage`,t)}}var Jp;function Yp(){return Jp??Kp()}function Xp(){return[(0,u.useSyncExternalStore)(qp,Yp,()=>!1),e=>{Jp=e;try{localStorage.setItem(Wp,e?`split`:`inline`),Jp=void 0}catch{}window.dispatchEvent(new Event(Gp))}]}var Zp=4e3,Qp=(0,u.lazy)(()=>vn(()=>import(`./CodeMirrorEditor-xxJP_tVy.js`).then(e=>({default:e.CodeMirrorEditor})),__vite__mapDeps([21,1]))),$p=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},em=15e3,tm=e=>new $p(408,{error:`请求超时:${em/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function nm(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),em);try{let r=t?.signal?AbortSignal.any([t.signal,n.signal]):n.signal,i=await Ne(e,{...t,signal:r}),a;try{a=await i.json()}catch{a=void 0}if(!i.ok)throw new $p(i.status,a??{error:`HTTP ${i.status}`});return a}catch(t){throw n.signal.aborted?tm(e):t}finally{clearTimeout(r)}}var rm=e=>e instanceof $p?e:new $p(0,{error:e instanceof Error?e.message:`读取失败`}),im=e=>encodeURIComponent(e),am=e=>e?`&cwd=${im(e)}`:``,om=(e,t,n)=>`/api/files?workspaceId=${im(e)}&path=${im(t)}${am(n)}`,sm=`//workspace/`,cm=e=>e.startsWith(sm)?e.slice(12):void 0,lm=(e,t,n)=>{let r=cm(t);return`/api/file?workspaceId=${im(e)}&path=${im(r??t)}${am(r?``:n)}`},um=(e,t,n)=>lm(e,t,n)+`&meta=1`,dm=(e,t,n)=>`/api/files?workspaceId=${im(e)}&q=${im(t)}${am(n)}`;async function fm(e,t,n){let r=t.current;if(!r)return t.current=nm(e+`&refresh=1`,{cache:`no-store`}),t.current;if(await r.catch(()=>{}),n())return nm(e,{cache:`no-store`})}function pm(e){let t=e.trim();if(/^(["']).*\1$/u.test(t)&&(t=t.slice(1,-1)),!/^file:\/\//iu.test(t))return t;try{let e=new URL(t);return e.hostname||e.search||e.hash?t:decodeURIComponent(e.pathname).replace(/^\/(?=[a-z]:[\\/])/iu,``)}catch{return t}}function mm(e){return{path:e,name:e.split(/[\\/]/).at(-1)||e,text:null,openLink:!0}}function hm(e){let t=pm(e);if(/^(?:\/|[a-z]:[\\/]|\\\\)/iu.test(t))return mm(t)}function gm(e){return pm(e).replaceAll(`\\`,`/`).replace(/^\.\//u,``)}async function _m(e,t,n){if(n.openLink){let r=await nm(`/api/files/open?workspaceId=${im(e)}${am(t)}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:n.path})}),{path:i,name:a,text:o,ticket:s,content:c,meta:l}=r,u=jf(r.targetName??i),d=o===!1&&u===`table`?`download`:u??(o===!1?`download`:void 0);return{path:i,name:a,content:c??``,etag:l.etag,dirty:!1,view:d,assetTicket:s}}let{path:r,name:i,text:a}=n,o=jf(r);if(a===!1&&!o)throw Error(`此文件可通过文件操作菜单下载。`);if(o&&o!==`table`)return{path:r,name:i,content:``,etag:(await nm(um(e,r,t))).etag,dirty:!1,view:o};try{let n=await nm(lm(e,r,t));return{path:cm(r)?r:n.path,name:i,content:n.content,etag:n.meta.etag,dirty:!1,view:o}}catch(n){if(!(n instanceof $p)||![413,415].includes(n.status))throw n;return{path:r,name:i,content:``,etag:(await nm(um(e,r,t))).etag,dirty:!1,view:`download`}}}var vm=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function ym({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:d,depth:f,linked:p,presentation:m}){let h=r[t],g=i.has(t);(0,u.useEffect)(()=>{g&&h===void 0&&o(t)},[g,t,h,o]);let _=m.inline(t,`entry`,f),v=m.inline(t,`child`,f+1);return(0,F.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-linked":p,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,F.jsxs)(`div`,{className:`file-explorer-row`,"data-file-drop-target":m.dropPath===t?`1`:void 0,hidden:!!_,style:{"--file-depth":f},children:[(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":g,tabIndex:-1,draggable:!p,title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:(0,F.jsx)(yf,{name:g?`down`:`right`})}),(0,F.jsx)(Fr,{category:g?`folder-open`:`folder`}),(0,F.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,F.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),(0,F.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,tabIndex:-1,"aria-haspopup":`menu`,"aria-label":`${n} 的文件操作`,children:(0,F.jsx)(yf,{name:`more`})})]}),_,g&&(0,F.jsxs)(`ul`,{className:`file-children`,children:[v&&(0,F.jsx)(`li`,{children:v}),h===void 0?(0,F.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in h?(0,F.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,title:kr(h.error.message),children:Or(h.error.message,`这个目录读取失败。`)}):h.entries.length===0?(0,F.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,F.jsxs)(F.Fragment,{children:[h.truncated&&(0,F.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),h.entries.map(t=>t.kind===`directory`?(0,F.jsx)(ym,{workspaceId:e,entryPath:t.path,name:t.name,linked:t.symlink,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:d,depth:f+1,presentation:m},t.path):(0,F.jsx)(bm,{entry:t,depth:f+1,openPaths:s,changedPaths:l,onOpen:d,presentation:m},t.path))]})]})]})}function bm({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i,presentation:a}){let o={"--file-depth":t};if(e.kind===`symlink`&&!e.openLink)return(0,F.jsx)(`li`,{className:`file-node file-explorer-row`,"data-file-entry":e.path,"data-file-outside":e.path,style:o,children:(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 的目标目录在当前工作区之外,或目标文件不可用`,tabIndex:-1,children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,F.jsx)(`span`,{className:`file-name`,children:e.name}),(0,F.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let s=n.has(e.path),c=r.has(e.path),l=jf(e.path),u=!!(e.outside&&e.openLink||e.text||l),d=a.currentPath===e.path,f=a.inline(e.path,`entry`,t);return(0,F.jsxs)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-linked":e.symlink,"data-file-outside":e.outside?e.path:void 0,"data-file-row-open":s?`1`:`0`,"data-file-row-changed":c?`1`:`0`,children:[(0,F.jsxs)(`div`,{className:`file-explorer-row`,"data-file-current":d?`1`:void 0,hidden:!!f,style:o,children:[(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,"aria-disabled":!u||void 0,title:u?e.path:`${e.name} 可以通过文件操作菜单下载`,tabIndex:-1,"aria-current":d?`true`:void 0,draggable:!e.symlink,onClick:t=>{u&&i(e.openLink&&!e.outside?{...e,openLink:void 0}:e,t.detail>1)},children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,F.jsx)(Fr,{path:e.path}),(0,F.jsx)(`span`,{className:`file-name`,children:e.name}),s&&(0,F.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),c&&(0,F.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),e.document&&(0,F.jsx)(`span`,{className:`file-badge`,"data-file-document":`1`,"aria-label":`文档文件`,children:`文档`}),e.outside&&(0,F.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`}),!u&&!e.document&&(0,F.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]}),!e.outside&&(0,F.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,"aria-haspopup":`menu`,tabIndex:-1,"aria-label":`${e.name} 的文件操作`,children:(0,F.jsx)(yf,{name:`more`})})]}),f]})}function xm({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c,workspaceId:l,cwd:d=``,navigation:f,embedded:p=!1,onPosition:m,languageOverride:h}){let[g,_]=(0,u.useState)(!0),v=(0,u.useRef)(null),[y,b]=(0,u.useState)({}),[x,S]=(0,u.useState)(null),C=(0,u.useRef)(0),w=!!e.assetTicket,T=!w&&y[e.path]===!0&&!!l,E=l?d?`${l}:${d}`:l:``;(0,u.useEffect)(()=>{let t=++C.current;if(!T||!l){S(null);return}let n=new AbortController,i=bp(E,e.path,e.etag),a=r?void 0:Cp(i);if(a){S({state:a.supported?`ready`:`unsupported`,response:a,path:e.path,workspaceId:E,note:a.supported?null:Dp(a.reason)});return}S({state:`loading`,response:null,path:e.path,workspaceId:E,note:null});let o=cm(e.path);return vp(l,o??e.path,{signal:n.signal,cwd:o?``:d}).then(n=>{t===C.current&&(r||wp(i,n),S({state:n.supported?`ready`:`unsupported`,response:n,path:e.path,workspaceId:E,note:n.supported?null:Dp(n.reason)}))}).catch(n=>{if(t!==C.current||n instanceof gp)return;let r=Op(n);S({state:r.state,response:null,path:e.path,workspaceId:E,note:r.note})}),()=>{n.abort()}},[T,l,d,E,e.path,e.etag,r]);let D=x&&x.path===e.path&&x.workspaceId===E?x:null,O=T?D?.state??`loading`:`off`,k=O===`ready`&&Ip(e.content,D?.response??null,e.dirty||r),A=[];D?.note&&A.push(D.note),O===`ready`&&D?.response?.truncated&&A.push({code:`truncated`,text:`Blame 数据已截断,只显示了前面一部分(共 ${D.response.totalLines} 行)`}),k&&A.push({code:`stale`,text:`内容已改动,Blame 对应的是磁盘上的版本`});let j=O===`loading`?`⌛ Blame`:O===`ready`?`✓ Blame`:O===`off`?`Blame`:`! Blame`;(0,u.useEffect)(()=>{i&&_(!1)},[e.path,i]),(0,u.useEffect)(()=>{let e=v.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
|
|
288
288
|
`).length),n=e.value.split(`
|
|
289
289
|
`),r=n.slice(0,t-1).reduce((e,t)=>e+t.length+1,0),a=n[t-1].length;e.focus(),e.setSelectionRange(r+Math.min(a,(i.column??1)-1),r+a);let o=parseFloat(getComputedStyle(e).lineHeight);e.scrollTop=Math.max(0,(t-1)*o-e.clientHeight/2),e.scrollLeft=0;let s=e.previousElementSibling;s instanceof HTMLElement&&(s.scrollTop=e.scrollTop,s.scrollLeft=0)},[e.path,i,g]);let ee=/\.md$/i.test(e.path);return(0,F.jsxs)(`div`,{className:`file-editor`,"data-file-editor":e.path,"data-save-state":t,"data-file-readonly":w?`1`:void 0,children:[(0,F.jsxs)(`div`,{className:`file-editor-head`,children:[f??(!p&&(0,F.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path})),(0,F.jsxs)(`span`,{className:`file-editor-flags`,children:[ee&&(0,F.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:()=>_(e=>!e),children:g?`原文`:`预览`}),e.assetTicket&&l&&!p&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`span`,{children:`外部文件 · 只读`}),(0,F.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:s,children:`重新读取`}),(0,F.jsx)(`a`,{className:`file-preview-toggle`,href:Tf(`asset`,l,d,e.assetTicket,{download:`1`}),download:e.name,children:`下载`})]}),!w&&(0,F.jsx)(`button`,{type:`button`,className:`file-blame-toggle`,"data-file-blame-toggle":e.path,"data-file-blame-state":O,"aria-pressed":T,"aria-label":T?`关闭 Git Blame`:`显示 Git Blame`,onClick:()=>b(t=>({...t,[e.path]:t[e.path]!==!0})),children:j}),e.dirty&&(0,F.jsx)(`span`,{className:`file-dirty`,"data-file-dirty":`1`,children:`未保存`}),!w&&(0,F.jsxs)(`button`,{type:`button`,className:`file-save`,"data-file-save":e.path,onClick:o,title:`保存文件 (Ctrl+S)`,disabled:t===`saving`,children:[(0,F.jsx)(yf,{name:`save`}),t===`saving`?`保存中…`:`保存`]})]})]}),A.length>0&&(0,F.jsx)(`p`,{className:`file-blame-note`,"data-file-blame-reason":A.map(e=>e.code).join(` `),role:`status`,children:A.map(e=>e.text).join(`;`)}),r&&t!==`conflict`&&(0,F.jsxs)(`div`,{className:`file-conflict`,"data-file-external":e.path,role:`alert`,children:[(0,F.jsx)(`p`,{children:`这个文件在磁盘上已经被改过了,你的修改还没有覆盖它。`}),(0,F.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,F.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,F.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),t===`conflict`&&(0,F.jsxs)(`div`,{className:`file-conflict`,"data-file-conflict":e.path,role:`alert`,children:[(0,F.jsx)(`p`,{children:`保存被拒绝:这个文件在磁盘上已经被改过了,覆盖会丢掉对方的改动。`}),(0,F.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,F.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,F.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),n&&t!==`conflict`&&!r&&(0,F.jsx)(`p`,{className:`file-editor-message file-message-${t}`,"data-file-message":t,role:`status`,children:n}),ee&&g?(0,F.jsx)(`div`,{className:`file-markdown-preview`,"data-file-preview":`markdown`,children:(0,F.jsx)(ef,{source:e.content})}):(0,F.jsx)(Uf,{fallback:(t,n)=>(0,F.jsxs)(`div`,{className:`file-editor-fallback`,"data-file-editor-fallback":`1`,children:[(0,F.jsxs)(`div`,{className:`file-editor-fallback-bar`,children:[(0,F.jsxs)(`span`,{children:[`⚠️ 高级编辑器加载异常(`,t.message||`未知错误`,`),已自动降级为安全模式`]}),(0,F.jsx)(`button`,{type:`button`,onClick:n,children:`重新加载`})]}),(0,F.jsx)(`textarea`,{className:`file-textarea`,readOnly:w,value:e.content,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),o())}})]}),children:(0,F.jsx)(u.Suspense,{fallback:(0,F.jsx)(`div`,{className:`file-cm-wrap`,"data-file-text":e.path,"data-file-content":e.content,"data-file-selection":`0,0`,"data-file-editor-ready":`0`,children:(0,F.jsx)(`span`,{className:`file-cm-status`,"data-file-editor-loading":`1`,children:`⌛ 正在加载编辑器…`})}),children:(0,F.jsx)(Qp,{path:e.path,languageOverride:h,value:e.content,onChange:a,jumpToLine:i,onSave:o,readOnly:w,workspaceId:l,onPosition:m,blame:T&&D&&!k?{state:D.state,response:D.response,path:D.path,workspaceId:l??``}:void 0})})})]})}function Sm({line:e}){if(e.kind===`fold`)return(0,F.jsx)(`div`,{className:`file-diff-line file-diff-fold`,"data-diff-kind":`fold`,children:e.text});let t=e.kind===`added`?`+`:e.kind===`removed`?`-`:` `;return(0,F.jsxs)(`div`,{className:`file-diff-line file-diff-${e.kind}`,"data-diff-kind":e.kind,"data-diff-no-newline":e.noNewline?`1`:void 0,children:[(0,F.jsx)(`span`,{className:`file-diff-mark`,"aria-hidden":`true`,children:t}),(0,F.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.oldLine??``}),(0,F.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.newLine??``}),(0,F.jsx)(`span`,{className:`file-diff-text`,children:e.text}),e.noNewline&&(0,F.jsx)(`span`,{className:`file-diff-no-newline`,title:`这个版本的末尾没有换行`,children:`(末尾无换行)`})]})}function Cm(e){let t=[];for(let n=0;n<e.length;){let r=e[n];if(r.kind===`same`||r.kind===`fold`){t.push({before:r,after:r}),n++;continue}let i=[],a=[];for(;n<e.length&&[`removed`,`added`].includes(e[n].kind);){let t=e[n++];(t.kind===`removed`?i:a).push(t)}for(let e=0;e<Math.max(i.length,a.length);e++)t.push({before:i[e],after:a[e]})}return t}function wm({diff:e,loading:t,error:n,bufferContent:r,mode:i,onMode:a}){let[o,s]=(0,u.useState)(),[c,l]=Xp(),d=JSON.stringify([e?.path,i]),f=o===d,{scrollBox:p,capture:m}=Up(f,`.file-diff-added, .file-diff-removed`);if(t)return(0,F.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`loading`,children:(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-diff-loading":`1`,children:`正在读取差异…`})});if(n)return(0,F.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`error`,children:(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-diff-error":`1`,title:kr(n),children:Or(n,`这个文件的差异读取失败。`)})});if(!e)return(0,F.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`empty`,children:(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-diff-empty":`1`,children:`没有选中的差异。`})});let h=typeof r==`string`,g=i===`buffer`&&h,_=g?e.after:e.before,v=g?r:e.after,y=g?`我未保存的修改`:e.label,b=g?`buffer`:e.baseline,x=h&&e.baseline!==`none`?(0,F.jsxs)(`span`,{className:`file-diff-switch`,"data-file-diff-switch":`1`,children:[(0,F.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${g?``:` file-diff-switch-active`}`,"data-file-diff-base":`server`,"aria-pressed":!g,onClick:()=>a(`server`),children:`agent 的改动`}),(0,F.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${g?` file-diff-switch-active`:``}`,"data-file-diff-base":`buffer`,"aria-pressed":g,onClick:()=>a(`buffer`),children:`我的修改`})]}):null;if(b===`none`)return(0,F.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`none`,"data-file-diff-baseline":b,children:[(0,F.jsxs)(`div`,{className:`file-editor-head`,children:[(0,F.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,F.jsx)(`span`,{className:`file-editor-flags`,children:x})]}),(0,F.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-nobaseline":`1`,children:y})]});let S=ip(_,v),C=ap(S),w=f?S.lines:C.lines,T=c?Cm(w):[];return(0,F.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`ready`,"data-file-diff-baseline":b,"data-file-diff-added":S.added,"data-file-diff-removed":S.removed,"data-file-diff-layout":c?`split`:`inline`,children:[(0,F.jsxs)(`div`,{className:`file-editor-head`,children:[(0,F.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,F.jsxs)(`span`,{className:`file-editor-flags`,children:[x,(0,F.jsx)(`span`,{className:`file-diff-baseline`,"data-file-diff-label":`1`,children:y}),(0,F.jsxs)(`span`,{className:`file-diff-count`,"data-file-diff-count":`1`,children:[`+`,S.added,` / -`,S.removed]}),(0,F.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,"data-file-diff-layout-button":!0,onClick:()=>l(!c),title:c?`切换为全局内联视图`:`切换为全局分栏视图`,children:c?`内联`:`分栏`}),!S.identical&&C.folded>0&&(0,F.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,"data-file-diff-context":!0,"aria-pressed":f,onClick:()=>{m(),s(f?void 0:d)},children:f?`折叠未改动行`:`显示全文`})]})]}),e.beforeUnknown&&!g&&(0,F.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-before-unknown":`1`,role:`status`,children:`读不到改动前的版本(文件太大或无法读取),这里只显示现在的内容。`}),e.before===null&&!e.beforeUnknown&&!g&&(0,F.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-is-new":`1`,role:`status`,children:`这个文件是新建的,下面是它的全部内容。`}),S.identical?(0,F.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-identical":`1`,children:`两个版本没有区别。`}):(0,F.jsx)(`div`,{ref:p,className:`file-diff-body`,"data-file-diff-body":`1`,"data-file-diff-context-mode":f?`full`:`compact`,children:c?(0,F.jsx)(`div`,{className:`file-diff-split-grid`,children:[`before`,`after`].map(e=>(0,F.jsx)(`div`,{"data-diff-side":e,"aria-label":e===`before`?`修改前`:`修改后`,children:T.map((t,n)=>t[e]?(0,F.jsx)(Sm,{line:t[e]},n):(0,F.jsx)(`div`,{className:`file-diff-line`,"aria-hidden":`true`,children:`\xA0`},n))},e))}):w.map((e,t)=>(0,F.jsx)(Sm,{line:e},t))})]})}function Tm({error:e}){let t=e.body.code,n=typeof e.body.details?.path==`string`?e.body.details.path:``,r=t===`workspace_missing`?`missing`:t===`timeout`?`timeout`:`failed`;return(0,F.jsxs)(`div`,{className:`rail-empty file-problem`,"data-file-root-error":`1`,"data-file-error-kind":r,role:`alert`,children:[r===`missing`&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`工作区路径不存在,无法读取文件。`}),(0,F.jsx)(`p`,{className:`file-problem-hint`,children:`请确认这个路径是写错了,还是目录被移动或删除了:`}),(0,F.jsx)(`code`,{className:`file-problem-path`,"data-file-error-path":`1`,children:n||Or(e.message,`路径未知`)})]}),r===`timeout`&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取超时,服务端没有回应。`}),(0,F.jsxs)(`p`,{className:`file-problem-hint`,children:[`已经等了 `,em/1e3,` 秒。如果这个工作区在网络盘上,请检查它是否已连接,然后点上面的 ↻ 重试。`]})]}),r===`failed`&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取失败。`}),(0,F.jsx)(`p`,{className:`file-problem-hint`,title:kr(e.message),children:Or(e.message,`读取失败,请稍后重试。`)})]})]})}function Em(e,t=``,{navigation:n,showingFile:r=!1,splitFilePath:i}={}){let a=t.trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``),o=e?a?`${e}:${a}`:e:void 0,s=(0,u.useRef)(o);s.current=o;let[c,l]=(0,u.useState)([]),[d,f]=(0,u.useState)(e),p=(0,u.useRef)(c);p.current=c;let[m,h]=(0,u.useState)(),[g,_]=(0,u.useState)(``),[v,y]=(0,u.useState)({}),[b,x]=(0,u.useState)({}),[S,C]=(0,u.useState)({}),[w,T]=(0,u.useState)(()=>new Set),[E,D]=(0,u.useState)(),O=(0,u.useRef)(w);O.current=w;let k=(0,u.useRef)(new Map),A=(0,u.useRef)(new Map),[j,ee]=(0,u.useState)(0),[M,te]=(0,u.useState)(``),[N,ne]=(0,u.useState)(null),[re,ie]=(0,u.useState)(null),[ae,oe]=(0,u.useState)(!1),[se,ce]=(0,u.useState)({});(0,u.useEffect)(()=>{if(f(e),k.current=new Map,l([]),h(void 0),_(``),y({}),x({}),C({}),T(new Set),D(void 0),ne(null),ie(null),te(``),oe(!1),!e)return;let t=!0;return nm(om(e,``,a)).then(e=>{t&&C({"":e})}).catch(e=>{t&&C({"":{error:rm(e)}})}),()=>{if(t=!1,o&&s.current!==o){let e=p.current.filter(e=>e.dirty);e.length?A.current.set(o,e):A.current.delete(o),mp(`super-pi.file-drafts.v1.`+o,e),Am(o)}}},[e,a,o]);let[le,ue]=(0,u.useState)(),[de,fe]=(0,u.useState)(void 0);(0,u.useEffect)(()=>{if(!e||!o)return;let t=!0;fe(void 0),ue(void 0);let r=Om()[o]??{expanded:[],open:[]},i=e=>({path:e,name:e.split(/[\\/]/).at(-1)||e,text:!0,openLink:r.explicit?.includes(e)?!0:void 0}),a=pp(`super-pi.file-drafts.v1.`+o,[]),c=new Map((A.current.get(o)??a).map(e=>[e.path,e]));r.expanded.length&&T(new Set(r.expanded)),typeof r.listHeight==`number`&&ne(r.listHeight);let u=new Set([...r.open,...c.keys()]);if(!u.size){ue(o);return}let d=r.active??[...c.keys()].at(-1),f=n?.current,p=()=>t&&n?.current===f;return(async()=>{let e,n=r.preview&&!c.has(r.preview)?r.preview:void 0;for(let r of u){if(r===n)continue;let a=c.get(r);a&&l(e=>e.some(e=>e.path===r)?e:[...e,a]);let u=a?.path??await we(i(r),{activate:!1,isCurrent:()=>t});if(!t||s.current!==o)return;r===d&&(e=u)}if(n&&p()&&(e=await we(i(n),{activate:!1,isCurrent:p})),e&&s.current===o&&p()){let t=e;r.preview===r.active&&l(e=>e.map(e=>e.path===t&&!e.dirty?{...e,preview:!0}:e)),h(t),fe(t)}})().finally(()=>{t&&s.current===o&&ue(o)}),()=>{t=!1}},[e,a,o,n]),(0,u.useEffect)(()=>{if(!e||!o)return;let t=setTimeout(()=>{let e=Om();e[o]={open:c.map(e=>e.path),explicit:c.filter(e=>e.assetTicket).map(e=>e.path),expanded:[...w],...r&&m?{active:m}:{},...r&&m&&c.some(e=>e.path===m&&e.preview)?{preview:m}:{},...N===null?{}:{listHeight:N}},km(e)},400);return()=>{clearTimeout(t)}},[e,o,c,w,m,N,r]),(0,u.useEffect)(()=>{if(!o||le!==o)return;let e=()=>{if(s.current!==o)return;let e=p.current.filter(e=>e.dirty);return mp(`super-pi.file-drafts.v1.`+o,e)||e.length===0},t=window.setTimeout(()=>{e()===!1&&_(`浏览器无法保存文件草稿,刷新前请先保存修改。`)},250);return window.addEventListener(`pagehide`,e),()=>{window.clearTimeout(t),window.removeEventListener(`pagehide`,e)}},[o,le,c]);let pe=(0,u.useCallback)(async(t,n=!1)=>{if(!e)return;let r={},i=k.current;i.set(t,r);let c=()=>s.current===o&&k.current===i&&i.get(t)===r;await nm(om(e,t,a)+(n?`&revalidate=1`:``)).then(e=>{c()&&C(n=>({...n,[t]:e}))}).catch(e=>{c()&&C(n=>({...n,[t]:{error:rm(e)}}))}).finally(()=>{c()&&i.delete(t)})},[e,a,o]),me=(0,u.useCallback)(e=>{T(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),he=(0,u.useCallback)(t=>{if(!e)return;let n=new Set([``,...O.current]),r=t&&new Set(t.map(Mf)),i=e=>!r||r.has(e)||t.some(t=>Nf(e,t));C(e=>Object.fromEntries(Object.entries(e).filter(([e])=>n.has(e)||!i(e))));for(let e of k.current.keys())!n.has(e)&&i(e)&&k.current.delete(e);Promise.all([...n].filter(i).map(e=>pe(e,!t&&!e))).then(()=>{s.current===o&&ee(e=>e+1)})},[e,o,pe]),ge=(0,u.useCallback)(()=>he(),[he]),P=(0,u.useRef)(void 0),_e=(0,u.useRef)(new Set);(0,u.useEffect)(()=>()=>{clearTimeout(P.current),P.current=void 0,_e.current=new Set},[o]);let ve=(0,u.useCallback)((t,n)=>{if(t!==e)return;let r=a?`${a}/`:``,i=n?.flatMap(e=>e.startsWith(r)?[e.slice(r.length)]:[]);if(i?.length===0){if(!n?.some(e=>Nf(a,e)))return;_e.current=null}else if(!i)_e.current=null;else for(let e of i)_e.current?.add(e);P.current||=setTimeout(()=>{P.current=void 0;let e=_e.current;_e.current=new Set,he(e?[...e]:void 0)},100)},[e,a,he]),ye=(0,u.useCallback)(e=>{let t=new Set;for(let n=Mf(e);n;n=Mf(n))t.add(n);te(``),T(e=>new Set([...e,...t]))},[]),be=(0,u.useCallback)((e,t)=>{ye(t&&e?`${e}/`:e),D({path:e,directory:t})},[ye]),xe=(0,u.useCallback)(()=>T(new Set),[]),Se=(0,u.useCallback)((e,t,n)=>{let r=n=>Nf(n,e)?t+n.slice(e.length):n,i=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[r(e),t]));l(t=>t.map(t=>{let i=r(t.path);if(i===t.path)return t;let a=jf(i),o=t.view&&t.view!==`table`&&(!a||a===`table`)||t.path===e&&n===!1&&!a?`download`:a;return{...t,path:i,view:o,name:i.split(`/`).at(-1)??t.name}})),h(e=>e&&r(e)),T(e=>new Set([...e].map(r))),y(i),x(i);for(let t of k.current.keys())Nf(t,e)&&k.current.delete(t);C(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!Nf(t,e)))),ye(t)},[ye]),Ce=(0,u.useRef)(void 0);(0,u.useEffect)(()=>{Ce.current=void 0},[e,a]),(0,u.useEffect)(()=>{let t=gm(M);if(!e||!t||hm(M)){Ce.current=void 0,ie(null),oe(!1);return}let n=!0,r,i=async()=>{try{let o=await fm(dm(e,t,a),Ce,()=>n);if(!n||!o)return;ie(o),oe(!1),o.indexed||(r=setTimeout(()=>void i(),400))}catch(e){if(!n)return;ie(null),oe(!1),_(Or(e,`文件查找没有完成`))}};return oe(!0),r=setTimeout(()=>void i(),80),()=>{n=!1,clearTimeout(r)}},[M,e,a,j]);let we=(0,u.useCallback)(async(t,{preview:n=!1,activate:r=!0,isCurrent:i,throwOnError:c,requireText:u}={})=>{if(!(!e||i&&!i())){_(``);try{let c=p.current.find(e=>e.path===t.path),d=c??await _m(e,a,t);if(s.current!==o||i&&!i())return;if(u&&d.view&&d.view!==`table`)throw Error(`已找到匹配行,但此文件无法在文本编辑器中定位。可以在搜索结果中查看这一行。`);return c?(r&&h(t.path),t.path):(l(e=>e.some(e=>e.path===d.path)?e:[...e,{...d,...n?{preview:n}:{}}]),r&&h(d.path),x(e=>({...e,[d.path]:!1})),d.path)}catch(e){if(s.current!==o||i&&!i())return;if(c)throw e;_(`打不开「${t.name}」:${e instanceof Error?e.message:`未知错误`}`)}}},[e,a,o]),Te=(0,u.useCallback)(e=>{o&&p.current.some(t=>t.path===e&&t.preview&&!t.dirty)&&Am(o,e),l(t=>{let n=t.find(t=>t.path===e);if(n?.dirty&&!window.confirm(`「${n.name}」有未保存的修改,关掉就丢了。仍然关闭?`))return t;let r=t.findIndex(t=>t.path===e),i=t.filter(t=>t.path!==e);return e===m&&h(i.length===0?void 0:i[Math.min(r,i.length-1)]?.path),i})},[m,o]),Ee=(0,u.useCallback)(e=>{l(t=>t.map(t=>t.path===e&&t.preview?{...t,preview:!1}:t))},[]),De=(0,u.useCallback)(e=>{l(t=>t.filter(t=>t.path!==e||!t.preview||t.dirty)),h(t=>t===e?void 0:t),o&&Am(o,e)},[o]),Oe=(0,u.useCallback)((e,t)=>{l(n=>n.map(n=>n.path===e&&!n.assetTicket&&n.content!==t?{...n,content:t,dirty:!0,preview:!1}:n))},[]);(0,u.useEffect)(()=>{if(!e||c.length===0)return;let t=!0,n=setInterval(()=>{for(let{path:n,assetTicket:r}of p.current)r||nm(um(e,n,a)).then(e=>{if(!t)return;let r=p.current.find(e=>e.path===n);r?.view&&r.view!==`table`&&e.etag!==r.etag?l(t=>t.map(t=>t.path===n&&t.etag===r.etag?{...t,etag:e.etag}:t)):r&&e.etag!==r.etag&&x(e=>({...e,[n]:!0}))}).catch(e=>{t&&rm(e).status===404&&x(e=>({...e,[n]:!0}))})},Zp);return()=>{t=!1,clearInterval(n)}},[e,a,c.length]);let ke=(0,u.useCallback)(async(t,n)=>{if(!e)return;let r=c.find(e=>e.path===t);if(!r||r.assetTicket)return;y(e=>({...e,[t]:{state:`saving`,message:``}}));let i=r.etag;if(n)try{i=(await nm(um(e,t,a))).etag}catch(e){s.current===o&&y(n=>({...n,[t]:{state:`error`,message:`无法读取磁盘上的最新版本:${e instanceof Error?e.message:`未知错误`}`}}));return}let u=r.content;try{let n=await nm(lm(e,t,a),{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({path:cm(t)??t,content:u,baseEtag:i})});if(s.current!==o)return;let r=p.current.find(e=>e.path===t),c=r!==void 0&&r.content!==u;l(e=>e.map(e=>e.path===t?{...e,etag:n.meta.etag,dirty:e.content!==u}:e)),x(e=>({...e,[t]:!1})),y(e=>({...e,[t]:{state:`saved`,message:c?`已保存,但你又改了;最新修改仍未保存`:`已保存 ${vm(n.meta.modifiedAt)}`}}))}catch(e){if(s.current!==o)return;let n=e instanceof $p&&e.body.code===`stale`;y(r=>({...r,[t]:{state:n?`conflict`:`error`,message:e instanceof Error?e.message:`保存失败`}})),n&&x(e=>({...e,[t]:!0}))}},[e,a,o,c]),Ae=(0,u.useCallback)(async t=>{if(!e)return;let n=p.current.find(e=>e.path===t),r=n?.content;try{if(n?.assetTicket){let r=await _m(e,a,{path:t,name:n.name,text:null,openLink:!0});if(!r.assetTicket||r.path!==t)throw Error(`链接目标已变化,请关闭后重新打开。`);s.current===o&&(l(e=>e.map(e=>e.path===t?{...r,preview:e.preview}:e)),y(e=>({...e,[t]:{state:`idle`,message:``}})));return}let i=await nm(lm(e,t,a));if(s.current!==o)return;let c=p.current.find(e=>e.path===t),u=c!==void 0&&c.content!==r;l(e=>e.map(e=>e.path===t?{...e,content:u?e.content:i.content,etag:i.meta.etag,dirty:u}:e)),x(e=>({...e,[t]:!1})),y(e=>({...e,[t]:{state:`saved`,message:u?`已读取磁盘版本;你后来输入的修改仍未保存`:`已重新载入磁盘版本`}}))}catch(e){s.current===o&&y(n=>({...n,[t]:{state:`error`,message:e instanceof Error?e.message:`重新载入失败`}}))}},[e,a,o]),je=c.find(e=>e.path===m),Me=(0,u.useMemo)(()=>c.map(e=>({id:e.path,label:e.name,title:cm(e.path)??e.path,closable:!0,badge:e.dirty?(0,F.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[c]),Ne=(0,u.useMemo)(()=>new Set(c.map(e=>e.path)),[c]),Pe=(0,u.useCallback)((e,t,n)=>{ce(r=>({...r,[e]:{changes:t,dropped:n}}))},[]),Fe=e?se[e]:void 0,Ie=(0,u.useMemo)(()=>{let e=Fe?.changes??[];if(!a)return e;let t=`${a}/`;return e.flatMap(e=>e.path.startsWith(t)?[{...e,path:e.path.slice(t.length)}]:[])},[Fe,a]),Le=Fe?.dropped??0,Re=(0,u.useMemo)(()=>new Set(Ie.map(e=>e.path)),[Ie]),ze=(0,u.useMemo)(()=>{let e=new Set;for(let t of Ie){let n=t.path.split(`/`);for(let t=1;t<n.length;t++)e.add(n.slice(0,t).join(`/`))}return e},[Ie]);return{ownerWorkspaceId:d,open:c,activePath:m,visiblePath:r?m:i,location:E,active:je,tabItems:Me,openPaths:Ne,notice:g,setNotice:_,saves:v,external:b,restoringWorkbench:!!(o&&le!==o),openFile:we,setActivePath:h,closeFile:Te,pinFile:Ee,discardPreview:De,updateBuffer:Oe,save:ke,reload:Ae,listings:S,expanded:w,toggleDirectory:me,loadDirectory:pe,refreshTree:ge,invalidateTree:ve,revealPath:ye,locatePath:be,collapseDirectories:xe,movePath:Se,listHeight:N,setListHeight:ne,query:M,setQuery:te,hits:re,searching:ae,changed:Ie,changedPaths:Re,changedDirs:ze,changedDropped:Le,setChangedFor:Pe,restoredActive:de}}var Dm=`super-pi.file-workbench.v1`;function Om(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.file-workbench.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!=`object`)continue;let e=r,i=Array.isArray(e.open)?e.open.filter(e=>typeof e==`string`):[],a=typeof e.preview==`string`?e.preview:void 0;a&&a!==e.active&&(i=i.filter(e=>e!==a));let o=Array.isArray(e.expanded)?e.expanded.filter(e=>typeof e==`string`):[],s=typeof e.listHeight==`number`&&Number.isFinite(e.listHeight)&&e.listHeight>0?Math.round(e.listHeight):void 0,c=Array.isArray(e.explicit)?e.explicit.filter(e=>typeof e==`string`):[];t[n]={open:i,expanded:o,explicit:c,...typeof e.active==`string`?{active:e.active}:{},...a&&a===e.active?{preview:a}:{},...s?{listHeight:s}:{}}}return t}catch{return{}}}function km(e){try{typeof window<`u`&&window.localStorage.setItem(Dm,JSON.stringify(e))}catch{}}function Am(e,t){let n=Om(),r=n[e];!r?.preview||t&&r.preview!==t||(n[e]={...r,open:r.open.filter(e=>e!==r.preview),active:void 0,preview:void 0},km(n))}function jm({height:e,onHeight:t,panelRef:n,min:r=120}){let[i,a]=(0,u.useState)(!1),o=()=>{let e=n.current?.querySelector(`.files-tree`)??null;return{list:e,height:e?.getBoundingClientRect().height??0}},s=e=>{e.preventDefault(),e.currentTarget.focus();let n=e.clientY,{height:i}=o();a(!0);let s=document.body,c=s.style.cursor,l=s.style.userSelect;s.style.cursor=`row-resize`,s.style.userSelect=`none`;let u=e=>{let a=Math.round(i+(e.clientY-n));t(Math.max(r,a))},d=()=>{s.style.cursor=c,s.style.userSelect=l,a(!1),window.removeEventListener(`mousemove`,u),window.removeEventListener(`mouseup`,d)};window.addEventListener(`mousemove`,u),window.addEventListener(`mouseup`,d)},c=e=>e.shiftKey?96:24;return(0,F.jsx)(`div`,{className:`files-splitter${i?` files-splitter-dragging`:``}`,"data-file-splitter":`1`,"data-file-splitter-dragging":i?`true`:`false`,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整文件列表高度`,"aria-valuenow":e??void 0,"aria-valuemin":r,tabIndex:0,onMouseDown:s,onKeyDown:e=>{let i=c(e);if(e.key===`ArrowDown`){e.preventDefault();let{height:n}=o();t(Math.max(r,Math.round(n)+i))}else if(e.key===`ArrowUp`){e.preventDefault();let{height:n}=o(),a=Math.round(n)-i;t(a<=r?null:a)}else if(e.key===`Home`)e.preventDefault(),t(null);else if(e.key===`End`){e.preventDefault();let i=n.current?.querySelector(`.files-tree`)?.parentElement?.clientHeight??0;t(Math.max(r,i))}}})}var Mm=()=>null,Nm=`application/x-super-pi-workspace-file`;function Pm({workspaceId:e,workspaceName:t,cwd:n=``,files:r,onOpenFile:i,onOpenChanged:a,onReference:o,onMoved:s,onSearchFolder:c}){let{open:l,openPaths:d,notice:f,setNotice:p,openFile:m,listings:h,expanded:g,toggleDirectory:_,loadDirectory:v,refreshTree:y,listHeight:b,setListHeight:x,query:S,setQuery:C,hits:w,searching:T,changed:E,changedPaths:D,changedDirs:O,changedDropped:k}=r,A=(0,u.useCallback)((e,t)=>{i?i(e,t):m(e)},[i,m]),j=n.split(`/`).at(-1)||t||`工作目录`,ee=zf({workspaceId:e,cwd:n,scopeName:j,files:r,onOpen:A,onReference:o,onMoved:s,onSearchFolder:c}),[M,te]=(0,u.useState)(),N=(0,u.useRef)(void 0),[ne,re]=(0,u.useState)(!1),ie=ee.editing?ee.inline:Mm,ae=(0,u.useMemo)(()=>({currentPath:r.visiblePath,dropPath:M,inline:ie}),[r.visiblePath,M,ie]);(0,u.useEffect)(()=>{y();function e(){y()}return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[y]),(0,u.useEffect)(()=>{te(void 0),N.current=void 0,re(!1)},[e,n]);let oe=h[``],se=S.trim(),ce=e?hm(S):void 0,le=(0,u.useRef)(null),ue=(0,u.useRef)(null),de=(0,u.useRef)(void 0);function fe(e){let t=ue.current;t&&(de.current&&de.current!==e&&(de.current.tabIndex=-1),de.current=e,t.tabIndex=e?-1:0,e&&(e.tabIndex=0))}let pe=(0,u.useRef)(void 0);(0,u.useEffect)(()=>{let{location:e}=r;if(!e||pe.current===e)return;let t=le.current?.querySelector(e.path?`[${e.directory?`data-file-dir-toggle`:`data-file-open`}="${CSS.escape(e.path)}"]`:`[data-explorer-root]`);t&&(pe.current=e,t.focus({preventScroll:!0}),t.scrollIntoView({block:`nearest`}))},[r.location,h,g,S]),(0,u.useEffect)(()=>{if(!M||g.has(M))return;let e=window.setTimeout(()=>_(M),650);return()=>window.clearTimeout(e)},[M,g,_]);let me=(0,u.useCallback)(e=>{let t=le.current;if(!t)return;let n=e.target?.closest(`.file-row`);if(!n)return;let r=Ff(n);if(r&&!ee.busy){if(e.key===`ContextMenu`||e.shiftKey&&e.key===`F10`){e.preventDefault(),ee.openMenu(r,bf(n));return}if(!r.linked&&e.key===`F2`){e.preventDefault(),ee.showAction(`move`,r,!1,n);return}if(!r.linked&&e.key===`Delete`){e.preventDefault(),ee.showAction(`trash`,r,!1,n);return}}let i=[...(n.closest(`.files-tree, .files-changed`)??t).querySelectorAll(`.file-row:not(:disabled)`)].filter(e=>e.offsetParent!==null),a=i.indexOf(n);if(a<0)return;let o=e=>{let t=Math.max(0,Math.min(i.length-1,e));i[t]?.focus()};if(e.key===`ArrowDown`)e.preventDefault(),o(a+1);else if(e.key===`ArrowUp`)e.preventDefault(),o(a-1);else if(e.key===`Home`)e.preventDefault(),o(0);else if(e.key===`End`)e.preventDefault(),o(i.length-1);else if(e.key===`ArrowRight`){let t=n.getAttribute(`data-file-dir-toggle`);if(t&&n.getAttribute(`aria-expanded`)===`false`)e.preventDefault(),_(t);else if(t){let t=n.closest(`.file-node`)?.querySelector(`.file-children .file-row:not(:disabled)`);t&&(e.preventDefault(),t.focus())}}else if(e.key===`ArrowLeft`){let r=n.getAttribute(`data-file-dir-toggle`);if(r&&n.getAttribute(`aria-expanded`)===`true`){e.preventDefault(),_(r);return}let i=n.getAttribute(`data-file-open`)??n.getAttribute(`data-file-hit`)??r;if(i){e.preventDefault();let n=i.lastIndexOf(`/`),r=n<0?``:i.slice(0,n);(r?t.querySelector(`[data-file-dir-toggle="${CSS.escape(r)}"]`):null)?.focus()}}},[_,ee]),[he,ge]=(0,u.useState)(200);(0,u.useEffect)(()=>{ge(200)},[se,e]);let P=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(se===``)return;let e=P.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&ge(e=>e>=(w?.hits.length??0)?e:e+200)},{rootMargin:`200px`});return t.observe(e),()=>t.disconnect()},[se,w]);let _e=(0,u.useMemo)(()=>{if(ce)return(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-exact-path":ce.path,title:ce.path,onClick:()=>A(ce),children:[(0,F.jsx)(Fr,{path:ce.path}),(0,F.jsxs)(`span`,{className:`file-name`,children:[`打开 `,ce.name]})]});if(se){if(T)return(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-searching":`1`,children:`搜索中…`});if(!w)return null;if(w.hits.length===0)return(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-search-empty":`1`,children:w.indexed?`没有匹配「${se}」的文件。`:`正在建立索引…`});let e=w.hits.slice(0,he),t=[],n=new Map;for(let r of e){let e=n.get(r.directory);if(e)e.push(r);else{let e=[r];n.set(r.directory,e),t.push({directory:r.directory,hits:e})}}return(0,F.jsxs)(F.Fragment,{children:[t.map(e=>(0,F.jsxs)(`section`,{className:`file-group`,"data-file-search-group":e.directory,children:[(0,F.jsxs)(`h3`,{className:`file-group-head`,"data-file-search-group-head":e.directory,children:[(0,F.jsx)(`span`,{className:`file-group-name`,children:e.directory||`/`}),(0,F.jsx)(`span`,{className:`file-group-count`,children:e.hits.length})]}),(0,F.jsx)(`ul`,{className:`file-list`,children:e.hits.map(e=>(0,F.jsxs)(`li`,{className:`file-explorer-row`,"data-file-entry":e.path,"data-linked":e.openLink,"data-file-current":r.visiblePath===e.path?`1`:void 0,children:[(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-hit":e.path,tabIndex:-1,"aria-current":r.visiblePath===e.path?`true`:void 0,"data-file-hit-open":d.has(e.path)?`1`:`0`,onClick:()=>A({...e,text:!0}),children:[(0,F.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,F.jsx)(Fr,{path:e.path}),(0,F.jsx)(`span`,{className:`file-name`,children:e.name}),d.has(e.path)&&(0,F.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`})]}),!e.openLink&&(0,F.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,tabIndex:-1,"aria-haspopup":`menu`,"aria-label":`${e.name} 的文件操作`,children:(0,F.jsx)(yf,{name:`more`})})]},e.path))})]},e.directory||`/`)),e.length<w.hits.length&&(0,F.jsx)(`div`,{ref:P,className:`file-sentinel`,"data-file-search-more":`1`,children:`正在载入更多…`})]})}return e?oe===void 0?(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-root-loading":`1`,children:`读取工作区…`}):`error`in oe?(0,F.jsx)(Tm,{error:oe.error}):(0,F.jsxs)(F.Fragment,{children:[oe.truncated&&(0,F.jsx)(`p`,{className:`file-search-note`,"data-file-truncated-root":`1`,children:`条目过多,只显示前一部分。`}),oe.entries.length===0?(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-root-empty":`1`,children:`这个工作区是空的,没有文件也没有子目录。`}):(0,F.jsx)(`ul`,{className:`file-list`,children:oe.entries.map(t=>t.kind===`directory`?(0,F.jsx)(ym,{workspaceId:e,entryPath:t.path,name:t.name,linked:t.symlink,listings:h,expanded:g,toggle:_,loadDirectory:v,openPaths:d,changedDirs:O,changedPaths:D,onOpen:A,depth:0,presentation:ae},t.path):(0,F.jsx)(bm,{entry:t,depth:0,openPaths:d,changedPaths:D,onOpen:A,presentation:ae},t.path))})]}):(0,F.jsx)(`p`,{className:`rail-empty`,"data-file-no-workspace":`1`,children:`先在左侧选一个工作区,这里会显示它的文件。`})},[ce,se,T,w,he,e,oe,h,g,_,v,A,d,O,D,ae,r.visiblePath]),ve=e=>{let t=Ff(e);if(!t?.linked)return t?t.directory?t.path:Mf(t.path):``},ye=(e,t)=>e!==Mf(t.path)&&!(t.directory&&Nf(e,t.path));return(0,u.useLayoutEffect)(()=>{let e=ue.current;if(!e)return;let t=[...e.querySelectorAll(`.file-row:not(:disabled)`)].filter(e=>e.offsetParent!==null),n=de.current;fe(n&&t.includes(n)?n:t.find(e=>e.hasAttribute(`aria-current`))??t[0])},[_e,ee.editing]),(0,F.jsxs)(`div`,{className:`files-panel`,"data-files-panel":`1`,"data-files-open-count":l.length,"data-files-changed-count":E.length,ref:le,onKeyDown:me,onClick:e=>{let t=e.target instanceof Element?e.target.closest(`[data-explorer-action]`):void 0,n=Ff(t??null);t&&n&&!ee.busy&&ee.openMenu(n,bf(t))},onContextMenu:e=>{let t=Ff(e.target),n=e.target instanceof Element?e.target.closest(`.file-row, [data-explorer-action]`):void 0;t&&n&&!ee.busy&&(e.preventDefault(),ee.openMenu(t,{x:e.clientX,y:e.clientY,origin:n}))},onDragStart:e=>{let t=Ff(e.target instanceof Element?e.target.closest(`.file-row[draggable=true]`):null);!t||t.linked||ee.busy||se||(N.current=t,e.dataTransfer.setData(Nm,t.path),e.dataTransfer.effectAllowed=`move`)},onDragEnd:()=>{N.current=void 0,te(void 0)},onDragLeave:e=>{(!(e.relatedTarget instanceof Node)||!e.currentTarget.contains(e.relatedTarget))&&te(void 0)},onDragOver:t=>{let n=t.dataTransfer.types.includes(`Files`),r=N.current&&t.dataTransfer.types.includes(Nm)?N.current:void 0;if(!e||ee.busy||!n&&!r)return;t.preventDefault();let i=ve(t.target),a=i!==void 0&&(!r||ye(i,r));t.dataTransfer.dropEffect=a?r?`move`:`copy`:`none`,te(a?i:void 0)},onDrop:t=>{te(void 0);let n=t.dataTransfer.types.includes(Nm)?N.current:void 0;if(N.current=void 0,!e||ee.busy||!n&&!t.dataTransfer.types.includes(`Files`))return;t.preventDefault();let r=ve(t.target);if(r===void 0){p(`请选择工作区里的普通文件夹。`);return}if(n){ye(r,n)&&ee.moveTo(n,r);return}let i=Array.from(t.dataTransfer.items).filter(e=>!e.webkitGetAsEntry?.()?.isDirectory).map(e=>e.getAsFile()).filter(e=>e!==null);i.length?ee.upload(r,i):t.dataTransfer.files.length&&!t.dataTransfer.items.length?ee.upload(r,Array.from(t.dataTransfer.files)):p(`请选择要上传的文件。`)},children:[(0,F.jsxs)(`header`,{className:`file-explorer-header`,"data-file-drop-target":M===``?`1`:void 0,children:[(0,F.jsxs)(`div`,{className:`file-explorer-scope`,"data-explorer-root":`1`,tabIndex:-1,title:n?`${t??`工作区`}/${n}`:j,children:[(0,F.jsx)(Fr,{category:`folder-open`}),(0,F.jsx)(`span`,{children:j})]}),ee.toolbar]}),(0,F.jsxs)(`div`,{className:`files-search`,children:[(0,F.jsx)(`span`,{className:`files-search-icon`,"aria-hidden":`true`,children:(0,F.jsx)(yf,{name:`search`})}),(0,F.jsx)(`input`,{type:`search`,className:`files-search-input`,"data-file-search-input":`1`,value:S,placeholder:`筛选文件或输入绝对路径`,"aria-label":`按文件名搜索`,onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),C(``)):e.key===`Enter`&&ce&&(e.preventDefault(),A(ce))},onChange:e=>C(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`explorer-icon-button`,disabled:!r.activePath||!!cm(r.activePath)||!!(r.active?.assetTicket&&hm(r.activePath)),onClick:()=>{r.activePath&&r.locatePath(r.activePath,!1)},title:`定位打开的文件`,"aria-label":`在文件树中定位当前文件`,children:(0,F.jsx)(yf,{name:`locate`})})]}),ee.controls,!ce&&se&&w&&!T&&(0,F.jsxs)(`p`,{className:`files-count`,"data-file-search-count":`1`,role:`status`,children:[(0,F.jsx)(`b`,{children:w.total.toLocaleString(`zh-CN`)}),` 个结果`,w.indexed===!1&&(0,F.jsx)(`span`,{className:`files-count-note`,"data-file-search-indexing":`1`,children:`正在建立索引…`}),w.indexed&&w.incomplete&&(0,F.jsx)(`span`,{className:`files-count-note`,children:`索引不完整`})]}),f&&(0,F.jsx)(`p`,{className:`rail-empty file-explorer-notice`,"data-file-notice":`1`,role:`status`,children:f}),ee.busy&&(0,F.jsx)(`p`,{className:`file-explorer-notice`,role:`status`,children:`正在处理文件…`}),(0,F.jsx)(`div`,{className:`files-tree`,ref:ue,"data-file-tree":se?`search`:`browse`,tabIndex:0,"aria-label":`文件树`,onFocus:e=>{e.target instanceof HTMLElement&&e.target.matches(`.file-row:not(:disabled)`)&&fe(e.target)},style:b===null?void 0:{height:`${b}px`,flex:`0 0 auto`},children:(0,F.jsxs)(`div`,{className:`files-tree-body`,children:[ee.inline(``,`child`,0),_e]})}),(0,F.jsx)(jm,{height:b,onHeight:x,panelRef:le}),(0,F.jsxs)(`div`,{className:`files-changed`,"data-file-changed-list":`1`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`files-changed-head`,"data-file-changed-head":`1`,"aria-expanded":ne,onClick:()=>re(e=>!e),children:[(0,F.jsx)(yf,{name:ne?`down`:`right`}),(0,F.jsx)(yf,{name:`changes`}),(0,F.jsx)(`span`,{children:`改动`}),(0,F.jsx)(`span`,{className:`files-change-count`,children:E.length})]}),ne&&(0,F.jsxs)(`div`,{className:`files-change-list`,children:[k>0&&(0,F.jsxs)(`p`,{className:`file-search-note`,"data-file-changed-dropped":`1`,children:[`还有 `,k,` 个改动没有记录(超过保留上限)。`]}),!E.length&&(0,F.jsx)(`p`,{className:`file-row-empty`,children:`没有 agent 改动。`}),(0,F.jsx)(`ul`,{className:`file-list`,children:E.map(e=>(0,F.jsx)(`li`,{children:(0,F.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-changed-open":e.path,title:`${e.path}(点击查看改动)`,onClick:()=>a?.(e.path),children:[(0,F.jsx)(Fr,{path:e.path}),(0,F.jsx)(`span`,{className:`file-name`,children:e.path.split(`/`).pop()}),(0,F.jsx)(`span`,{className:`file-badge-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)||`/`}),(0,F.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed-kind":e.path,children:e.baseline===null&&!e.baselineUnknown?`新建`:`已改`})]})},e.path))})]})]})]})}function Fm(e,t){let[n,r]=(0,u.useState)(!1),[i,a]=(0,u.useState)(``);return{choose:async(i,o,s)=>{if(i&&!n){r(!0),a(``);try{await e(i,o,s)&&t()}catch(e){a(Or(e,`文件无法打开`))}finally{r(!1)}}},openError:i,opening:n,setOpenError:a}}var Im=200;async function Lm(e,t,n){let r=await Ne(e,{signal:t,cache:`no-store`});if(!r.ok)throw new $p(r.status,await r.json());if(!r.body)throw Error(`服务端没有返回搜索结果。`);let i=r.body.pipeThrough(new TextDecoderStream).getReader(),a=``,o=!1;try{for(;;){let e=await i.read();if(e.done)break;let t=(a+e.value).split(`
|
|
290
|
-
`);a=t.pop();for(let e of t){if(!e)continue;let t=JSON.parse(e);if(t.type===`error`)throw Error(t.error);n(t),t.type===`done`&&(o=!0)}}if(!o)throw Error(`搜索连接提前断开,结果可能不完整。`)}finally{await i.cancel().catch(()=>void 0),i.releaseLock()}}function Rm(e,t){return{path:t?e.startsWith(t+`/`)?e.slice(t.length+1):sm+e:e,name:e.split(`/`).at(-1)??e,text:!0}}function zm(e,t,n){return{...Rm(t?t+`/`+e.path:e.path,n),name:e.name}}function Bm({workspaceId:e,cwd:t=``,directory:n,initialQuery:r=``,onOpen:i,onClose:a,onMode:o,presentation:s}){let[c,l]=(0,u.useState)(r),[d,f]=(0,u.useState)(n??``),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(!0),[y,b]=(0,u.useState)([]),[x,S]=(0,u.useState)(),[C,w]=(0,u.useState)(Im),[T,E]=(0,u.useState)(``),[D,O]=(0,u.useState)(!1),[k,A]=(0,u.useState)(!1),[j,ee]=(0,u.useState)(0),{choose:M,openError:te,opening:N,setOpenError:ne}=Fm(i,a),re=!!hm(c),ie=(0,u.useRef)(null),ae=(0,u.useRef)(null),oe=(0,u.useRef)(void 0),se=(0,u.useId)();(0,u.useEffect)(()=>{ie.current?.focus()},[]),(0,u.useEffect)(()=>{ae.current?.scrollIntoView({block:`nearest`})},[j]),(0,u.useEffect)(()=>{let t=c.trim(),n=new AbortController;if(oe.current=n,b([]),S(void 0),E(``),A(!1),w(Im),ee(0),!e||!t){O(!1);return}if(t.length>256){E(`搜索词不能超过 256 个字符。`),O(!1);return}let r=new URLSearchParams({workspaceId:e,q:t,stream:`1`,ignore:_?`1`:`0`});d&&r.set(`cwd`,d),p.trim()&&r.set(`include`,p.trim()),h.trim()&&r.set(`exclude`,h.trim()),O(!0);let i=setTimeout(()=>{n.signal.aborted||Lm(`/api/files/search?`+r,n.signal,e=>{n.signal.aborted||(e.type===`matches`?b(t=>[...t,...e.hits]):e.type===`done`&&S(e.summary))}).catch(e=>{n.signal.aborted||E(Or(e,`搜索没有完成`))}).finally(()=>{n.signal.aborted||O(!1)})},220);return()=>{n.abort(),clearTimeout(i)}},[c,e,d,p,h,_]);let ce=(0,u.useMemo)(()=>{let e=new Map;return y.slice(0,C).forEach((t,n)=>{let r=e.get(t.path);r?r.push({hit:t,row:n}):e.set(t.path,[{hit:t,row:n}])}),[...e]},[y,C]),le=e=>{e&&M(zm(e,d,t),e.line,e.column)},ue=x?.complete===!1,de={time:`搜索超时`,results:`达到全局结果上限`,line:`部分行太长`,encoding:`部分文件的编码无法读取`,unreadable:`部分文件无法读取`};return(0,F.jsxs)(Vf,{mode:`content`,query:c,onMode:o,onClose:a,presentation:s,children:[(0,F.jsx)(`input`,{ref:ie,className:`quick-open-input`,"data-content-search-input":`1`,value:c,readOnly:N,placeholder:`内容搜索(区分大小写,按字面匹配)`,role:`combobox`,"aria-label":`内容搜索`,"aria-autocomplete":`list`,"aria-controls":se,"aria-expanded":y.length>0,"aria-activedescendant":y[j]?`${se}-${j}`:void 0,onChange:e=>{l(e.target.value),ne(``)},onKeyDown:e=>{e.nativeEvent.isComposing||(e.key===`ArrowDown`?(e.preventDefault(),ee(e=>Math.min(e+1,Math.max(0,Math.min(C,y.length)-1)))):e.key===`ArrowUp`?(e.preventDefault(),ee(e=>Math.max(0,e-1))):e.key===`Enter`&&(e.preventDefault(),le(y[j])))}}),(0,F.jsxs)(`div`,{className:`content-search-controls`,children:[(0,F.jsxs)(`label`,{children:[`范围 `,(0,F.jsxs)(`select`,{value:d,"aria-label":`搜索范围`,onChange:e=>f(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`整个工作区`}),t&&(0,F.jsxs)(`option`,{value:t,children:[`当前目录 · `,t]}),n&&n!==t&&(0,F.jsxs)(`option`,{value:n,children:[`文件夹 · `,n]})]})]}),D&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>{oe.current?.abort(),ie.current?.focus(),O(!1),A(!0)},children:`取消搜索`})]}),(0,F.jsxs)(`details`,{className:`content-search-filters`,children:[(0,F.jsx)(`summary`,{children:`文件筛选`}),(0,F.jsxs)(`label`,{children:[`包含 `,(0,F.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),placeholder:`例如 **/*.cpp`})]}),(0,F.jsxs)(`label`,{children:[`排除 `,(0,F.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),placeholder:`例如 **/generated/**`})]}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>v(e.target.checked)}),` 遵循忽略文件和默认排除`]})]}),(0,F.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":T?`error`:D?`searching`:k?`cancelled`:ue?`partial`:`complete`,children:[T?`搜索失败:`+T:D?`搜索中…`:k?`已取消`:e?ue?`结果不完整`:x?`搜索完成`:`输入要搜索的内容`:`请先选择工作区`,(y.length>0||x)&&` · ${y.length} 条命中`]}),re&&(0,F.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>o(`path`,c),children:`按文件路径打开`}),ue&&(0,F.jsx)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:x.reasons.map(e=>de[e]??e).join(`;`)}),x?.complete&&!y.length&&(0,F.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`没有匹配的行`}),te&&(0,F.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:te}),(0,F.jsx)(`ul`,{id:se,className:`quick-open-results content-search-results`,role:`listbox`,"aria-label":`正文搜索结果`,children:ce.map(([e,t])=>(0,F.jsxs)(`li`,{className:`content-search-group`,role:`presentation`,children:[(0,F.jsx)(`div`,{className:`content-search-file`,title:e,children:e}),t.map(({hit:e,row:t})=>(0,F.jsxs)(`button`,{id:`${se}-${t}`,ref:t===j?ae:void 0,type:`button`,role:`option`,tabIndex:-1,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${j===t?` quick-open-result-active`:``}`,"aria-selected":j===t,"aria-label":`${e.path}:${e.line}:${e.column} ${e.text}`,onMouseEnter:()=>ee(t),onClick:()=>le(e),children:[(0,F.jsxs)(`span`,{title:`${e.path}:${e.line}:${e.column}`,className:`content-search-result-position`,children:[e.line,`:`,e.column]}),(0,F.jsx)(`small`,{title:e.text,children:e.text})]},e.line))]},e))}),y.length>C&&(0,F.jsxs)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-content-search-more":`1`,onClick:()=>{C+Im>=y.length&&ie.current?.focus(),w(e=>e+Im)},children:[`显示更多结果(已显示 `,C,` / `,y.length,`)`]})]})}function Vm({workspaceId:e,cwd:t=``,connected:n,initialQuery:r=``,onOpen:i,onClose:a,onMode:o,presentation:s}){let[c,l]=(0,u.useState)(r),[d,f]=(0,u.useState)(0),[p,m]=(0,u.useState)(0),[h,g]=(0,u.useState)(),_=(0,u.useRef)(void 0),v=(0,u.useRef)(void 0),{choose:y,openError:b,opening:x,setOpenError:S}=Fm(i,a),C=(0,u.useRef)(null),w=(0,u.useRef)(null),T=gm(c),E=e?hm(c):void 0,D=!!E;(0,u.useEffect)(()=>{if(!n||!e)return;let r=new AbortController,i=dm(e,``,t)+`&quick=1&refresh=1`;return _.current=nm(i,{cache:`no-store`,signal:r.signal}).catch(()=>void 0),()=>{r.abort(),_.current=void 0}},[n,e,t]),(0,u.useEffect)(()=>{if(!n||!e||D)return;let r=new AbortController,i=r.signal,a=dm(e,T,t)+`&quick=1&page=${p}`,o,s=async e=>{try{let t=e?await _.current:void 0;if(i.aborted)return;let n=e&&!T&&t?t:await nm(a,{cache:`no-store`,signal:i});if(i.aborted)return;g({query:T,page:p,response:n}),n.indexed||(o=setTimeout(()=>void s(!1),350))}catch(e){i.aborted||g({query:T,page:p,error:Or(e,`文件查找没有完成`)})}};return o=setTimeout(()=>void s(!0),T?120:0),()=>{r.abort(),clearTimeout(o)}},[n,e,t,T,D,p]);let O=h?.query===T&&h.page===p?h:void 0,k=O?.response,A=(0,u.useMemo)(()=>{if(E)return[E];let t=k?.hits.map(e=>({...e,text:null}))??[];return p>0||e&&T.includes(`/`)&&!T.endsWith(`/`)&&!T.split(`/`).includes(`..`)&&!t.some(e=>e.path.toLowerCase()===T.toLowerCase())&&(k?.total?t.push(mm(T)):t.unshift(mm(T))),t},[E,T,k,p,e]),j=e=>{v.current=void 0,m(e),g(void 0),f(0),S(``),C.current?.focus()},ee=!D&&!(!e||O?.error||k?.indexed);return(0,u.useEffect)(()=>{let e=v.current;e===void 0||ee||(v.current=void 0,y(A[Math.min(e,A.length-1)]))},[ee,A,y]),(0,u.useEffect)(()=>{C.current?.focus()},[]),(0,u.useEffect)(()=>{w.current?.scrollIntoView({block:`nearest`})},[d]),(0,F.jsxs)(Vf,{mode:`path`,query:c,onMode:o,onClose:a,presentation:s,children:[(0,F.jsx)(`input`,{ref:C,className:`quick-open-input`,"data-quick-open-input":`1`,value:c,readOnly:x,placeholder:`快速打开:输入文件名或路径`,"aria-label":`快速打开文件路径`,onChange:e=>{let t=e.target.value;v.current=void 0,(gm(t)!==T||p!==0)&&g(void 0),l(t),m(0),f(0),S(``)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`)e.preventDefault(),f(e=>Math.min(e+1,Math.max(0,A.length-1)));else if(e.key===`ArrowUp`)e.preventDefault(),f(e=>Math.max(e-1,0));else if(e.key===`Enter`){e.preventDefault();let t=A[Math.min(d,A.length-1)],n=k?.hits.some(e=>e.path===t?.path&&[e.name,e.path].some(e=>e.toLowerCase()===T.toLowerCase()));ee&&!n?v.current=d:y(t)}}}}),(0,F.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"aria-live":`polite`,"data-quick-open-status":D||k?.indexed&&!k.incomplete?`complete`:`partial`,children:[D?`按 Enter 打开指定文件`:e?n?O?.error||(ee?`正在检查文件索引…`:T?k?.incomplete?`索引不完整 · ${k.total} 条命中`:k?.total?`${k.total} 条命中${p?` · 第 ${p+1} 页`:``}`:A.length?`近似路径`:`没有匹配的文件名或路径`:`输入文件名或路径以查找当前目录中的文件`):`等待连接…`:`请先选择工作区`,` · Esc 关闭`]}),b&&(0,F.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:b}),(0,F.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:A.map((e,t)=>(0,F.jsx)(`li`,{children:(0,F.jsxs)(`button`,{ref:t===d?w:void 0,type:`button`,"data-quick-open-result":e.path,className:t===d?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===d,onMouseMove:()=>f(t),onClick:()=>{v.current=void 0,y(e)},children:[(0,F.jsx)(`span`,{title:e.name,children:e.name}),(0,F.jsx)(`small`,{title:e.path,children:e.path})]})},e.path))}),T&&k?.indexed&&(p>0||k.truncated)&&(0,F.jsxs)(`div`,{className:`quick-open-pages`,"aria-label":`文件搜索翻页`,children:[p>0&&(0,F.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>j(p-1),children:`上一页`}),k.truncated&&(0,F.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-quick-open-next-page":!0,onClick:()=>j(p+1),children:`下一页`})]})]})}function Hm({workspaceId:e,workspaceName:t,cwd:n,connected:r,onOpen:i,onSession:a,active:o=!0}){let[s,c]=(0,u.useState)(`content`),[l,d]=(0,u.useState)(``),f=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(!o)return;let e=requestAnimationFrame(()=>f.current?.parentElement?.querySelector(`[data-content-search-input], [data-quick-open-input], [data-session-search-input]`)?.focus());return()=>cancelAnimationFrame(e)},[o,s]);let p={workspaceId:e,cwd:n,initialQuery:l,presentation:`sidebar`,onClose:()=>{},onMode:(e,t)=>{d(t),c(e)}};return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{ref:f,className:`workbench-search-heading`,children:[(0,F.jsx)(`strong`,{children:`搜索`}),(0,F.jsx)(`span`,{title:t,children:t??`请选择工作区`})]}),s===`content`?(0,F.jsx)(Bm,{...p,onOpen:i}):s===`path`?(0,F.jsx)(Vm,{...p,connected:r,onOpen:i}):(0,F.jsx)(Hf,{...p,onOpen:a})]})}function Um(e,t,n=88,r=200){let i=Math.max(0,Math.floor(e));if(!Number.isFinite(t)||t<=0)return{perRow:Math.max(1,i),width:n};if(i===0)return{perRow:1,width:n};if(i===1)return{perRow:1,width:Math.min(r,t)};let a=t/i;if(a>=n)return{perRow:i,width:Math.min(a,r)};for(let e=2;e<=i;e+=1){let a=Math.ceil(i/e),o=t/a;if(o>=n)return{perRow:a,width:Math.min(o,r)}}return{perRow:1,width:n}}function Wm(e,t){let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}function Gm(e,t,n=88,r=200){let[i,a]=(0,u.useState)(()=>Um(e,0,n,r)),[o,s]=(0,u.useState)(null),c=(0,u.useCallback)(()=>{let i=Um(e,t,n,r);s({count:e,containerWidth:t}),a(e=>e.perRow===i.perRow&&e.width===i.width?e:i)},[e,t,n,r]),l=(0,u.useRef)(t);(0,u.useLayoutEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let d=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let t=d.current;d.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function Km({tabs:e,activeId:t,onSelect:n,onClose:r,onActivate:i,ariaLabel:a,minWidth:o=88,maxWidth:s=200,prefix:c=`workspace-tab`,idPrefix:l=c,className:d}){let f=(0,u.useRef)(null),[p,m]=(0,u.useState)(0),{layout:h,frozen:g,recompute:_}=Gm(e.length,p,o,s);(0,u.useLayoutEffect)(()=>{let e=f.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&m(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let v=Wm(e,h.perRow),y=(e,t)=>t===void 0?{}:{[`data-${c}-${e}`]:t},b=e.filter(e=>e.kind===`file`).length,x=e.filter(e=>e.kind===`session`||!e.kind).length,S=t=>({[`data-${t}-strip`]:`1`,...g?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?b:t===`session-tab`?x:e.length,[`data-${t}-min`]:o,[`data-${t}-max`]:s,[`data-${t}-per-row`]:h.perRow,[`data-${t}-width`]:Math.round(h.width*100)/100}),C=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&_()},w=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&_()};(0,u.useEffect)(()=>{if(!g)return;let e=f.current;if(!e)return;let t=t=>{let n=e.getBoundingClientRect();t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom||_()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[g,_]);let T=[`${c}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,d].filter(Boolean).join(` `);return(0,F.jsx)(`div`,{ref:f,className:T,role:`tablist`,"aria-label":a??`工作区标签页`,...y(`strip`,`1`),...S(`workspace-tab`),...S(`session-tab`),...S(`file-tab`),style:{"--tab-w":`${h.width}px`},onMouseEnter:C,onMouseLeave:w,children:v.map((a,o)=>(0,F.jsx)(`div`,{className:`${c}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,...y(`row`,o),children:a.map(a=>{let o=a.id===t||a.rawId!==void 0&&a.rawId===t,s=a.title??a.label,u=a.kind,d=a.rawId??a.id,f=e.findIndex(e=>e.id===a.id),p=[c,o?`${c}-active`:``,`workspace-tab`,o?`workspace-tab-active`:``,u?`${u}-tab`:``,u&&o?`${u}-tab-active`:``,a.preview?`${c}-preview`:``,a.preview?`workspace-tab-preview`:``,a.preview&&u?`${u}-tab-preview`:``].filter(Boolean).join(` `);return(0,F.jsxs)(`div`,{role:`tab`,id:`${l}-${a.id}`,"aria-selected":o,"aria-controls":`${l}-panel-${a.id}`,tabIndex:o?0:-1,className:p,...y(`id`,d),...y(`index`,f),...o?y(`active`,`1`):{},...y(`closable`,a.closable===!1?`0`:`1`),...u?{"data-tab-kind":u}:{},...a.preview?{"data-tab-preview":`1`}:{},...u===`session`||!u?{"data-session-tab-id":d,"data-session-tab-index":f,...o?{"data-session-tab-active":`1`}:{},"data-session-tab-closable":a.closable===!1?`0`:`1`,...a.preview?{"data-session-tab-preview":`1`}:{}}:{},...u===`file`?{"data-file-tab-id":d,"data-file-tab-index":f,...o?{"data-file-tab-active":`1`}:{},"data-file-tab-closable":a.closable===!1?`0`:`1`}:{},...u===`diff`?{"data-diff-tab-id":d,"data-diff-tab-index":f,...o?{"data-diff-tab-active":`1`}:{},"data-diff-tab-closable":a.closable===!1?`0`:`1`}:{},title:s,style:{width:h.width,boxSizing:`border-box`},onClick:()=>n?.(a.id),onDoubleClick:i?()=>i(a.id):void 0,onAuxClick:e=>{e.button===1&&(e.preventDefault(),e.stopPropagation(),a.closable!==!1&&r&&r(a.id))},onMouseDown:e=>{e.button===1&&e.preventDefault()},onKeyDown:t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)return;t.preventDefault();let r=t.key===`ArrowRight`?1:-1,i=e[(e.findIndex(e=>e.id===a.id)+r+e.length)%e.length];i&&(document.getElementById(`${l}-${i.id}`)?.focus(),n?.(i.id))},children:[a.icon&&(0,F.jsx)(`span`,{className:`${c}-icon workspace-tab-icon`,children:a.icon}),a.badge,(0,F.jsx)(`span`,{className:`${c}-label workspace-tab-label ${u?`${u}-tab-label`:``}`,...y(`label`,d),...u===`session`||!u?{"data-session-tab-label":d}:{},...u===`file`?{"data-file-tab-label":d}:{},...u===`diff`?{"data-diff-tab-label":d}:{},children:a.label}),a.closable!==!1&&r&&(0,F.jsx)(`button`,{type:`button`,className:`${c}-close workspace-tab-close ${u?`${u}-tab-close`:``}`,...y(`close`,d),...u===`session`||!u?{"data-session-tab-close":d}:{},...u===`file`?{"data-file-tab-close":d}:{},...u===`diff`?{"data-diff-tab-close":d}:{},onClick:e=>{e.stopPropagation(),r(a.id)},onDoubleClick:e=>{e.stopPropagation()},title:`关闭 ${s}`,"aria-label":`关闭 ${s}`,children:`×`})]},a.id)})},`row_${o}`))})}var qm=25,Jm=75;function Ym({share:e,onShare:t}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),a=e=>t(Math.round(Math.min(Jm,Math.max(qm,e))));return(0,u.useLayoutEffect)(()=>{let e=n.current?.parentElement;if(!e)return;let t=()=>i(getComputedStyle(e).flexDirection===`column`);t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]),(0,F.jsx)(`div`,{ref:n,className:`workbench-split-divider`,"data-workbench-split-divider":!0,role:`separator`,"aria-label":`调整拆分大小`,"aria-orientation":r?`horizontal`:`vertical`,"aria-valuenow":e,"aria-valuemin":qm,"aria-valuemax":Jm,tabIndex:0,onPointerDown:e=>{e.button===0&&(e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{if(!e.currentTarget.hasPointerCapture(e.pointerId))return;let t=e.currentTarget.parentElement?.getBoundingClientRect();t&&a(r?(e.clientY-t.top)/t.height*100:(e.clientX-t.left)/t.width*100)},onKeyDown:t=>{let n=t.key===(r?`ArrowDown`:`ArrowRight`),i=t.key===(r?`ArrowUp`:`ArrowLeft`);if(n||i)a(e+(n?5:-5));else if(t.key===`Home`)a(qm);else if(t.key===`End`)a(Jm);else return;t.preventDefault()}})}function Xm({tabs:e,selected:t,onSelect:n,onPin:r,onCloseTab:i,onClose:a,children:o}){let s=e.find(e=>e.id===t);return(0,F.jsxs)(`section`,{className:`workbench-split-pane`,"data-workbench-split-pane":!0,"aria-label":`拆分区`,children:[(0,F.jsxs)(`div`,{className:`workbench-split-bar`,children:[(0,F.jsxs)(`select`,{"aria-label":`拆分区标签页`,"data-workbench-split-tabs":!0,value:t??``,onChange:e=>n(e.target.value),title:s?.title,"data-workbench-split-preview":s?.preview||void 0,children:[(0,F.jsx)(`option`,{value:``,disabled:!0,children:`选择文件或差异`}),e.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),t&&s?.preview&&(0,F.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`固定标签页`,"aria-label":`固定拆分区标签页`,onClick:()=>r(t),children:(0,F.jsx)(Gr,{name:`pin`})}),t&&(0,F.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`关闭此标签页`,"aria-label":`关闭拆分区标签页`,onClick:()=>i(t),children:(0,F.jsx)(Gr,{name:`close`})}),(0,F.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,"data-close-workbench-split":!0,title:`合并主区`,"aria-label":`合并主区`,onClick:a,children:(0,F.jsx)(Gr,{name:`split`})})]}),o??(0,F.jsx)(`p`,{className:`rail-empty`,children:`从文件或 Git 面板打开一个文件或差异。`})]})}function Zm(e,t){if(e.entries[e.index]?.key===t.key)return e;let n=[...e.entries.slice(0,e.index+1),t].slice(-100);return{entries:n,index:n.length-1}}function Qm(e,t,n,r){for(let i=t+n;i>=0&&i<e.entries.length;i+=n)if(r(e.entries[i]))return i;return-1}var $m={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},eh={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},th={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},nh={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function rh(e){let t=Math.max(0,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60)%60,i=Math.floor(t/3600),a=e=>String(e).padStart(2,`0`);return i>0?`${i}h ${a(r)}:${a(n)}`:`${r}:${a(n)}`}function ih(e){let t=e.status===`running`,[n,r]=(0,u.useState)(0);(0,u.useEffect)(()=>{if(!t)return;r(Date.now());let e=window.setInterval(()=>r(Date.now()),200);return()=>window.clearInterval(e)},[t,e.startedAt]);let i=Date.parse(e.startedAt);if(Number.isFinite(i)){if(!t){let t=Date.parse(e.finishedAt??``);return Number.isFinite(t)?t-i:void 0}return n>0?n-i:void 0}}function ah({step:e,names:t}){let n=e.attempts.length,r=e.attempts[n-1],i=t.get(e.agentId)||e.agentId,a=e.label?.trim()||i;return(0,F.jsxs)(`li`,{className:`workflow-step workflow-step-${e.status}`,"data-workflow-step":e.index+1,"data-workflow-step-status":e.status,"data-workflow-step-agent":e.agentId,"data-workflow-step-attempts":n,children:[(0,F.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:th[e.status]}),(0,F.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,F.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,F.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,F.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,F.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:$m[e.status]}),e.status===`failed`&&r?.error&&(0,F.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,title:kr(r.error),children:Or(r.error,`这一步没有完成。`)})]})}function oh({nodes:e,steps:t,names:n}){return(0,F.jsx)(`ol`,{className:`workflow-steps`,children:e.map((e,r)=>{if(e.kind===`step`){let r=t[e.stepIndex];return r?(0,F.jsx)(ah,{step:r,names:n},`step-${e.stepIndex}`):null}return e.kind===`loop`?(0,F.jsxs)(`li`,{className:`workflow-node workflow-loop`,"data-workflow-loop":!0,"data-workflow-loop-rounds":e.rounds.length,"data-workflow-loop-max":e.max,"data-workflow-until":e.until,children:[(0,F.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`↻`}),(0,F.jsx)(`strong`,{children:`循环`}),(0,F.jsxs)(`span`,{children:[`直到「`,e.until,`」`]}),(0,F.jsxs)(`span`,{"data-workflow-loop-progress":!0,children:[`已跑 `,e.rounds.length,`/`,e.max,` 轮`]})]}),e.rounds.map(e=>(0,F.jsxs)(`section`,{className:`workflow-round`,"data-workflow-round":e.n,"data-workflow-round-met":e.untilMet?`true`:`false`,children:[(0,F.jsxs)(`div`,{className:`workflow-round-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:e.untilMet?`✓`:`○`}),`第 `,e.n,` 轮 · `,e.untilMet?`条件满足`:`条件未满足`]}),(0,F.jsx)(oh,{nodes:e.nodes,steps:t,names:n})]},e.n))]},`loop-${r}`):(0,F.jsxs)(`li`,{className:`workflow-node workflow-foreach`,"data-workflow-foreach":!0,"data-workflow-foreach-count":e.items.length,children:[(0,F.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`≡`}),(0,F.jsx)(`strong`,{children:`逐项执行`}),(0,F.jsxs)(`span`,{children:[e.items.length,` 个由 primary 给出的项目`]})]}),e.iterations.map((e,r)=>(0,F.jsxs)(`section`,{className:`workflow-item`,"data-workflow-item":r+1,"data-workflow-item-value":e.item,children:[(0,F.jsxs)(`div`,{className:`workflow-item-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),`第 `,r+1,` 项 · `,e.item]}),(0,F.jsx)(oh,{nodes:e.nodes,steps:t,names:n})]},`${r}-${e.item}`))]},`foreach-${r}`)})})}function sh({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=ih(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,F.jsxs)(`article`,{className:`workflow-card workflow-${e.status}`,"data-workflow-card":e.id,"data-workflow-status":e.status,"data-workflow-steps":e.steps.length,"data-workflow-current":e.currentIndex+1,children:[(0,F.jsxs)(`div`,{className:`workflow-head`,children:[(0,F.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,F.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,F.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,F.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:eh[e.status]??`未知状态`}),(0,F.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:nh[e.onFailure]??e.onFailure}),a!==void 0&&(0,F.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,rh(a)]}),i&&(0,F.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),e.nodes?(0,F.jsx)(oh,{nodes:e.nodes,steps:e.steps,names:t}):(0,F.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,F.jsx)(ah,{step:e,names:t},e.index))})]})}var ch=[{id:`agents`,label:`智能体与创建`,icon:`🤖`,title:`Agent 智能体系统与创建指南`,description:`了解 Super Pi 的角色设定机制,以及如何一步步创建你自己的自定义 Agent。`},{id:`workspace`,label:`工作区与会话`,icon:`🗂️`,title:`工作区与多会话管理`,description:`高效管理本地代码仓库、独立会话标签页与多模态图文输入。`},{id:`subagents`,label:`子任务与编排`,icon:`⚡`,title:`子智能体委托与顺序编排使用指南`,description:`让主 Agent 安排分工、交接结果,并查看进度、处理失败与停止任务。`},{id:`model-policy`,label:`模型使用规则`,icon:`🔒`,title:`模型过滤规则(按工作区限制可用模型)`,description:`用正则规则限定哪些工作区只能用哪些模型,防止敏感代码被发到不该用的模型上。`},{id:`memory`,label:`主动记忆`,icon:`🧠`,title:`主动记忆与技能经验`,description:`让 Super Pi 在得到明确证据后保存长期事实、用户偏好和可复用工作方法。`},{id:`knowledge`,label:`知识库`,icon:`📚`,title:`工作区知识库`,description:`导入规范与设计文档,让 Agent 检索原文作答,而不是凭记忆编造。`},{id:`feishu`,label:`飞书`,icon:`📄`,title:`飞书云文档的读写`,description:`让 Agent 读一篇飞书文档、写回结论。接入方式、连接步骤与常见问题。`},{id:`tools`,label:`侧边栏工具`,icon:`🧩`,title:`全局工具:开发、导出与导入`,description:`让 Agent 写一个工具,用一个文件分享给别人,导入前先看清它会做什么。`},{id:`cli`,label:`指令与快捷键`,icon:`⌨️`,title:`Pi 终端命令与键盘快捷操作`,description:`利用 Pi 终端斜杠指令控制服务生命周期,掌握常用快捷键提升效率。`},{id:`themes`,label:`外观与主题`,icon:`🎨`,title:`界面主题与个性化显示`,description:`内置 4 款专业高对比度主题,针对不同环境提供舒适体验。`}];function lh({onClose:e}){let[t,n]=(0,u.useState)(`agents`);(0,u.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=ch.find(e=>e.id===t)??ch[0];return(0,F.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,F.jsxs)(`div`,{className:`picker settings-window help-window`,"data-help-window":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-labelledby":`help-window-title`,children:[(0,F.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,F.jsxs)(`div`,{className:`help-head-title`,children:[(0,F.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,F.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,F.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,F.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,F.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,F.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),ch.map(e=>(0,F.jsxs)(`button`,{type:`button`,id:`help-tab-${e.id}`,className:`settings-category help-category`,role:`tab`,"aria-selected":e.id===r.id,"aria-controls":`help-panel`,tabIndex:e.id===r.id?0:-1,onClick:()=>n(e.id),children:[(0,F.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,F.jsx)(`span`,{children:e.label})]},e.id))]}),(0,F.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,F.jsxs)(`div`,{className:`help-panel-header`,children:[(0,F.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,F.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,F.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,F.jsx)(fh,{}),r.id===`workspace`&&(0,F.jsx)(ph,{}),r.id===`subagents`&&(0,F.jsx)(hh,{}),r.id===`model-policy`&&(0,F.jsx)(mh,{}),r.id===`memory`&&(0,F.jsx)(uh,{}),r.id===`knowledge`&&(0,F.jsx)(dh,{}),r.id===`feishu`&&(0,F.jsx)(gh,{}),r.id===`tools`&&(0,F.jsx)(_h,{}),r.id===`cli`&&(0,F.jsx)(vh,{}),r.id===`themes`&&(0,F.jsx)(yh,{})]}),(0,F.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function uh(){return(0,F.jsxs)(`div`,{className:`help-section-group`,children:[(0,F.jsxs)(`div`,{className:`help-card highlight`,children:[(0,F.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,F.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,F.jsx)(`code`,{children:`memory`}),` 和 `,(0,F.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,F.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,F.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`权限与审批`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,F.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,F.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function dh(){return(0,F.jsxs)(`div`,{className:`help-section-group`,children:[(0,F.jsxs)(`div`,{className:`help-card highlight`,children:[(0,F.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,F.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库的内容来自工作区里真实存在的文档。`})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`怎么用`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文、手动填写相对路径,或者直接对 Agent 说“把某某文件加入知识库”——它会用 `,(0,F.jsx)(`code`,{children:`knowledge_import`}),` 导入,走的是同一条服务端校验。`]}),(0,F.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,F.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,F.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,F.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`语义检索是内置的`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,F.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,F.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,F.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`它不知道的事`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,F.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,F.jsxs)(`li`,{children:[`Agent 可以按你的要求把工作区文件导入知识库(`,(0,F.jsx)(`code`,{children:`knowledge_import`}),`,只接受文本类文件),但`,(0,F.jsx)(`strong`,{children:`不能删除`}),`——删除文档只有你能在“设置 → 知识库”里做。`]})]})]})]})}function fh(){return(0,F.jsxs)(`div`,{className:`help-section-group`,children:[(0,F.jsxs)(`div`,{className:`help-card highlight`,children:[(0,F.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,F.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,F.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[(0,F.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,F.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,F.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,F.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,F.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,F.jsxs)(`li`,{children:[(0,F.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,F.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,F.jsxs)(`div`,{className:`help-steps`,children:[(0,F.jsxs)(`div`,{className:`help-step`,children:[(0,F.jsx)(`span`,{className:`step-num`,children:`1`}),(0,F.jsxs)(`div`,{className:`step-body`,children:[(0,F.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,F.jsxs)(`p`,{children:[`在 `,(0,F.jsx)(`code`,{children:`agents/`}),` 或 `,(0,F.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,F.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-step`,children:[(0,F.jsx)(`span`,{className:`step-num`,children:`2`}),(0,F.jsxs)(`div`,{className:`step-body`,children:[(0,F.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,F.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,F.jsx)(`pre`,{className:`help-code-block`,children:(0,F.jsx)(`code`,{children:`---
|
|
290
|
+
`);a=t.pop();for(let e of t){if(!e)continue;let t=JSON.parse(e);if(t.type===`error`)throw Error(t.error);n(t),t.type===`done`&&(o=!0)}}if(!o)throw Error(`搜索连接提前断开,结果可能不完整。`)}finally{await i.cancel().catch(()=>void 0),i.releaseLock()}}function Rm(e,t){return{path:t?e.startsWith(t+`/`)?e.slice(t.length+1):sm+e:e,name:e.split(`/`).at(-1)??e,text:!0}}function zm(e,t,n){return{...Rm(t?t+`/`+e.path:e.path,n),name:e.name}}function Bm({workspaceId:e,cwd:t=``,directory:n,initialQuery:r=``,onOpen:i,onClose:a,onMode:o,presentation:s}){let[c,l]=(0,u.useState)(r),[d,f]=(0,u.useState)(n??``),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(!0),[y,b]=(0,u.useState)([]),[x,S]=(0,u.useState)(),[C,w]=(0,u.useState)(Im),[T,E]=(0,u.useState)(``),[D,O]=(0,u.useState)(!1),[k,A]=(0,u.useState)(!1),[j,ee]=(0,u.useState)(0),{choose:M,openError:te,opening:N,setOpenError:ne}=Fm(i,a),re=!!hm(c),ie=(0,u.useRef)(null),ae=(0,u.useRef)(null),oe=(0,u.useRef)(void 0),se=(0,u.useId)();(0,u.useEffect)(()=>{ie.current?.focus()},[]),(0,u.useEffect)(()=>{ae.current?.scrollIntoView({block:`nearest`})},[j]),(0,u.useEffect)(()=>{let t=c.trim(),n=new AbortController;if(oe.current=n,b([]),S(void 0),E(``),A(!1),w(Im),ee(0),!e||!t){O(!1);return}if(t.length>256){E(`搜索词不能超过 256 个字符。`),O(!1);return}let r=new URLSearchParams({workspaceId:e,q:t,stream:`1`,ignore:_?`1`:`0`});d&&r.set(`cwd`,d),p.trim()&&r.set(`include`,p.trim()),h.trim()&&r.set(`exclude`,h.trim()),O(!0);let i=setTimeout(()=>{n.signal.aborted||Lm(`/api/files/search?`+r,n.signal,e=>{n.signal.aborted||(e.type===`matches`?b(t=>[...t,...e.hits]):e.type===`done`&&S(e.summary))}).catch(e=>{n.signal.aborted||E(Or(e,`搜索没有完成`))}).finally(()=>{n.signal.aborted||O(!1)})},220);return()=>{n.abort(),clearTimeout(i)}},[c,e,d,p,h,_]);let ce=(0,u.useMemo)(()=>{let e=new Map;return y.slice(0,C).forEach((t,n)=>{let r=e.get(t.path);r?r.push({hit:t,row:n}):e.set(t.path,[{hit:t,row:n}])}),[...e]},[y,C]),le=e=>{e&&M(zm(e,d,t),e.line,e.column)},ue=x?.complete===!1,de={time:`搜索超时`,results:`达到全局结果上限`,line:`部分行太长`,encoding:`部分文件的编码无法读取`,unreadable:`部分文件无法读取`};return(0,F.jsxs)(Vf,{mode:`content`,query:c,onMode:o,onClose:a,presentation:s,children:[(0,F.jsx)(`input`,{ref:ie,className:`quick-open-input`,"data-content-search-input":`1`,value:c,readOnly:N,placeholder:`内容搜索(区分大小写,按字面匹配)`,role:`combobox`,"aria-label":`内容搜索`,"aria-autocomplete":`list`,"aria-controls":se,"aria-expanded":y.length>0,"aria-activedescendant":y[j]?`${se}-${j}`:void 0,onChange:e=>{l(e.target.value),ne(``)},onKeyDown:e=>{e.nativeEvent.isComposing||(e.key===`ArrowDown`?(e.preventDefault(),ee(e=>Math.min(e+1,Math.max(0,Math.min(C,y.length)-1)))):e.key===`ArrowUp`?(e.preventDefault(),ee(e=>Math.max(0,e-1))):e.key===`Enter`&&(e.preventDefault(),le(y[j])))}}),(0,F.jsxs)(`div`,{className:`content-search-controls`,children:[(0,F.jsxs)(`label`,{children:[`范围 `,(0,F.jsxs)(`select`,{value:d,"aria-label":`搜索范围`,onChange:e=>f(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`整个工作区`}),t&&(0,F.jsxs)(`option`,{value:t,children:[`当前目录 · `,t]}),n&&n!==t&&(0,F.jsxs)(`option`,{value:n,children:[`文件夹 · `,n]})]})]}),D&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>{oe.current?.abort(),ie.current?.focus(),O(!1),A(!0)},children:`取消搜索`})]}),(0,F.jsxs)(`details`,{className:`content-search-filters`,children:[(0,F.jsx)(`summary`,{children:`文件筛选`}),(0,F.jsxs)(`label`,{children:[`包含 `,(0,F.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),placeholder:`例如 **/*.cpp`})]}),(0,F.jsxs)(`label`,{children:[`排除 `,(0,F.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),placeholder:`例如 **/generated/**`})]}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>v(e.target.checked)}),` 遵循忽略文件和默认排除`]})]}),(0,F.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":T?`error`:D?`searching`:k?`cancelled`:ue?`partial`:`complete`,children:[T?`搜索失败:`+T:D?`搜索中…`:k?`已取消`:e?ue?`结果不完整`:x?`搜索完成`:`输入要搜索的内容`:`请先选择工作区`,(y.length>0||x)&&` · ${y.length} 条命中`]}),re&&(0,F.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>o(`path`,c),children:`按文件路径打开`}),ue&&(0,F.jsx)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:x.reasons.map(e=>de[e]??e).join(`;`)}),x?.complete&&!y.length&&(0,F.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`没有匹配的行`}),te&&(0,F.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:te}),(0,F.jsx)(`ul`,{id:se,className:`quick-open-results content-search-results`,role:`listbox`,"aria-label":`正文搜索结果`,children:ce.map(([e,t])=>(0,F.jsxs)(`li`,{className:`content-search-group`,role:`presentation`,children:[(0,F.jsx)(`div`,{className:`content-search-file`,title:e,children:e}),t.map(({hit:e,row:t})=>(0,F.jsxs)(`button`,{id:`${se}-${t}`,ref:t===j?ae:void 0,type:`button`,role:`option`,tabIndex:-1,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${j===t?` quick-open-result-active`:``}`,"aria-selected":j===t,"aria-label":`${e.path}:${e.line}:${e.column} ${e.text}`,onMouseEnter:()=>ee(t),onClick:()=>le(e),children:[(0,F.jsxs)(`span`,{title:`${e.path}:${e.line}:${e.column}`,className:`content-search-result-position`,children:[e.line,`:`,e.column]}),(0,F.jsx)(`small`,{title:e.text,children:e.text})]},e.line))]},e))}),y.length>C&&(0,F.jsxs)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-content-search-more":`1`,onClick:()=>{C+Im>=y.length&&ie.current?.focus(),w(e=>e+Im)},children:[`显示更多结果(已显示 `,C,` / `,y.length,`)`]})]})}function Vm({workspaceId:e,cwd:t=``,connected:n,initialQuery:r=``,onOpen:i,onClose:a,onMode:o,presentation:s}){let[c,l]=(0,u.useState)(r),[d,f]=(0,u.useState)(0),[p,m]=(0,u.useState)(0),[h,g]=(0,u.useState)(),_=(0,u.useRef)(void 0),v=(0,u.useRef)(void 0),{choose:y,openError:b,opening:x,setOpenError:S}=Fm(i,a),C=(0,u.useRef)(null),w=(0,u.useRef)(null),T=gm(c),E=e?hm(c):void 0,D=!!E;(0,u.useEffect)(()=>{if(!n||!e)return;let r=new AbortController,i=dm(e,``,t)+`&quick=1&refresh=1`;return _.current=nm(i,{cache:`no-store`,signal:r.signal}).catch(()=>void 0),()=>{r.abort(),_.current=void 0}},[n,e,t]),(0,u.useEffect)(()=>{if(!n||!e||D)return;let r=new AbortController,i=r.signal,a=dm(e,T,t)+`&quick=1&page=${p}`,o,s=async e=>{try{let t=e?await _.current:void 0;if(i.aborted)return;let n=e&&!T&&t?t:await nm(a,{cache:`no-store`,signal:i});if(i.aborted)return;g({query:T,page:p,response:n}),n.indexed||(o=setTimeout(()=>void s(!1),350))}catch(e){i.aborted||g({query:T,page:p,error:Or(e,`文件查找没有完成`)})}};return o=setTimeout(()=>void s(!0),T?120:0),()=>{r.abort(),clearTimeout(o)}},[n,e,t,T,D,p]);let O=h?.query===T&&h.page===p?h:void 0,k=O?.response,A=(0,u.useMemo)(()=>{if(E)return[E];let t=k?.hits.map(e=>({...e,text:null}))??[];return p>0||e&&T.includes(`/`)&&!T.endsWith(`/`)&&!T.split(`/`).includes(`..`)&&!t.some(e=>e.path.toLowerCase()===T.toLowerCase())&&(k?.total?t.push(mm(T)):t.unshift(mm(T))),t},[E,T,k,p,e]),j=e=>{v.current=void 0,m(e),g(void 0),f(0),S(``),C.current?.focus()},ee=!D&&!(!e||O?.error||k?.indexed);return(0,u.useEffect)(()=>{let e=v.current;e===void 0||ee||(v.current=void 0,y(A[Math.min(e,A.length-1)]))},[ee,A,y]),(0,u.useEffect)(()=>{C.current?.focus()},[]),(0,u.useEffect)(()=>{w.current?.scrollIntoView({block:`nearest`})},[d]),(0,F.jsxs)(Vf,{mode:`path`,query:c,onMode:o,onClose:a,presentation:s,children:[(0,F.jsx)(`input`,{ref:C,className:`quick-open-input`,"data-quick-open-input":`1`,value:c,readOnly:x,placeholder:`快速打开:输入文件名或路径`,"aria-label":`快速打开文件路径`,onChange:e=>{let t=e.target.value;v.current=void 0,(gm(t)!==T||p!==0)&&g(void 0),l(t),m(0),f(0),S(``)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`)e.preventDefault(),f(e=>Math.min(e+1,Math.max(0,A.length-1)));else if(e.key===`ArrowUp`)e.preventDefault(),f(e=>Math.max(e-1,0));else if(e.key===`Enter`){e.preventDefault();let t=A[Math.min(d,A.length-1)],n=k?.hits.some(e=>e.path===t?.path&&[e.name,e.path].some(e=>e.toLowerCase()===T.toLowerCase()));ee&&!n?v.current=d:y(t)}}}}),(0,F.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"aria-live":`polite`,"data-quick-open-status":D||k?.indexed&&!k.incomplete?`complete`:`partial`,children:[D?`按 Enter 打开指定文件`:e?n?O?.error||(ee?`正在检查文件索引…`:T?k?.incomplete?`索引不完整 · ${k.total} 条命中`:k?.total?`${k.total} 条命中${p?` · 第 ${p+1} 页`:``}`:A.length?`近似路径`:`没有匹配的文件名或路径`:`输入文件名或路径以查找当前目录中的文件`):`等待连接…`:`请先选择工作区`,` · Esc 关闭`]}),b&&(0,F.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:b}),(0,F.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:A.map((e,t)=>(0,F.jsx)(`li`,{children:(0,F.jsxs)(`button`,{ref:t===d?w:void 0,type:`button`,"data-quick-open-result":e.path,className:t===d?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===d,onMouseMove:()=>f(t),onClick:()=>{v.current=void 0,y(e)},children:[(0,F.jsx)(`span`,{title:e.name,children:e.name}),(0,F.jsx)(`small`,{title:e.path,children:e.path})]})},e.path))}),T&&k?.indexed&&(p>0||k.truncated)&&(0,F.jsxs)(`div`,{className:`quick-open-pages`,"aria-label":`文件搜索翻页`,children:[p>0&&(0,F.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>j(p-1),children:`上一页`}),k.truncated&&(0,F.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-quick-open-next-page":!0,onClick:()=>j(p+1),children:`下一页`})]})]})}function Hm({workspaceId:e,workspaceName:t,cwd:n,connected:r,onOpen:i,onSession:a,active:o=!0}){let[s,c]=(0,u.useState)(`content`),[l,d]=(0,u.useState)(``),f=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(!o)return;let e=requestAnimationFrame(()=>f.current?.parentElement?.querySelector(`[data-content-search-input], [data-quick-open-input], [data-session-search-input]`)?.focus());return()=>cancelAnimationFrame(e)},[o,s]);let p={workspaceId:e,cwd:n,initialQuery:l,presentation:`sidebar`,onClose:()=>{},onMode:(e,t)=>{d(t),c(e)}};return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{ref:f,className:`workbench-search-heading`,children:[(0,F.jsx)(`strong`,{children:`搜索`}),(0,F.jsx)(`span`,{title:t,children:t??`请选择工作区`})]}),s===`content`?(0,F.jsx)(Bm,{...p,onOpen:i}):s===`path`?(0,F.jsx)(Vm,{...p,connected:r,onOpen:i}):(0,F.jsx)(Hf,{...p,onOpen:a})]})}function Um(e,t,n,r,i){let a=Number.isFinite(t)&&t>0?t:n,o=e.map(e=>({id:e.id,width:Math.min(a,Math.max(Math.min(n,a),Number.isFinite(e.width)?e.width:n))}));if(o.every(e=>e.width<=i.width)){let t=[];for(let n=0;n<e.length;n+=Math.max(1,i.perRow))t.push({ids:e.slice(n,n+Math.max(1,i.perRow)).map(e=>e.id),width:Math.min(a,i.width)});return t}let s=[],c=[],l=0,u=()=>{c.length&&(s.push({ids:c.map(e=>e.id),width:Math.min(a/c.length,Math.max(r,l))}),c=[],l=0)};for(let e of o)c.length&&Math.max(l,e.width)*(c.length+1)>a+.1&&u(),c.push(e),l=Math.max(l,e.width);return u(),s}function Wm(e,t,n=88,r=200){let i=Math.max(0,Math.floor(e));if(!Number.isFinite(t)||t<=0)return{perRow:Math.max(1,i),width:n};if(i===0)return{perRow:1,width:n};if(i===1)return{perRow:1,width:Math.min(r,t)};let a=t/i;if(a>=n)return{perRow:i,width:Math.min(a,r)};for(let e=2;e<=i;e+=1){let a=Math.ceil(i/e),o=t/a;if(o>=n)return{perRow:a,width:Math.min(o,r)}}return{perRow:1,width:n}}function Gm(e,t,n=88,r=200){let[i,a]=(0,u.useState)(()=>Wm(e,0,n,r)),[o,s]=(0,u.useState)(null),c=(0,u.useCallback)(()=>{let i=Wm(e,t,n,r);s({count:e,containerWidth:t}),a(e=>e.perRow===i.perRow&&e.width===i.width?e:i)},[e,t,n,r]),l=(0,u.useRef)(t);(0,u.useLayoutEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let d=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let t=d.current;d.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function Km({tabs:e,activeId:t,onSelect:n,onClose:r,onActivate:i,ariaLabel:a,minWidth:o=88,maxWidth:s=200,prefix:c=`workspace-tab`,idPrefix:l=c,className:d}){let f=(0,u.useRef)(null),[p,m]=(0,u.useState)(0),{layout:h,frozen:g,recompute:_}=Gm(e.length,p,o,s);(0,u.useLayoutEffect)(()=>{let e=f.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&m(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let[v,y]=(0,u.useState)({}),[b,x]=(0,u.useState)([]),S=JSON.stringify(e.map(e=>[e.id,e.label]));(0,u.useLayoutEffect)(()=>{let e=f.current;if(!e)return;let t=()=>{let t={};for(let n of e.querySelectorAll(`[role=tab]`)){let e=n.querySelector(`.workspace-tab-label`),r=n.id.slice(l.length+1);if(!e||!r)continue;let i=document.createRange();i.selectNodeContents(e);let a=n.getBoundingClientRect().width-e.getBoundingClientRect().width;t[r]=Math.ceil(i.getBoundingClientRect().width+a+2)}y(e=>JSON.stringify(e)===JSON.stringify(t)?e:t)};return t(),document.fonts?.addEventListener(`loadingdone`,t),()=>document.fonts?.removeEventListener(`loadingdone`,t)},[S,p,l]);let C=Um(e.map(e=>({id:e.id,width:v[e.id]??o})),p,o,s,h),w=JSON.stringify(C);(0,u.useLayoutEffect)(()=>{g||x(e=>JSON.stringify(e)===w?e:C)},[g,w]);let T=b.length&&e.every(e=>b.some(t=>t.ids.includes(e.id)))?b:C,E=0,D=T.map(t=>{let n=g?e.slice(E,E+=t.ids.length):t.ids.flatMap(t=>{let n=e.find(e=>e.id===t);return n?[n]:[]});return{...t,tabs:n}}).filter(e=>e.tabs.length),O=D.map(e=>e.tabs),k=D.map(e=>e.width),A=(e,t)=>t===void 0?{}:{[`data-${c}-${e}`]:t},j=e.filter(e=>e.kind===`file`).length,ee=e.filter(e=>e.kind===`session`||!e.kind).length,M=t=>({[`data-${t}-strip`]:`1`,...g?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?j:t===`session-tab`?ee:e.length,[`data-${t}-min`]:o,[`data-${t}-max`]:s,[`data-${t}-per-row`]:O[0]?.length??h.perRow,[`data-${t}-width`]:Math.round((k[0]??h.width)*100)/100}),te=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&_()},N=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&_()};(0,u.useEffect)(()=>{if(!g)return;let e=f.current;if(!e)return;let t=t=>{let n=e.getBoundingClientRect();t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom||_()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[g,_]);let ne=[`${c}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,d].filter(Boolean).join(` `);return(0,F.jsx)(`div`,{ref:f,className:ne,role:`tablist`,"aria-label":a??`工作区标签页`,...A(`strip`,`1`),...M(`workspace-tab`),...M(`session-tab`),...M(`file-tab`),style:{"--tab-w":`${h.width}px`},onMouseEnter:te,onMouseLeave:N,children:O.map((a,o)=>(0,F.jsx)(`div`,{className:`${c}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,...A(`row`,o),"data-tab-row-width":k[o],children:a.map(a=>{let s={width:k[o]},u=a.id===t||a.rawId!==void 0&&a.rawId===t,d=a.title?a.title.includes(a.label)?a.title:`${a.label}\n${a.title}`:a.label,f=a.kind,p=a.rawId??a.id,m=e.findIndex(e=>e.id===a.id),h=[c,u?`${c}-active`:``,`workspace-tab`,u?`workspace-tab-active`:``,f?`${f}-tab`:``,f&&u?`${f}-tab-active`:``,a.preview?`${c}-preview`:``,a.preview?`workspace-tab-preview`:``,a.preview&&f?`${f}-tab-preview`:``].filter(Boolean).join(` `);return(0,F.jsxs)(`div`,{role:`tab`,id:`${l}-${a.id}`,"aria-selected":u,"aria-controls":`${l}-panel-${a.id}`,tabIndex:u?0:-1,className:h,...A(`id`,p),...A(`index`,m),...u?A(`active`,`1`):{},...A(`closable`,a.closable===!1?`0`:`1`),...f?{"data-tab-kind":f}:{},...a.preview?{"data-tab-preview":`1`}:{},...f===`session`||!f?{"data-session-tab-id":p,"data-session-tab-index":m,...u?{"data-session-tab-active":`1`}:{},"data-session-tab-closable":a.closable===!1?`0`:`1`,...a.preview?{"data-session-tab-preview":`1`}:{}}:{},...f===`file`?{"data-file-tab-id":p,"data-file-tab-index":m,...u?{"data-file-tab-active":`1`}:{},"data-file-tab-closable":a.closable===!1?`0`:`1`}:{},...f===`diff`?{"data-diff-tab-id":p,"data-diff-tab-index":m,...u?{"data-diff-tab-active":`1`}:{},"data-diff-tab-closable":a.closable===!1?`0`:`1`}:{},title:d,style:{width:s.width,boxSizing:`border-box`},onClick:()=>n?.(a.id),onDoubleClick:i?()=>i(a.id):void 0,onAuxClick:e=>{e.button===1&&(e.preventDefault(),e.stopPropagation(),a.closable!==!1&&r&&r(a.id))},onMouseDown:e=>{e.button===1&&e.preventDefault()},onKeyDown:t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)return;t.preventDefault();let r=t.key===`ArrowRight`?1:-1,i=e[(e.findIndex(e=>e.id===a.id)+r+e.length)%e.length];i&&(document.getElementById(`${l}-${i.id}`)?.focus(),n?.(i.id))},children:[a.icon&&(0,F.jsx)(`span`,{className:`${c}-icon workspace-tab-icon`,children:a.icon}),a.badge,(0,F.jsx)(`span`,{className:`${c}-label workspace-tab-label ${f?`${f}-tab-label`:``}`,title:d,...A(`label`,p),...f===`session`||!f?{"data-session-tab-label":p}:{},...f===`file`?{"data-file-tab-label":p}:{},...f===`diff`?{"data-diff-tab-label":p}:{},children:a.label}),a.closable!==!1&&r&&(0,F.jsx)(`button`,{type:`button`,className:`${c}-close workspace-tab-close ${f?`${f}-tab-close`:``}`,...A(`close`,p),...f===`session`||!f?{"data-session-tab-close":p}:{},...f===`file`?{"data-file-tab-close":p}:{},...f===`diff`?{"data-diff-tab-close":p}:{},onClick:e=>{e.stopPropagation(),r(a.id)},onDoubleClick:e=>{e.stopPropagation()},title:`关闭 ${d}`,"aria-label":`关闭 ${d}`,children:`×`})]},a.id)})},`row_${o}`))})}var qm=25,Jm=75;function Ym({share:e,onShare:t}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),a=e=>t(Math.round(Math.min(Jm,Math.max(qm,e))));return(0,u.useLayoutEffect)(()=>{let e=n.current?.parentElement;if(!e)return;let t=()=>i(getComputedStyle(e).flexDirection===`column`);t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]),(0,F.jsx)(`div`,{ref:n,className:`workbench-split-divider`,"data-workbench-split-divider":!0,role:`separator`,"aria-label":`调整拆分大小`,"aria-orientation":r?`horizontal`:`vertical`,"aria-valuenow":e,"aria-valuemin":qm,"aria-valuemax":Jm,tabIndex:0,onPointerDown:e=>{e.button===0&&(e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{if(!e.currentTarget.hasPointerCapture(e.pointerId))return;let t=e.currentTarget.parentElement?.getBoundingClientRect();t&&a(r?(e.clientY-t.top)/t.height*100:(e.clientX-t.left)/t.width*100)},onKeyDown:t=>{let n=t.key===(r?`ArrowDown`:`ArrowRight`),i=t.key===(r?`ArrowUp`:`ArrowLeft`);if(n||i)a(e+(n?5:-5));else if(t.key===`Home`)a(qm);else if(t.key===`End`)a(Jm);else return;t.preventDefault()}})}function Xm({tabs:e,selected:t,onSelect:n,onPin:r,onCloseTab:i,onClose:a,children:o}){let s=e.find(e=>e.id===t);return(0,F.jsxs)(`section`,{className:`workbench-split-pane`,"data-workbench-split-pane":!0,"aria-label":`拆分区`,children:[(0,F.jsxs)(`div`,{className:`workbench-split-bar`,children:[(0,F.jsxs)(`select`,{"aria-label":`拆分区标签页`,"data-workbench-split-tabs":!0,value:t??``,onChange:e=>n(e.target.value),title:s?.title,"data-workbench-split-preview":s?.preview||void 0,children:[(0,F.jsx)(`option`,{value:``,disabled:!0,children:`选择文件或差异`}),e.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),t&&s?.preview&&(0,F.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`固定标签页`,"aria-label":`固定拆分区标签页`,onClick:()=>r(t),children:(0,F.jsx)(Gr,{name:`pin`})}),t&&(0,F.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`关闭此标签页`,"aria-label":`关闭拆分区标签页`,onClick:()=>i(t),children:(0,F.jsx)(Gr,{name:`close`})}),(0,F.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,"data-close-workbench-split":!0,title:`合并主区`,"aria-label":`合并主区`,onClick:a,children:(0,F.jsx)(Gr,{name:`split`})})]}),o??(0,F.jsx)(`p`,{className:`rail-empty`,children:`从文件或 Git 面板打开一个文件或差异。`})]})}function Zm(e,t){if(e.entries[e.index]?.key===t.key)return e;let n=[...e.entries.slice(0,e.index+1),t].slice(-100);return{entries:n,index:n.length-1}}function Qm(e,t,n,r){for(let i=t+n;i>=0&&i<e.entries.length;i+=n)if(r(e.entries[i]))return i;return-1}var $m={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},eh={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},th={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},nh={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function rh(e){let t=Math.max(0,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60)%60,i=Math.floor(t/3600),a=e=>String(e).padStart(2,`0`);return i>0?`${i}h ${a(r)}:${a(n)}`:`${r}:${a(n)}`}function ih(e){let t=e.status===`running`,[n,r]=(0,u.useState)(0);(0,u.useEffect)(()=>{if(!t)return;r(Date.now());let e=window.setInterval(()=>r(Date.now()),200);return()=>window.clearInterval(e)},[t,e.startedAt]);let i=Date.parse(e.startedAt);if(Number.isFinite(i)){if(!t){let t=Date.parse(e.finishedAt??``);return Number.isFinite(t)?t-i:void 0}return n>0?n-i:void 0}}function ah({step:e,names:t}){let n=e.attempts.length,r=e.attempts[n-1],i=t.get(e.agentId)||e.agentId,a=e.label?.trim()||i;return(0,F.jsxs)(`li`,{className:`workflow-step workflow-step-${e.status}`,"data-workflow-step":e.index+1,"data-workflow-step-status":e.status,"data-workflow-step-agent":e.agentId,"data-workflow-step-attempts":n,children:[(0,F.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:th[e.status]}),(0,F.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,F.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,F.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,F.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,F.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:$m[e.status]}),e.status===`failed`&&r?.error&&(0,F.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,title:kr(r.error),children:Or(r.error,`这一步没有完成。`)})]})}function oh({nodes:e,steps:t,names:n}){return(0,F.jsx)(`ol`,{className:`workflow-steps`,children:e.map((e,r)=>{if(e.kind===`step`){let r=t[e.stepIndex];return r?(0,F.jsx)(ah,{step:r,names:n},`step-${e.stepIndex}`):null}return e.kind===`loop`?(0,F.jsxs)(`li`,{className:`workflow-node workflow-loop`,"data-workflow-loop":!0,"data-workflow-loop-rounds":e.rounds.length,"data-workflow-loop-max":e.max,"data-workflow-until":e.until,children:[(0,F.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`↻`}),(0,F.jsx)(`strong`,{children:`循环`}),(0,F.jsxs)(`span`,{children:[`直到「`,e.until,`」`]}),(0,F.jsxs)(`span`,{"data-workflow-loop-progress":!0,children:[`已跑 `,e.rounds.length,`/`,e.max,` 轮`]})]}),e.rounds.map(e=>(0,F.jsxs)(`section`,{className:`workflow-round`,"data-workflow-round":e.n,"data-workflow-round-met":e.untilMet?`true`:`false`,children:[(0,F.jsxs)(`div`,{className:`workflow-round-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:e.untilMet?`✓`:`○`}),`第 `,e.n,` 轮 · `,e.untilMet?`条件满足`:`条件未满足`]}),(0,F.jsx)(oh,{nodes:e.nodes,steps:t,names:n})]},e.n))]},`loop-${r}`):(0,F.jsxs)(`li`,{className:`workflow-node workflow-foreach`,"data-workflow-foreach":!0,"data-workflow-foreach-count":e.items.length,children:[(0,F.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`≡`}),(0,F.jsx)(`strong`,{children:`逐项执行`}),(0,F.jsxs)(`span`,{children:[e.items.length,` 个由 primary 给出的项目`]})]}),e.iterations.map((e,r)=>(0,F.jsxs)(`section`,{className:`workflow-item`,"data-workflow-item":r+1,"data-workflow-item-value":e.item,children:[(0,F.jsxs)(`div`,{className:`workflow-item-head`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),`第 `,r+1,` 项 · `,e.item]}),(0,F.jsx)(oh,{nodes:e.nodes,steps:t,names:n})]},`${r}-${e.item}`))]},`foreach-${r}`)})})}function sh({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=ih(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,F.jsxs)(`article`,{className:`workflow-card workflow-${e.status}`,"data-workflow-card":e.id,"data-workflow-status":e.status,"data-workflow-steps":e.steps.length,"data-workflow-current":e.currentIndex+1,children:[(0,F.jsxs)(`div`,{className:`workflow-head`,children:[(0,F.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,F.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,F.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,F.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:eh[e.status]??`未知状态`}),(0,F.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:nh[e.onFailure]??e.onFailure}),a!==void 0&&(0,F.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,rh(a)]}),i&&(0,F.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),e.nodes?(0,F.jsx)(oh,{nodes:e.nodes,steps:e.steps,names:t}):(0,F.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,F.jsx)(ah,{step:e,names:t},e.index))})]})}var ch=[{id:`agents`,label:`智能体与创建`,icon:`🤖`,title:`Agent 智能体系统与创建指南`,description:`了解 Super Pi 的角色设定机制,以及如何一步步创建你自己的自定义 Agent。`},{id:`workspace`,label:`工作区与会话`,icon:`🗂️`,title:`工作区与多会话管理`,description:`高效管理本地代码仓库、独立会话标签页与多模态图文输入。`},{id:`subagents`,label:`子任务与编排`,icon:`⚡`,title:`子智能体委托与顺序编排使用指南`,description:`让主 Agent 安排分工、交接结果,并查看进度、处理失败与停止任务。`},{id:`model-policy`,label:`模型使用规则`,icon:`🔒`,title:`模型过滤规则(按工作区限制可用模型)`,description:`用正则规则限定哪些工作区只能用哪些模型,防止敏感代码被发到不该用的模型上。`},{id:`memory`,label:`主动记忆`,icon:`🧠`,title:`主动记忆与技能经验`,description:`让 Super Pi 在得到明确证据后保存长期事实、用户偏好和可复用工作方法。`},{id:`knowledge`,label:`知识库`,icon:`📚`,title:`工作区知识库`,description:`导入规范与设计文档,让 Agent 检索原文作答,而不是凭记忆编造。`},{id:`feishu`,label:`飞书`,icon:`📄`,title:`飞书云文档的读写`,description:`让 Agent 读一篇飞书文档、写回结论。接入方式、连接步骤与常见问题。`},{id:`tools`,label:`侧边栏工具`,icon:`🧩`,title:`全局工具:开发、导出与导入`,description:`让 Agent 写一个工具,用一个文件分享给别人,导入前先看清它会做什么。`},{id:`cli`,label:`指令与快捷键`,icon:`⌨️`,title:`Pi 终端命令与键盘快捷操作`,description:`利用 Pi 终端斜杠指令控制服务生命周期,掌握常用快捷键提升效率。`},{id:`themes`,label:`外观与主题`,icon:`🎨`,title:`界面主题与个性化显示`,description:`内置 4 款专业高对比度主题,针对不同环境提供舒适体验。`}];function lh({onClose:e}){let[t,n]=(0,u.useState)(`agents`);(0,u.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=ch.find(e=>e.id===t)??ch[0];return(0,F.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,F.jsxs)(`div`,{className:`picker settings-window help-window`,"data-help-window":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-labelledby":`help-window-title`,children:[(0,F.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,F.jsxs)(`div`,{className:`help-head-title`,children:[(0,F.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,F.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,F.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,F.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,F.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,F.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),ch.map(e=>(0,F.jsxs)(`button`,{type:`button`,id:`help-tab-${e.id}`,className:`settings-category help-category`,role:`tab`,"aria-selected":e.id===r.id,"aria-controls":`help-panel`,tabIndex:e.id===r.id?0:-1,onClick:()=>n(e.id),children:[(0,F.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,F.jsx)(`span`,{children:e.label})]},e.id))]}),(0,F.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,F.jsxs)(`div`,{className:`help-panel-header`,children:[(0,F.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,F.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,F.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,F.jsx)(fh,{}),r.id===`workspace`&&(0,F.jsx)(ph,{}),r.id===`subagents`&&(0,F.jsx)(hh,{}),r.id===`model-policy`&&(0,F.jsx)(mh,{}),r.id===`memory`&&(0,F.jsx)(uh,{}),r.id===`knowledge`&&(0,F.jsx)(dh,{}),r.id===`feishu`&&(0,F.jsx)(gh,{}),r.id===`tools`&&(0,F.jsx)(_h,{}),r.id===`cli`&&(0,F.jsx)(vh,{}),r.id===`themes`&&(0,F.jsx)(yh,{})]}),(0,F.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function uh(){return(0,F.jsxs)(`div`,{className:`help-section-group`,children:[(0,F.jsxs)(`div`,{className:`help-card highlight`,children:[(0,F.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,F.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,F.jsx)(`code`,{children:`memory`}),` 和 `,(0,F.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,F.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,F.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`权限与审批`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,F.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,F.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function dh(){return(0,F.jsxs)(`div`,{className:`help-section-group`,children:[(0,F.jsxs)(`div`,{className:`help-card highlight`,children:[(0,F.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,F.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库的内容来自工作区里真实存在的文档。`})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`怎么用`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文、手动填写相对路径,或者直接对 Agent 说“把某某文件加入知识库”——它会用 `,(0,F.jsx)(`code`,{children:`knowledge_import`}),` 导入,走的是同一条服务端校验。`]}),(0,F.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,F.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,F.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,F.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`语义检索是内置的`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,F.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,F.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,F.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`它不知道的事`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,F.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,F.jsxs)(`li`,{children:[`Agent 可以按你的要求把工作区文件导入知识库(`,(0,F.jsx)(`code`,{children:`knowledge_import`}),`,只接受文本类文件),但`,(0,F.jsx)(`strong`,{children:`不能删除`}),`——删除文档只有你能在“设置 → 知识库”里做。`]})]})]})]})}function fh(){return(0,F.jsxs)(`div`,{className:`help-section-group`,children:[(0,F.jsxs)(`div`,{className:`help-card highlight`,children:[(0,F.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,F.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,F.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,F.jsxs)(`ul`,{className:`help-list`,children:[(0,F.jsxs)(`li`,{children:[(0,F.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,F.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,F.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,F.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,F.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,F.jsxs)(`li`,{children:[(0,F.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,F.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,F.jsxs)(`div`,{className:`help-steps`,children:[(0,F.jsxs)(`div`,{className:`help-step`,children:[(0,F.jsx)(`span`,{className:`step-num`,children:`1`}),(0,F.jsxs)(`div`,{className:`step-body`,children:[(0,F.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,F.jsxs)(`p`,{children:[`在 `,(0,F.jsx)(`code`,{children:`agents/`}),` 或 `,(0,F.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,F.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,F.jsxs)(`div`,{className:`help-step`,children:[(0,F.jsx)(`span`,{className:`step-num`,children:`2`}),(0,F.jsxs)(`div`,{className:`step-body`,children:[(0,F.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,F.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,F.jsx)(`pre`,{className:`help-code-block`,children:(0,F.jsx)(`code`,{children:`---
|
|
291
291
|
name: 系统架构师
|
|
292
292
|
description: 专注于系统架构拆解、模块解耦与技术选型分析
|
|
293
293
|
---
|
|
@@ -312,39 +312,39 @@ pi update npm:@evandu/super-pi
|
|
|
312
312
|
|
|
313
313
|
# 独立启动(无需 Pi 环境)
|
|
314
314
|
npx @evandu/super-pi`})})]}),(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`🎯 键盘快捷键`}),(0,F.jsxs)(`div`,{className:`help-command-table`,children:[(0,F.jsxs)(`div`,{className:`cmd-row`,children:[(0,F.jsx)(`code`,{children:`Enter`}),(0,F.jsx)(`span`,{children:`发送对话消息`})]}),(0,F.jsxs)(`div`,{className:`cmd-row`,children:[(0,F.jsx)(`code`,{children:`Shift + Enter`}),(0,F.jsx)(`span`,{children:`输入框内换行`})]}),(0,F.jsxs)(`div`,{className:`cmd-row`,children:[(0,F.jsx)(`code`,{children:`Esc`}),(0,F.jsx)(`span`,{children:`快速关闭当前顶层弹窗(使用指南、设置、工作区选择器等)`})]})]})]})]})}function yh(){return(0,F.jsx)(`div`,{className:`help-section-group`,children:(0,F.jsxs)(`div`,{className:`help-card`,children:[(0,F.jsx)(`h4`,{children:`🎨 4 款主题,来自 VSCode 流行主题`}),(0,F.jsxs)(`div`,{className:`help-theme-list`,children:[(0,F.jsxs)(`div`,{className:`help-theme-item`,children:[(0,F.jsx)(`strong`,{children:`🟣 Dracula`}),(0,F.jsx)(`p`,{children:`紫调暗色,饱满对比,适合夜间专注编程。`})]}),(0,F.jsxs)(`div`,{className:`help-theme-item`,children:[(0,F.jsx)(`strong`,{children:`🟠 Monokai`}),(0,F.jsx)(`p`,{children:`暖调暗色,橙红点缀,经典编辑器风格。`})]}),(0,F.jsxs)(`div`,{className:`help-theme-item`,children:[(0,F.jsx)(`strong`,{children:`🟡 Solarized Light`}),(0,F.jsx)(`p`,{children:`暖黄米色调,柔和护眼,适合长时间阅读。`})]}),(0,F.jsxs)(`div`,{className:`help-theme-item`,children:[(0,F.jsx)(`strong`,{children:`🔵 GitHub Light`}),(0,F.jsx)(`p`,{children:`冷调浅色,中性清晰,日常办公首选。`})]})]}),(0,F.jsxs)(`p`,{className:`help-hint`,children:[`可在左侧栏底部的 `,(0,F.jsx)(`strong`,{children:`⚙ 设置`}),` 中一键切换主题,设置会自动持久化保存在本地。`]})]})})}function bh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(``),[i,a]=(0,u.useState)(!1);return(0,u.useEffect)(()=>{window.superPiDesktop?.status().then(t).catch(()=>r(`无法读取桌面运行状态`))},[]),(0,F.jsx)(`div`,{className:`server-connections-panel`,children:(0,F.jsxs)(`section`,{className:`server-connection-card`,children:[(0,F.jsx)(`h4`,{children:window.superPiDesktop?`Super Pi 桌面端`:`桌面端与浏览器共用同一套工作台`}),(0,F.jsx)(`p`,{children:`完整 npm 包已包含桌面端,无需另装增强包。桌面窗口和浏览器连接同一本地入口时,共用 SSH 托管列表、模型配置、会话与文件;已有服务的直接连接列表保存在各自浏览器中。`}),e?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:e.autoStart,disabled:i,onChange:async n=>{let i=n.target.checked;a(!0),r(``);try{let n=await window.superPiDesktop.setAutoStart(i);t({...e,autoStart:n.autoStart})}catch{r(`无法修改开机自启,请检查系统权限`)}finally{a(!1)}}}),`登录系统后自动启动并保持后台运行`]}),(0,F.jsx)(`p`,{children:`关闭窗口会隐藏到托盘;本地管理服务与 SSH 连接继续运行。`}),(0,F.jsxs)(`div`,{className:`server-connection-actions`,children:[(0,F.jsx)(`button`,{type:`button`,onClick:()=>void window.superPiDesktop?.openBrowser(),children:`在浏览器打开同一工作台`}),(0,F.jsx)(`button`,{type:`button`,onClick:()=>void window.superPiDesktop?.minimize(),children:`隐藏到托盘`})]})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{children:`在管理电脑运行:`}),(0,F.jsx)(`code`,{children:`super_pi desktop`}),(0,F.jsxs)(`p`,{children:[`首次启动需要下载桌面运行时。服务器只需要安装轻量的 `,(0,F.jsx)(`code`,{children:`@evandu/super-pi-server`}),`;通过 SSH 托管时会自动选择轻量包。`]})]}),n&&(0,F.jsx)(`p`,{role:`alert`,className:`server-connection-error`,children:n})]})})}function xh({name:e,children:t}){let{settingsServer:n,connections:r}=ue(),i=r.find(e=>e.id===n);if(!i?.managed||i.legacy)return(0,F.jsx)(F.Fragment,{children:t});let a=r.find(e=>e.id===`entry`)?.name??`当前入口`;return(0,F.jsxs)(`section`,{className:`settings-section`,"data-entry-integration":e,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[e,` · 入口配置`]}),(0,F.jsxs)(`p`,{children:[`「`,i.name,`」通过已配对的服务通道使用「`,a,`」的 `,e,` 连接与额度。请在入口完成配置。`]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`入口和托管服务都需要支持共享连接,旧版本请先通过软件更新升级。`}),(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,onClick:()=>me(`entry`),children:[`管理入口的 `,e]})]})}function Sh({workspaceId:e,onClose:t}){let[n,r]=(0,u.useState)(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(!1),[c,l]=(0,u.useState)(`memory`),[d,f]=(0,u.useState)(``),[p,m]=(0,u.useState)(),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)({budget:``,interval:``}),[y,b]=(0,u.useState)(!1),[x,S]=(0,u.useState)(!1),[C,w]=(0,u.useState)([]),T=`${e}:${h}:${y}`,E=(0,u.useRef)(T);E.current=T;let D=(0,u.useRef)(0);async function O(t){if(!e)return;let n=++D.current;s(!0),a(``);try{let i=await Pe(`/api/memory?workspaceId=${encodeURIComponent(e)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t??{},contextConversationId:h||void 0,includeArchived:y})}),a=await i.json();if(!i.ok)throw Error(a.error);return E.current!==T||n!==D.current?!1:(r(a),t||v({budget:String(a.settings.recallBudgetTokens),interval:String(a.settings.reviewInterval)}),(c===`role`&&!a.context.agentId||c===`tree`&&!a.context.treeId||c===`session`&&!a.context.conversationId)&&l(`memory`),!0)}catch(e){return E.current===T&&n===D.current&&a(Or(e,`记忆读取失败。`)),!1}finally{E.current===T&&n===D.current&&s(!1)}}return(0,u.useEffect)(()=>{g(``)},[e]),(0,u.useEffect)(()=>{r(void 0),m(void 0),f(``),w([]),S(!1),!h&&[`role`,`tree`,`session`].includes(c)&&l(`memory`),O()},[e,h,y]),e?(0,F.jsxs)(`section`,{"data-memory-panel":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`工程经验跨项目共享,每条附来源和适用条件。任务结论在会话树内共享,会话笔记保持独立。每轮按相关性召回。`})}),i&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:i}),n&&(0,F.jsxs)(`fieldset`,{disabled:o,className:`settings-memory-fieldset`,children:[(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`主动记忆机制配置`}),(0,F.jsxs)(`div`,{className:`settings-memory-switches`,children:[(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:n.settings.enabled,onChange:e=>void O({action:`configure`,settings:{...n.settings,enabled:e.target.checked}})}),`启用主动记忆`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:n.settings.writeApproval,onChange:e=>void O({action:`configure`,settings:{...n.settings,writeApproval:e.target.checked}})}),`Agent 写入均需审批`]})]}),(0,F.jsxs)(`label`,{className:`settings-memory-interval-label`,children:[`每轮召回预算(token 上限估算)`,(0,F.jsx)(`input`,{"aria-label":`召回预算`,type:`number`,min:`2048`,max:`16000`,className:`settings-dir-input settings-interval-input`,value:_.budget,onChange:e=>v({..._,budget:e.target.value})}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!_.budget.trim()||!Number.isInteger(Number(_.budget))||Number(_.budget)<2048||Number(_.budget)>16e3,onClick:()=>void O({action:`configure`,settings:{...n.settings,recallBudgetTokens:Number(_.budget)}}),children:`保存预算`})]}),(0,F.jsxs)(`div`,{className:`settings-memory-interval-row`,style:{marginTop:10},children:[(0,F.jsxs)(`label`,{className:`settings-memory-interval-label`,children:[`复盘间隔(用户回合,0 为关闭):`,(0,F.jsx)(`input`,{"aria-label":`复盘间隔`,type:`number`,min:`0`,className:`settings-dir-input settings-interval-input`,value:_.interval,onChange:e=>v({..._,interval:e.target.value})})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!_.interval.trim()||!Number.isInteger(Number(_.interval))||Number(_.interval)<0,onClick:()=>void O({action:`configure`,settings:{...n.settings,reviewInterval:Number(_.interval)}}),children:`保存间隔`})]})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`label`,{className:`settings-memory-interval-label`,children:[`记忆上下文`,(0,F.jsxs)(`select`,{"aria-label":`记忆上下文`,className:`settings-memory-select`,value:h,onChange:e=>g(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`工作区与全局`}),n.contexts.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[e.title,e.agentId?` · ${e.agentId}`:``]},e.id))]})]}),(0,F.jsxs)(`div`,{className:`settings-memory-category-header`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`记忆条目管理`}),(0,F.jsxs)(`select`,{"aria-label":`记忆类别`,className:`settings-memory-select`,value:c,onChange:e=>{l(e.target.value),m(void 0),f(``),w([]),S(!1)},children:[(0,F.jsx)(`option`,{value:`user`,children:`用户档案(全局共享)`}),(0,F.jsx)(`option`,{value:`experience`,children:`工程经验(全局参考)`}),(0,F.jsx)(`option`,{value:`memory`,children:`工作区事实(当前工作区)`}),(0,F.jsx)(`option`,{value:`skills`,children:`技能(当前工作区)`}),(0,F.jsx)(`option`,{value:`role`,disabled:!n.context.agentId,children:`角色笔记(所选会话角色)`}),(0,F.jsx)(`option`,{value:`tree`,disabled:!n.context.treeId,children:`共享任务记忆(所选会话树)`}),(0,F.jsx)(`option`,{value:`session`,disabled:!n.context.conversationId,children:`工作笔记(所选会话)`})]})]}),(0,F.jsxs)(`p`,{className:`settings-agents-desc`,"data-memory-usage":`1`,children:[`活跃内容 `,n.usage[c]?.used??0,` / `,n.usage[c]?.limit??0,` 字符;存储配额与每轮召回预算独立。`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{"aria-label":`显示归档记忆`,type:`checkbox`,checked:y,onChange:e=>b(e.target.checked)}),`显示归档条目`]}),(n.entries[c]??[]).length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`当前类别暂无条目。在下方输入内容即可添加。`}):(0,F.jsx)(`div`,{className:`settings-memory-entries-list`,children:(n.entries[c]??[]).map(e=>(0,F.jsxs)(`article`,{"data-memory-entry":e.id,className:`settings-memory-card`,children:[(0,F.jsxs)(`div`,{className:`settings-memory-card-main`,children:[(0,F.jsx)(`pre`,{className:`settings-memory-content`,children:e.content}),e.experience&&(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[`来源 `,e.experience.projectName??e.experience.workspaceName,` · 适用条件 `,e.experience.applicability]}),(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[e.archivedAt?`已归档`:e.pinned?`核心记忆`:`按需召回`,` · 版本 `,e.revision??1,e.conversationId?` · 来源 ${e.conversationId}`:``]})]}),(0,F.jsxs)(`div`,{className:`settings-memory-card-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,disabled:!!e.archivedAt,onClick:()=>{m(e.id),f(e.content),S(!!e.pinned),w([])},children:`编辑`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>void O({action:`write`,operation:{target:c,action:e.archivedAt?`restore`:`archive`,id:e.id,expectedRevision:e.revision??1}}),children:e.archivedAt?`恢复`:`归档`}),!e.archivedAt&&(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{"aria-label":`选择整理 ${e.id}`,type:`checkbox`,checked:C.includes(e.id),onChange:t=>w(t.target.checked?[...C,e.id]:C.filter(t=>t!==e.id))}),`选择整理`]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void O({action:`write`,operation:{target:c,action:`remove`,id:e.id,expectedRevision:e.revision??1}}),children:`删除`})]})]},e.id))}),(0,F.jsxs)(`div`,{className:`settings-memory-editor`,style:{marginTop:12},children:[(0,F.jsx)(`h5`,{className:`settings-memory-editor-title`,children:p?`编辑条目`:`添加新条目`}),(0,F.jsx)(`textarea`,{"aria-label":`记忆内容`,className:`settings-memory-textarea`,placeholder:c===`skills`?`# 技能名称
|
|
315
|
-
已验证的步骤、命令和注意事项`:`输入长期有效的事实或偏好`,value:d,onChange:e=>f(e.target.value)}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{"aria-label":`核心记忆`,type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),`核心记忆(预算内优先召回)`]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!d.trim(),onClick:async()=>{await O({action:`write`,operation:{target:c,action:p?`replace`:`add`,id:p,content:d,pinned:x,expectedRevision:n.entries[c]?.find(e=>e.id===p)?.revision??1}})&&(m(void 0),f(``),S(!1))},children:[`保存`,p?`修改`:`新条目`]}),C.length>=2&&(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!d.trim(),onClick:async()=>{await O({action:`write`,operation:{target:c,action:`consolidate`,ids:C,content:d,pinned:x,expectedRevisions:Object.fromEntries(n.entries[c].filter(e=>C.includes(e.id)).map(e=>[e.id,e.revision??1]))}})&&(w([]),f(``),m(void 0))},children:[`合并所选 `,C.length,` 条并归档原文`]}),p&&(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{m(void 0),f(``)},children:`取消编辑`})]})]})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`待审批提案(共 `,n.pending.length,` 个)`]}),n.pending.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无待审批提案。`}):(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:n.pending.map(e=>(0,F.jsxs)(`article`,{"data-memory-proposal":e.id,className:`settings-proposal-card`,children:[(0,F.jsxs)(`div`,{className:`settings-proposal-header`,children:[(0,F.jsx)(`span`,{className:`settings-proposal-badge`,children:e.operation.target}),(0,F.jsx)(`span`,{className:`settings-proposal-action`,children:e.operation.action})]}),e.previous&&(0,F.jsxs)(`pre`,{className:`settings-proposal-diff old`,children:[`原内容:`,e.previous]}),(0,F.jsx)(`pre`,{className:`settings-proposal-diff new`,children:e.operation.content}),(0,F.jsxs)(`div`,{className:`settings-proposal-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>void O({action:`approve`,proposalId:e.id}),children:`批准`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void O({action:`discard`,proposalId:e.id}),children:`拒绝`})]})]},e.id))})]})]}),t&&(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})})]}):(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理其专属记忆与技能。`})}function Ch({workspaceId:e,onClose:t,onPick:n}){let[r,i]=(0,u.useState)(),[a,o]=(0,u.useState)(!1),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)(``),[f,p]=(0,u.useState)(),m=(0,u.useRef)(0);async function h(t){let n=++m.current;o(!0),c(``);try{let r=await Pe(`/api/files?workspaceId=${encodeURIComponent(e)}${t?`&path=${encodeURIComponent(t)}`:``}`),a=await r.json();if(!r.ok)throw Error(a.error??`HTTP ${r.status}`);if(n!==m.current)return;i(a),p(void 0)}catch(e){n===m.current&&c(Or(e,`这个目录读取失败。`))}finally{n===m.current&&o(!1)}}(0,u.useEffect)(()=>{h()},[e]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.isComposing&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let g=l.trim().toLocaleLowerCase(),_=(0,u.useMemo)(()=>(r?.entries??[]).filter(e=>e.kind===`directory`||e.kind===`file`&&(e.text||e.document)&&!e.outside),[r]),v=g?_.filter(e=>e.name.toLocaleLowerCase().includes(g)):_;return(0,F.jsx)(`div`,{className:`overlay`,onClick:t,children:(0,F.jsxs)(`div`,{className:`picker knowledge-picker`,"data-knowledge-picker":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-label":`选择要导入的文档`,children:[(0,F.jsx)(`h2`,{children:`选择要导入的文档`}),(0,F.jsxs)(`div`,{className:`picker-path-bar`,children:[(0,F.jsx)(`input`,{"aria-label":`按文件名过滤`,className:`picker-path-input`,placeholder:`按文件名过滤…`,value:l,onChange:e=>d(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!r||r.parent===null||a,onClick:()=>void h(r?.parent??void 0),"aria-label":`上一级`,children:`↑`})]}),(0,F.jsx)(`div`,{className:`picker-status`,"data-knowledge-picker-path":r?.path??``,children:r?r.path||`工作区根目录`:`读取中…`}),s&&(0,F.jsx)(`div`,{className:`picker-error`,role:`alert`,children:s}),(0,F.jsx)(`div`,{className:`picker-list`,"data-knowledge-picker-list":v.length,children:v.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:g?`没有匹配的文件。`:`这个目录里没有可导入的文件。`}):v.map(e=>e.kind===`directory`?(0,F.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-dir":e.path,onClick:()=>void h(e.path),children:[`📁 `,e.name]},e.path):(0,F.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-file":e.path,"data-knowledge-picker-document":e.document?`1`:void 0,"aria-pressed":f===e.path,onClick:()=>p(e.path),onDoubleClick:()=>n(e.path),children:[e.document?`📕 文档`:`📄`,` `,e.name]},e.path))}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!f,"data-knowledge-picker-ok":f??``,onClick:()=>{f&&n(f)},children:`导入这个文档`})]})]})})}function wh({workspaceId:e,onClose:t}){let[n,r]=(0,u.useState)(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(!1),[c,l]=(0,u.useState)(``),[d,f]=(0,u.useState)(``),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(!1),y=(0,u.useRef)(e);y.current=e;let b=(0,u.useRef)(0);async function x(t){if(!e)return;let n=++b.current;s(!0),a(``);try{let i=await Pe(`/api/knowledge?workspaceId=${encodeURIComponent(e)}`,{method:t?`POST`:`GET`,headers:{"Content-Type":`application/json`},...t?{body:JSON.stringify(t)}:{}}),a=await i.json();if(!i.ok)throw Error(a.error);return y.current!==e||n!==b.current?!1:(r(a),!0)}catch(t){return y.current===e&&n===b.current&&a(Or(t,`知识库读取失败。`)),!1}finally{y.current===e&&n===b.current&&s(!1)}}if((0,u.useEffect)(()=>{r(void 0),l(``),f(``),m(``),g(``),x()},[e]),!e)return(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理它的知识库。`});let S=n?.documents??[],C=S.reduce((e,t)=>e+t.characters,0),w=n?.semantic,T=w?w.enabled?w.error?`不可用:${Or(w.error,`本地语义模型没有加载成功`)};已退回关键词检索`:w.ready?`已就绪,已索引 ${w.indexed} 个片段`:w.bundled===!1?`随包分发的模型缺失;已退回关键词检索`:`首次检索时加载本地模型,之后一直可用`:`已关闭(SUPER_PI_KNOWLEDGE_EMBEDDINGS=0)`:`未启用`;return(0,F.jsxs)(`section`,{"data-knowledge-panel":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`项目自己的文档。`}),` 浏览工作区里的规范、设计稿、会议纪要导入进来,Agent 就能在回答前检索原文,而不是凭记忆编造。文档按当前工作区隔离,检索结果只回传片段而不回传全文。关键词检索始终可用;语义检索能在用词不同的情况下找到片段,但代价是首次使用要下载一个本地模型。`]})}),(0,F.jsxs)(`div`,{className:`settings-dir-info`,"data-knowledge-semantic":w?w.error?`unavailable`:w.ready?`ready`:`loading`:`off`,title:w?.error,children:[`语义检索:`,T]}),i&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:i}),n&&(0,F.jsxs)(`fieldset`,{disabled:o,className:`settings-memory-fieldset`,children:[(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`从工作区文件导入(`,S.length,` 篇,共 `,C,` 字符)`]}),(0,F.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-knowledge-browse":`1`,onClick:()=>v(!0),children:`浏览工作区文件…`}),(0,F.jsx)(`span`,{className:`settings-dir-info`,children:`在工作区里挑选一个 Markdown 或文本文件`})]}),(0,F.jsxs)(`div`,{className:`settings-add-dir-form`,style:{marginTop:8},children:[(0,F.jsx)(`input`,{"aria-label":`文档路径`,className:`settings-dir-input`,placeholder:`或直接填写相对路径,例如 docs/design.md`,value:c,onChange:e=>l(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!c.trim(),onClick:async()=>{await x({action:`add`,path:c})&&l(``)},children:`导入`})]}),(0,F.jsxs)(`div`,{className:`settings-memory-editor`,style:{marginTop:12},children:[(0,F.jsx)(`h5`,{className:`settings-memory-editor-title`,children:`或者直接粘贴正文`}),(0,F.jsx)(`input`,{"aria-label":`文档标题`,className:`settings-dir-input`,placeholder:`标题(留空则取正文首行)`,value:d,onChange:e=>f(e.target.value)}),(0,F.jsx)(`textarea`,{"aria-label":`文档正文`,className:`settings-memory-textarea`,placeholder:`以 # 开头的标题会成为检索结果里的段落归属`,value:p,onChange:e=>m(e.target.value)}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!p.trim(),onClick:async()=>{await x({action:`add`,title:d,text:p})&&(f(``),m(``))},children:`保存文档`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{f(``),m(``)},children:`清空`})]})]})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`已导入文档`}),S.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`还没有文档。导入后,下一条消息起 Agent 就能检索到它们。`}):(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:S.map(e=>(0,F.jsxs)(`article`,{"data-knowledge-document":e.id,className:`settings-memory-card`,children:[(0,F.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,F.jsx)(`span`,{className:`settings-dir-tag`,children:e.format||`txt`}),(0,F.jsx)(`span`,{className:`settings-dir-path`,children:e.title}),(0,F.jsxs)(`span`,{className:`settings-dir-count`,children:[e.characters,` 字符`]})]}),(0,F.jsx)(`div`,{className:`settings-dir-info`,children:e.source}),(0,F.jsx)(`div`,{className:`settings-memory-card-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void x({action:`remove`,documentId:e.id}),children:`删除`})})]},e.id))})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`试检索`}),(0,F.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,F.jsx)(`input`,{"aria-label":`检索词`,className:`settings-dir-input`,placeholder:`用和提问时相同的措辞试试`,value:h,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&h.trim()&&x({action:`search`,query:h})}}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!h.trim(),onClick:()=>void x({action:`search`,query:h}),children:`检索`})]}),h.trim()&&(n?.hits?.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`没有命中。知识库确实没有这段内容——Agent 也会得到同样的空结果。`}):(0,F.jsx)(`div`,{className:`settings-memory-entries-list`,children:(n?.hits??[]).map(e=>(0,F.jsxs)(`article`,{"data-knowledge-hit":`${e.documentId}#${e.chunk}`,className:`settings-memory-card`,children:[(0,F.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,F.jsx)(`span`,{className:`settings-dir-tag`,children:e.title}),(0,F.jsxs)(`span`,{className:`settings-dir-count`,title:`相关度(越高越接近)`,children:[`相关度 `,e.score.toFixed(2)]})]}),e.heading&&(0,F.jsx)(`div`,{className:`settings-dir-info`,children:e.heading}),(0,F.jsx)(`pre`,{className:`settings-memory-content`,children:e.text})]},`${e.documentId}#${e.chunk}`))}))]})]}),t&&(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})}),_&&(0,F.jsx)(Ch,{workspaceId:e,onClose:()=>v(!1),onPick:async e=>{v(!1),await x({action:`add`,path:e})&&l(``)}})]})}function Th(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(!1),d=(0,u.useCallback)(async()=>{try{let e=await Pe(`/api/feishu/status`),n=await e.json();if(!e.ok)throw Error(n.error??`读取飞书状态失败`);t(n)}catch(e){s(Or(e,`读取飞书状态失败。`))}},[]);(0,u.useEffect)(()=>{d()},[d]);let f=async()=>{l(!0),a(``),s(``),r(void 0);try{let e=await Pe(`/api/feishu/connect`,{method:`POST`}),t=await e.json();if(!e.ok)throw Error(t.message??`连接失败`);r(t)}catch(e){s(Or(e,`连接飞书账号失败。`))}finally{l(!1)}},p=async()=>{l(!0),a(``),s(``);try{let e=await Pe(`/api/feishu/connect/complete`,{method:`POST`}),t=await e.json();if(!e.ok)throw Error(t.message??`完成连接失败`);r(void 0),a(t.message),await d()}catch(e){s(Or(e,`完成连接失败。`))}finally{l(!1)}},m=async()=>{l(!0),a(``),s(``);try{let e=await Pe(`/api/feishu/verify`,{method:`POST`}),t=await e.json();if(!e.ok)throw Error(t.message??`测试失败`);a(t.ok?t.message:`还没连上:${t.message}`),!t.ok&&t.hint&&s(t.hint),await d()}catch(e){s(Or(e,`测试飞书连接失败。`))}finally{l(!1)}},h=e?.step??1,g=e?.installed===!0,_=e?.connected===!0,v=e=>e<h?`done`:e===h?`current`:`pending`;return(0,F.jsxs)(`section`,{"data-feishu-panel":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`让 Agent 直接读写飞书云文档。`}),` 通过飞书官方的 CLI(`,(0,F.jsx)(`code`,{children:`lark-cli`}),`)接入:授权一次之后,Agent 就能用 feishu_doc_read 读一篇飞书文档、用 feishu_doc_write 追加或改写它。凭据由官方 CLI 保管在系统钥匙串里,Super Pi 不接触、不保存、也不显示。`]})}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`连接状态`}),(0,F.jsxs)(`div`,{className:`settings-dir-info`,"data-feishu-status":e?_?`connected`:g?`not-connected`:`not-installed`:void 0,children:[e?.message??`正在读取飞书 CLI 的状态…`,e?.version?`(CLI ${e.version})`:``,e?.appId?` 应用 ${e.appId}`:``,e?.identity?` 身份 ${e.identity===`user`?`你的账号`:`应用`}`:``]}),e?.detail&&(0,F.jsx)(`div`,{className:`settings-dir-info`,"data-feishu-detail":`1`,children:e.detail}),e?.hint&&(0,F.jsx)(`div`,{className:`settings-dir-info`,"data-feishu-hint":`1`,children:e.hint}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,style:{marginTop:8},children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-feishu-connect":`1`,disabled:c||!g,onClick:()=>void f(),children:e?.rebuild?`重新连接`:`连接飞书账号`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-feishu-verify":`1`,disabled:c||!g,onClick:()=>void m(),children:`测试连接`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,"data-feishu-refresh":`1`,disabled:c,onClick:()=>void d(),children:`刷新状态`})]}),i&&(0,F.jsx)(`div`,{className:`settings-dir-info`,"data-feishu-message":`1`,children:i}),o&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,"data-feishu-error":`1`,children:o})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`怎么连上`}),(0,F.jsxs)(`ol`,{className:`settings-agents-desc`,children:[(0,F.jsxs)(`li`,{"data-feishu-step":`1`,"data-feishu-step-state":v(1),children:[(0,F.jsx)(`b`,{children:`装官方 CLI。`}),`在终端里运行一次:`,(0,F.jsx)(`div`,{className:`settings-dir-input`,"data-feishu-install":`1`,children:`npm i -g @larksuite/cli`}),`已经装过就跳过这步。若 Super Pi 找不到它(两边的 PATH 不一样),用环境变量 `,(0,F.jsx)(`code`,{children:`SUPER_PI_FEISHU_CLI`}),` 指向它的完整路径再重启 Super Pi。`]}),(0,F.jsxs)(`li`,{"data-feishu-step":`2`,"data-feishu-step-state":v(2),children:[(0,F.jsx)(`b`,{children:`连上你的账号。`}),`点上面的「连接飞书账号」:浏览器里会打开一个确认链接(第一次是确认创建应用,之后是授权你的账号),确认完回到这里点「我已完成」。整个过程不用打开飞书开发者后台。`]}),(0,F.jsxs)(`li`,{"data-feishu-step":`3`,"data-feishu-step-state":v(3),children:[(0,F.jsx)(`b`,{children:`开始用。`}),`在对话里直接说「把这篇飞书文档读一下」「把结论写回文档」就行。Agent 以你的身份操作,你自己的文档不需要逐篇授权。`]})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`完整说明和常见问题在右侧「使用指南 → 飞书」里。`})]}),n&&(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:n.step===`app`?`确认创建应用`:`确认授权`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:n.message}),n.verificationUri&&(0,F.jsx)(`a`,{className:`settings-dir-add-btn`,"data-feishu-verify-link":`1`,href:n.verificationUri,target:`_blank`,rel:`noreferrer`,children:`打开授权链接`}),n.hint&&(0,F.jsx)(`div`,{className:`settings-dir-info`,children:n.hint}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,style:{marginTop:8},children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-feishu-complete":`1`,disabled:c,onClick:()=>void p(),children:`我已完成`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,disabled:c,onClick:()=>r(void 0),children:`取消`})]})]})]})}var Eh=e=>![`google`,`google-vertex`].includes(e.id)&&![`google-generative-ai`,`google-vertex`].includes(e.api);async function Dh(e){let t=await e.json();if(!e.ok)throw Error(t.error||`代理设置请求失败`);return t}function Oh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(!1);return(0,u.useEffect)(()=>{let e=new AbortController;return Ne(`/api/providers/network`,{signal:e.signal},`entry`).then(Dh).then(n=>{e.signal.aborted||t(n)}).catch(()=>{e.signal.aborted||r(!0)}),()=>e.abort()},[]),(0,F.jsxs)(`p`,{"data-entry-proxy":!0,children:[`入口代理 · `,n?`读取失败`:e?e.httpProxy?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`code`,{children:e.httpProxy}),` · `,e.providers.join(`、`)||`未选用供应商`]}):`未配置`:`正在读取…`]})}function kh({providers:e}){let{settingsServer:t,connections:n}=ue(),r=n.find(e=>e.id===t)?.name??`当前入口`,[i,a]=(0,u.useState)(),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(!1),[d,f]=(0,u.useState)([]),[p,m]=(0,u.useState)(!1),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(!1),y=`/api/providers/network`,b=e=>{a(e),s(e.hasAuth?``:e.httpProxy),f(e.providers),l(!1)};(0,u.useEffect)(()=>{let e=new AbortController;return Pe(y,{signal:e.signal}).then(Dh).then(t=>{e.signal.aborted||b(t)}).catch(t=>{e.signal.aborted||g(t instanceof Error?t.message:`读取失败`)}),()=>e.abort()},[]);let x=async()=>{if(p||!i)return;m(!0),g(``),v(!1);let t={providers:d.filter(t=>e.some(e=>e.id===t&&Eh(e))),...c?{httpProxy:o}:{}};try{b(await Pe(y,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).then(Dh)),v(!0)}catch(e){g(e instanceof Error?e.message:`保存失败`)}finally{m(!1)}};return(0,F.jsxs)(`section`,{className:`provider-network`,"data-provider-network":!0,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`代理`}),(0,F.jsxs)(`div`,{className:`provider-network-form`,children:[(0,F.jsx)(`p`,{children:`地址只需填写一次,再勾选使用代理的供应商。保存后,未勾选的供应商直连。`}),(0,F.jsxs)(`p`,{children:[`支持 HTTP / HTTPS 代理。地址中的 `,(0,F.jsx)(`code`,{children:`127.0.0.1`}),` 指运行「`,r,`」服务的电脑。`,t===`entry`&&`托管服务器借用入口模型时,也从这台电脑连接代理。`]}),!i&&!h&&(0,F.jsx)(`p`,{role:`status`,children:`正在读取代理设置…`}),i&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`代理地址`}),(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-provider-network-http":!0,autoComplete:`off`,value:o,disabled:p,placeholder:i.hasAuth?`已配置认证代理 ${i.httpProxy},留空保留`:`http://127.0.0.1:7890`,onChange:e=>{s(e.target.value),l(!0),v(!1)}})]}),(0,F.jsxs)(`fieldset`,{className:`provider-network-providers`,disabled:p,children:[(0,F.jsx)(`legend`,{children:`使用代理的供应商`}),e.length===0&&(0,F.jsx)(`p`,{children:`添加供应商后即可在这里勾选。`}),e.map(e=>(0,F.jsxs)(`label`,{className:`provider-network-choice`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-provider-network-choice":e.id,disabled:!Eh(e),checked:Eh(e)&&d.includes(e.id),onChange:t=>{f(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id)),v(!1)}}),(0,F.jsxs)(`span`,{children:[e.name||e.id,e.name&&e.name!==e.id?` (${e.id})`:``,e.disabled?` · 已停用`:``,Eh(e)?``:` · 原生 SDK 暂不支持此代理`]})]},e.id))]}),(0,F.jsx)(`div`,{className:`provider-network-actions`,children:(0,F.jsx)(`button`,{type:`button`,"data-provider-network-save":!0,disabled:p,onClick:()=>void x(),children:p?`正在保存…`:`保存代理设置`})})]}),h&&(0,F.jsx)(`p`,{className:`provider-network-warning`,role:`alert`,children:h}),_&&(0,F.jsx)(`p`,{role:`status`,"data-provider-network-saved":!0,children:`已保存,后续请求使用新设置。`})]})]})}async function Ah(e){let t=await e.json();if(!e.ok)throw Error(t.error??`Tavily 设置请求失败。`);return t}function jh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(``),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(``),d=(0,u.useCallback)(async()=>{s(``);try{t(await Pe(`/api/tavily/settings`,{cache:`no-store`}).then(Ah))}catch(e){s(e instanceof Error?e.message:`读取 Tavily 状态失败。`)}},[]);(0,u.useEffect)(()=>{d()},[d]);let f=async e=>{if(e.preventDefault(),!i&&n.trim()){a(!0),s(``),l(``);try{let e=await Pe(`/api/tavily/settings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:`connect`,apiKey:n})}).then(Ah);r(``),t(e),l(`Tavily 已连接。后续 Agent 会自动获得网页搜索工具。`)}catch(e){s(e instanceof Error?e.message:`连接 Tavily 失败。`)}finally{a(!1)}}},p=async()=>{if(!i){a(!0),s(``),l(``);try{let e=await Pe(`/api/tavily/settings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:`disconnect`})}).then(Ah);t(e),l(`已断开 Tavily,网页搜索工具已从 Agent 工具列表中移除。`)}catch(e){s(e instanceof Error?e.message:`断开 Tavily 失败。`)}finally{a(!1)}}};return(0,F.jsxs)(`section`,{className:`tavily-settings`,"data-tavily-panel":!0,children:[(0,F.jsx)(`p`,{className:`tavily-description`,children:`连接自己的 Tavily 账号,让 Agent 使用你的搜索额度。API key 保存在 Super Pi 服务端,不会交给 Agent。`}),(0,F.jsxs)(`section`,{className:`tavily-section`,children:[(0,F.jsxs)(`div`,{className:`tavily-section-heading`,children:[(0,F.jsx)(`h4`,{children:`连接状态`}),(0,F.jsxs)(`div`,{className:`tavily-actions`,children:[(0,F.jsx)(`button`,{type:`button`,disabled:i||!e,onClick:()=>void d(),children:`刷新状态`}),e?.configured&&(0,F.jsx)(`button`,{type:`button`,"data-tavily-disconnect":!0,disabled:i,onClick:()=>void p(),children:`断开并删除 key`})]})]}),(0,F.jsx)(`p`,{className:`tavily-status`,role:`status`,"data-tavily-status":e?e.connected?`connected`:e.configured?`invalid`:`disconnected`:`loading`,children:e?e.connected?`已连接${e.keyHint?`(${e.keyHint})`:``}`:e.configured?`已保存的 key 暂时无法验证`:`未连接;Agent 不会看到网页搜索工具`:`正在读取 Tavily 状态…`}),e?.usage&&(0,F.jsxs)(`p`,{className:`tavily-description`,"data-tavily-usage":!0,children:[e.usage.plan?`${e.usage.plan} · `:``,`已用 `,e.usage.used.toLocaleString(),` / `,e.usage.limit.toLocaleString(),` credits,剩余 `,e.usage.remaining.toLocaleString()]}),e?.error&&(0,F.jsx)(`p`,{className:`tavily-feedback`,role:`status`,children:e.error})]}),!e?.configured&&(0,F.jsxs)(`section`,{className:`tavily-section`,children:[(0,F.jsx)(`h4`,{children:`连接你的账号`}),(0,F.jsxs)(`ol`,{className:`tavily-steps`,children:[(0,F.jsx)(`li`,{children:(0,F.jsx)(`a`,{href:`https://app.tavily.com`,target:`_blank`,rel:`noopener noreferrer`,children:`注册或登录 Tavily ↗`})}),(0,F.jsx)(`li`,{children:`在 Tavily 控制台复制你的 API key。`}),(0,F.jsx)(`li`,{children:`粘贴到下方。Super Pi 会先用不消耗搜索额度的用量接口验证 key。`})]}),(0,F.jsxs)(`form`,{className:`tavily-connect-form`,onSubmit:e=>void f(e),children:[(0,F.jsx)(`label`,{htmlFor:`tavily-api-key`,children:`Tavily API key`}),(0,F.jsx)(`input`,{id:`tavily-api-key`,"aria-describedby":`tavily-key-hint`,"data-tavily-key":!0,type:`password`,autoComplete:`new-password`,spellCheck:!1,value:n,onChange:e=>r(e.target.value),placeholder:`粘贴 Tavily API key`,disabled:i}),(0,F.jsx)(`p`,{id:`tavily-key-hint`,className:`tavily-hint`,children:`使用你自己的额度;付费方案由你在 Tavily 管理。`}),(0,F.jsx)(`div`,{className:`tavily-actions`,children:(0,F.jsx)(`button`,{type:`submit`,"data-tavily-connect":!0,disabled:i||!n.trim(),children:i?`正在验证…`:`连接 Tavily`})})]})]}),e?.configured&&(0,F.jsxs)(`section`,{className:`tavily-section`,children:[(0,F.jsx)(`h4`,{children:`Agent 搜索额度`}),(0,F.jsx)(`p`,{children:`Agent 使用 Tavily Basic Search。可在 Tavily 控制台查看用量、调整方案或管理付费。`}),(0,F.jsx)(`a`,{href:`https://app.tavily.com`,target:`_blank`,rel:`noopener noreferrer`,children:`打开 Tavily 控制台 ↗`})]}),o&&(0,F.jsx)(`p`,{className:`tavily-feedback`,role:`alert`,"data-tavily-error":!0,children:o}),c&&(0,F.jsx)(`p`,{className:`tavily-feedback`,role:`status`,"data-tavily-notice":!0,children:c})]})}async function Mh(e){let t=await e.json();if(!e.ok)throw Error(t.error||`缓存设置请求失败`);return t}function Nh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(`off`),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(!1),d=(0,u.useRef)(!1),f=(0,u.useRef)(!1),p=(0,u.useRef)(0),m=`/api/pi/cache-warming`;(0,u.useEffect)(()=>{let e=new AbortController,n=()=>{if(f.current)return;let n=++p.current;Pe(m,{signal:e.signal}).then(Mh).then(i=>{e.signal.aborted||n!==p.current||(t(i),d.current||(r(i.mode),d.current=!0,s(``)))}).catch(t=>{!e.signal.aborted&&!d.current&&s(t instanceof Error?t.message:`读取失败`)})};n();let i=window.setInterval(n,5e3);return()=>{e.abort(),window.clearInterval(i)}},[]);let h=async()=>{a(!0),s(``),l(!1),f.current=!0,p.current++;try{let e=await Pe(m,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({mode:n})}).then(Mh);t(e),r(e.mode),l(!0)}catch(e){s(e instanceof Error?e.message:`保存失败`)}finally{f.current=!1,a(!1)}};return(0,F.jsxs)(`section`,{className:`settings-section`,"data-cache-warming":!0,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`模型缓存预热`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`让支持缓存的模型保留最近请求的缓存,减少下一次回答的等待。预热可能产生额外请求和费用,用量计入对应会话总量。此设置在服务端运行,对所有工作区生效。`}),!e&&!o&&(0,F.jsx)(`p`,{role:`status`,children:`正在读取缓存设置…`}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`预热模式`}),(0,F.jsxs)(`select`,{className:`settings-model-select`,"data-cache-warming-mode":!0,disabled:i||!e,value:n,onChange:e=>{r(e.target.value),l(!1)},children:[(0,F.jsx)(`option`,{value:`off`,children:`关闭`}),(0,F.jsx)(`option`,{value:`streaming`,children:`仅回答期间`}),(0,F.jsx)(`option`,{value:`idle`,children:`回答及空闲期间`})]})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`空闲预热最多持续约 30 分钟,Pi 会按模型支持情况和成本决定是否继续;切换到空闲模式后,从下一次模型请求开始生效。`}),e&&(0,F.jsxs)(`p`,{className:`settings-agents-desc`,"data-cache-warming-status":!0,children:[`已加载 `,e.liveSessions,` 个会话 · `,e.scheduled,` 个等待预热 · `,e.refreshing,` 个正在预热`]}),(0,F.jsx)(`div`,{className:`settings-rule-form-buttons`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-cache-warming-save":!0,disabled:i||!e||n===e.mode,onClick:()=>void h(),children:i?`正在保存…`:`保存预热设置`})}),o&&(0,F.jsx)(`p`,{className:`settings-dir-error`,role:`alert`,children:o}),c&&(0,F.jsx)(`p`,{className:`settings-agents-desc`,role:`status`,"data-cache-warming-saved":!0,children:`已保存,现有会话已同步。`})]})}var Ph={deferred:`按需搜索`,direct:`直接提供`,codemode:`通过编排调用`,hidden:`隐藏工具`},Fh={connected:`测试通过`,connecting:`连接中`,failed:`连接失败`,"needs-auth":`需要登录`,disabled:`已停用`,disconnected:`连接已断开`,closed:`已关闭`},Ih=[[`mcp`,`MCP 外部服务`,`连接服务端命令或远程 HTTP 服务,使用其工具和资源。`],[`toolSearch`,`按需发现工具`,`工具多时先搜索再调用,减少每轮请求携带的工具说明。`],[`codemode`,`批量编排调用`,`合并多次工具调用、并行读取或筛选结果,减少来回等待。`]];function Lh({workspaceId:e}){let[t,n]=(0,u.useState)(),[r,i]=(0,u.useState)(``),[a,o]=(0,u.useState)(``),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)(``),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(`http`),[g,_]=(0,u.useState)(``),[v,y]=(0,u.useState)(``),[b,x]=(0,u.useState)(``),[S,C]=(0,u.useState)(`deferred`),[w,T]=(0,u.useState)({}),E=(0,u.useRef)(!1),D=(0,u.useRef)(0),O=async e=>{let t=await e.json();if(!e.ok)throw Error(t.error||`外部工具请求失败。`);return t};(0,u.useEffect)(()=>{let e=new AbortController,t=()=>{if(E.current)return;let t=++D.current;Pe(`/api/native-tools`,{signal:e.signal}).then(O).then(r=>{!e.signal.aborted&&t===D.current&&(n(r),c(``))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:`读取失败。`)})};t();let r=window.setInterval(t,2e3);return()=>{e.abort(),window.clearInterval(r)}},[]);let k=async(t,r,a=``)=>{if(E.current)return!1;E.current=!0,D.current++,i(t),o(``),d(``);try{let t=await Pe(`/api/native-tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...r,workspaceId:e})}).then(O);return n(t),d(a),!0}catch(e){return o(e instanceof Error?e.message:`操作失败。`),!1}finally{E.current=!1,i(``)}},A=async e=>{e.preventDefault();let t;try{if(t=b.trim()?JSON.parse(b):{},!t||typeof t!=`object`||Array.isArray(t))throw Error()}catch{o(`高级配置须为 JSON 对象。`);return}let n={...t,...m===`http`?{url:g.trim()}:{command:g.trim(),args:v.split(/\r?\n/).filter(Boolean)},exposure:S};await k(`save`,{action:`save`,name:f.trim(),config:n},`已保存,下一轮执行生效。`)&&(p(``),_(``),y(``),x(``))},j=t?.servers.some(e=>e.name===f.trim());return(0,F.jsxs)(`section`,{className:`settings-panel-container native-tools`,"data-native-tools":!0,children:[(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`让 Agent 查询外部资料、处理服务数据,或把多次工具调用合并执行。主会话、工具型群成员和后台子 Agent 使用同一套权限;自定义 Agent 保留原来的工具授权。`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`这里管理服务端的全局配置,与 Pi 共用 mcp.json。项目自己的配置继续按 Pi 的信任规则加载。保存后下一轮执行采用新配置,当前工作继续运行。`}),(a||s)&&(0,F.jsx)(`p`,{className:`settings-dir-error`,role:`alert`,"data-native-error":!0,children:a||s}),l&&(0,F.jsx)(`p`,{role:`status`,"data-native-notice":!0,children:l}),!t&&!a&&!s&&(0,F.jsx)(`p`,{role:`status`,children:`正在读取外部工具…`}),t&&(0,F.jsxs)(F.Fragment,{children:[t.configurationWarning&&(0,F.jsx)(`p`,{role:`alert`,children:t.configurationWarning}),(0,F.jsx)(`section`,{className:`settings-section native-tool-flags`,"aria-label":`工具能力`,children:Ih.map(([e,n,i])=>(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-native-flag":e,checked:t.settings[e],disabled:!!r,onChange:t=>void k(e,{action:`settings`,settings:{[e]:t.target.checked}},`已保存工具开关。`)}),(0,F.jsxs)(`span`,{children:[(0,F.jsx)(`strong`,{children:n}),(0,F.jsx)(`small`,{children:i})]})]},e))}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`div`,{className:`native-tools-heading`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`MCP 服务`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-mcp-diagnose":!0,disabled:!!r||t.diagnostics?.running||!e||!t.servers.length,onClick:()=>void k(`diagnose`,{action:`diagnose`}),children:t.diagnostics?.running?`正在测试 ${t.diagnostics.servers.length}/${t.diagnostics.total}…`:`测试连接`})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`连接测试会临时连接后关闭;实际执行时由会话保持连接。命令运行在 Super Pi 服务端,环境变量和请求头中的已有值不回显。`}),!t.servers.length&&(0,F.jsx)(`p`,{className:`settings-empty-hint`,children:`还没有全局 MCP 服务,在下方添加第一个。`}),t.servers.map(n=>{let i=t.diagnostics?.servers.find(e=>e.name===n.name);return(0,F.jsxs)(`article`,{className:`native-server`,"data-mcp-server":n.name,children:[(0,F.jsxs)(`div`,{className:`native-server-title`,children:[(0,F.jsx)(`strong`,{children:n.name}),(0,F.jsx)(`span`,{children:n.transport===`http`?`HTTP`:`命令`}),(0,F.jsx)(`span`,{"data-mcp-state":i?.state??`untested`,children:n.enabled?i?Fh[i.state]??i.state:`尚未测试`:`已停用`})]}),n.description&&(0,F.jsx)(`p`,{children:n.description}),(0,F.jsxs)(`div`,{className:`native-server-actions`,children:[(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-mcp-enabled":!0,checked:n.enabled,disabled:!!r,onChange:e=>void k(n.name,{action:`patch`,name:n.name,enabled:e.target.checked})}),`启用`]}),(0,F.jsx)(`select`,{"aria-label":`${n.name} 的工具提供方式`,"data-mcp-exposure":!0,value:n.exposure,disabled:!!r,onChange:e=>void k(n.name,{action:`patch`,name:n.name,exposure:e.target.value}),children:Object.entries(Ph).map(([e,t])=>(0,F.jsx)(`option`,{value:e,children:t},e))}),n.supportsLogin&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-mcp-login":!0,disabled:!!r||!e,onClick:()=>void k(n.name,{action:`login`,name:n.name}),children:n.authenticated?`重新登录`:`登录`}),n.authenticated&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,disabled:!!r,onClick:()=>void k(n.name,{action:`logout`,name:n.name},`已移除 MCP 网页登录凭据。`),children:`退出登录`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-mcp-remove":!0,disabled:!!r,onClick:()=>{window.confirm(`删除 MCP 服务 ${n.name}?`)&&k(n.name,{action:`delete`,name:n.name})},children:`删除`})]}),i?.error&&(0,F.jsx)(`p`,{role:`status`,children:i.error}),i&&i.tools.length>0&&(0,F.jsxs)(`details`,{"data-mcp-tools":!0,children:[(0,F.jsxs)(`summary`,{children:[i.tools.length,` 个可用工具`]}),(0,F.jsx)(`ul`,{children:i.tools.map(e=>(0,F.jsx)(`li`,{children:(0,F.jsx)(`code`,{children:e})},e))})]})]},n.name)}),t.diagnostics?.error&&(0,F.jsx)(`p`,{role:`status`,children:t.diagnostics.error})]}),t.logins.map(e=>(0,F.jsxs)(`section`,{className:`settings-section native-login`,"data-mcp-login-state":e.state,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[e.name,` · `,e.state===`completed`?`登录完成`:e.state===`starting`?`正在连接授权服务`:e.state===`authorizing`?`等待网页授权`:e.state===`cancelled`?`登录已取消`:`登录未完成`]}),e.url&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`a`,{className:`settings-oauth-open-link native-login-open`,href:e.url,target:`_blank`,rel:`noopener noreferrer`,children:`打开授权页面 ↗`}),(0,F.jsx)(`p`,{children:`如果远程浏览器无法打开回调页面,可复制地址栏里的完整回调地址粘贴到下方。`}),(0,F.jsxs)(`form`,{onSubmit:t=>{t.preventDefault(),k(e.id,{action:`redirect`,id:e.id,url:w[e.id]}).then(t=>{t&&T(t=>({...t,[e.id]:``}))})},children:[(0,F.jsx)(`input`,{className:`settings-oauth-input`,type:`password`,"aria-label":`完整回调地址`,autoComplete:`off`,placeholder:`粘贴完整回调地址`,value:w[e.id]??``,onChange:t=>T(n=>({...n,[e.id]:t.target.value}))}),(0,F.jsx)(`button`,{className:`settings-dir-add-btn settings-oauth-continue`,disabled:!!r||!w[e.id],type:`submit`,children:`完成授权`})]})]}),e.error&&(0,F.jsx)(`p`,{role:`status`,children:e.error}),[`starting`,`authorizing`].includes(e.state)&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>void k(e.id,{action:`cancel-login`,id:e.id}),children:`取消登录`})]},e.id))]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`添加服务`}),(0,F.jsxs)(`form`,{onSubmit:e=>void A(e),className:`native-server-form`,children:[(0,F.jsxs)(`div`,{className:`settings-model-grid`,children:[(0,F.jsxs)(`label`,{children:[`服务名`,(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-mcp-name":!0,required:!0,value:f,onChange:e=>p(e.target.value)})]}),(0,F.jsxs)(`label`,{children:[`连接方式`,(0,F.jsxs)(`select`,{className:`settings-model-select`,"data-mcp-type":!0,value:m,onChange:e=>{h(e.target.value),_(``)},children:[(0,F.jsx)(`option`,{value:`http`,children:`远程 HTTP`}),(0,F.jsx)(`option`,{value:`stdio`,children:`服务端命令`})]})]})]}),(0,F.jsxs)(`label`,{children:[m===`http`?`服务地址`:`可执行命令`,(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-mcp-address":!0,required:!0,value:g,onChange:e=>_(e.target.value),placeholder:m===`http`?`https://example.com/mcp`:`npx`})]}),m===`stdio`&&(0,F.jsxs)(`label`,{children:[`参数(每行一个)`,(0,F.jsx)(`textarea`,{className:`settings-dir-input`,"data-mcp-args":!0,value:v,onChange:e=>y(e.target.value),spellCheck:!1})]}),(0,F.jsxs)(`label`,{children:[`工具提供方式`,(0,F.jsx)(`select`,{className:`settings-model-select`,value:S,onChange:e=>C(e.target.value),children:Object.entries(Ph).map(([e,t])=>(0,F.jsx)(`option`,{value:e,children:t},e))})]}),(0,F.jsxs)(`details`,{children:[(0,F.jsx)(`summary`,{children:`环境变量、请求头与高级配置`}),(0,F.jsx)(`p`,{children:`填写单个服务配置的 JSON 字段,例如 env、headers、oauth、toolExposure。可以使用环境变量引用;保存后清空此输入。`}),(0,F.jsx)(`textarea`,{className:`settings-dir-input`,"data-mcp-extra":!0,value:b,onChange:e=>x(e.target.value),spellCheck:!1,placeholder:'{"env":{"SERVICE_KEY":"${SERVICE_KEY}"}}'})]}),j&&(0,F.jsx)(`p`,{children:`同名服务已存在,本次保存将完整替换其配置。调整开关或提供方式可直接使用上方操作,保留已有凭据。`}),(0,F.jsx)(`button`,{type:`submit`,className:`settings-dir-add-btn`,"data-mcp-save":!0,disabled:!!r||!t,children:r===`save`?`正在保存…`:j?`替换服务配置`:`添加服务`})]})]})]})}function Rh(){let e=Qd();return(0,F.jsxs)(`fieldset`,{className:`markdown-syntax-settings`,"data-markdown-syntax-settings":`1`,children:[(0,F.jsx)(`legend`,{children:`消息 Markdown 语法`}),(0,F.jsx)(`p`,{children:`关闭后按原样显示符号。讨论 A* 算法时可关闭斜体;代码块不受影响。`}),[{key:`italic`,label:`斜体`,example:`*文字* / _文字_`},{key:`bold`,label:`粗体`,example:`**文字** / __文字__`},{key:`strikethrough`,label:`删除线`,example:`~~文字~~`}].map(t=>(0,F.jsxs)(`label`,{className:`markdown-syntax-row`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-markdown-syntax-setting":t.key,checked:e[t.key],onChange:e=>Yd({[t.key]:e.target.checked})}),(0,F.jsx)(`span`,{children:t.label}),(0,F.jsx)(`code`,{children:t.example})]},t.key)),(0,F.jsxs)(`div`,{className:`markdown-syntax-footer`,children:[(0,F.jsx)(`span`,{children:`仅影响当前浏览器的显示,立即生效。`}),(0,F.jsx)(`button`,{type:`button`,onClick:()=>Yd(Hd),"data-markdown-syntax-reset":`1`,children:`恢复默认`})]})]})}var zh=e=>+(e===`subagent`);function Bh(e){return[...e].sort((e,t)=>{let n=+!e.builtin,r=+!t.builtin;if(n!==r)return n-r;let i=zh(e.mode)-zh(t.mode);return i===0?e.id.localeCompare(t.id):i})}var Vh=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Hh(e,t){let n=e.trim(),r=n.replace(/\/+$/,``);try{let e=new URL(n);r=`${e.origin}${e.pathname.replace(/\/+$/,``)}${e.search}`}catch{}return`${r}|${t.trim()||`openai-completions`}`}function Uh(e){return e?Vh.filter(t=>e[t]!=null):[]}function Wh(e){return Uh(e).join(` / `)}var Gh=e=>e.nativeEvent.isComposing||e.keyCode===229,Kh=`super-pi.theme`,qh=[{id:`dracula`,name:`Dracula`,blurb:`冷灰深底,柔紫选中和焦点。`},{id:`monokai`,name:`Monokai`,blurb:`暖灰深底,琥珀色操作和焦点。`},{id:`solarized-light`,name:`Solarized Light`,blurb:`米白正文,鼠尾草绿选中。`},{id:`github-light`,name:`GitHub Light`,blurb:`白色正文,冷灰侧栏和蓝色选中。`}],Jh=`dracula`,Yh=e=>typeof e==`string`&&qh.some(t=>t.id===e);function Xh(){try{let e=window.localStorage.getItem(Kh);if(!e)return Jh;let t=JSON.parse(e),n=typeof t==`string`?t:t?.id;return Yh(n)?n:Jh}catch{return Jh}}function Zh(e){document.documentElement.setAttribute(`data-theme`,e);try{window.localStorage.setItem(Kh,JSON.stringify({id:e,version:1}))}catch{}}function Qh(){let[e,t]=(0,u.useState)(Jh);return(0,u.useEffect)(()=>{t(Xh());let e=e=>{if(e.key===`super-pi.theme`&&e.newValue)try{let n=JSON.parse(e.newValue),r=typeof n==`string`?n:n?.id;Yh(r)&&(document.documentElement.setAttribute(`data-theme`,r),t(r))}catch{}};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),{theme:e,setTheme:(0,u.useCallback)(e=>{Zh(e),t(e)},[])}}function $h({theme:e,onChooseTheme:t,onClose:n}){let r=qh.find(t=>t.id===e);return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`主题只影响这台设备的显示,不改变任何内容;切换立即生效。`}),(0,F.jsx)(Rh,{}),qh.length===0?(0,F.jsx)(`div`,{className:`theme-empty`,"data-theme-empty":`1`,children:`没有可用的主题。界面将继续使用默认配色,你可以在主题文件恢复后重试。`}):(0,F.jsx)(`div`,{className:`theme-options`,role:`radiogroup`,"aria-label":`主题`,children:qh.map(n=>{let r=n.id===e;return(0,F.jsxs)(`button`,{type:`button`,className:`theme-option`,role:`radio`,"aria-checked":r,"aria-pressed":r,"data-theme-option":n.id,"data-theme-current":r?`1`:`0`,onClick:()=>t(n.id),children:[(0,F.jsx)(`span`,{className:`theme-preview-strip`,"data-preview":n.id,"aria-hidden":`true`}),(0,F.jsxs)(`span`,{className:`theme-option-name`,children:[n.name,r&&(0,F.jsx)(`span`,{className:`theme-option-current`,children:`当前 ✓`})]}),(0,F.jsx)(`span`,{className:`theme-option-blurb`,children:n.blurb})]},n.id)})}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-theme-close":`1`,onClick:n,children:`完成`})}),(0,F.jsxs)(`div`,{className:`settings-scope theme-current-line`,children:[`当前:`,r?`${r.name}(${r.id})`:`默认`]})]})}function eg({userNickname:e,onSetUserNickname:t,onClose:n}){return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`昵称会显示在消息时间戳旁和头像上,替代默认的「你」。留空恢复默认。`}),(0,F.jsxs)(`div`,{className:`general-nickname`,children:[(0,F.jsx)(`label`,{className:`general-nickname-label`,htmlFor:`general-nickname-input`,children:`昵称`}),(0,F.jsx)(`input`,{id:`general-nickname-input`,type:`text`,className:`general-nickname-input`,"data-general-nickname":`1`,maxLength:24,placeholder:`你`,value:e??``,onChange:e=>t?.(e.target.value)}),(0,F.jsx)(`span`,{className:`general-nickname-hint`,"data-general-nickname-preview":`1`,title:`当前显示`,children:e?.trim()?`将显示为:${e.trim()}`:`将显示为:你`})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`完成`})})]})}function tg(e){return(0,F.jsx)(rg,{context:e})}function ng({context:e}){let[t,n]=(0,u.useState)(),[r,i]=(0,u.useState)(``),a=(0,u.useRef)(void 0),o=()=>{window.superPiDesktop.notifications.status().then(n).catch(()=>i(`无法读取桌面通知状态`))};(0,u.useEffect)(()=>(o(),()=>a.current?.close()),[]);let s=!!e.browserNotificationsEnabled;return(0,F.jsxs)(`section`,{className:`settings-panel-container`,"data-desktop-notifications":`1`,children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`通过 Super Pi 桌面应用发送系统通知,使用 Super Pi 图标;点击提醒会回到对应会话。仅提醒顶层会话,通知不包含问题全文或代码。`}),(0,F.jsxs)(`div`,{className:`settings-notification-row`,children:[(0,F.jsxs)(`div`,{className:`settings-notification-copy`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`Agent 状态提醒`}),(0,F.jsx)(`p`,{children:`任务完成、等待回答或需要决定时提醒。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"aria-pressed":s,disabled:!s&&!t?.supported,onClick:()=>e.onSetBrowserNotifications?.(!s),children:s?`关闭通知`:`启用通知`})]}),(0,F.jsxs)(`section`,{className:`settings-notification-check`,"aria-label":`桌面通知检测`,children:[(0,F.jsxs)(`dl`,{children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`通知来源`}),(0,F.jsx)(`dd`,{children:`Super Pi 桌面应用`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`桌面通知支持`}),(0,F.jsx)(`dd`,{children:t?t.supported?`系统支持`:`当前系统不支持`:`检测中…`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`通知权限`}),(0,F.jsx)(`dd`,{children:`由操作系统管理`})]})]}),(0,F.jsx)(`p`,{role:`status`,children:s?t?.lastError??`桌面通知已开启,最终显示取决于系统通知权限及勿扰模式。`:`通知未启用。`}),(0,F.jsxs)(`div`,{className:`settings-notification-check-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:o,children:`重新检测`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,disabled:!s||!t?.supported,onClick:async()=>{try{a.current?.close();let e=ra(`Super Pi · 测试通知`,{tag:`super-pi-permission-test`,body:`这是一条由 Super Pi 桌面端发送的系统通知。`});a.current=e;let t=await e.ready;i(t?.state===`shown`?`系统已接收 Super Pi 通知;若没有看到,请检查通知设置及勿扰模式。`:`已发出通知请求,尚未收到系统显示回执。请检查系统通知设置。`)}catch(e){i(e instanceof Error?e.message:`系统未能显示通知`)}finally{o()}},children:`发送测试通知`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:async()=>{try{(await window.superPiDesktop.notifications.openSettings()).opened||i(`请在系统设置中打开 Super Pi 的通知权限。`)}catch{i(`无法打开系统设置,请手动检查系统通知权限。`)}},children:`打开系统通知设置`})]}),(0,F.jsx)(`p`,{className:`settings-notification-help`,children:`操作系统未提供可可靠读取的统一授权状态时,这里不会把支持通知误报为已经授权。可以使用测试通知确认实际显示。`}),r&&(0,F.jsx)(`p`,{role:`status`,children:r})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function rg({context:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)();if((0,u.useEffect)(()=>{e.onCheckBrowserNotifications?.()},[e.onCheckBrowserNotifications]),(0,u.useEffect)(()=>()=>r?.close(),[r]),window.superPiDesktop?.notifications)return(0,F.jsx)(ng,{context:e});let a=!!e.browserNotificationsEnabled,o=e.browserNotificationPermission??`unsupported`,s=o!==`unsupported`&&o!==`insecure`,c=o===`granted`?`浏览器已授权通知。`:o===`denied`?`浏览器已阻止此站点发送通知。请在地址栏的站点设置中允许通知,然后返回这里重新检测。`:o===`insecure`?`当前连接不是安全来源。浏览器通知需要 HTTPS 或 localhost。`:o===`unsupported`?`当前浏览器不支持系统通知。`:`尚未授权。点击按钮后,浏览器会询问是否允许 Super Pi 发送通知。`,l=a&&o===`granted`;return(0,F.jsxs)(`section`,{className:`settings-panel-container`,"data-browser-notifications":`1`,children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`当页面处于后台或没有焦点时,Agent 完成一轮工作或等待你回答问题,会通过浏览器系统通知提醒。通知不会包含问题全文或代码。`}),(0,F.jsxs)(`div`,{className:`settings-notification-row`,children:[(0,F.jsxs)(`div`,{className:`settings-notification-copy`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`Agent 状态提醒`}),(0,F.jsx)(`p`,{children:`仅提醒顶层会话;后台子会话不会逐个打断你。点击通知会打开对应会话。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-browser-notifications-toggle":`1`,"aria-pressed":a,disabled:!a&&(!s||o===`denied`),onClick:()=>e.onSetBrowserNotifications?.(!a),children:a?`关闭通知`:o===`granted`?`启用通知`:`授权并启用`})]}),(0,F.jsxs)(`section`,{className:`settings-notification-check`,"aria-label":`通知权限检测`,"data-browser-notification-permission":o,children:[(0,F.jsxs)(`dl`,{children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`Super Pi 通知开关`}),(0,F.jsx)(`dd`,{children:a?`已开启`:`已关闭`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`当前浏览器站点权限`}),(0,F.jsx)(`dd`,{"data-notification-permission-label":!0,children:o===`granted`?`已允许`:o===`denied`?`已阻止`:o==="default"?`尚未授权`:o===`insecure`?`需要 HTTPS 或 localhost`:`浏览器不支持`})]})]}),(0,F.jsxs)(`p`,{role:`status`,"data-notification-effective":l?`enabled`:a?`blocked`:`disabled`,children:[(0,F.jsx)(`strong`,{children:l?`浏览器通知已就绪`:a?`通知尚未生效`:`通知未启用`}),a&&o!==`granted`?`:平台开关已开启,但浏览器尚不允许发送通知。`:``]}),(0,F.jsx)(`p`,{children:c}),(0,F.jsxs)(`div`,{className:`settings-notification-check-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-notification-recheck":!0,onClick:()=>{e.onCheckBrowserNotifications?.(),n(`已重新读取当前浏览器的站点通知权限。`)},children:`重新检测`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-notification-test":!0,disabled:!l,onClick:()=>{if(e.onCheckBrowserNotifications?.(),!(`Notification`in window)||Notification.permission!==`granted`)n(`浏览器当前未允许通知,请先调整站点权限。`);else try{i(new Notification(`Super Pi · 测试通知`,{body:`如果你看到这条系统通知,说明当前浏览器的通知可以正常显示。`,tag:`super-pi-permission-test`})),n(`已请求发送测试通知;若没有看到,请检查系统对浏览器的通知权限及勿扰模式。`)}catch{n(`浏览器未能发送测试通知,请检查站点和系统通知设置。`)}},children:`发送测试通知`})]}),(0,F.jsx)(`p`,{className:`settings-notification-help`,children:`此检测反映当前站点的浏览器授权。操作系统的通知开关、勿扰模式也可能拦截显示,可用测试通知确认。`}),t&&(0,F.jsx)(`p`,{role:`status`,children:t})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function ig({context:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)(``),[a,o]=(0,u.useState)(!1),s=e.agentCatalog,c=e.subagentCatalog,l=s?.agents??[],d=c?.agents??[],f=Bh([...l,...d]),p=[...s?.problems??[],...c?.problems??[]],m=[...new Set([...s?.directories??(s?.directory?[s.directory]:[]),...e.customAgentDirs??[]])],h=e.customAgentDirs??[],g=r=>{if(r.preventDefault(),e.pendingSettings)return;let a=t.trim();a&&(h.includes(a)?i(`该路径已存在于自定义目录列表中`):(e.onSetCustomAgentDirs?.([...h,a]),n(``),i(``)))},_=t=>{let n=h.filter(e=>e!==t);e.onSetCustomAgentDirs?.(n)};return(0,F.jsxs)(`div`,{className:`settings-agents-container`,children:[(0,F.jsxs)(`div`,{className:`settings-agents-header`,children:[(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`Super Pi 支持多目录发现智能体。系统会按优先级自上而下合并扫描目录;若存在同名配置,高优先级目录的文件将覆盖低优先级目录。`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:()=>{o(!0),e.onRescanAgents?.(),setTimeout(()=>o(!1),600)},disabled:a,title:`重新扫描所有目录中的智能体定义文件`,children:a?`正在扫描…`:`🔄 立即重新扫描`})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`发现路径清单(按优先级自高到低)`}),(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:m.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无活跃的发现路径`}):m.map((t,n)=>{let r=h.includes(t),i=t.includes(`.super_pi`)||t.includes(`.super-pi`)||t.includes(`.pi`),a=!r&&!i,o=f.filter(e=>e.sourceDir===t).length;return(0,F.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,F.jsxs)(`div`,{className:`settings-dir-info`,children:[(0,F.jsxs)(`span`,{className:`settings-dir-priority`,children:[`#`,n+1]}),(0,F.jsx)(`span`,{className:`settings-dir-path`,title:t,children:t}),(0,F.jsx)(`span`,{className:`settings-dir-tag`,children:r?`自定义`:i?`用户全局`:a?`内置`:`环境`}),(0,F.jsxs)(`span`,{className:`settings-dir-count`,children:[`(发现 `,o,` 个智能体)`]})]}),r&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,disabled:e.pendingSettings,onClick:()=>_(t),title:`移除此自定义扫描路径`,children:`移除`})]},t)})})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`添加自定义路径`}),(0,F.jsxs)(`form`,{onSubmit:g,className:`settings-add-dir-form`,children:[(0,F.jsx)(`input`,{type:`text`,className:`settings-dir-input`,value:t,onChange:e=>{n(e.target.value),r&&i(``)},onKeyDown:e=>{e.key===`Enter`&&Gh(e)&&e.preventDefault()},placeholder:`输入本地目录绝对路径或 ~/ 开头路径,如 D:\\agents 或 ~/.super_pi/agents`}),(0,F.jsx)(`button`,{type:`submit`,className:`settings-dir-add-btn`,disabled:e.pendingSettings||!t.trim(),children:`添加目录`})]}),r&&(0,F.jsx)(`div`,{className:`settings-dir-error`,children:r})]}),p.length>0&&(0,F.jsxs)(`section`,{className:`settings-section settings-problems-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-problems-title`,children:[`⚠️ 发现 `,p.length,` 个文件解析问题`]}),(0,F.jsx)(`div`,{className:`settings-problems-list`,children:p.map((e,t)=>(0,F.jsxs)(`div`,{className:`settings-problem-row`,children:[(0,F.jsx)(`span`,{className:`settings-problem-file`,children:e.file}),`: `,e.message]},t))})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`已发现的智能体(共 `,f.length,` 个)`]}),f.length===0?(0,F.jsxs)(`div`,{className:`settings-empty-hint`,children:[`当前未发现任何智能体。请在上述目录中添加 `,(0,F.jsx)(`code`,{children:`.md`}),` 文件(需包含 YAML frontmatter)。`]}):(0,F.jsx)(`div`,{className:`settings-agent-grid`,children:f.map(e=>(0,F.jsxs)(`div`,{className:`settings-agent-card`,children:[(0,F.jsxs)(`div`,{className:`settings-agent-card-header`,children:[(0,F.jsx)(`span`,{className:`settings-agent-name`,children:e.name}),(0,F.jsxs)(`span`,{className:`settings-agent-id`,children:[`(`,e.id,`)`]}),(0,F.jsx)(`span`,{className:`settings-agent-mode-badge ${e.mode}`,children:e.mode===`primary`?`主智能体`:`子智能体`})]}),e.sourceDir&&(0,F.jsxs)(`div`,{className:`settings-agent-source`,title:e.sourceDir,children:[`来源:`,e.sourceDir]}),e.description&&(0,F.jsx)(`div`,{className:`settings-agent-desc`,children:e.description}),(0,F.jsxs)(`div`,{className:`settings-agent-footer`,children:[(0,F.jsx)(`span`,{className:`settings-agent-tools`,children:e.toolSummary}),e.model&&(0,F.jsxs)(`span`,{className:`settings-agent-model`,children:[e.model.provider,`/`,e.model.modelId]})]})]},`${e.sourceDir}-${e.id}`))})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function ag(e){return(0,F.jsx)(ig,{context:e})}function og({context:e}){let[t,n]=(0,u.useState)({enabled:!1}),[r,i]=(0,u.useState)(``),a=(0,u.useCallback)(async e=>{try{let[t,r]=await Promise.all([Pe(`/api/terminal`).then(e=>e.json()),Pe(`/api/terminal-shell`).then(e=>e.json())]);n({...r,enabled:t.enabled}),e&&i(r.shell?[r.shell.file,...r.shell.args].map(e=>/\s/.test(e)?`"${e}"`:e).join(` `):``)}catch{}},[]);(0,u.useEffect)(()=>{a(!0)},[a]);let o=(0,u.useRef)(e.terminalShell);return(0,u.useEffect)(()=>{o.current!==e.terminalShell&&(o.current=e.terminalShell,a(!1))},[e.terminalShell,a]),t.enabled?(0,F.jsx)(`section`,{className:`settings-panel-container`,"data-terminal-settings":`1`,children:(0,F.jsxs)(`div`,{className:`settings-section`,children:[(0,F.jsxs)(`p`,{className:`settings-empty-hint`,children:[`当前生效:`,(0,F.jsx)(`code`,{children:t.shell?[t.shell.file,...t.shell.args].join(` `):``}),`(来自`,t.source,`)。只影响新开的终端。`]}),(0,F.jsx)(`label`,{className:`settings-section-title`,children:`默认 shell`}),(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-terminal-shell-input":`1`,value:r,onChange:e=>i(e.target.value),placeholder:`例如 wsl.exe -e zsh`}),(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:(t.candidates??[]).map(e=>(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:()=>i([e.file,...e.args].map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)),children:e.label},`${e.file}:${e.args.join(` `)}`))}),(0,F.jsx)(`div`,{children:(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-terminal-shell-save":`1`,onClick:()=>e.onSetTerminalShell?.(r.trim()||null),children:`保存`})})]})}):(0,F.jsx)(`section`,{className:`settings-panel-container`,"data-terminal-settings":`disabled`,children:(0,F.jsx)(`p`,{className:`settings-empty-hint`,children:`终端没有启用,无法设置默认 shell。`})})}function sg({context:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)(``),[a,o]=(0,u.useState)(),s=e=>{try{return new RegExp(e,`i`),!1}catch{return!0}},c=s(t),l=s(r),d=e.modelFilterRules??[];return(0,F.jsxs)(`section`,{"data-model-rules":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`按工作区约束可用模型。`}),`当工作区名称匹配指定正则表达式时,会话中仅可选择符合模型正则的模型(匹配模型名称或 `,(0,F.jsx)(`code`,{children:`provider/modelId`}),`)。多条命中规则必须全部满足。`]})}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`已配置的过滤规则(共 `,d.length,` 条)`]}),d.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无模型过滤规则。所有工作区默认可使用全部已配置模型。`}):(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:d.map(t=>{let r=a===t.id;return(0,F.jsxs)(`div`,{className:`settings-rule-card ${r?`editing`:``}`,children:[(0,F.jsx)(`div`,{className:`settings-rule-info`,children:(0,F.jsxs)(`div`,{className:`settings-rule-patterns`,children:[(0,F.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,F.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`工作区`}),(0,F.jsx)(`code`,{className:`settings-rule-code`,title:t.workspacePattern,children:t.workspacePattern})]}),(0,F.jsx)(`span`,{className:`settings-rule-arrow`,"aria-hidden":`true`,children:`→`}),(0,F.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,F.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`允许模型`}),(0,F.jsx)(`code`,{className:`settings-rule-code`,title:t.modelPattern,children:t.modelPattern})]})]})}),(0,F.jsxs)(`div`,{className:`settings-rule-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>{o(t.id),n(t.workspacePattern),i(t.modelPattern)},children:r?`编辑中`:`编辑`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>{a===t.id&&(o(void 0),n(``),i(``)),e.onSetModelRules?.(d.filter(e=>e.id!==t.id))},children:`删除`})]})]},t.id)})})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:a?`编辑过滤规则`:`添加新规则`}),(0,F.jsxs)(`fieldset`,{disabled:e.pendingSettings,className:`model-rules-fields settings-rule-fieldset`,children:[(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`工作区名正则表达式`}),(0,F.jsx)(`input`,{type:`text`,"data-rule-workspace":`1`,className:`settings-dir-input`,value:t,"aria-invalid":c,placeholder:`如 ^proj- 或 my-workspace`,onChange:e=>n(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`允许的模型名正则表达式`}),(0,F.jsx)(`input`,{type:`text`,"data-rule-model":`1`,className:`settings-dir-input`,value:r,"aria-invalid":l,placeholder:`如 anthropic/.* 或 gpt-4o|claude`,onChange:e=>i(e.target.value)})]})]}),(c||l)&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ 正则表达式语法不合法,请检查后修正。`}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,"data-rule-save":`1`,className:`settings-dir-add-btn`,disabled:!t.trim()||!r.trim()||c||l,onClick:()=>{let s={id:a??Wt(),workspacePattern:t.trim(),modelPattern:r.trim()};e.onSetModelRules?.([...d.filter(e=>e.id!==s.id),s]),n(``),i(``),o(void 0)},children:a?`保存修改`:`添加规则`}),a&&(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{o(void 0),n(``),i(``)},children:`取消编辑`})]})]})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function cg({catalog:e,customProviders:t,onEditModel:n}){let[r,i]=(0,u.useState)(!0),a=e?.models??[];if(a.length===0)return null;let o={};for(let e of a){let t=e.provider||`other`;o[t]||(o[t]=[]),o[t].push(e)}let s=Object.keys(o).sort(),c=new Set((t??[]).filter(e=>e.builtin).map(e=>e.id));return(0,F.jsxs)(`div`,{className:`settings-system-models`,"data-system-models":`1`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`settings-system-models-toggle`,onClick:()=>i(!r),"aria-expanded":!r,children:[(0,F.jsx)(`span`,{className:`settings-system-models-icon`,children:r?`▸`:`▾`}),(0,F.jsxs)(`span`,{className:`settings-system-models-title`,children:[`已发现的可用模型清单(共 `,a.length,` 个模型 · `,s.length,` 个供应商)`]})]}),!r&&(0,F.jsxs)(`div`,{className:`settings-system-models-content`,children:[(0,F.jsx)(`p`,{className:`settings-agents-desc settings-system-models-note`,children:`Pi 现在实际提供这些模型。改动和删除请在下方「Pi 的供应商与模型」里做——那里编辑的就是 Pi 自己的配置,这里只是它被 Pi 读出来的结果。`}),s.map(e=>{let t=o[e],r=c.has(e);return(0,F.jsxs)(`div`,{className:`settings-system-group`,children:[(0,F.jsxs)(`div`,{className:`settings-system-group-head`,children:[(0,F.jsx)(`span`,{className:`settings-system-group-name`,children:e}),(0,F.jsxs)(`span`,{className:`settings-system-group-count`,children:[`(`,t.length,` 个模型)`]}),(0,F.jsx)(`span`,{className:`settings-system-badge ${r?`system`:`custom`}`,children:r?`Pi 提供`:`models.json 定义`})]}),(0,F.jsx)(`div`,{className:`settings-system-model-list`,children:t.map(t=>(0,F.jsxs)(`div`,{className:`settings-system-model-row`,children:[(0,F.jsxs)(`div`,{className:`settings-system-model-info`,children:[(0,F.jsx)(`span`,{className:`settings-system-model-name`,children:t.label||t.modelId}),(0,F.jsx)(`code`,{className:`settings-system-model-id`,children:t.modelId})]}),n&&(0,F.jsx)(`div`,{className:`settings-system-model-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,"data-system-model-edit":`${e}:${t.modelId}`,onClick:()=>n?.(e,t.modelId,t.label),children:`编辑配置`})})]},t.modelId))})]},e)})]})]})}var lg=e=>{try{let t=e.trim();if(!t)return`custom-provider`;let n=new URL(t.startsWith(`http`)?t:`https://${t}`),r=n.hostname.toLowerCase();if(r.includes(`openai`))return`openai`;if(r.includes(`anthropic`))return`anthropic`;if(r.includes(`deepseek`))return`deepseek`;if(r.includes(`google`)||r.includes(`gemini`))return`google`;if(r.includes(`groq`))return`groq`;if(r.includes(`mistral`))return`mistral`;if(r.includes(`moonshot`)||r.includes(`kimi`))return`moonshot`;if(r.includes(`ollama`)||n.port===`11434`)return`ollama`;let i=r.split(`.`).filter(e=>e!==`api`&&e!==`v1`&&e!==`com`&&e!==`org`&&e!==`net`&&e!==`cn`&&e!==`ai`&&e!==`io`);return i.length>0&&i[0]&&i[0].replace(/[^a-z0-9_-]/g,``)||`custom-provider`}catch{return`custom-provider`}};function ug({context:e,externalEditModel:t,offered:n}){let r=e.providers??[],i=e.providerApis??[],[a,o]=(0,u.useState)({kind:`add`}),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)(``),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(``),[g,_]=(0,u.useState)(``),[v,y]=(0,u.useState)(!1),[b,x]=(0,u.useState)(``),[S,C]=(0,u.useState)(``),[w,T]=(0,u.useState)(!1),[E,D]=(0,u.useState)(!1),[O,k]=(0,u.useState)(``),[A,j]=(0,u.useState)(``),[ee,M]=(0,u.useState)(!0),[te,N]=(0,u.useState)(!0),[ne,re]=(0,u.useState)(),[ie,ae]=(0,u.useState)(``),[oe,se]=(0,u.useState)(!1),[ce,le]=(0,u.useState)(),[ue,de]=(0,u.useState)([]),[fe,pe]=(0,u.useState)(``),[me,he]=(0,u.useState)(new Set),[ge,P]=(0,u.useState)(),_e=(0,u.useRef)(``);_e.current=Hh(f,m),(0,u.useEffect)(()=>{if(!t)return;let{provider:e,modelId:n,label:a}=t;ye.current=!0;let s=r.find(t=>t.id===e);if(s){Ce(s);let t=s.models.find(e=>e.id===n);t?(we(t,Hh(s.baseUrl,s.api)),o({kind:`editModel`,providerId:e,modelId:n})):(we(void 0,``),x(n),C(a&&a!==n?a:``),o({kind:`addModel`,providerId:e}))}else c(e),d(e),p(``),h(i[0]??`openai-completions`),_(``),y(!1),x(n),C(a&&a!==n?a:``),T(!1),D(!1),k(``),j(``),o({kind:`add`});document.querySelector(`.settings-provider-form`)?.scrollIntoView({behavior:`smooth`})},[t]);let ve=a.kind===`add`?void 0:r.find(e=>e.id===a.providerId),ye=(0,u.useRef)(!1),be=()=>{ye.current=!0},xe=(0,u.useRef)(!1);(0,u.useEffect)(()=>{xe.current&&(xe.current=!1,!ye.current&&Se())},[r]);let Se=()=>{o({kind:`add`}),ye.current=!1,c(``),d(``),p(``),h(i[0]??`openai-completions`),_(``),y(!1),x(``),C(``),T(!1),D(!1),k(``),j(``),M(!0),N(!0),re(void 0),ae(``),se(!1),le(void 0),de([]),pe(``),he(new Set),P(void 0)},Ce=e=>{c(e.id),d(e.name===e.id?``:e.name),p(e.baseUrl),h(e.api),_(``),y(!1)},we=(e,t)=>{x(e?.id??``),C(!e||e.name===e.id?``:e.name),T(e?.reasoning??!1),D(e?.imageInput??!1),k(e?String(e.contextWindow):``),j(e?String(e.maxTokens):``),M(!0),N(!0),re(e?.thinkingLevelMap?{map:{...e.thinkingLevelMap},endpoint:t,modelId:e.id}:void 0)},Te=e=>{let t=r.find(t=>t.id===e);t&&(be(),o({kind:`addModel`,providerId:e}),Ce(t),we(void 0,``))},Ee=(e,t)=>{let n=r.find(t=>t.id===e),i=n?.models.find(e=>e.id===t);n&&i&&(be(),o({kind:`editModel`,providerId:e,modelId:t}),Ce(n),we(i,Hh(n.baseUrl,n.api)))},De=(e,t)=>{let n=r.find(t=>t.id===e),i=n?.models.find(e=>e.id===t);if(n&&i?.thinkingLevelMap)return{map:i.thinkingLevelMap,endpoint:Hh(n.baseUrl,n.api),reasoning:i.reasoning}},Oe=(e,t,n)=>{let r=De(e,t.id);we(r?.endpoint===n?{...t,reasoning:r.reasoning}:t,n)},ke=(e,t,n)=>{let r=Hh(f,m),i=De(e,t);if(i?.endpoint!==r){if(n)return ie===r?{...n}:null;if(i)return null}},Ae=(e,t)=>{let n=Hh(f,m),r=De(e,t);if(r&&r.endpoint===n)return{...r.map};if(ne&&ne.modelId===t&&ne.endpoint===n)return ne.map;if(r)return null},je=e=>e===void 0?{}:{thinkingLevelMap:e},Me=ie===Hh(f,m),Ne=async()=>{if(!f.trim()){le(`请先填写 API 地址`);return}if(!s.trim()){let e=lg(f);c(e),l.trim()||d(e)}se(!0),le(void 0);let e=Hh(f,m);try{let t=s.trim()||lg(f),n=await Pe(`/api/providers/fetch-models`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({baseUrl:f.trim(),apiKey:g.trim(),api:m,providerId:t})}),r=await n.json();if(!n.ok||!r.ok)throw Error(r.error||`获取模型失败`);if(_e.current!==e){de([]),he(new Set),le(`API 地址已改动,这次探测的结果没有采用`);return}let i=r.models||[];de(i),he(new Set(i.map(e=>e.id))),ae(e),i.length===1&&Oe(t,i[0],e)}catch(e){le(e instanceof Error?e.message:String(e))}finally{se(!1)}},Fe=()=>{if(me.size===0||!f.trim()||ie!==Hh(f,m))return;let t=s.trim()||lg(f);s.trim()||c(t);let n=ue.filter(e=>me.has(e.id));n.length&&(xe.current=!0,ye.current=!1,e.onSetProvider?.({id:t,...l.trim()?{name:l.trim()}:{name:t},baseUrl:f.trim(),api:m.trim()||`openai-completions`,...g.trim()?{apiKey:g.trim()}:{},models:n.map(e=>({id:e.id,name:e.name||e.id,reasoning:e.reasoning,imageInput:e.imageInput,contextWindow:e.contextWindow,maxTokens:e.maxTokens,supportsDeveloperRole:!0,supportsReasoningEffort:!0,...je(ke(t,e.id,e.thinkingLevelMap))}))}),de([]))},Ie=s.trim()||(f.trim()?lg(f):``),Le=f.trim()&&b.trim()&&!e.pendingSettings,[Re,ze]=(0,u.useState)(``),Be=r.filter(e=>!e.disabled&&(!e.builtin||e.id===Re||e.id===t?.provider)),Ve=r.filter(e=>e.disabled);return(0,F.jsxs)(`section`,{className:`settings-section`,"data-settings-providers":`1`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`Pi 的供应商与模型`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`停用后保留配置,随时可以重新启用。`}),(0,F.jsx)(kh,{providers:r}),(0,F.jsx)(dg,{providers:r}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`Pi 内置供应商配置`}),(0,F.jsxs)(`select`,{className:`settings-model-select`,"data-builtin-provider-picker":!0,value:Re,onChange:e=>ze(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`选择需要配置的供应商`}),r.filter(e=>e.builtin&&!e.disabled).map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),Be.length>0?(0,F.jsx)(`div`,{className:`settings-provider-list`,children:Be.map(t=>(0,F.jsxs)(`div`,{className:`settings-provider-card`,"data-provider-row":t.id,children:[(0,F.jsxs)(`div`,{className:`settings-provider-head`,children:[(0,F.jsx)(`span`,{className:`settings-provider-id`,children:t.id}),t.name!==t.id&&(0,F.jsx)(`span`,{className:`settings-provider-name`,children:t.name}),t.hasKey&&t.authType!==`oauth`&&(0,F.jsx)(`span`,{className:`settings-provider-badge`,children:`已设置 key`}),t.authType===`oauth`&&(0,F.jsx)(`span`,{className:`settings-provider-badge`,children:t.authenticated?`已授权登录`:`OAuth 授权`}),t.keyInModelsJson&&(0,F.jsx)(`span`,{className:`settings-provider-badge`,children:`key 在 models.json`}),t.builtin&&(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-builtin`,children:`Pi 内置`})]}),t.builtin?(0,F.jsx)(`div`,{className:`settings-provider-meta`,children:`模型由 Pi 提供,可停用`}):(0,F.jsxs)(`div`,{className:`settings-provider-meta`,children:[t.baseUrl,` · `,t.api]}),t.invalidFields&&t.invalidFields.length>0&&(0,F.jsxs)(`div`,{className:`settings-provider-note settings-provider-note-warn`,children:[`这个条目的 `,t.invalidFields.join(`、`),` 是空字符串,Pi 的 schema 不接受, 于是它拒绝整个 models.json —— 文件里所有自定义供应商都不会出现在选择器里。`]}),t.authType!==`oauth`&&!t.hasKey&&!t.keyInModelsJson&&(0,F.jsx)(`div`,{className:`settings-provider-note settings-provider-note-warn`,children:`没有可用凭据,Pi 不会提供这个供应商的模型 —— 它不会出现在任何模型选择器里。编辑里填一个 key 就能恢复。`}),t.authType!==`oauth`&&t.keyInModelsJson&&!t.hasKey&&(0,F.jsx)(`div`,{className:`settings-provider-note`,children:`key 写在 models.json 里(Pi 按其中的写法解析,例如 $VAR)。解析不到时 Pi 不会提供它。`}),n&&(n.has(t.id)?(0,F.jsx)(`div`,{className:`settings-provider-note`,children:`Pi 正在提供它的模型。`}):!t.hasKey&&!t.keyInModelsJson?null:(0,F.jsx)(`div`,{className:`settings-provider-note settings-provider-note-warn`,children:`Pi 现在没有提供它的模型(凭据可能已失效,或环境变量没解析到)。`})),(0,F.jsxs)(`div`,{className:`settings-provider-models`,children:[t.models.map(n=>(0,F.jsxs)(`div`,{className:`settings-provider-model-row`,"data-model-row":`${t.id}:${n.id}`,children:[(0,F.jsx)(`span`,{className:`settings-provider-model`,children:n.name}),(0,F.jsx)(`code`,{className:`settings-provider-model-id`,children:n.id}),!t.builtin&&(0,F.jsxs)(`div`,{className:`settings-provider-model-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,"data-model-edit":`${t.id}:${n.id}`,onClick:()=>Ee(t.id,n.id),children:`编辑`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link danger`,"data-model-delete":`${t.id}:${n.id}`,onClick:()=>e.onRemoveProviderModel?.(t.id,n.id),children:`删除`})]})]},n.id)),t.builtin&&t.models.length===0&&(0,F.jsx)(`div`,{className:`settings-provider-empty-note`,children:`暂未读取到模型清单`})]}),(0,F.jsxs)(`div`,{className:`settings-provider-actions`,children:[!t.builtin&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-provider-add-model":t.id,onClick:()=>Te(t.id),children:`添加模型`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-disable":t.id,onClick:()=>e.onToggleProvider?.(t.id,!1),children:`停用`}),ge===t.id?(0,F.jsxs)(`div`,{className:`settings-provider-delete-confirm`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn danger-confirm`,onClick:()=>{P(void 0),e.onRemoveProvider?.(t.id)},children:`确定删除?`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>P(void 0),children:`取消`})]}):(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-delete":t.id,onClick:()=>P(t.id),children:`删除供应商`})]})]},t.id))}):(0,F.jsx)(`div`,{className:`settings-empty-hint settings-provider-empty-note`,children:`选择上方的 Pi 内置供应商查看配置,也可以在下方添加自定义供应商。`}),Ve.length>0&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`已停用的供应商`}),(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[`这些供应商已经从 Pi 的配置里拿掉,所以不会出现在任何模型选择器里。启用会把`,(0,F.jsx)(`code`,{children:`models.json`}),` 定义和凭据原样放回去。`]}),(0,F.jsx)(`div`,{className:`settings-provider-list`,children:Ve.map(t=>(0,F.jsxs)(`div`,{className:`settings-provider-card settings-provider-card-off`,"data-provider-off-row":t.id,children:[(0,F.jsxs)(`div`,{className:`settings-provider-head`,children:[(0,F.jsx)(`span`,{className:`settings-provider-id`,children:t.id}),t.name!==t.id&&(0,F.jsx)(`span`,{className:`settings-provider-name`,children:t.name}),(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-off`,children:`已停用`}),t.builtin&&(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-builtin`,children:`Pi 内置`})]}),(0,F.jsx)(`div`,{className:`settings-provider-meta`,children:t.models.length?`原模型:${t.models.map(e=>e.name).join(`、`)}`:t.hasKey?`已保留凭据`:`无模型记录`}),(0,F.jsxs)(`div`,{className:`settings-provider-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-provider-enable":t.id,onClick:()=>e.onToggleProvider?.(t.id,!0),children:`启用`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-forget":t.id,onClick:()=>e.onRemoveProvider?.(t.id),children:`彻底删除`})]})]},t.id))})]}),(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[a.kind===`add`&&`添加供应商与模型`,a.kind===`addModel`&&`为供应商「${a.providerId}」添加模型`,a.kind===`editModel`&&`编辑模型「${a.modelId}」`]}),a.kind!==`add`&&(0,F.jsxs)(`p`,{className:`settings-agents-desc`,"data-provider-shared-note":`1`,children:[`上面这些是这个供应商下`,(0,F.jsx)(`b`,{children:`所有模型共用`}),`的(地址、API 类型、key)。改动会同时影响它下面的每个模型。`]}),(0,F.jsxs)(`div`,{className:`settings-provider-form`,onChange:be,children:[(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`供应商 id`}),(0,F.jsx)(`input`,{type:`text`,"data-provider-id":`1`,className:`settings-dir-input`,value:s,placeholder:`如 my-proxy`,readOnly:a.kind!==`add`,onChange:e=>c(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`显示名称`}),(0,F.jsx)(`input`,{type:`text`,"data-provider-name":`1`,className:`settings-dir-input`,value:l,placeholder:`如 公司中转`,onChange:e=>d(e.target.value)})]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 地址`}),(0,F.jsx)(`input`,{type:`text`,"data-provider-base-url":`1`,className:`settings-dir-input`,value:f,placeholder:`如 https://api.example.com/v1`,onBlur:()=>{if(f.trim()&&!s.trim()){let e=lg(f);c(e),l.trim()||d(e)}},onChange:e=>p(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 类型`}),(0,F.jsx)(`select`,{"data-provider-api":`1`,className:`settings-model-select`,value:m,onChange:e=>h(e.target.value),children:(i.length?i:[`openai-completions`]).map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))})]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`API key`}),(0,F.jsx)(`input`,{type:`password`,"data-provider-api-key":`1`,className:`settings-dir-input`,value:g,autoComplete:`off`,placeholder:ve?.hasKey?`已设置,留空表示不修改`:`如 sk-...`,onChange:e=>_(e.target.value)})]}),(0,F.jsxs)(`div`,{className:`settings-rule-input-group settings-fetch-models-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`智能探测`}),(0,F.jsx)(`div`,{className:`settings-fetch-models-row`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-fetch-models-btn`,"data-fetch-models-btn":`1`,disabled:!f.trim()||oe,onClick:Ne,children:oe?`正在连接并获取模型列表…`:`🔍 自动获取可用模型`})})]})]}),ce&&(0,F.jsx)(`div`,{className:`settings-fetch-models-error`,children:ce}),ue.length>0&&(0,F.jsxs)(`div`,{className:`settings-discovered-box`,"data-discovered-box":`1`,children:[(0,F.jsxs)(`div`,{className:`settings-discovered-head`,children:[(0,F.jsxs)(`span`,{className:`settings-discovered-title`,children:[`从远程接口探测到 `,ue.length,` 个可用模型`]}),(0,F.jsxs)(`div`,{className:`settings-discovered-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,onClick:()=>he(new Set(ue.map(e=>e.id))),children:`全选`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,onClick:()=>he(new Set),children:`清空`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link danger`,onClick:()=>de([]),children:`收起列表`})]})]}),(0,F.jsx)(`input`,{type:`text`,className:`settings-dir-input settings-discovered-search`,placeholder:`搜索模型名称或 ID…`,value:fe,onChange:e=>pe(e.target.value)}),(0,F.jsx)(`div`,{className:`settings-discovered-list`,children:ue.filter(e=>!fe||e.id.toLowerCase().includes(fe.toLowerCase())).map(e=>{let t=me.has(e.id);return(0,F.jsxs)(`div`,{className:`settings-discovered-item`,children:[(0,F.jsxs)(`label`,{className:`settings-discovered-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:t,onChange:t=>{let n=new Set(me);t.target.checked?n.add(e.id):n.delete(e.id),he(n)}}),(0,F.jsx)(`span`,{className:`settings-discovered-name`,children:e.name}),e.reasoning&&(0,F.jsx)(`span`,{className:`settings-discovered-tag reasoning`,children:`推理`}),e.imageInput&&(0,F.jsx)(`span`,{className:`settings-discovered-tag vision`,children:`视觉`}),e.thinkingLevelMap&&(0,F.jsxs)(`span`,{className:`settings-discovered-tag levels`,"data-discovered-levels":e.id,children:[`档位 `,Wh(e.thinkingLevelMap)]})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,title:`将此模型的参数填入下方单个编辑表单`,onClick:()=>Oe(Ie,e,ie),children:`填入下方`})]},e.id)})}),(0,F.jsx)(`div`,{className:`settings-discovered-footer`,children:(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-discovered-import":`1`,disabled:me.size===0||!f.trim()||oe||!Me,onClick:Fe,children:[`批量导入选中的 `,me.size,` 个模型并保存`]})}),!Me&&(0,F.jsx)(`div`,{className:`settings-fetch-models-error`,"data-discovered-stale":`1`,children:`API 地址已改动,下面这些候选是旧地址的,不能导入。改回原地址,或重新探测一次。`})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型 id`}),(0,F.jsx)(`input`,{type:`text`,"data-model-id":`1`,className:`settings-dir-input`,value:b,placeholder:`如 gpt-4o 或点击上方自动探测填入`,onChange:e=>x(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型显示名`}),(0,F.jsx)(`input`,{type:`text`,"data-model-name":`1`,className:`settings-dir-input`,value:S,placeholder:`留空则用模型 id`,onChange:e=>C(e.target.value)})]})]}),(0,F.jsx)(`div`,{className:`settings-rule-form-grid`,children:(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`上下文窗口 / 最大输出`}),(0,F.jsxs)(`div`,{className:`settings-provider-numbers`,children:[(0,F.jsx)(`input`,{type:`number`,"data-model-context-window":`1`,className:`settings-dir-input`,value:O,placeholder:`128000`,onChange:e=>k(e.target.value)}),(0,F.jsx)(`input`,{type:`number`,"data-model-max-tokens":`1`,className:`settings-dir-input`,value:A,placeholder:`16384`,onChange:e=>j(e.target.value)})]})]})}),(0,F.jsxs)(`div`,{className:`settings-provider-switches`,children:[(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-reasoning":`1`,checked:w,onChange:e=>T(e.target.checked)}),`推理模型`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-image-input":`1`,checked:E,onChange:e=>D(e.target.checked)}),`支持图片输入`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-developer-role":`1`,checked:ee,onChange:e=>M(e.target.checked)}),`支持 developer 角色`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-reasoning-effort":`1`,checked:te,onChange:e=>N(e.target.checked)}),`支持 reasoning_effort`]}),ve?.hasKey&&(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-provider-clear-key":`1`,checked:v,onChange:e=>y(e.target.checked)}),`清除已保存的 key`]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,"data-provider-save":`1`,className:`settings-dir-add-btn`,disabled:!Le,onClick:()=>{xe.current=!0,ye.current=!1;let t=s.trim()||Ie;e.onSetProvider?.({id:t,...l.trim()?{name:l.trim()}:{name:t},baseUrl:f.trim(),api:m.trim()||`openai-completions`,...g.trim()?{apiKey:g.trim()}:{},...v?{clearKey:!0}:{},models:[{id:b.trim(),...S.trim()?{name:S.trim()}:{},reasoning:w,...E?{imageInput:!0}:{},...O.trim()?{contextWindow:Number(O)}:{},...A.trim()?{maxTokens:Number(A)}:{},...ee?{}:{supportsDeveloperRole:!1},...te?{}:{supportsReasoningEffort:!1},...je(Ae(t,b.trim()))}]})},children:a.kind===`add`?`添加单个模型`:a.kind===`addModel`?`添加模型`:`保存修改`}),a.kind!==`add`&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-cancel":`1`,onClick:Se,children:`取消`})]})]})]})}function dg({providers:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)([]),[a,o]=(0,u.useState)(``),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)({}),f=e.filter(e=>e.authType===`oauth`&&!e.disabled),p=async e=>{let t=await Pe(`/api/providers/oauth`,{...e?{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}:{}}),n=await t.json();if(!t.ok)throw Error(n.error||`OAuth 授权失败。`);i(n.jobs??[])};(0,u.useEffect)(()=>{let e=!0,t=()=>{Pe(`/api/providers/oauth`).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error);e&&(i(n.jobs??[]),c(``))}).catch(t=>{e&&c(t instanceof Error?t.message:`无法读取登录状态。`)})};t();let n=window.setInterval(t,1200);return()=>{e=!1,window.clearInterval(n)}},[]);let m=async(e,t)=>{o(e),c(``);try{await p(t)}catch(e){c(e instanceof Error?e.message:`OAuth 操作失败。`)}finally{o(``)}};return f.length?(0,F.jsxs)(`section`,{className:`settings-section`,"data-provider-oauth":`1`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`内置供应商登录`}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`选择供应商`}),(0,F.jsx)(`select`,{className:`settings-model-select`,"data-oauth-provider-picker":!0,value:f.some(e=>e.id===t)?t:f[0]?.id??``,onChange:e=>n(e.target.value),children:f.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[e.name,e.authenticated?` · 已登录`:``]},e.id))})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`使用 Pi 内置的 OAuth 流程登录订阅或账号授权。令牌保存在服务端 Pi 凭据目录,不会显示在此页面。`}),s&&(0,F.jsx)(`p`,{className:`settings-dir-error`,role:`alert`,children:s}),(0,F.jsx)(`div`,{className:`settings-provider-list`,children:f.filter(e=>e.id===(f.some(e=>e.id===t)?t:f[0]?.id)).map(e=>{let t=[...r].reverse().find(t=>t.providerId===e.id),n=t&&[`starting`,`authorizing`,`prompt`].includes(t.state);return(0,F.jsxs)(`article`,{className:`settings-provider-card settings-oauth-card`,"data-oauth-provider":e.id,"data-oauth-state":t?.state??`idle`,children:[(0,F.jsxs)(`div`,{className:`settings-oauth-provider-head`,children:[(0,F.jsx)(`span`,{className:`settings-oauth-provider-mark`,"aria-hidden":`true`,children:e.name.trim().slice(0,1).toUpperCase()}),(0,F.jsxs)(`div`,{className:`settings-oauth-provider-copy`,children:[(0,F.jsx)(`span`,{className:`settings-provider-id`,children:e.name}),(0,F.jsx)(`span`,{className:`settings-oauth-provider-id`,children:e.id})]}),(0,F.jsxs)(`div`,{className:`settings-oauth-badges`,children:[e.oauthSubscription&&(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-builtin`,children:`订阅授权`}),(0,F.jsx)(`span`,{className:`settings-provider-badge ${e.authenticated?`settings-oauth-badge-connected`:``}`,children:e.authenticated?`已登录`:`未登录`})]})]}),(0,F.jsx)(`div`,{className:`settings-provider-meta settings-oauth-provider-meta`,children:e.oauthLoginLabel||`Pi 内置 OAuth`}),(0,F.jsxs)(`div`,{className:`settings-provider-actions settings-oauth-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!!a||!!n,onClick:()=>void m(e.id,{action:`login`,providerId:e.id}),children:n?`授权处理中…`:e.authenticated?`重新登录`:`登录`}),e.authenticated&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,disabled:!!a,onClick:()=>void m(e.id,{action:`logout`,providerId:e.id}),children:`退出登录`}),n&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>void m(t.id,{action:`cancel`,id:t.id}),children:`取消`})]}),t?.event?.type===`auth_url`&&(0,F.jsxs)(`div`,{className:`settings-oauth-step`,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`strong`,{children:`下一步:在浏览器中授权`}),t.event.instructions&&(0,F.jsx)(`p`,{children:String(t.event.instructions)})]}),(0,F.jsx)(`a`,{className:`settings-oauth-open-link`,href:String(t.event.url),target:`_blank`,rel:`noopener noreferrer`,children:`打开授权页面 ↗`})]}),t?.event?.type===`device_code`&&(0,F.jsxs)(`div`,{className:`settings-oauth-step settings-oauth-device-step`,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`strong`,{children:`在另一台设备上完成授权`}),(0,F.jsxs)(`p`,{children:[`访问 `,(0,F.jsx)(`a`,{href:String(t.event.verificationUri),target:`_blank`,rel:`noopener noreferrer`,children:String(t.event.verificationUri)}),`,并输入此设备码。`]})]}),(0,F.jsx)(`code`,{className:`settings-oauth-device-code`,children:String(t.event.userCode)})]}),t?.event?.type===`info`&&(0,F.jsx)(`p`,{className:`settings-oauth-message`,children:String(t.event.message??``)}),t?.event?.type===`progress`&&(0,F.jsxs)(`p`,{className:`settings-oauth-message`,role:`status`,children:[(0,F.jsx)(`span`,{className:`settings-oauth-progress-dot`}),String(t.event.message??`授权处理中`)]}),t?.prompt&&(0,F.jsxs)(`form`,{className:`settings-oauth-prompt`,onSubmit:e=>{e.preventDefault(),m(t.id,{action:`answer`,id:t.id,answer:l[t.id]??``})},children:[(0,F.jsxs)(`div`,{className:`settings-oauth-prompt-heading`,children:[(0,F.jsx)(`strong`,{children:`继续登录`}),(0,F.jsx)(`span`,{children:`完成身份验证所需的信息`})]}),t.prompt.type===`select`?(0,F.jsxs)(`label`,{className:`settings-oauth-field`,children:[(0,F.jsx)(`span`,{children:t.prompt.message}),(0,F.jsxs)(`select`,{className:`settings-oauth-select`,value:l[t.id]??``,onChange:e=>d(n=>({...n,[t.id]:e.target.value})),children:[(0,F.jsx)(`option`,{value:``,children:`请选择`}),t.prompt.options?.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),t.prompt.options?.find(e=>e.id===l[t.id])?.description&&(0,F.jsx)(`small`,{className:`settings-oauth-field-help`,children:t.prompt.options.find(e=>e.id===l[t.id]).description})]}):(0,F.jsxs)(`label`,{className:`settings-oauth-field`,children:[(0,F.jsx)(`span`,{children:t.prompt.message}),(0,F.jsx)(`input`,{className:`settings-oauth-input`,type:t.prompt.type===`secret`?`password`:`text`,autoComplete:`off`,placeholder:t.prompt.placeholder,value:l[t.id]??``,onChange:e=>d(n=>({...n,[t.id]:e.target.value}))})]}),(0,F.jsx)(`button`,{className:`settings-dir-add-btn settings-oauth-continue`,type:`submit`,disabled:!!a||!l[t.id],children:`继续`})]}),n&&(0,F.jsx)(`p`,{className:`settings-oauth-message`,children:`授权网页成功后,请等待服务端完成凭据交换与保存。`}),t?.state===`completed`&&(0,F.jsx)(`p`,{role:`status`,children:t.warning?`登录完成,凭据已保存。`:`登录完成,Pi 模型清单已刷新。`}),t?.warning&&(0,F.jsx)(`p`,{className:`settings-provider-note-warn`,role:`status`,children:t.warning}),t?.error&&(0,F.jsx)(`p`,{className:`settings-provider-note-warn`,role:`status`,children:t.error})]},e.id)})})]}):null}function fg({context:e}){let{connections:t,settingsServer:n,modelChannels:r}=ue(),i=t.find(e=>e.id===n),a=t.find(e=>e.id===`entry`)?.name??`当前入口`,o=i?.managed&&!i.legacy,s=i?.name??`当前入口`,c=e.modelCatalog,l=e.defaultModel,d=c?.models??[],f=d.reduce((e,t)=>e.includes(t.provider)?e:[...e,t.provider],[]),p=l?`${l.provider}/${l.modelId}`:``,[m,h]=(0,u.useState)(l?.provider??``),[g,_]=(0,u.useState)(l?.modelId??``),v=(0,u.useRef)(void 0);(0,u.useEffect)(()=>{v.current!==p&&(v.current=p,h(l?.provider??``),_(l?.modelId??``))},[p,l]);let y=l&&!f.includes(l.provider)?[...f,l.provider]:f,b=y.includes(m)?m:y[0]??``,x=d.filter(e=>e.provider===b),S=l&&l.provider===b&&!x.some(e=>e.modelId===l.modelId)?[...x,{provider:l.provider,modelId:l.modelId,label:l.label}]:x,C=S.some(e=>e.modelId===g)?g:S[0]?.modelId??``,w=!l||d.some(e=>e.provider===l.provider&&e.modelId===l.modelId),T=b&&C?`${b}/${C}`:``,E=T!==p,D=!c,O=c?.source===`unavailable`,[k,A]=(0,u.useState)(),j=e=>{h(e);let t=d.filter(t=>t.provider===e);_(e=>t.some(t=>t.modelId===e)?e:t[0]?.modelId??``)};return(0,F.jsxs)(`section`,{"data-settings-model":`1`,className:`settings-panel-container`,children:[o?(0,F.jsxs)(`section`,{className:`settings-section`,"data-model-route":`managed`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`模型请求路径`}),(0,F.jsxs)(`p`,{children:[s,` → 模型通道 → `,a,`(入口电脑) → 供应商`]}),(0,F.jsxs)(`p`,{children:[`供应商登录、API 密钥和代理保存在入口电脑。代理地址中的 `,(0,F.jsx)(`code`,{children:`127.0.0.1`}),` 指入口电脑,`,s,` 无需安装该代理。`]}),(0,F.jsxs)(`p`,{role:`status`,children:[`模型通道 · `,r[i.managedId??``]??`状态未知`]}),(0,F.jsx)(Oh,{}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,onClick:()=>me(`entry`),children:`在入口管理供应商、登录与代理`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>window.dispatchEvent(new Event(`super-pi-open-server-management`)),children:`查看服务器连接`})]})]}):null,(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`设置新建会话的默认模型。`}),`这里的选择适用于「`,s,`」上的工作区。工作区自己的默认模型优先,两者都没有时跟随 Pi 的默认模型。 默认值只在会话创建时复制一次,之后改这里不会改动已经存在的会话。`]})}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`当前默认模型`}),(0,F.jsx)(`div`,{className:`settings-model-current`,"data-model-current":`1`,children:l?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`span`,{className:`settings-model-current-name`,children:l.label}),(0,F.jsxs)(`code`,{className:`settings-model-current-pair`,children:[l.provider,`/`,l.modelId]})]}):(0,F.jsx)(`span`,{className:`settings-model-current-none`,children:`跟随 Pi 默认模型`})}),l&&!w&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ Pi 当前不再提供这个模型,新会话会改用 Pi 的默认模型。`})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`修改默认模型`}),D?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`正在读取 Pi 的模型列表…`}):O?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`无法读取 Pi 的模型列表,暂时不能设置默认模型。`}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`settings-model-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`供应商`}),(0,F.jsx)(`select`,{"data-model-provider":`1`,className:`settings-model-select`,value:b,disabled:e.pendingSettings||y.length===0,onChange:e=>j(e.target.value),children:y.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))})]}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`模型`}),(0,F.jsx)(`select`,{"data-model-select":`1`,className:`settings-model-select`,value:C,disabled:e.pendingSettings||S.length===0,onChange:e=>_(e.target.value),children:S.map(e=>(0,F.jsx)(`option`,{value:e.modelId,children:e.label},e.modelId))})]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,"data-model-save":`1`,className:`settings-dir-add-btn`,disabled:!E||e.pendingSettings||!T,onClick:()=>{let t=d.find(e=>e.provider===b&&e.modelId===C);t&&e.onSetDefaultModel?.({provider:t.provider,modelId:t.modelId,label:t.label})},children:`保存默认模型`}),(0,F.jsx)(`button`,{type:`button`,"data-model-clear":`1`,className:`settings-dir-cancel-btn`,disabled:!l||e.pendingSettings,onClick:()=>e.onSetDefaultModel?.(null),children:`清除默认模型`})]})]})]}),!o&&e.modelCatalog?.configError&&(0,F.jsxs)(`div`,{className:`settings-provider-note settings-provider-note-warn settings-provider-config-error`,"data-provider-config-error":`1`,children:[(0,F.jsx)(`div`,{children:`Pi 拒绝了自己的模型配置,因此它不提供文件里的任何自定义供应商:`}),(0,F.jsx)(`pre`,{className:`settings-provider-config-error-text`,children:e.modelCatalog.configError}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-repair":`1`,onClick:()=>e.onRepairProviders?.(),children:`修好这个文件`})]}),(0,F.jsx)(Nh,{}),!o&&(0,F.jsxs)(`section`,{className:`settings-section`,"data-model-route":`independent`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`供应商连接 · `,s]}),(0,F.jsxs)(`p`,{children:[`模型请求由「`,s,`」上的 Super Pi 服务发出,使用这台机器的登录和代理设置。`,n===`entry`&&`通过入口调用模型的托管服务器也使用这组供应商连接。`]})]}),!o&&(0,F.jsx)(ug,{context:e,externalEditModel:k,offered:new Set((e.modelCatalog?.models??[]).map(e=>e.provider))}),(0,F.jsx)(cg,{catalog:e.modelCatalog,customProviders:e.providers,onEditModel:o?void 0:(e,t,n)=>A({provider:e,modelId:t,label:n})}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}var pg=[{id:`appearance`,label:`外观`,render:$h},{id:`general`,label:`通用`,render:eg},{id:`desktop`,label:`桌面与后台`,render:()=>(0,F.jsx)(bh,{})},{id:`notifications`,label:`通知`,render:tg},{id:`memory`,label:`主动记忆`,render:e=>(0,F.jsx)(Sh,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`knowledge`,label:`知识库`,render:e=>(0,F.jsx)(wh,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`feishu`,label:`飞书`,render:()=>(0,F.jsx)(xh,{name:`飞书`,children:(0,F.jsx)(Th,{})})},{id:`tavily`,label:`Tavily 搜索`,render:()=>(0,F.jsx)(xh,{name:`Tavily`,children:(0,F.jsx)(jh,{})})},{id:`servers`,label:`服务器连接`,render:()=>(0,F.jsx)(Mn,{})},{id:`agents`,label:`智能体`,render:ag},{id:`model`,label:`模型`,render:e=>(0,F.jsx)(fg,{context:e})},{id:`native-tools`,label:`外部工具`,render:e=>(0,F.jsx)(Lh,{workspaceId:e.workspaceId})},{id:`model-rules`,label:`模型过滤`,render:e=>(0,F.jsx)(sg,{context:e})},{id:`terminal`,label:`终端`,render:e=>(0,F.jsx)(og,{context:e})}],mg=pg[0]?.id;function hg({initialCategory:e,workspaceId:t,theme:n,onChooseTheme:r,onClose:i,agentCatalog:a,subagentCatalog:o,modelFilterRules:s,onSetModelRules:c,defaultModel:l,modelCatalog:d,onSetDefaultModel:f,providers:p,providerApis:m,onSetProvider:h,onRemoveProvider:g,onToggleProvider:_,onRepairProviders:v,onRemoveProviderModel:y,customAgentDirs:b,pendingSettings:x,onSetCustomAgentDirs:S,onRescanAgents:C,userNickname:w,onSetUserNickname:T,terminalShell:E,onSetTerminalShell:D,browserNotificationsEnabled:O,browserNotificationPermission:k,onSetBrowserNotifications:A,onCheckBrowserNotifications:j}){let[ee,M]=(0,u.useState)(e??mg);(0,u.useEffect)(()=>{let e=()=>M(`servers`);return window.addEventListener(`super-pi-open-server-management`,e),()=>window.removeEventListener(`super-pi-open-server-management`,e)},[]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]);let{settingsServer:te}=ue();(0,u.useEffect)(()=>{let e=()=>{me(`entry`),M(`model`)};return window.addEventListener(`super-pi-open-local-model-settings`,e),()=>window.removeEventListener(`super-pi-open-local-model-settings`,e)},[]);let N=pg.find(e=>e.id===ee)??pg[0];return(0,F.jsx)(`div`,{className:`overlay`,onClick:i,children:(0,F.jsxs)(`div`,{className:`picker settings-window`,"data-theme-dialog":`1`,"data-settings-window":`1`,onClick:e=>e.stopPropagation(),children:[(0,F.jsxs)(`div`,{className:`settings-window-head`,children:[(0,F.jsx)(`h2`,{children:`设置`}),(0,F.jsx)(An,{})]}),(0,F.jsxs)(`div`,{className:`settings-window-body`,children:[(0,F.jsxs)(`nav`,{className:`settings-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`设置分类`,"data-settings-nav":`1`,children:[(0,F.jsx)(`div`,{className:`settings-nav-label`,children:`分类`}),pg.map(e=>(0,F.jsx)(`button`,{type:`button`,id:`settings-tab-${e.id}`,className:`settings-category`,role:`tab`,"aria-selected":e.id===N?.id,"aria-controls":`settings-panel`,tabIndex:e.id===N?.id?0:-1,"data-settings-category":e.id,onClick:()=>M(e.id),children:e.label},e.id))]}),N&&(0,F.jsxs)(`div`,{className:`settings-panel`,id:`settings-panel`,role:`tabpanel`,"aria-labelledby":`settings-tab-${N.id}`,"data-settings-panel":N.id,children:[(0,F.jsx)(`h3`,{className:`settings-panel-title`,"data-settings-panel-title":N.id,children:N.label}),N.render({workspaceId:t&&de(t)===te?t:void 0,theme:n,onChooseTheme:r,onClose:i,agentCatalog:a,subagentCatalog:o,modelFilterRules:s,onSetModelRules:c,defaultModel:l,modelCatalog:d,onSetDefaultModel:f,providers:p,providerApis:m,onSetProvider:h,onRemoveProvider:g,onToggleProvider:_,onRepairProviders:v,onRemoveProviderModel:y,customAgentDirs:b,pendingSettings:x,onSetCustomAgentDirs:S,onRescanAgents:C,userNickname:w,onSetUserNickname:T,terminalShell:E,onSetTerminalShell:D,browserNotificationsEnabled:O,browserNotificationPermission:k,onSetBrowserNotifications:A,onCheckBrowserNotifications:j})]},te)]})]})})}var gg=Object.defineProperty,_g=Object.getOwnPropertyDescriptor,vg=(e,t)=>{for(var n in t)gg(e,n,{get:t[n],enumerable:!0})},yg=(e,t,n,r)=>{for(var i=r>1?void 0:r?_g(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&gg(t,n,i),i},bg=(e,t)=>(n,r)=>t(n,r,e),xg=`Terminal input`,Sg={get:()=>xg,set:e=>xg=e},Cg=`Too much output to announce, navigate to rows manually to read`,wg={get:()=>Cg,set:e=>Cg=e};function Tg(e){return e.replace(/\r?\n/g,`\r`)}function Eg(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function Dg(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Og(e,t,n,r){e.stopPropagation(),e.clipboardData&&kg(e.clipboardData.getData(`text/plain`),t,n,r)}function kg(e,t,n,r){e=Tg(e),e=Eg(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function Ag(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function jg(e,t,n,r,i){Ag(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Mg(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ng(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Pg=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},Fg=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Ig=``,Lg=` `,Rg=class e{constructor(){this.fg=0,this.bg=0,this.extended=new zg}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},zg=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Bg=class e extends Rg{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new zg,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Mg(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Vg=`di$target`,Hg=`di$dependencies`,Ug=new Map;function Wg(e){return e[Hg]||[]}function Gg(e){if(Ug.has(e))return Ug.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Kg(t,e,r)};return t._id=e,Ug.set(e,t),t}function Kg(e,t,n){t[Vg]===t?t[Hg].push({id:e,index:n}):(t[Hg]=[{id:e,index:n}],t[Vg]=t)}var qg=Gg(`BufferService`),Jg=Gg(`CoreMouseService`),Yg=Gg(`CoreService`),Xg=Gg(`CharsetService`),Zg=Gg(`InstantiationService`),Qg=Gg(`LogService`),$g=Gg(`OptionsService`),e_=Gg(`OscLinkService`),t_=Gg(`UnicodeService`),n_=Gg(`DecorationService`),r_=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Bg,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):i_(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};r_=yg([bg(0,qg),bg(1,$g),bg(2,e_)],r_);function i_(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
315
|
+
已验证的步骤、命令和注意事项`:`输入长期有效的事实或偏好`,value:d,onChange:e=>f(e.target.value)}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{"aria-label":`核心记忆`,type:`checkbox`,checked:x,onChange:e=>S(e.target.checked)}),`核心记忆(预算内优先召回)`]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!d.trim(),onClick:async()=>{await O({action:`write`,operation:{target:c,action:p?`replace`:`add`,id:p,content:d,pinned:x,expectedRevision:n.entries[c]?.find(e=>e.id===p)?.revision??1}})&&(m(void 0),f(``),S(!1))},children:[`保存`,p?`修改`:`新条目`]}),C.length>=2&&(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!d.trim(),onClick:async()=>{await O({action:`write`,operation:{target:c,action:`consolidate`,ids:C,content:d,pinned:x,expectedRevisions:Object.fromEntries(n.entries[c].filter(e=>C.includes(e.id)).map(e=>[e.id,e.revision??1]))}})&&(w([]),f(``),m(void 0))},children:[`合并所选 `,C.length,` 条并归档原文`]}),p&&(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{m(void 0),f(``)},children:`取消编辑`})]})]})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`待审批提案(共 `,n.pending.length,` 个)`]}),n.pending.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无待审批提案。`}):(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:n.pending.map(e=>(0,F.jsxs)(`article`,{"data-memory-proposal":e.id,className:`settings-proposal-card`,children:[(0,F.jsxs)(`div`,{className:`settings-proposal-header`,children:[(0,F.jsx)(`span`,{className:`settings-proposal-badge`,children:e.operation.target}),(0,F.jsx)(`span`,{className:`settings-proposal-action`,children:e.operation.action})]}),e.previous&&(0,F.jsxs)(`pre`,{className:`settings-proposal-diff old`,children:[`原内容:`,e.previous]}),(0,F.jsx)(`pre`,{className:`settings-proposal-diff new`,children:e.operation.content}),(0,F.jsxs)(`div`,{className:`settings-proposal-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>void O({action:`approve`,proposalId:e.id}),children:`批准`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void O({action:`discard`,proposalId:e.id}),children:`拒绝`})]})]},e.id))})]})]}),t&&(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})})]}):(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理其专属记忆与技能。`})}function Ch({workspaceId:e,onClose:t,onPick:n}){let[r,i]=(0,u.useState)(),[a,o]=(0,u.useState)(!1),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)(``),[f,p]=(0,u.useState)(),m=(0,u.useRef)(0);async function h(t){let n=++m.current;o(!0),c(``);try{let r=await Pe(`/api/files?workspaceId=${encodeURIComponent(e)}${t?`&path=${encodeURIComponent(t)}`:``}`),a=await r.json();if(!r.ok)throw Error(a.error??`HTTP ${r.status}`);if(n!==m.current)return;i(a),p(void 0)}catch(e){n===m.current&&c(Or(e,`这个目录读取失败。`))}finally{n===m.current&&o(!1)}}(0,u.useEffect)(()=>{h()},[e]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.isComposing&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let g=l.trim().toLocaleLowerCase(),_=(0,u.useMemo)(()=>(r?.entries??[]).filter(e=>e.kind===`directory`||e.kind===`file`&&(e.text||e.document)&&!e.outside),[r]),v=g?_.filter(e=>e.name.toLocaleLowerCase().includes(g)):_;return(0,F.jsx)(`div`,{className:`overlay`,onClick:t,children:(0,F.jsxs)(`div`,{className:`picker knowledge-picker`,"data-knowledge-picker":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-label":`选择要导入的文档`,children:[(0,F.jsx)(`h2`,{children:`选择要导入的文档`}),(0,F.jsxs)(`div`,{className:`picker-path-bar`,children:[(0,F.jsx)(`input`,{"aria-label":`按文件名过滤`,className:`picker-path-input`,placeholder:`按文件名过滤…`,value:l,onChange:e=>d(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!r||r.parent===null||a,onClick:()=>void h(r?.parent??void 0),"aria-label":`上一级`,children:`↑`})]}),(0,F.jsx)(`div`,{className:`picker-status`,"data-knowledge-picker-path":r?.path??``,children:r?r.path||`工作区根目录`:`读取中…`}),s&&(0,F.jsx)(`div`,{className:`picker-error`,role:`alert`,children:s}),(0,F.jsx)(`div`,{className:`picker-list`,"data-knowledge-picker-list":v.length,children:v.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:g?`没有匹配的文件。`:`这个目录里没有可导入的文件。`}):v.map(e=>e.kind===`directory`?(0,F.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-dir":e.path,onClick:()=>void h(e.path),children:[`📁 `,e.name]},e.path):(0,F.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-file":e.path,"data-knowledge-picker-document":e.document?`1`:void 0,"aria-pressed":f===e.path,onClick:()=>p(e.path),onDoubleClick:()=>n(e.path),children:[e.document?`📕 文档`:`📄`,` `,e.name]},e.path))}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!f,"data-knowledge-picker-ok":f??``,onClick:()=>{f&&n(f)},children:`导入这个文档`})]})]})})}function wh({workspaceId:e,onClose:t}){let[n,r]=(0,u.useState)(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(!1),[c,l]=(0,u.useState)(``),[d,f]=(0,u.useState)(``),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(!1),y=(0,u.useRef)(e);y.current=e;let b=(0,u.useRef)(0);async function x(t){if(!e)return;let n=++b.current;s(!0),a(``);try{let i=await Pe(`/api/knowledge?workspaceId=${encodeURIComponent(e)}`,{method:t?`POST`:`GET`,headers:{"Content-Type":`application/json`},...t?{body:JSON.stringify(t)}:{}}),a=await i.json();if(!i.ok)throw Error(a.error);return y.current!==e||n!==b.current?!1:(r(a),!0)}catch(t){return y.current===e&&n===b.current&&a(Or(t,`知识库读取失败。`)),!1}finally{y.current===e&&n===b.current&&s(!1)}}if((0,u.useEffect)(()=>{r(void 0),l(``),f(``),m(``),g(``),x()},[e]),!e)return(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理它的知识库。`});let S=n?.documents??[],C=S.reduce((e,t)=>e+t.characters,0),w=n?.semantic,T=w?w.enabled?w.error?`不可用:${Or(w.error,`本地语义模型没有加载成功`)};已退回关键词检索`:w.ready?`已就绪,已索引 ${w.indexed} 个片段`:w.bundled===!1?`随包分发的模型缺失;已退回关键词检索`:`首次检索时加载本地模型,之后一直可用`:`已关闭(SUPER_PI_KNOWLEDGE_EMBEDDINGS=0)`:`未启用`;return(0,F.jsxs)(`section`,{"data-knowledge-panel":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`项目自己的文档。`}),` 浏览工作区里的规范、设计稿、会议纪要导入进来,Agent 就能在回答前检索原文,而不是凭记忆编造。文档按当前工作区隔离,检索结果只回传片段而不回传全文。关键词检索始终可用;语义检索能在用词不同的情况下找到片段,但代价是首次使用要下载一个本地模型。`]})}),(0,F.jsxs)(`div`,{className:`settings-dir-info`,"data-knowledge-semantic":w?w.error?`unavailable`:w.ready?`ready`:`loading`:`off`,title:w?.error,children:[`语义检索:`,T]}),i&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:i}),n&&(0,F.jsxs)(`fieldset`,{disabled:o,className:`settings-memory-fieldset`,children:[(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`从工作区文件导入(`,S.length,` 篇,共 `,C,` 字符)`]}),(0,F.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-knowledge-browse":`1`,onClick:()=>v(!0),children:`浏览工作区文件…`}),(0,F.jsx)(`span`,{className:`settings-dir-info`,children:`在工作区里挑选一个 Markdown 或文本文件`})]}),(0,F.jsxs)(`div`,{className:`settings-add-dir-form`,style:{marginTop:8},children:[(0,F.jsx)(`input`,{"aria-label":`文档路径`,className:`settings-dir-input`,placeholder:`或直接填写相对路径,例如 docs/design.md`,value:c,onChange:e=>l(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!c.trim(),onClick:async()=>{await x({action:`add`,path:c})&&l(``)},children:`导入`})]}),(0,F.jsxs)(`div`,{className:`settings-memory-editor`,style:{marginTop:12},children:[(0,F.jsx)(`h5`,{className:`settings-memory-editor-title`,children:`或者直接粘贴正文`}),(0,F.jsx)(`input`,{"aria-label":`文档标题`,className:`settings-dir-input`,placeholder:`标题(留空则取正文首行)`,value:d,onChange:e=>f(e.target.value)}),(0,F.jsx)(`textarea`,{"aria-label":`文档正文`,className:`settings-memory-textarea`,placeholder:`以 # 开头的标题会成为检索结果里的段落归属`,value:p,onChange:e=>m(e.target.value)}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!p.trim(),onClick:async()=>{await x({action:`add`,title:d,text:p})&&(f(``),m(``))},children:`保存文档`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{f(``),m(``)},children:`清空`})]})]})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`已导入文档`}),S.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`还没有文档。导入后,下一条消息起 Agent 就能检索到它们。`}):(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:S.map(e=>(0,F.jsxs)(`article`,{"data-knowledge-document":e.id,className:`settings-memory-card`,children:[(0,F.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,F.jsx)(`span`,{className:`settings-dir-tag`,children:e.format||`txt`}),(0,F.jsx)(`span`,{className:`settings-dir-path`,children:e.title}),(0,F.jsxs)(`span`,{className:`settings-dir-count`,children:[e.characters,` 字符`]})]}),(0,F.jsx)(`div`,{className:`settings-dir-info`,children:e.source}),(0,F.jsx)(`div`,{className:`settings-memory-card-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void x({action:`remove`,documentId:e.id}),children:`删除`})})]},e.id))})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`试检索`}),(0,F.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,F.jsx)(`input`,{"aria-label":`检索词`,className:`settings-dir-input`,placeholder:`用和提问时相同的措辞试试`,value:h,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&h.trim()&&x({action:`search`,query:h})}}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!h.trim(),onClick:()=>void x({action:`search`,query:h}),children:`检索`})]}),h.trim()&&(n?.hits?.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`没有命中。知识库确实没有这段内容——Agent 也会得到同样的空结果。`}):(0,F.jsx)(`div`,{className:`settings-memory-entries-list`,children:(n?.hits??[]).map(e=>(0,F.jsxs)(`article`,{"data-knowledge-hit":`${e.documentId}#${e.chunk}`,className:`settings-memory-card`,children:[(0,F.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,F.jsx)(`span`,{className:`settings-dir-tag`,children:e.title}),(0,F.jsxs)(`span`,{className:`settings-dir-count`,title:`相关度(越高越接近)`,children:[`相关度 `,e.score.toFixed(2)]})]}),e.heading&&(0,F.jsx)(`div`,{className:`settings-dir-info`,children:e.heading}),(0,F.jsx)(`pre`,{className:`settings-memory-content`,children:e.text})]},`${e.documentId}#${e.chunk}`))}))]})]}),t&&(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})}),_&&(0,F.jsx)(Ch,{workspaceId:e,onClose:()=>v(!1),onPick:async e=>{v(!1),await x({action:`add`,path:e})&&l(``)}})]})}function Th(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(!1),d=(0,u.useCallback)(async()=>{try{let e=await Pe(`/api/feishu/status`),n=await e.json();if(!e.ok)throw Error(n.error??`读取飞书状态失败`);t(n)}catch(e){s(Or(e,`读取飞书状态失败。`))}},[]);(0,u.useEffect)(()=>{d()},[d]);let f=async()=>{l(!0),a(``),s(``),r(void 0);try{let e=await Pe(`/api/feishu/connect`,{method:`POST`}),t=await e.json();if(!e.ok)throw Error(t.message??`连接失败`);r(t)}catch(e){s(Or(e,`连接飞书账号失败。`))}finally{l(!1)}},p=async()=>{l(!0),a(``),s(``);try{let e=await Pe(`/api/feishu/connect/complete`,{method:`POST`}),t=await e.json();if(!e.ok)throw Error(t.message??`完成连接失败`);r(void 0),a(t.message),await d()}catch(e){s(Or(e,`完成连接失败。`))}finally{l(!1)}},m=async()=>{l(!0),a(``),s(``);try{let e=await Pe(`/api/feishu/verify`,{method:`POST`}),t=await e.json();if(!e.ok)throw Error(t.message??`测试失败`);a(t.ok?t.message:`还没连上:${t.message}`),!t.ok&&t.hint&&s(t.hint),await d()}catch(e){s(Or(e,`测试飞书连接失败。`))}finally{l(!1)}},h=e?.step??1,g=e?.installed===!0,_=e?.connected===!0,v=e=>e<h?`done`:e===h?`current`:`pending`;return(0,F.jsxs)(`section`,{"data-feishu-panel":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`让 Agent 直接读写飞书云文档。`}),` 通过飞书官方的 CLI(`,(0,F.jsx)(`code`,{children:`lark-cli`}),`)接入:授权一次之后,Agent 就能用 feishu_doc_read 读一篇飞书文档、用 feishu_doc_write 追加或改写它。凭据由官方 CLI 保管在系统钥匙串里,Super Pi 不接触、不保存、也不显示。`]})}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`连接状态`}),(0,F.jsxs)(`div`,{className:`settings-dir-info`,"data-feishu-status":e?_?`connected`:g?`not-connected`:`not-installed`:void 0,children:[e?.message??`正在读取飞书 CLI 的状态…`,e?.version?`(CLI ${e.version})`:``,e?.appId?` 应用 ${e.appId}`:``,e?.identity?` 身份 ${e.identity===`user`?`你的账号`:`应用`}`:``]}),e?.detail&&(0,F.jsx)(`div`,{className:`settings-dir-info`,"data-feishu-detail":`1`,children:e.detail}),e?.hint&&(0,F.jsx)(`div`,{className:`settings-dir-info`,"data-feishu-hint":`1`,children:e.hint}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,style:{marginTop:8},children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-feishu-connect":`1`,disabled:c||!g,onClick:()=>void f(),children:e?.rebuild?`重新连接`:`连接飞书账号`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-feishu-verify":`1`,disabled:c||!g,onClick:()=>void m(),children:`测试连接`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,"data-feishu-refresh":`1`,disabled:c,onClick:()=>void d(),children:`刷新状态`})]}),i&&(0,F.jsx)(`div`,{className:`settings-dir-info`,"data-feishu-message":`1`,children:i}),o&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,"data-feishu-error":`1`,children:o})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`怎么连上`}),(0,F.jsxs)(`ol`,{className:`settings-agents-desc`,children:[(0,F.jsxs)(`li`,{"data-feishu-step":`1`,"data-feishu-step-state":v(1),children:[(0,F.jsx)(`b`,{children:`装官方 CLI。`}),`在终端里运行一次:`,(0,F.jsx)(`div`,{className:`settings-dir-input`,"data-feishu-install":`1`,children:`npm i -g @larksuite/cli`}),`已经装过就跳过这步。若 Super Pi 找不到它(两边的 PATH 不一样),用环境变量 `,(0,F.jsx)(`code`,{children:`SUPER_PI_FEISHU_CLI`}),` 指向它的完整路径再重启 Super Pi。`]}),(0,F.jsxs)(`li`,{"data-feishu-step":`2`,"data-feishu-step-state":v(2),children:[(0,F.jsx)(`b`,{children:`连上你的账号。`}),`点上面的「连接飞书账号」:浏览器里会打开一个确认链接(第一次是确认创建应用,之后是授权你的账号),确认完回到这里点「我已完成」。整个过程不用打开飞书开发者后台。`]}),(0,F.jsxs)(`li`,{"data-feishu-step":`3`,"data-feishu-step-state":v(3),children:[(0,F.jsx)(`b`,{children:`开始用。`}),`在对话里直接说「把这篇飞书文档读一下」「把结论写回文档」就行。Agent 以你的身份操作,你自己的文档不需要逐篇授权。`]})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`完整说明和常见问题在右侧「使用指南 → 飞书」里。`})]}),n&&(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:n.step===`app`?`确认创建应用`:`确认授权`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:n.message}),n.verificationUri&&(0,F.jsx)(`a`,{className:`settings-dir-add-btn`,"data-feishu-verify-link":`1`,href:n.verificationUri,target:`_blank`,rel:`noreferrer`,children:`打开授权链接`}),n.hint&&(0,F.jsx)(`div`,{className:`settings-dir-info`,children:n.hint}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,style:{marginTop:8},children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-feishu-complete":`1`,disabled:c,onClick:()=>void p(),children:`我已完成`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,disabled:c,onClick:()=>r(void 0),children:`取消`})]})]})]})}var Eh=e=>![`google`,`google-vertex`].includes(e.id)&&![`google-generative-ai`,`google-vertex`].includes(e.api);async function Dh(e){let t=await e.json();if(!e.ok)throw Error(t.error||`代理设置请求失败`);return t}function Oh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(!1);return(0,u.useEffect)(()=>{let e=new AbortController;return Ne(`/api/providers/network`,{signal:e.signal},`entry`).then(Dh).then(n=>{e.signal.aborted||t(n)}).catch(()=>{e.signal.aborted||r(!0)}),()=>e.abort()},[]),(0,F.jsxs)(`p`,{"data-entry-proxy":!0,children:[`入口代理 · `,n?`读取失败`:e?e.httpProxy?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`code`,{children:e.httpProxy}),` · `,e.providers.join(`、`)||`未选用供应商`]}):`未配置`:`正在读取…`]})}function kh({providers:e}){let{settingsServer:t,connections:n}=ue(),r=n.find(e=>e.id===t)?.name??`当前入口`,[i,a]=(0,u.useState)(),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(!1),[d,f]=(0,u.useState)([]),[p,m]=(0,u.useState)(!1),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(!1),y=`/api/providers/network`,b=e=>{a(e),s(e.hasAuth?``:e.httpProxy),f(e.providers),l(!1)};(0,u.useEffect)(()=>{let e=new AbortController;return Pe(y,{signal:e.signal}).then(Dh).then(t=>{e.signal.aborted||b(t)}).catch(t=>{e.signal.aborted||g(t instanceof Error?t.message:`读取失败`)}),()=>e.abort()},[]);let x=async()=>{if(p||!i)return;m(!0),g(``),v(!1);let t={providers:d.filter(t=>e.some(e=>e.id===t&&Eh(e))),...c?{httpProxy:o}:{}};try{b(await Pe(y,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).then(Dh)),v(!0)}catch(e){g(e instanceof Error?e.message:`保存失败`)}finally{m(!1)}};return(0,F.jsxs)(`section`,{className:`provider-network`,"data-provider-network":!0,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`代理`}),(0,F.jsxs)(`div`,{className:`provider-network-form`,children:[(0,F.jsx)(`p`,{children:`地址只需填写一次,再勾选使用代理的供应商。保存后,未勾选的供应商直连。`}),(0,F.jsxs)(`p`,{children:[`支持 HTTP / HTTPS 代理。地址中的 `,(0,F.jsx)(`code`,{children:`127.0.0.1`}),` 指运行「`,r,`」服务的电脑。`,t===`entry`&&`托管服务器借用入口模型时,也从这台电脑连接代理。`]}),!i&&!h&&(0,F.jsx)(`p`,{role:`status`,children:`正在读取代理设置…`}),i&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`代理地址`}),(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-provider-network-http":!0,autoComplete:`off`,value:o,disabled:p,placeholder:i.hasAuth?`已配置认证代理 ${i.httpProxy},留空保留`:`http://127.0.0.1:7890`,onChange:e=>{s(e.target.value),l(!0),v(!1)}})]}),(0,F.jsxs)(`fieldset`,{className:`provider-network-providers`,disabled:p,children:[(0,F.jsx)(`legend`,{children:`使用代理的供应商`}),e.length===0&&(0,F.jsx)(`p`,{children:`添加供应商后即可在这里勾选。`}),e.map(e=>(0,F.jsxs)(`label`,{className:`provider-network-choice`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-provider-network-choice":e.id,disabled:!Eh(e),checked:Eh(e)&&d.includes(e.id),onChange:t=>{f(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id)),v(!1)}}),(0,F.jsxs)(`span`,{children:[e.name||e.id,e.name&&e.name!==e.id?` (${e.id})`:``,e.disabled?` · 已停用`:``,Eh(e)?``:` · 原生 SDK 暂不支持此代理`]})]},e.id))]}),(0,F.jsx)(`div`,{className:`provider-network-actions`,children:(0,F.jsx)(`button`,{type:`button`,"data-provider-network-save":!0,disabled:p,onClick:()=>void x(),children:p?`正在保存…`:`保存代理设置`})})]}),h&&(0,F.jsx)(`p`,{className:`provider-network-warning`,role:`alert`,children:h}),_&&(0,F.jsx)(`p`,{role:`status`,"data-provider-network-saved":!0,children:`已保存,后续请求使用新设置。`})]})]})}async function Ah(e){let t=await e.json();if(!e.ok)throw Error(t.error??`Tavily 设置请求失败。`);return t}function jh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(``),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(``),d=(0,u.useCallback)(async()=>{s(``);try{t(await Pe(`/api/tavily/settings`,{cache:`no-store`}).then(Ah))}catch(e){s(e instanceof Error?e.message:`读取 Tavily 状态失败。`)}},[]);(0,u.useEffect)(()=>{d()},[d]);let f=async e=>{if(e.preventDefault(),!i&&n.trim()){a(!0),s(``),l(``);try{let e=await Pe(`/api/tavily/settings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:`connect`,apiKey:n})}).then(Ah);r(``),t(e),l(`Tavily 已连接。后续 Agent 会自动获得网页搜索工具。`)}catch(e){s(e instanceof Error?e.message:`连接 Tavily 失败。`)}finally{a(!1)}}},p=async()=>{if(!i){a(!0),s(``),l(``);try{let e=await Pe(`/api/tavily/settings`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:`disconnect`})}).then(Ah);t(e),l(`已断开 Tavily,网页搜索工具已从 Agent 工具列表中移除。`)}catch(e){s(e instanceof Error?e.message:`断开 Tavily 失败。`)}finally{a(!1)}}};return(0,F.jsxs)(`section`,{className:`tavily-settings`,"data-tavily-panel":!0,children:[(0,F.jsx)(`p`,{className:`tavily-description`,children:`连接自己的 Tavily 账号,让 Agent 使用你的搜索额度。API key 保存在 Super Pi 服务端,不会交给 Agent。`}),(0,F.jsxs)(`section`,{className:`tavily-section`,children:[(0,F.jsxs)(`div`,{className:`tavily-section-heading`,children:[(0,F.jsx)(`h4`,{children:`连接状态`}),(0,F.jsxs)(`div`,{className:`tavily-actions`,children:[(0,F.jsx)(`button`,{type:`button`,disabled:i||!e,onClick:()=>void d(),children:`刷新状态`}),e?.configured&&(0,F.jsx)(`button`,{type:`button`,"data-tavily-disconnect":!0,disabled:i,onClick:()=>void p(),children:`断开并删除 key`})]})]}),(0,F.jsx)(`p`,{className:`tavily-status`,role:`status`,"data-tavily-status":e?e.connected?`connected`:e.configured?`invalid`:`disconnected`:`loading`,children:e?e.connected?`已连接${e.keyHint?`(${e.keyHint})`:``}`:e.configured?`已保存的 key 暂时无法验证`:`未连接;Agent 不会看到网页搜索工具`:`正在读取 Tavily 状态…`}),e?.usage&&(0,F.jsxs)(`p`,{className:`tavily-description`,"data-tavily-usage":!0,children:[e.usage.plan?`${e.usage.plan} · `:``,`已用 `,e.usage.used.toLocaleString(),` / `,e.usage.limit.toLocaleString(),` credits,剩余 `,e.usage.remaining.toLocaleString()]}),e?.error&&(0,F.jsx)(`p`,{className:`tavily-feedback`,role:`status`,children:e.error})]}),!e?.configured&&(0,F.jsxs)(`section`,{className:`tavily-section`,children:[(0,F.jsx)(`h4`,{children:`连接你的账号`}),(0,F.jsxs)(`ol`,{className:`tavily-steps`,children:[(0,F.jsx)(`li`,{children:(0,F.jsx)(`a`,{href:`https://app.tavily.com`,target:`_blank`,rel:`noopener noreferrer`,children:`注册或登录 Tavily ↗`})}),(0,F.jsx)(`li`,{children:`在 Tavily 控制台复制你的 API key。`}),(0,F.jsx)(`li`,{children:`粘贴到下方。Super Pi 会先用不消耗搜索额度的用量接口验证 key。`})]}),(0,F.jsxs)(`form`,{className:`tavily-connect-form`,onSubmit:e=>void f(e),children:[(0,F.jsx)(`label`,{htmlFor:`tavily-api-key`,children:`Tavily API key`}),(0,F.jsx)(`input`,{id:`tavily-api-key`,"aria-describedby":`tavily-key-hint`,"data-tavily-key":!0,type:`password`,autoComplete:`new-password`,spellCheck:!1,value:n,onChange:e=>r(e.target.value),placeholder:`粘贴 Tavily API key`,disabled:i}),(0,F.jsx)(`p`,{id:`tavily-key-hint`,className:`tavily-hint`,children:`使用你自己的额度;付费方案由你在 Tavily 管理。`}),(0,F.jsx)(`div`,{className:`tavily-actions`,children:(0,F.jsx)(`button`,{type:`submit`,"data-tavily-connect":!0,disabled:i||!n.trim(),children:i?`正在验证…`:`连接 Tavily`})})]})]}),e?.configured&&(0,F.jsxs)(`section`,{className:`tavily-section`,children:[(0,F.jsx)(`h4`,{children:`Agent 搜索额度`}),(0,F.jsx)(`p`,{children:`Agent 使用 Tavily Basic Search。可在 Tavily 控制台查看用量、调整方案或管理付费。`}),(0,F.jsx)(`a`,{href:`https://app.tavily.com`,target:`_blank`,rel:`noopener noreferrer`,children:`打开 Tavily 控制台 ↗`})]}),o&&(0,F.jsx)(`p`,{className:`tavily-feedback`,role:`alert`,"data-tavily-error":!0,children:o}),c&&(0,F.jsx)(`p`,{className:`tavily-feedback`,role:`status`,"data-tavily-notice":!0,children:c})]})}async function Mh(e){let t=await e.json();if(!e.ok)throw Error(t.error||`缓存设置请求失败`);return t}function Nh(){let[e,t]=(0,u.useState)(),[n,r]=(0,u.useState)(`off`),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(!1),d=(0,u.useRef)(!1),f=(0,u.useRef)(!1),p=(0,u.useRef)(0),m=`/api/pi/cache-warming`;(0,u.useEffect)(()=>{let e=new AbortController,n=()=>{if(f.current)return;let n=++p.current;Pe(m,{signal:e.signal}).then(Mh).then(i=>{e.signal.aborted||n!==p.current||(t(i),d.current||(r(i.mode),d.current=!0,s(``)))}).catch(t=>{!e.signal.aborted&&!d.current&&s(t instanceof Error?t.message:`读取失败`)})};n();let i=window.setInterval(n,5e3);return()=>{e.abort(),window.clearInterval(i)}},[]);let h=async()=>{a(!0),s(``),l(!1),f.current=!0,p.current++;try{let e=await Pe(m,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({mode:n})}).then(Mh);t(e),r(e.mode),l(!0)}catch(e){s(e instanceof Error?e.message:`保存失败`)}finally{f.current=!1,a(!1)}};return(0,F.jsxs)(`section`,{className:`settings-section`,"data-cache-warming":!0,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`模型缓存预热`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`让支持缓存的模型保留最近请求的缓存,减少下一次回答的等待。预热可能产生额外请求和费用,用量计入对应会话总量。此设置在服务端运行,对所有工作区生效。`}),!e&&!o&&(0,F.jsx)(`p`,{role:`status`,children:`正在读取缓存设置…`}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`预热模式`}),(0,F.jsxs)(`select`,{className:`settings-model-select`,"data-cache-warming-mode":!0,disabled:i||!e,value:n,onChange:e=>{r(e.target.value),l(!1)},children:[(0,F.jsx)(`option`,{value:`off`,children:`关闭`}),(0,F.jsx)(`option`,{value:`streaming`,children:`仅回答期间`}),(0,F.jsx)(`option`,{value:`idle`,children:`回答及空闲期间`})]})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`空闲预热最多持续约 30 分钟,Pi 会按模型支持情况和成本决定是否继续;切换到空闲模式后,从下一次模型请求开始生效。`}),e&&(0,F.jsxs)(`p`,{className:`settings-agents-desc`,"data-cache-warming-status":!0,children:[`已加载 `,e.liveSessions,` 个会话 · `,e.scheduled,` 个等待预热 · `,e.refreshing,` 个正在预热`]}),(0,F.jsx)(`div`,{className:`settings-rule-form-buttons`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-cache-warming-save":!0,disabled:i||!e||n===e.mode,onClick:()=>void h(),children:i?`正在保存…`:`保存预热设置`})}),o&&(0,F.jsx)(`p`,{className:`settings-dir-error`,role:`alert`,children:o}),c&&(0,F.jsx)(`p`,{className:`settings-agents-desc`,role:`status`,"data-cache-warming-saved":!0,children:`已保存,现有会话已同步。`})]})}function Ph(){let{settingsServer:e}=ue(),t=(0,u.useRef)(e);t.current=e;let[n,r]=(0,u.useState)(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(!1);(0,u.useEffect)(()=>{let e=!0,t=new AbortController;r(void 0),a(``);let n=async()=>{try{let n=await Pe(`/api/providers/discovery`,{signal:t.signal});if(!n.ok)throw Error();let i=await n.json();e&&(r(i),a(``))}catch{e&&a(`暂时无法读取检查状态,已有模型仍可使用。`)}};n();let i=setInterval(()=>{n()},4e3);return()=>{e=!1,t.abort(),clearInterval(i)}},[e]);let c=async()=>{s(!0);let n=e;try{let e=await Pe(`/api/providers/discovery`,{method:`POST`});if(!e.ok)throw Error();let i=await e.json();t.current===n&&(r(i),a(``))}catch{t.current===n&&a(`检查请求未能发出,请稍后重试。`)}finally{s(!1)}};return(0,F.jsxs)(`section`,{className:`model-discovery`,"data-model-discovery":!0,"aria-label":`模型自动发现`,children:[(0,F.jsxs)(`div`,{className:`model-discovery-heading`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`模型自动发现`}),(0,F.jsx)(`button`,{className:`settings-dir-add-btn`,type:`button`,disabled:o||n?.running,onClick:()=>{c()},children:o||n?.running?`正在检查…`:`立即检查`})]}),(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[n&&!n.automatic?`当前运行环境未启用后台检查,可手动检查。`:`OAuth 与 API Key 供应商均每 ${n?.intervalHours??4} 小时后台检查。`,`新模型自动加入列表,保留当前模型和手动参数。未确认的能力参数仍可在模型设置中调整。`]}),i&&(0,F.jsx)(`p`,{className:`settings-provider-note-warn`,role:`status`,children:i}),n&&(0,F.jsxs)(`details`,{children:[(0,F.jsxs)(`summary`,{children:[n.providers.length,` 个供应商 · 查看检查状态`]}),(0,F.jsx)(`ul`,{children:n.providers.map(e=>(0,F.jsxs)(`li`,{"data-model-discovery-provider":e.providerId,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`span`,{children:e.state===`checking`?`检查中`:e.state===`failed`?`检查失败`:e.state===`unsupported`?`暂不支持枚举`:e.succeededAt?`已检查`:`待检查`})]}),(0,F.jsx)(`p`,{children:e.detail}),e.succeededAt&&(0,F.jsxs)(`small`,{children:[`上次成功:`,new Date(e.succeededAt).toLocaleString()]})]},e.providerId))})]})]})}var Fh={deferred:`按需搜索`,direct:`直接提供`,codemode:`通过编排调用`,hidden:`隐藏工具`},Ih={connected:`测试通过`,connecting:`连接中`,failed:`连接失败`,"needs-auth":`需要登录`,disabled:`已停用`,disconnected:`连接已断开`,closed:`已关闭`},Lh=[[`mcp`,`MCP 外部服务`,`连接服务端命令或远程 HTTP 服务,使用其工具和资源。`],[`toolSearch`,`按需发现工具`,`工具多时先搜索再调用,减少每轮请求携带的工具说明。`],[`codemode`,`批量编排调用`,`合并多次工具调用、并行读取或筛选结果,减少来回等待。`]];function Rh({workspaceId:e}){let[t,n]=(0,u.useState)(),[r,i]=(0,u.useState)(``),[a,o]=(0,u.useState)(``),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)(``),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(`http`),[g,_]=(0,u.useState)(``),[v,y]=(0,u.useState)(``),[b,x]=(0,u.useState)(``),[S,C]=(0,u.useState)(`deferred`),[w,T]=(0,u.useState)({}),E=(0,u.useRef)(!1),D=(0,u.useRef)(0),O=async e=>{let t=await e.json();if(!e.ok)throw Error(t.error||`外部工具请求失败。`);return t};(0,u.useEffect)(()=>{let e=new AbortController,t=()=>{if(E.current)return;let t=++D.current;Pe(`/api/native-tools`,{signal:e.signal}).then(O).then(r=>{!e.signal.aborted&&t===D.current&&(n(r),c(``))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:`读取失败。`)})};t();let r=window.setInterval(t,2e3);return()=>{e.abort(),window.clearInterval(r)}},[]);let k=async(t,r,a=``)=>{if(E.current)return!1;E.current=!0,D.current++,i(t),o(``),d(``);try{let t=await Pe(`/api/native-tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...r,workspaceId:e})}).then(O);return n(t),d(a),!0}catch(e){return o(e instanceof Error?e.message:`操作失败。`),!1}finally{E.current=!1,i(``)}},A=async e=>{e.preventDefault();let t;try{if(t=b.trim()?JSON.parse(b):{},!t||typeof t!=`object`||Array.isArray(t))throw Error()}catch{o(`高级配置须为 JSON 对象。`);return}let n={...t,...m===`http`?{url:g.trim()}:{command:g.trim(),args:v.split(/\r?\n/).filter(Boolean)},exposure:S};await k(`save`,{action:`save`,name:f.trim(),config:n},`已保存,下一轮执行生效。`)&&(p(``),_(``),y(``),x(``))},j=t?.servers.some(e=>e.name===f.trim());return(0,F.jsxs)(`section`,{className:`settings-panel-container native-tools`,"data-native-tools":!0,children:[(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`让 Agent 查询外部资料、处理服务数据,或把多次工具调用合并执行。主会话、工具型群成员和后台子 Agent 使用同一套权限;自定义 Agent 保留原来的工具授权。`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`这里管理服务端的全局配置,与 Pi 共用 mcp.json。项目自己的配置继续按 Pi 的信任规则加载。保存后下一轮执行采用新配置,当前工作继续运行。`}),(a||s)&&(0,F.jsx)(`p`,{className:`settings-dir-error`,role:`alert`,"data-native-error":!0,children:a||s}),l&&(0,F.jsx)(`p`,{role:`status`,"data-native-notice":!0,children:l}),!t&&!a&&!s&&(0,F.jsx)(`p`,{role:`status`,children:`正在读取外部工具…`}),t&&(0,F.jsxs)(F.Fragment,{children:[t.configurationWarning&&(0,F.jsx)(`p`,{role:`alert`,children:t.configurationWarning}),(0,F.jsx)(`section`,{className:`settings-section native-tool-flags`,"aria-label":`工具能力`,children:Lh.map(([e,n,i])=>(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-native-flag":e,checked:t.settings[e],disabled:!!r,onChange:t=>void k(e,{action:`settings`,settings:{[e]:t.target.checked}},`已保存工具开关。`)}),(0,F.jsxs)(`span`,{children:[(0,F.jsx)(`strong`,{children:n}),(0,F.jsx)(`small`,{children:i})]})]},e))}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`div`,{className:`native-tools-heading`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`MCP 服务`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-mcp-diagnose":!0,disabled:!!r||t.diagnostics?.running||!e||!t.servers.length,onClick:()=>void k(`diagnose`,{action:`diagnose`}),children:t.diagnostics?.running?`正在测试 ${t.diagnostics.servers.length}/${t.diagnostics.total}…`:`测试连接`})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`连接测试会临时连接后关闭;实际执行时由会话保持连接。命令运行在 Super Pi 服务端,环境变量和请求头中的已有值不回显。`}),!t.servers.length&&(0,F.jsx)(`p`,{className:`settings-empty-hint`,children:`还没有全局 MCP 服务,在下方添加第一个。`}),t.servers.map(n=>{let i=t.diagnostics?.servers.find(e=>e.name===n.name);return(0,F.jsxs)(`article`,{className:`native-server`,"data-mcp-server":n.name,children:[(0,F.jsxs)(`div`,{className:`native-server-title`,children:[(0,F.jsx)(`strong`,{children:n.name}),(0,F.jsx)(`span`,{children:n.transport===`http`?`HTTP`:`命令`}),(0,F.jsx)(`span`,{"data-mcp-state":i?.state??`untested`,children:n.enabled?i?Ih[i.state]??i.state:`尚未测试`:`已停用`})]}),n.description&&(0,F.jsx)(`p`,{children:n.description}),(0,F.jsxs)(`div`,{className:`native-server-actions`,children:[(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-mcp-enabled":!0,checked:n.enabled,disabled:!!r,onChange:e=>void k(n.name,{action:`patch`,name:n.name,enabled:e.target.checked})}),`启用`]}),(0,F.jsx)(`select`,{"aria-label":`${n.name} 的工具提供方式`,"data-mcp-exposure":!0,value:n.exposure,disabled:!!r,onChange:e=>void k(n.name,{action:`patch`,name:n.name,exposure:e.target.value}),children:Object.entries(Fh).map(([e,t])=>(0,F.jsx)(`option`,{value:e,children:t},e))}),n.supportsLogin&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-mcp-login":!0,disabled:!!r||!e,onClick:()=>void k(n.name,{action:`login`,name:n.name}),children:n.authenticated?`重新登录`:`登录`}),n.authenticated&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,disabled:!!r,onClick:()=>void k(n.name,{action:`logout`,name:n.name},`已移除 MCP 网页登录凭据。`),children:`退出登录`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-mcp-remove":!0,disabled:!!r,onClick:()=>{window.confirm(`删除 MCP 服务 ${n.name}?`)&&k(n.name,{action:`delete`,name:n.name})},children:`删除`})]}),i?.error&&(0,F.jsx)(`p`,{role:`status`,children:i.error}),i&&i.tools.length>0&&(0,F.jsxs)(`details`,{"data-mcp-tools":!0,children:[(0,F.jsxs)(`summary`,{children:[i.tools.length,` 个可用工具`]}),(0,F.jsx)(`ul`,{children:i.tools.map(e=>(0,F.jsx)(`li`,{children:(0,F.jsx)(`code`,{children:e})},e))})]})]},n.name)}),t.diagnostics?.error&&(0,F.jsx)(`p`,{role:`status`,children:t.diagnostics.error})]}),t.logins.map(e=>(0,F.jsxs)(`section`,{className:`settings-section native-login`,"data-mcp-login-state":e.state,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[e.name,` · `,e.state===`completed`?`登录完成`:e.state===`starting`?`正在连接授权服务`:e.state===`authorizing`?`等待网页授权`:e.state===`cancelled`?`登录已取消`:`登录未完成`]}),e.url&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`a`,{className:`settings-oauth-open-link native-login-open`,href:e.url,target:`_blank`,rel:`noopener noreferrer`,children:`打开授权页面 ↗`}),(0,F.jsx)(`p`,{children:`如果远程浏览器无法打开回调页面,可复制地址栏里的完整回调地址粘贴到下方。`}),(0,F.jsxs)(`form`,{onSubmit:t=>{t.preventDefault(),k(e.id,{action:`redirect`,id:e.id,url:w[e.id]}).then(t=>{t&&T(t=>({...t,[e.id]:``}))})},children:[(0,F.jsx)(`input`,{className:`settings-oauth-input`,type:`password`,"aria-label":`完整回调地址`,autoComplete:`off`,placeholder:`粘贴完整回调地址`,value:w[e.id]??``,onChange:t=>T(n=>({...n,[e.id]:t.target.value}))}),(0,F.jsx)(`button`,{className:`settings-dir-add-btn settings-oauth-continue`,disabled:!!r||!w[e.id],type:`submit`,children:`完成授权`})]})]}),e.error&&(0,F.jsx)(`p`,{role:`status`,children:e.error}),[`starting`,`authorizing`].includes(e.state)&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>void k(e.id,{action:`cancel-login`,id:e.id}),children:`取消登录`})]},e.id))]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`添加服务`}),(0,F.jsxs)(`form`,{onSubmit:e=>void A(e),className:`native-server-form`,children:[(0,F.jsxs)(`div`,{className:`settings-model-grid`,children:[(0,F.jsxs)(`label`,{children:[`服务名`,(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-mcp-name":!0,required:!0,value:f,onChange:e=>p(e.target.value)})]}),(0,F.jsxs)(`label`,{children:[`连接方式`,(0,F.jsxs)(`select`,{className:`settings-model-select`,"data-mcp-type":!0,value:m,onChange:e=>{h(e.target.value),_(``)},children:[(0,F.jsx)(`option`,{value:`http`,children:`远程 HTTP`}),(0,F.jsx)(`option`,{value:`stdio`,children:`服务端命令`})]})]})]}),(0,F.jsxs)(`label`,{children:[m===`http`?`服务地址`:`可执行命令`,(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-mcp-address":!0,required:!0,value:g,onChange:e=>_(e.target.value),placeholder:m===`http`?`https://example.com/mcp`:`npx`})]}),m===`stdio`&&(0,F.jsxs)(`label`,{children:[`参数(每行一个)`,(0,F.jsx)(`textarea`,{className:`settings-dir-input`,"data-mcp-args":!0,value:v,onChange:e=>y(e.target.value),spellCheck:!1})]}),(0,F.jsxs)(`label`,{children:[`工具提供方式`,(0,F.jsx)(`select`,{className:`settings-model-select`,value:S,onChange:e=>C(e.target.value),children:Object.entries(Fh).map(([e,t])=>(0,F.jsx)(`option`,{value:e,children:t},e))})]}),(0,F.jsxs)(`details`,{children:[(0,F.jsx)(`summary`,{children:`环境变量、请求头与高级配置`}),(0,F.jsx)(`p`,{children:`填写单个服务配置的 JSON 字段,例如 env、headers、oauth、toolExposure。可以使用环境变量引用;保存后清空此输入。`}),(0,F.jsx)(`textarea`,{className:`settings-dir-input`,"data-mcp-extra":!0,value:b,onChange:e=>x(e.target.value),spellCheck:!1,placeholder:'{"env":{"SERVICE_KEY":"${SERVICE_KEY}"}}'})]}),j&&(0,F.jsx)(`p`,{children:`同名服务已存在,本次保存将完整替换其配置。调整开关或提供方式可直接使用上方操作,保留已有凭据。`}),(0,F.jsx)(`button`,{type:`submit`,className:`settings-dir-add-btn`,"data-mcp-save":!0,disabled:!!r||!t,children:r===`save`?`正在保存…`:j?`替换服务配置`:`添加服务`})]})]})]})}function zh(){let e=Qd();return(0,F.jsxs)(`fieldset`,{className:`markdown-syntax-settings`,"data-markdown-syntax-settings":`1`,children:[(0,F.jsx)(`legend`,{children:`消息 Markdown 语法`}),(0,F.jsx)(`p`,{children:`关闭后按原样显示符号。讨论 A* 算法时可关闭斜体;代码块不受影响。`}),[{key:`italic`,label:`斜体`,example:`*文字* / _文字_`},{key:`bold`,label:`粗体`,example:`**文字** / __文字__`},{key:`strikethrough`,label:`删除线`,example:`~~文字~~`}].map(t=>(0,F.jsxs)(`label`,{className:`markdown-syntax-row`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-markdown-syntax-setting":t.key,checked:e[t.key],onChange:e=>Yd({[t.key]:e.target.checked})}),(0,F.jsx)(`span`,{children:t.label}),(0,F.jsx)(`code`,{children:t.example})]},t.key)),(0,F.jsxs)(`div`,{className:`markdown-syntax-footer`,children:[(0,F.jsx)(`span`,{children:`仅影响当前浏览器的显示,立即生效。`}),(0,F.jsx)(`button`,{type:`button`,onClick:()=>Yd(Hd),"data-markdown-syntax-reset":`1`,children:`恢复默认`})]})]})}var Bh=e=>+(e===`subagent`);function Vh(e){return[...e].sort((e,t)=>{let n=+!e.builtin,r=+!t.builtin;if(n!==r)return n-r;let i=Bh(e.mode)-Bh(t.mode);return i===0?e.id.localeCompare(t.id):i})}var Hh=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Uh(e,t){let n=e.trim(),r=n.replace(/\/+$/,``);try{let e=new URL(n);r=`${e.origin}${e.pathname.replace(/\/+$/,``)}${e.search}`}catch{}return`${r}|${t.trim()||`openai-completions`}`}function Wh(e){return e?Hh.filter(t=>e[t]!=null):[]}function Gh(e){return Wh(e).join(` / `)}var Kh=e=>e.nativeEvent.isComposing||e.keyCode===229,qh=`super-pi.theme`,Jh=[{id:`dracula`,name:`Dracula`,blurb:`冷灰深底,柔紫选中和焦点。`},{id:`monokai`,name:`Monokai`,blurb:`暖灰深底,琥珀色操作和焦点。`},{id:`solarized-light`,name:`Solarized Light`,blurb:`米白正文,鼠尾草绿选中。`},{id:`github-light`,name:`GitHub Light`,blurb:`白色正文,冷灰侧栏和蓝色选中。`}],Yh=`dracula`,Xh=e=>typeof e==`string`&&Jh.some(t=>t.id===e);function Zh(){try{let e=window.localStorage.getItem(qh);if(!e)return Yh;let t=JSON.parse(e),n=typeof t==`string`?t:t?.id;return Xh(n)?n:Yh}catch{return Yh}}function Qh(e){document.documentElement.setAttribute(`data-theme`,e);try{window.localStorage.setItem(qh,JSON.stringify({id:e,version:1}))}catch{}}function $h(){let[e,t]=(0,u.useState)(Yh);return(0,u.useEffect)(()=>{t(Zh());let e=e=>{if(e.key===`super-pi.theme`&&e.newValue)try{let n=JSON.parse(e.newValue),r=typeof n==`string`?n:n?.id;Xh(r)&&(document.documentElement.setAttribute(`data-theme`,r),t(r))}catch{}};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),{theme:e,setTheme:(0,u.useCallback)(e=>{Qh(e),t(e)},[])}}function eg({theme:e,onChooseTheme:t,onClose:n}){let r=Jh.find(t=>t.id===e);return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`主题只影响这台设备的显示,不改变任何内容;切换立即生效。`}),(0,F.jsx)(zh,{}),Jh.length===0?(0,F.jsx)(`div`,{className:`theme-empty`,"data-theme-empty":`1`,children:`没有可用的主题。界面将继续使用默认配色,你可以在主题文件恢复后重试。`}):(0,F.jsx)(`div`,{className:`theme-options`,role:`radiogroup`,"aria-label":`主题`,children:Jh.map(n=>{let r=n.id===e;return(0,F.jsxs)(`button`,{type:`button`,className:`theme-option`,role:`radio`,"aria-checked":r,"aria-pressed":r,"data-theme-option":n.id,"data-theme-current":r?`1`:`0`,onClick:()=>t(n.id),children:[(0,F.jsx)(`span`,{className:`theme-preview-strip`,"data-preview":n.id,"aria-hidden":`true`}),(0,F.jsxs)(`span`,{className:`theme-option-name`,children:[n.name,r&&(0,F.jsx)(`span`,{className:`theme-option-current`,children:`当前 ✓`})]}),(0,F.jsx)(`span`,{className:`theme-option-blurb`,children:n.blurb})]},n.id)})}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-theme-close":`1`,onClick:n,children:`完成`})}),(0,F.jsxs)(`div`,{className:`settings-scope theme-current-line`,children:[`当前:`,r?`${r.name}(${r.id})`:`默认`]})]})}function tg({userNickname:e,onSetUserNickname:t,onClose:n}){return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`昵称会显示在消息时间戳旁和头像上,替代默认的「你」。留空恢复默认。`}),(0,F.jsxs)(`div`,{className:`general-nickname`,children:[(0,F.jsx)(`label`,{className:`general-nickname-label`,htmlFor:`general-nickname-input`,children:`昵称`}),(0,F.jsx)(`input`,{id:`general-nickname-input`,type:`text`,className:`general-nickname-input`,"data-general-nickname":`1`,maxLength:24,placeholder:`你`,value:e??``,onChange:e=>t?.(e.target.value)}),(0,F.jsx)(`span`,{className:`general-nickname-hint`,"data-general-nickname-preview":`1`,title:`当前显示`,children:e?.trim()?`将显示为:${e.trim()}`:`将显示为:你`})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`完成`})})]})}function ng(e){return(0,F.jsx)(ig,{context:e})}function rg({context:e}){let[t,n]=(0,u.useState)(),[r,i]=(0,u.useState)(``),a=(0,u.useRef)(void 0),o=()=>{window.superPiDesktop.notifications.status().then(n).catch(()=>i(`无法读取桌面通知状态`))};(0,u.useEffect)(()=>(o(),()=>a.current?.close()),[]);let s=!!e.browserNotificationsEnabled;return(0,F.jsxs)(`section`,{className:`settings-panel-container`,"data-desktop-notifications":`1`,children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`通过 Super Pi 桌面应用发送系统通知,使用 Super Pi 图标;点击提醒会回到对应会话。仅提醒顶层会话,通知不包含问题全文或代码。`}),(0,F.jsxs)(`div`,{className:`settings-notification-row`,children:[(0,F.jsxs)(`div`,{className:`settings-notification-copy`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`Agent 状态提醒`}),(0,F.jsx)(`p`,{children:`任务完成、等待回答或需要决定时提醒。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"aria-pressed":s,disabled:!s&&!t?.supported,onClick:()=>e.onSetBrowserNotifications?.(!s),children:s?`关闭通知`:`启用通知`})]}),(0,F.jsxs)(`section`,{className:`settings-notification-check`,"aria-label":`桌面通知检测`,children:[(0,F.jsxs)(`dl`,{children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`通知来源`}),(0,F.jsx)(`dd`,{children:`Super Pi 桌面应用`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`桌面通知支持`}),(0,F.jsx)(`dd`,{children:t?t.supported?`系统支持`:`当前系统不支持`:`检测中…`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`通知权限`}),(0,F.jsx)(`dd`,{children:`由操作系统管理`})]})]}),(0,F.jsx)(`p`,{role:`status`,children:s?t?.lastError??`桌面通知已开启,最终显示取决于系统通知权限及勿扰模式。`:`通知未启用。`}),(0,F.jsxs)(`div`,{className:`settings-notification-check-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:o,children:`重新检测`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,disabled:!s||!t?.supported,onClick:async()=>{try{a.current?.close();let e=ra(`Super Pi · 测试通知`,{tag:`super-pi-permission-test`,body:`这是一条由 Super Pi 桌面端发送的系统通知。`});a.current=e;let t=await e.ready;i(t?.state===`shown`?`系统已接收 Super Pi 通知;若没有看到,请检查通知设置及勿扰模式。`:`已发出通知请求,尚未收到系统显示回执。请检查系统通知设置。`)}catch(e){i(e instanceof Error?e.message:`系统未能显示通知`)}finally{o()}},children:`发送测试通知`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:async()=>{try{(await window.superPiDesktop.notifications.openSettings()).opened||i(`请在系统设置中打开 Super Pi 的通知权限。`)}catch{i(`无法打开系统设置,请手动检查系统通知权限。`)}},children:`打开系统通知设置`})]}),(0,F.jsx)(`p`,{className:`settings-notification-help`,children:`操作系统未提供可可靠读取的统一授权状态时,这里不会把支持通知误报为已经授权。可以使用测试通知确认实际显示。`}),r&&(0,F.jsx)(`p`,{role:`status`,children:r})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function ig({context:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)();if((0,u.useEffect)(()=>{e.onCheckBrowserNotifications?.()},[e.onCheckBrowserNotifications]),(0,u.useEffect)(()=>()=>r?.close(),[r]),window.superPiDesktop?.notifications)return(0,F.jsx)(rg,{context:e});let a=!!e.browserNotificationsEnabled,o=e.browserNotificationPermission??`unsupported`,s=o!==`unsupported`&&o!==`insecure`,c=o===`granted`?`浏览器已授权通知。`:o===`denied`?`浏览器已阻止此站点发送通知。请在地址栏的站点设置中允许通知,然后返回这里重新检测。`:o===`insecure`?`当前连接不是安全来源。浏览器通知需要 HTTPS 或 localhost。`:o===`unsupported`?`当前浏览器不支持系统通知。`:`尚未授权。点击按钮后,浏览器会询问是否允许 Super Pi 发送通知。`,l=a&&o===`granted`;return(0,F.jsxs)(`section`,{className:`settings-panel-container`,"data-browser-notifications":`1`,children:[(0,F.jsx)(`div`,{className:`settings-scope`,children:`当页面处于后台或没有焦点时,Agent 完成一轮工作或等待你回答问题,会通过浏览器系统通知提醒。通知不会包含问题全文或代码。`}),(0,F.jsxs)(`div`,{className:`settings-notification-row`,children:[(0,F.jsxs)(`div`,{className:`settings-notification-copy`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`Agent 状态提醒`}),(0,F.jsx)(`p`,{children:`仅提醒顶层会话;后台子会话不会逐个打断你。点击通知会打开对应会话。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-browser-notifications-toggle":`1`,"aria-pressed":a,disabled:!a&&(!s||o===`denied`),onClick:()=>e.onSetBrowserNotifications?.(!a),children:a?`关闭通知`:o===`granted`?`启用通知`:`授权并启用`})]}),(0,F.jsxs)(`section`,{className:`settings-notification-check`,"aria-label":`通知权限检测`,"data-browser-notification-permission":o,children:[(0,F.jsxs)(`dl`,{children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`Super Pi 通知开关`}),(0,F.jsx)(`dd`,{children:a?`已开启`:`已关闭`})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`当前浏览器站点权限`}),(0,F.jsx)(`dd`,{"data-notification-permission-label":!0,children:o===`granted`?`已允许`:o===`denied`?`已阻止`:o==="default"?`尚未授权`:o===`insecure`?`需要 HTTPS 或 localhost`:`浏览器不支持`})]})]}),(0,F.jsxs)(`p`,{role:`status`,"data-notification-effective":l?`enabled`:a?`blocked`:`disabled`,children:[(0,F.jsx)(`strong`,{children:l?`浏览器通知已就绪`:a?`通知尚未生效`:`通知未启用`}),a&&o!==`granted`?`:平台开关已开启,但浏览器尚不允许发送通知。`:``]}),(0,F.jsx)(`p`,{children:c}),(0,F.jsxs)(`div`,{className:`settings-notification-check-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-notification-recheck":!0,onClick:()=>{e.onCheckBrowserNotifications?.(),n(`已重新读取当前浏览器的站点通知权限。`)},children:`重新检测`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-notification-test":!0,disabled:!l,onClick:()=>{if(e.onCheckBrowserNotifications?.(),!(`Notification`in window)||Notification.permission!==`granted`)n(`浏览器当前未允许通知,请先调整站点权限。`);else try{i(new Notification(`Super Pi · 测试通知`,{body:`如果你看到这条系统通知,说明当前浏览器的通知可以正常显示。`,tag:`super-pi-permission-test`})),n(`已请求发送测试通知;若没有看到,请检查系统对浏览器的通知权限及勿扰模式。`)}catch{n(`浏览器未能发送测试通知,请检查站点和系统通知设置。`)}},children:`发送测试通知`})]}),(0,F.jsx)(`p`,{className:`settings-notification-help`,children:`此检测反映当前站点的浏览器授权。操作系统的通知开关、勿扰模式也可能拦截显示,可用测试通知确认。`}),t&&(0,F.jsx)(`p`,{role:`status`,children:t})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function ag({context:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)(``),[a,o]=(0,u.useState)(!1),s=e.agentCatalog,c=e.subagentCatalog,l=s?.agents??[],d=c?.agents??[],f=Vh([...l,...d]),p=[...s?.problems??[],...c?.problems??[]],m=[...new Set([...s?.directories??(s?.directory?[s.directory]:[]),...e.customAgentDirs??[]])],h=e.customAgentDirs??[],g=r=>{if(r.preventDefault(),e.pendingSettings)return;let a=t.trim();a&&(h.includes(a)?i(`该路径已存在于自定义目录列表中`):(e.onSetCustomAgentDirs?.([...h,a]),n(``),i(``)))},_=t=>{let n=h.filter(e=>e!==t);e.onSetCustomAgentDirs?.(n)};return(0,F.jsxs)(`div`,{className:`settings-agents-container`,children:[(0,F.jsxs)(`div`,{className:`settings-agents-header`,children:[(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`Super Pi 支持多目录发现智能体。系统会按优先级自上而下合并扫描目录;若存在同名配置,高优先级目录的文件将覆盖低优先级目录。`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:()=>{o(!0),e.onRescanAgents?.(),setTimeout(()=>o(!1),600)},disabled:a,title:`重新扫描所有目录中的智能体定义文件`,children:a?`正在扫描…`:`🔄 立即重新扫描`})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`发现路径清单(按优先级自高到低)`}),(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:m.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无活跃的发现路径`}):m.map((t,n)=>{let r=h.includes(t),i=t.includes(`.super_pi`)||t.includes(`.super-pi`)||t.includes(`.pi`),a=!r&&!i,o=f.filter(e=>e.sourceDir===t).length;return(0,F.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,F.jsxs)(`div`,{className:`settings-dir-info`,children:[(0,F.jsxs)(`span`,{className:`settings-dir-priority`,children:[`#`,n+1]}),(0,F.jsx)(`span`,{className:`settings-dir-path`,title:t,children:t}),(0,F.jsx)(`span`,{className:`settings-dir-tag`,children:r?`自定义`:i?`用户全局`:a?`内置`:`环境`}),(0,F.jsxs)(`span`,{className:`settings-dir-count`,children:[`(发现 `,o,` 个智能体)`]})]}),r&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,disabled:e.pendingSettings,onClick:()=>_(t),title:`移除此自定义扫描路径`,children:`移除`})]},t)})})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`添加自定义路径`}),(0,F.jsxs)(`form`,{onSubmit:g,className:`settings-add-dir-form`,children:[(0,F.jsx)(`input`,{type:`text`,className:`settings-dir-input`,value:t,onChange:e=>{n(e.target.value),r&&i(``)},onKeyDown:e=>{e.key===`Enter`&&Kh(e)&&e.preventDefault()},placeholder:`输入本地目录绝对路径或 ~/ 开头路径,如 D:\\agents 或 ~/.super_pi/agents`}),(0,F.jsx)(`button`,{type:`submit`,className:`settings-dir-add-btn`,disabled:e.pendingSettings||!t.trim(),children:`添加目录`})]}),r&&(0,F.jsx)(`div`,{className:`settings-dir-error`,children:r})]}),p.length>0&&(0,F.jsxs)(`section`,{className:`settings-section settings-problems-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-problems-title`,children:[`⚠️ 发现 `,p.length,` 个文件解析问题`]}),(0,F.jsx)(`div`,{className:`settings-problems-list`,children:p.map((e,t)=>(0,F.jsxs)(`div`,{className:`settings-problem-row`,children:[(0,F.jsx)(`span`,{className:`settings-problem-file`,children:e.file}),`: `,e.message]},t))})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`已发现的智能体(共 `,f.length,` 个)`]}),f.length===0?(0,F.jsxs)(`div`,{className:`settings-empty-hint`,children:[`当前未发现任何智能体。请在上述目录中添加 `,(0,F.jsx)(`code`,{children:`.md`}),` 文件(需包含 YAML frontmatter)。`]}):(0,F.jsx)(`div`,{className:`settings-agent-grid`,children:f.map(e=>(0,F.jsxs)(`div`,{className:`settings-agent-card`,children:[(0,F.jsxs)(`div`,{className:`settings-agent-card-header`,children:[(0,F.jsx)(`span`,{className:`settings-agent-name`,children:e.name}),(0,F.jsxs)(`span`,{className:`settings-agent-id`,children:[`(`,e.id,`)`]}),(0,F.jsx)(`span`,{className:`settings-agent-mode-badge ${e.mode}`,children:e.mode===`primary`?`主智能体`:`子智能体`})]}),e.sourceDir&&(0,F.jsxs)(`div`,{className:`settings-agent-source`,title:e.sourceDir,children:[`来源:`,e.sourceDir]}),e.description&&(0,F.jsx)(`div`,{className:`settings-agent-desc`,children:e.description}),(0,F.jsxs)(`div`,{className:`settings-agent-footer`,children:[(0,F.jsx)(`span`,{className:`settings-agent-tools`,children:e.toolSummary}),e.model&&(0,F.jsxs)(`span`,{className:`settings-agent-model`,children:[e.model.provider,`/`,e.model.modelId]})]})]},`${e.sourceDir}-${e.id}`))})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function og(e){return(0,F.jsx)(ag,{context:e})}function sg({context:e}){let[t,n]=(0,u.useState)({enabled:!1}),[r,i]=(0,u.useState)(``),a=(0,u.useCallback)(async e=>{try{let[t,r]=await Promise.all([Pe(`/api/terminal`).then(e=>e.json()),Pe(`/api/terminal-shell`).then(e=>e.json())]);n({...r,enabled:t.enabled}),e&&i(r.shell?[r.shell.file,...r.shell.args].map(e=>/\s/.test(e)?`"${e}"`:e).join(` `):``)}catch{}},[]);(0,u.useEffect)(()=>{a(!0)},[a]);let o=(0,u.useRef)(e.terminalShell);return(0,u.useEffect)(()=>{o.current!==e.terminalShell&&(o.current=e.terminalShell,a(!1))},[e.terminalShell,a]),t.enabled?(0,F.jsx)(`section`,{className:`settings-panel-container`,"data-terminal-settings":`1`,children:(0,F.jsxs)(`div`,{className:`settings-section`,children:[(0,F.jsxs)(`p`,{className:`settings-empty-hint`,children:[`当前生效:`,(0,F.jsx)(`code`,{children:t.shell?[t.shell.file,...t.shell.args].join(` `):``}),`(来自`,t.source,`)。只影响新开的终端。`]}),(0,F.jsx)(`label`,{className:`settings-section-title`,children:`默认 shell`}),(0,F.jsx)(`input`,{className:`settings-dir-input`,"data-terminal-shell-input":`1`,value:r,onChange:e=>i(e.target.value),placeholder:`例如 wsl.exe -e zsh`}),(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:(t.candidates??[]).map(e=>(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:()=>i([e.file,...e.args].map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)),children:e.label},`${e.file}:${e.args.join(` `)}`))}),(0,F.jsx)(`div`,{children:(0,F.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,"data-terminal-shell-save":`1`,onClick:()=>e.onSetTerminalShell?.(r.trim()||null),children:`保存`})})]})}):(0,F.jsx)(`section`,{className:`settings-panel-container`,"data-terminal-settings":`disabled`,children:(0,F.jsx)(`p`,{className:`settings-empty-hint`,children:`终端没有启用,无法设置默认 shell。`})})}function cg({context:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)(``),[a,o]=(0,u.useState)(),s=e=>{try{return new RegExp(e,`i`),!1}catch{return!0}},c=s(t),l=s(r),d=e.modelFilterRules??[];return(0,F.jsxs)(`section`,{"data-model-rules":`1`,className:`settings-panel-container`,children:[(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`按工作区约束可用模型。`}),`当工作区名称匹配指定正则表达式时,会话中仅可选择符合模型正则的模型(匹配模型名称或 `,(0,F.jsx)(`code`,{children:`provider/modelId`}),`)。多条命中规则必须全部满足。`]})}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`已配置的过滤规则(共 `,d.length,` 条)`]}),d.length===0?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无模型过滤规则。所有工作区默认可使用全部已配置模型。`}):(0,F.jsx)(`div`,{className:`settings-dirs-list`,children:d.map(t=>{let r=a===t.id;return(0,F.jsxs)(`div`,{className:`settings-rule-card ${r?`editing`:``}`,children:[(0,F.jsx)(`div`,{className:`settings-rule-info`,children:(0,F.jsxs)(`div`,{className:`settings-rule-patterns`,children:[(0,F.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,F.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`工作区`}),(0,F.jsx)(`code`,{className:`settings-rule-code`,title:t.workspacePattern,children:t.workspacePattern})]}),(0,F.jsx)(`span`,{className:`settings-rule-arrow`,"aria-hidden":`true`,children:`→`}),(0,F.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,F.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`允许模型`}),(0,F.jsx)(`code`,{className:`settings-rule-code`,title:t.modelPattern,children:t.modelPattern})]})]})}),(0,F.jsxs)(`div`,{className:`settings-rule-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>{o(t.id),n(t.workspacePattern),i(t.modelPattern)},children:r?`编辑中`:`编辑`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>{a===t.id&&(o(void 0),n(``),i(``)),e.onSetModelRules?.(d.filter(e=>e.id!==t.id))},children:`删除`})]})]},t.id)})})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:a?`编辑过滤规则`:`添加新规则`}),(0,F.jsxs)(`fieldset`,{disabled:e.pendingSettings,className:`model-rules-fields settings-rule-fieldset`,children:[(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`工作区名正则表达式`}),(0,F.jsx)(`input`,{type:`text`,"data-rule-workspace":`1`,className:`settings-dir-input`,value:t,"aria-invalid":c,placeholder:`如 ^proj- 或 my-workspace`,onChange:e=>n(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`允许的模型名正则表达式`}),(0,F.jsx)(`input`,{type:`text`,"data-rule-model":`1`,className:`settings-dir-input`,value:r,"aria-invalid":l,placeholder:`如 anthropic/.* 或 gpt-4o|claude`,onChange:e=>i(e.target.value)})]})]}),(c||l)&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ 正则表达式语法不合法,请检查后修正。`}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,"data-rule-save":`1`,className:`settings-dir-add-btn`,disabled:!t.trim()||!r.trim()||c||l,onClick:()=>{let s={id:a??Wt(),workspacePattern:t.trim(),modelPattern:r.trim()};e.onSetModelRules?.([...d.filter(e=>e.id!==s.id),s]),n(``),i(``),o(void 0)},children:a?`保存修改`:`添加规则`}),a&&(0,F.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{o(void 0),n(``),i(``)},children:`取消编辑`})]})]})]}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function lg({catalog:e,customProviders:t,onEditModel:n}){let[r,i]=(0,u.useState)(!0),a=e?.models??[];if(a.length===0)return null;let o={};for(let e of a){let t=e.provider||`other`;o[t]||(o[t]=[]),o[t].push(e)}let s=Object.keys(o).sort(),c=new Set((t??[]).filter(e=>e.builtin).map(e=>e.id));return(0,F.jsxs)(`div`,{className:`settings-system-models`,"data-system-models":`1`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`settings-system-models-toggle`,onClick:()=>i(!r),"aria-expanded":!r,children:[(0,F.jsx)(`span`,{className:`settings-system-models-icon`,children:r?`▸`:`▾`}),(0,F.jsxs)(`span`,{className:`settings-system-models-title`,children:[`已发现的可用模型清单(共 `,a.length,` 个模型 · `,s.length,` 个供应商)`]})]}),!r&&(0,F.jsxs)(`div`,{className:`settings-system-models-content`,children:[(0,F.jsx)(`p`,{className:`settings-agents-desc settings-system-models-note`,children:`Pi 现在实际提供这些模型。改动和删除请在下方「Pi 的供应商与模型」里做——那里编辑的就是 Pi 自己的配置,这里只是它被 Pi 读出来的结果。`}),s.map(e=>{let t=o[e],r=c.has(e);return(0,F.jsxs)(`div`,{className:`settings-system-group`,children:[(0,F.jsxs)(`div`,{className:`settings-system-group-head`,children:[(0,F.jsx)(`span`,{className:`settings-system-group-name`,children:e}),(0,F.jsxs)(`span`,{className:`settings-system-group-count`,children:[`(`,t.length,` 个模型)`]}),(0,F.jsx)(`span`,{className:`settings-system-badge ${r?`system`:`custom`}`,children:r?`Pi 提供`:`models.json 定义`})]}),(0,F.jsx)(`div`,{className:`settings-system-model-list`,children:t.map(t=>(0,F.jsxs)(`div`,{className:`settings-system-model-row`,children:[(0,F.jsxs)(`div`,{className:`settings-system-model-info`,children:[(0,F.jsx)(`span`,{className:`settings-system-model-name`,children:t.label||t.modelId}),(0,F.jsx)(`code`,{className:`settings-system-model-id`,children:t.modelId})]}),n&&(0,F.jsx)(`div`,{className:`settings-system-model-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,"data-system-model-edit":`${e}:${t.modelId}`,onClick:()=>n?.(e,t.modelId,t.label),children:`编辑配置`})})]},t.modelId))})]},e)})]})]})}var ug=e=>{try{let t=e.trim();if(!t)return`custom-provider`;let n=new URL(t.startsWith(`http`)?t:`https://${t}`),r=n.hostname.toLowerCase();if(r.includes(`openai`))return`openai`;if(r.includes(`anthropic`))return`anthropic`;if(r.includes(`deepseek`))return`deepseek`;if(r.includes(`google`)||r.includes(`gemini`))return`google`;if(r.includes(`groq`))return`groq`;if(r.includes(`mistral`))return`mistral`;if(r.includes(`moonshot`)||r.includes(`kimi`))return`moonshot`;if(r.includes(`ollama`)||n.port===`11434`)return`ollama`;let i=r.split(`.`).filter(e=>e!==`api`&&e!==`v1`&&e!==`com`&&e!==`org`&&e!==`net`&&e!==`cn`&&e!==`ai`&&e!==`io`);return i.length>0&&i[0]&&i[0].replace(/[^a-z0-9_-]/g,``)||`custom-provider`}catch{return`custom-provider`}};function dg({context:e,externalEditModel:t,offered:n}){let r=e.providers??[],i=e.providerApis??[],[a,o]=(0,u.useState)({kind:`add`}),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)(``),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(``),[g,_]=(0,u.useState)(``),[v,y]=(0,u.useState)(!1),[b,x]=(0,u.useState)(``),[S,C]=(0,u.useState)(``),[w,T]=(0,u.useState)(!1),[E,D]=(0,u.useState)(!1),[O,k]=(0,u.useState)(``),[A,j]=(0,u.useState)(``),[ee,M]=(0,u.useState)(!0),[te,N]=(0,u.useState)(!0),[ne,re]=(0,u.useState)(),[ie,ae]=(0,u.useState)(``),[oe,se]=(0,u.useState)(!1),[ce,le]=(0,u.useState)(),[ue,de]=(0,u.useState)([]),[fe,pe]=(0,u.useState)(``),[me,he]=(0,u.useState)(new Set),[ge,P]=(0,u.useState)(),_e=(0,u.useRef)(``);_e.current=Uh(f,m),(0,u.useEffect)(()=>{if(!t)return;let{provider:e,modelId:n,label:a}=t;ye.current=!0;let s=r.find(t=>t.id===e);if(s){Ce(s);let t=s.models.find(e=>e.id===n);t?(we(t,Uh(s.baseUrl,s.api)),o({kind:`editModel`,providerId:e,modelId:n})):(we(void 0,``),x(n),C(a&&a!==n?a:``),o({kind:`addModel`,providerId:e}))}else c(e),d(e),p(``),h(i[0]??`openai-completions`),_(``),y(!1),x(n),C(a&&a!==n?a:``),T(!1),D(!1),k(``),j(``),o({kind:`add`});document.querySelector(`.settings-provider-form`)?.scrollIntoView({behavior:`smooth`})},[t]);let ve=a.kind===`add`?void 0:r.find(e=>e.id===a.providerId),ye=(0,u.useRef)(!1),be=()=>{ye.current=!0},xe=(0,u.useRef)(!1);(0,u.useEffect)(()=>{xe.current&&(xe.current=!1,!ye.current&&Se())},[r]);let Se=()=>{o({kind:`add`}),ye.current=!1,c(``),d(``),p(``),h(i[0]??`openai-completions`),_(``),y(!1),x(``),C(``),T(!1),D(!1),k(``),j(``),M(!0),N(!0),re(void 0),ae(``),se(!1),le(void 0),de([]),pe(``),he(new Set),P(void 0)},Ce=e=>{c(e.id),d(e.name===e.id?``:e.name),p(e.baseUrl),h(e.api),_(``),y(!1)},we=(e,t)=>{x(e?.id??``),C(!e||e.name===e.id?``:e.name),T(e?.reasoning??!1),D(e?.imageInput??!1),k(e?String(e.contextWindow):``),j(e?String(e.maxTokens):``),M(!0),N(!0),re(e?.thinkingLevelMap?{map:{...e.thinkingLevelMap},endpoint:t,modelId:e.id}:void 0)},Te=e=>{let t=r.find(t=>t.id===e);t&&(be(),o({kind:`addModel`,providerId:e}),Ce(t),we(void 0,``))},Ee=(e,t)=>{let n=r.find(t=>t.id===e),i=n?.models.find(e=>e.id===t);n&&i&&(be(),o({kind:`editModel`,providerId:e,modelId:t}),Ce(n),we(i,Uh(n.baseUrl,n.api)))},De=(e,t)=>{let n=r.find(t=>t.id===e),i=n?.models.find(e=>e.id===t);if(n&&i?.thinkingLevelMap)return{map:i.thinkingLevelMap,endpoint:Uh(n.baseUrl,n.api),reasoning:i.reasoning}},Oe=(e,t,n)=>{let r=De(e,t.id);we(r?.endpoint===n?{...t,reasoning:r.reasoning}:t,n)},ke=(e,t,n)=>{let r=Uh(f,m),i=De(e,t);if(i?.endpoint!==r){if(n)return ie===r?{...n}:null;if(i)return null}},Ae=(e,t)=>{let n=Uh(f,m),r=De(e,t);if(r&&r.endpoint===n)return{...r.map};if(ne&&ne.modelId===t&&ne.endpoint===n)return ne.map;if(r)return null},je=e=>e===void 0?{}:{thinkingLevelMap:e},Me=ie===Uh(f,m),Ne=async()=>{if(!f.trim()){le(`请先填写 API 地址`);return}if(!s.trim()){let e=ug(f);c(e),l.trim()||d(e)}se(!0),le(void 0);let e=Uh(f,m);try{let t=s.trim()||ug(f),n=await Pe(`/api/providers/fetch-models`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({baseUrl:f.trim(),apiKey:g.trim(),api:m,providerId:t})}),r=await n.json();if(!n.ok||!r.ok)throw Error(r.error||`获取模型失败`);if(_e.current!==e){de([]),he(new Set),le(`API 地址已改动,这次探测的结果没有采用`);return}let i=r.models||[];de(i),he(new Set(i.map(e=>e.id))),ae(e),i.length===1&&Oe(t,i[0],e)}catch(e){le(e instanceof Error?e.message:String(e))}finally{se(!1)}},Fe=()=>{if(me.size===0||!f.trim()||ie!==Uh(f,m))return;let t=s.trim()||ug(f);s.trim()||c(t);let n=ue.filter(e=>me.has(e.id));n.length&&(xe.current=!0,ye.current=!1,e.onSetProvider?.({id:t,...l.trim()?{name:l.trim()}:{name:t},baseUrl:f.trim(),api:m.trim()||`openai-completions`,...g.trim()?{apiKey:g.trim()}:{},models:n.map(e=>({id:e.id,name:e.name||e.id,reasoning:e.reasoning,imageInput:e.imageInput,contextWindow:e.contextWindow,maxTokens:e.maxTokens,supportsDeveloperRole:!0,supportsReasoningEffort:!0,...je(ke(t,e.id,e.thinkingLevelMap))}))}),de([]))},Ie=s.trim()||(f.trim()?ug(f):``),Le=f.trim()&&b.trim()&&!e.pendingSettings,[Re,ze]=(0,u.useState)(``),Be=r.filter(e=>!e.disabled&&(!e.builtin||e.id===Re||e.id===t?.provider)),Ve=r.filter(e=>e.disabled);return(0,F.jsxs)(`section`,{className:`settings-section`,"data-settings-providers":`1`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`Pi 的供应商与模型`}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`停用后保留配置,随时可以重新启用。`}),(0,F.jsx)(kh,{providers:r}),(0,F.jsx)(Ph,{}),(0,F.jsx)(fg,{providers:r}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`Pi 内置供应商配置`}),(0,F.jsxs)(`select`,{className:`settings-model-select`,"data-builtin-provider-picker":!0,value:Re,onChange:e=>ze(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`选择需要配置的供应商`}),r.filter(e=>e.builtin&&!e.disabled).map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),Be.length>0?(0,F.jsx)(`div`,{className:`settings-provider-list`,children:Be.map(t=>(0,F.jsxs)(`div`,{className:`settings-provider-card`,"data-provider-row":t.id,children:[(0,F.jsxs)(`div`,{className:`settings-provider-head`,children:[(0,F.jsx)(`span`,{className:`settings-provider-id`,children:t.id}),t.name!==t.id&&(0,F.jsx)(`span`,{className:`settings-provider-name`,children:t.name}),t.hasKey&&t.authType!==`oauth`&&(0,F.jsx)(`span`,{className:`settings-provider-badge`,children:`已设置 key`}),t.authType===`oauth`&&(0,F.jsx)(`span`,{className:`settings-provider-badge`,children:t.authenticated?`已授权登录`:`OAuth 授权`}),t.keyInModelsJson&&(0,F.jsx)(`span`,{className:`settings-provider-badge`,children:`key 在 models.json`}),t.builtin&&(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-builtin`,children:`Pi 内置`})]}),t.builtin?(0,F.jsx)(`div`,{className:`settings-provider-meta`,children:`模型由 Pi 提供,可停用`}):(0,F.jsxs)(`div`,{className:`settings-provider-meta`,children:[t.baseUrl,` · `,t.api]}),t.invalidFields&&t.invalidFields.length>0&&(0,F.jsxs)(`div`,{className:`settings-provider-note settings-provider-note-warn`,children:[`这个条目的 `,t.invalidFields.join(`、`),` 是空字符串,Pi 的 schema 不接受, 于是它拒绝整个 models.json —— 文件里所有自定义供应商都不会出现在选择器里。`]}),t.authType!==`oauth`&&!t.hasKey&&!t.keyInModelsJson&&(0,F.jsx)(`div`,{className:`settings-provider-note settings-provider-note-warn`,children:`没有可用凭据,Pi 不会提供这个供应商的模型 —— 它不会出现在任何模型选择器里。编辑里填一个 key 就能恢复。`}),t.authType!==`oauth`&&t.keyInModelsJson&&!t.hasKey&&(0,F.jsx)(`div`,{className:`settings-provider-note`,children:`key 写在 models.json 里(Pi 按其中的写法解析,例如 $VAR)。解析不到时 Pi 不会提供它。`}),n&&(n.has(t.id)?(0,F.jsx)(`div`,{className:`settings-provider-note`,children:`Pi 正在提供它的模型。`}):!t.hasKey&&!t.keyInModelsJson?null:(0,F.jsx)(`div`,{className:`settings-provider-note settings-provider-note-warn`,children:`Pi 现在没有提供它的模型(凭据可能已失效,或环境变量没解析到)。`})),(0,F.jsxs)(`div`,{className:`settings-provider-models`,children:[t.models.map(n=>(0,F.jsxs)(`div`,{className:`settings-provider-model-row`,"data-model-row":`${t.id}:${n.id}`,children:[(0,F.jsx)(`span`,{className:`settings-provider-model`,children:n.name}),(0,F.jsx)(`code`,{className:`settings-provider-model-id`,children:n.id}),!t.builtin&&(0,F.jsxs)(`div`,{className:`settings-provider-model-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,"data-model-edit":`${t.id}:${n.id}`,onClick:()=>Ee(t.id,n.id),children:`编辑`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link danger`,"data-model-delete":`${t.id}:${n.id}`,onClick:()=>e.onRemoveProviderModel?.(t.id,n.id),children:`删除`})]})]},n.id)),t.builtin&&t.models.length===0&&(0,F.jsx)(`div`,{className:`settings-provider-empty-note`,children:`暂未读取到模型清单`})]}),(0,F.jsxs)(`div`,{className:`settings-provider-actions`,children:[!t.builtin&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-provider-add-model":t.id,onClick:()=>Te(t.id),children:`添加模型`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-disable":t.id,onClick:()=>e.onToggleProvider?.(t.id,!1),children:`停用`}),ge===t.id?(0,F.jsxs)(`div`,{className:`settings-provider-delete-confirm`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn danger-confirm`,onClick:()=>{P(void 0),e.onRemoveProvider?.(t.id)},children:`确定删除?`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>P(void 0),children:`取消`})]}):(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-delete":t.id,onClick:()=>P(t.id),children:`删除供应商`})]})]},t.id))}):(0,F.jsx)(`div`,{className:`settings-empty-hint settings-provider-empty-note`,children:`选择上方的 Pi 内置供应商查看配置,也可以在下方添加自定义供应商。`}),Ve.length>0&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`已停用的供应商`}),(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[`这些供应商已经从 Pi 的配置里拿掉,所以不会出现在任何模型选择器里。启用会把`,(0,F.jsx)(`code`,{children:`models.json`}),` 定义和凭据原样放回去。`]}),(0,F.jsx)(`div`,{className:`settings-provider-list`,children:Ve.map(t=>(0,F.jsxs)(`div`,{className:`settings-provider-card settings-provider-card-off`,"data-provider-off-row":t.id,children:[(0,F.jsxs)(`div`,{className:`settings-provider-head`,children:[(0,F.jsx)(`span`,{className:`settings-provider-id`,children:t.id}),t.name!==t.id&&(0,F.jsx)(`span`,{className:`settings-provider-name`,children:t.name}),(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-off`,children:`已停用`}),t.builtin&&(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-builtin`,children:`Pi 内置`})]}),(0,F.jsx)(`div`,{className:`settings-provider-meta`,children:t.models.length?`原模型:${t.models.map(e=>e.name).join(`、`)}`:t.hasKey?`已保留凭据`:`无模型记录`}),(0,F.jsxs)(`div`,{className:`settings-provider-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-provider-enable":t.id,onClick:()=>e.onToggleProvider?.(t.id,!0),children:`启用`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-forget":t.id,onClick:()=>e.onRemoveProvider?.(t.id),children:`彻底删除`})]})]},t.id))})]}),(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[a.kind===`add`&&`添加供应商与模型`,a.kind===`addModel`&&`为供应商「${a.providerId}」添加模型`,a.kind===`editModel`&&`编辑模型「${a.modelId}」`]}),a.kind!==`add`&&(0,F.jsxs)(`p`,{className:`settings-agents-desc`,"data-provider-shared-note":`1`,children:[`上面这些是这个供应商下`,(0,F.jsx)(`b`,{children:`所有模型共用`}),`的(地址、API 类型、key)。改动会同时影响它下面的每个模型。`]}),(0,F.jsxs)(`div`,{className:`settings-provider-form`,onChange:be,children:[(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`供应商 id`}),(0,F.jsx)(`input`,{type:`text`,"data-provider-id":`1`,className:`settings-dir-input`,value:s,placeholder:`如 my-proxy`,readOnly:a.kind!==`add`,onChange:e=>c(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`显示名称`}),(0,F.jsx)(`input`,{type:`text`,"data-provider-name":`1`,className:`settings-dir-input`,value:l,placeholder:`如 公司中转`,onChange:e=>d(e.target.value)})]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 地址`}),(0,F.jsx)(`input`,{type:`text`,"data-provider-base-url":`1`,className:`settings-dir-input`,value:f,placeholder:`如 https://api.example.com/v1`,onBlur:()=>{if(f.trim()&&!s.trim()){let e=ug(f);c(e),l.trim()||d(e)}},onChange:e=>p(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 类型`}),(0,F.jsx)(`select`,{"data-provider-api":`1`,className:`settings-model-select`,value:m,onChange:e=>h(e.target.value),children:(i.length?i:[`openai-completions`]).map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))})]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`API key`}),(0,F.jsx)(`input`,{type:`password`,"data-provider-api-key":`1`,className:`settings-dir-input`,value:g,autoComplete:`off`,placeholder:ve?.hasKey?`已设置,留空表示不修改`:`如 sk-...`,onChange:e=>_(e.target.value)})]}),(0,F.jsxs)(`div`,{className:`settings-rule-input-group settings-fetch-models-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`智能探测`}),(0,F.jsx)(`div`,{className:`settings-fetch-models-row`,children:(0,F.jsx)(`button`,{type:`button`,className:`settings-fetch-models-btn`,"data-fetch-models-btn":`1`,disabled:!f.trim()||oe,onClick:Ne,children:oe?`正在连接并获取模型列表…`:`🔍 自动获取可用模型`})})]})]}),ce&&(0,F.jsx)(`div`,{className:`settings-fetch-models-error`,children:ce}),ue.length>0&&(0,F.jsxs)(`div`,{className:`settings-discovered-box`,"data-discovered-box":`1`,children:[(0,F.jsxs)(`div`,{className:`settings-discovered-head`,children:[(0,F.jsxs)(`span`,{className:`settings-discovered-title`,children:[`从远程接口探测到 `,ue.length,` 个可用模型`]}),(0,F.jsxs)(`div`,{className:`settings-discovered-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,onClick:()=>he(new Set(ue.map(e=>e.id))),children:`全选`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,onClick:()=>he(new Set),children:`清空`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link danger`,onClick:()=>de([]),children:`收起列表`})]})]}),(0,F.jsx)(`input`,{type:`text`,className:`settings-dir-input settings-discovered-search`,placeholder:`搜索模型名称或 ID…`,value:fe,onChange:e=>pe(e.target.value)}),(0,F.jsx)(`div`,{className:`settings-discovered-list`,children:ue.filter(e=>!fe||e.id.toLowerCase().includes(fe.toLowerCase())).map(e=>{let t=me.has(e.id);return(0,F.jsxs)(`div`,{className:`settings-discovered-item`,children:[(0,F.jsxs)(`label`,{className:`settings-discovered-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:t,onChange:t=>{let n=new Set(me);t.target.checked?n.add(e.id):n.delete(e.id),he(n)}}),(0,F.jsx)(`span`,{className:`settings-discovered-name`,children:e.name}),e.reasoning&&(0,F.jsx)(`span`,{className:`settings-discovered-tag reasoning`,children:`推理`}),e.imageInput&&(0,F.jsx)(`span`,{className:`settings-discovered-tag vision`,children:`视觉`}),e.thinkingLevelMap&&(0,F.jsxs)(`span`,{className:`settings-discovered-tag levels`,"data-discovered-levels":e.id,children:[`档位 `,Gh(e.thinkingLevelMap)]})]}),(0,F.jsx)(`button`,{type:`button`,className:`settings-provider-link`,title:`将此模型的参数填入下方单个编辑表单`,onClick:()=>Oe(Ie,e,ie),children:`填入下方`})]},e.id)})}),(0,F.jsx)(`div`,{className:`settings-discovered-footer`,children:(0,F.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-discovered-import":`1`,disabled:me.size===0||!f.trim()||oe||!Me,onClick:Fe,children:[`批量导入选中的 `,me.size,` 个模型并保存`]})}),!Me&&(0,F.jsx)(`div`,{className:`settings-fetch-models-error`,"data-discovered-stale":`1`,children:`API 地址已改动,下面这些候选是旧地址的,不能导入。改回原地址,或重新探测一次。`})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型 id`}),(0,F.jsx)(`input`,{type:`text`,"data-model-id":`1`,className:`settings-dir-input`,value:b,placeholder:`如 gpt-4o 或点击上方自动探测填入`,onChange:e=>x(e.target.value)})]}),(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型显示名`}),(0,F.jsx)(`input`,{type:`text`,"data-model-name":`1`,className:`settings-dir-input`,value:S,placeholder:`留空则用模型 id`,onChange:e=>C(e.target.value)})]})]}),(0,F.jsx)(`div`,{className:`settings-rule-form-grid`,children:(0,F.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,F.jsx)(`span`,{className:`settings-rule-label-text`,children:`上下文窗口 / 最大输出`}),(0,F.jsxs)(`div`,{className:`settings-provider-numbers`,children:[(0,F.jsx)(`input`,{type:`number`,"data-model-context-window":`1`,className:`settings-dir-input`,value:O,placeholder:`128000`,onChange:e=>k(e.target.value)}),(0,F.jsx)(`input`,{type:`number`,"data-model-max-tokens":`1`,className:`settings-dir-input`,value:A,placeholder:`16384`,onChange:e=>j(e.target.value)})]})]})}),(0,F.jsxs)(`div`,{className:`settings-provider-switches`,children:[(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-reasoning":`1`,checked:w,onChange:e=>T(e.target.checked)}),`推理模型`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-image-input":`1`,checked:E,onChange:e=>D(e.target.checked)}),`支持图片输入`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-developer-role":`1`,checked:ee,onChange:e=>M(e.target.checked)}),`支持 developer 角色`]}),(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-model-reasoning-effort":`1`,checked:te,onChange:e=>N(e.target.checked)}),`支持 reasoning_effort`]}),ve?.hasKey&&(0,F.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-provider-clear-key":`1`,checked:v,onChange:e=>y(e.target.checked)}),`清除已保存的 key`]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,"data-provider-save":`1`,className:`settings-dir-add-btn`,disabled:!Le,onClick:()=>{xe.current=!0,ye.current=!1;let t=s.trim()||Ie;e.onSetProvider?.({id:t,...l.trim()?{name:l.trim()}:{name:t},baseUrl:f.trim(),api:m.trim()||`openai-completions`,...g.trim()?{apiKey:g.trim()}:{},...v?{clearKey:!0}:{},models:[{id:b.trim(),...S.trim()?{name:S.trim()}:{},reasoning:w,...E?{imageInput:!0}:{},...O.trim()?{contextWindow:Number(O)}:{},...A.trim()?{maxTokens:Number(A)}:{},...ee?{}:{supportsDeveloperRole:!1},...te?{}:{supportsReasoningEffort:!1},...je(Ae(t,b.trim()))}]})},children:a.kind===`add`?`添加单个模型`:a.kind===`addModel`?`添加模型`:`保存修改`}),a.kind!==`add`&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-cancel":`1`,onClick:Se,children:`取消`})]})]})]})}function fg({providers:e}){let[t,n]=(0,u.useState)(``),[r,i]=(0,u.useState)([]),[a,o]=(0,u.useState)(``),[s,c]=(0,u.useState)(``),[l,d]=(0,u.useState)({}),f=e.filter(e=>e.authType===`oauth`&&!e.disabled),p=async e=>{let t=await Pe(`/api/providers/oauth`,{...e?{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}:{}}),n=await t.json();if(!t.ok)throw Error(n.error||`OAuth 授权失败。`);i(n.jobs??[])};(0,u.useEffect)(()=>{let e=!0,t=()=>{Pe(`/api/providers/oauth`).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error);e&&(i(n.jobs??[]),c(``))}).catch(t=>{e&&c(t instanceof Error?t.message:`无法读取登录状态。`)})};t();let n=window.setInterval(t,1200);return()=>{e=!1,window.clearInterval(n)}},[]);let m=async(e,t)=>{o(e),c(``);try{await p(t)}catch(e){c(e instanceof Error?e.message:`OAuth 操作失败。`)}finally{o(``)}};return f.length?(0,F.jsxs)(`section`,{className:`settings-section`,"data-provider-oauth":`1`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`内置供应商登录`}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`选择供应商`}),(0,F.jsx)(`select`,{className:`settings-model-select`,"data-oauth-provider-picker":!0,value:f.some(e=>e.id===t)?t:f[0]?.id??``,onChange:e=>n(e.target.value),children:f.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[e.name,e.authenticated?` · 已登录`:``]},e.id))})]}),(0,F.jsx)(`p`,{className:`settings-agents-desc`,children:`使用 Pi 内置的 OAuth 流程登录订阅或账号授权。令牌保存在服务端 Pi 凭据目录,不会显示在此页面。`}),s&&(0,F.jsx)(`p`,{className:`settings-dir-error`,role:`alert`,children:s}),(0,F.jsx)(`div`,{className:`settings-provider-list`,children:f.filter(e=>e.id===(f.some(e=>e.id===t)?t:f[0]?.id)).map(e=>{let t=[...r].reverse().find(t=>t.providerId===e.id),n=t&&[`starting`,`authorizing`,`prompt`].includes(t.state);return(0,F.jsxs)(`article`,{className:`settings-provider-card settings-oauth-card`,"data-oauth-provider":e.id,"data-oauth-state":t?.state??`idle`,children:[(0,F.jsxs)(`div`,{className:`settings-oauth-provider-head`,children:[(0,F.jsx)(`span`,{className:`settings-oauth-provider-mark`,"aria-hidden":`true`,children:e.name.trim().slice(0,1).toUpperCase()}),(0,F.jsxs)(`div`,{className:`settings-oauth-provider-copy`,children:[(0,F.jsx)(`span`,{className:`settings-provider-id`,children:e.name}),(0,F.jsx)(`span`,{className:`settings-oauth-provider-id`,children:e.id})]}),(0,F.jsxs)(`div`,{className:`settings-oauth-badges`,children:[e.oauthSubscription&&(0,F.jsx)(`span`,{className:`settings-provider-badge settings-provider-badge-builtin`,children:`订阅授权`}),(0,F.jsx)(`span`,{className:`settings-provider-badge ${e.authenticated?`settings-oauth-badge-connected`:``}`,children:e.authenticated?`已登录`:`未登录`})]})]}),(0,F.jsx)(`div`,{className:`settings-provider-meta settings-oauth-provider-meta`,children:e.oauthLoginLabel||`Pi 内置 OAuth`}),(0,F.jsxs)(`div`,{className:`settings-provider-actions settings-oauth-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!!a||!!n,onClick:()=>void m(e.id,{action:`login`,providerId:e.id}),children:n?`授权处理中…`:e.authenticated?`重新登录`:`登录`}),e.authenticated&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,disabled:!!a,onClick:()=>void m(e.id,{action:`logout`,providerId:e.id}),children:`退出登录`}),n&&(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>void m(t.id,{action:`cancel`,id:t.id}),children:`取消`})]}),t?.event?.type===`auth_url`&&(0,F.jsxs)(`div`,{className:`settings-oauth-step`,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`strong`,{children:`下一步:在浏览器中授权`}),t.event.instructions&&(0,F.jsx)(`p`,{children:String(t.event.instructions)})]}),(0,F.jsx)(`a`,{className:`settings-oauth-open-link`,href:String(t.event.url),target:`_blank`,rel:`noopener noreferrer`,children:`打开授权页面 ↗`})]}),t?.event?.type===`device_code`&&(0,F.jsxs)(`div`,{className:`settings-oauth-step settings-oauth-device-step`,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`strong`,{children:`在另一台设备上完成授权`}),(0,F.jsxs)(`p`,{children:[`访问 `,(0,F.jsx)(`a`,{href:String(t.event.verificationUri),target:`_blank`,rel:`noopener noreferrer`,children:String(t.event.verificationUri)}),`,并输入此设备码。`]})]}),(0,F.jsx)(`code`,{className:`settings-oauth-device-code`,children:String(t.event.userCode)})]}),t?.event?.type===`info`&&(0,F.jsx)(`p`,{className:`settings-oauth-message`,children:String(t.event.message??``)}),t?.event?.type===`progress`&&(0,F.jsxs)(`p`,{className:`settings-oauth-message`,role:`status`,children:[(0,F.jsx)(`span`,{className:`settings-oauth-progress-dot`}),String(t.event.message??`授权处理中`)]}),t?.prompt&&(0,F.jsxs)(`form`,{className:`settings-oauth-prompt`,onSubmit:e=>{e.preventDefault(),m(t.id,{action:`answer`,id:t.id,answer:l[t.id]??``})},children:[(0,F.jsxs)(`div`,{className:`settings-oauth-prompt-heading`,children:[(0,F.jsx)(`strong`,{children:`继续登录`}),(0,F.jsx)(`span`,{children:`完成身份验证所需的信息`})]}),t.prompt.type===`select`?(0,F.jsxs)(`label`,{className:`settings-oauth-field`,children:[(0,F.jsx)(`span`,{children:t.prompt.message}),(0,F.jsxs)(`select`,{className:`settings-oauth-select`,value:l[t.id]??``,onChange:e=>d(n=>({...n,[t.id]:e.target.value})),children:[(0,F.jsx)(`option`,{value:``,children:`请选择`}),t.prompt.options?.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),t.prompt.options?.find(e=>e.id===l[t.id])?.description&&(0,F.jsx)(`small`,{className:`settings-oauth-field-help`,children:t.prompt.options.find(e=>e.id===l[t.id]).description})]}):(0,F.jsxs)(`label`,{className:`settings-oauth-field`,children:[(0,F.jsx)(`span`,{children:t.prompt.message}),(0,F.jsx)(`input`,{className:`settings-oauth-input`,type:t.prompt.type===`secret`?`password`:`text`,autoComplete:`off`,placeholder:t.prompt.placeholder,value:l[t.id]??``,onChange:e=>d(n=>({...n,[t.id]:e.target.value}))})]}),(0,F.jsx)(`button`,{className:`settings-dir-add-btn settings-oauth-continue`,type:`submit`,disabled:!!a||!l[t.id],children:`继续`})]}),n&&(0,F.jsx)(`p`,{className:`settings-oauth-message`,children:`授权网页成功后,请等待服务端完成凭据交换与保存。`}),t?.state===`completed`&&(0,F.jsx)(`p`,{role:`status`,children:t.warning?`登录完成,凭据已保存。`:`登录完成,Pi 模型清单已刷新。`}),t?.warning&&(0,F.jsx)(`p`,{className:`settings-provider-note-warn`,role:`status`,children:t.warning}),t?.error&&(0,F.jsx)(`p`,{className:`settings-provider-note-warn`,role:`status`,children:t.error})]},e.id)})})]}):null}function pg({context:e}){let{connections:t,settingsServer:n,modelChannels:r}=ue(),i=t.find(e=>e.id===n),a=t.find(e=>e.id===`entry`)?.name??`当前入口`,o=i?.managed&&!i.legacy,s=i?.name??`当前入口`,c=e.modelCatalog,l=e.defaultModel,d=c?.models??[],f=d.reduce((e,t)=>e.includes(t.provider)?e:[...e,t.provider],[]),p=l?`${l.provider}/${l.modelId}`:``,[m,h]=(0,u.useState)(l?.provider??``),[g,_]=(0,u.useState)(l?.modelId??``),v=(0,u.useRef)(void 0);(0,u.useEffect)(()=>{v.current!==p&&(v.current=p,h(l?.provider??``),_(l?.modelId??``))},[p,l]);let y=l&&!f.includes(l.provider)?[...f,l.provider]:f,b=y.includes(m)?m:y[0]??``,x=d.filter(e=>e.provider===b),S=l&&l.provider===b&&!x.some(e=>e.modelId===l.modelId)?[...x,{provider:l.provider,modelId:l.modelId,label:l.label}]:x,C=S.some(e=>e.modelId===g)?g:S[0]?.modelId??``,w=!l||d.some(e=>e.provider===l.provider&&e.modelId===l.modelId),T=b&&C?`${b}/${C}`:``,E=T!==p,D=!c,O=c?.source===`unavailable`,[k,A]=(0,u.useState)(),j=e=>{h(e);let t=d.filter(t=>t.provider===e);_(e=>t.some(t=>t.modelId===e)?e:t[0]?.modelId??``)};return(0,F.jsxs)(`section`,{"data-settings-model":`1`,className:`settings-panel-container`,children:[o?(0,F.jsxs)(`section`,{className:`settings-section`,"data-model-route":`managed`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`模型请求路径`}),(0,F.jsxs)(`p`,{children:[s,` → 模型通道 → `,a,`(入口电脑) → 供应商`]}),(0,F.jsxs)(`p`,{children:[`供应商登录、API 密钥和代理保存在入口电脑。代理地址中的 `,(0,F.jsx)(`code`,{children:`127.0.0.1`}),` 指入口电脑,`,s,` 无需安装该代理。`]}),(0,F.jsxs)(`p`,{role:`status`,children:[`模型通道 · `,r[i.managedId??``]??`状态未知`]}),(0,F.jsx)(Oh,{}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,onClick:()=>me(`entry`),children:`在入口管理供应商、登录与代理`}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,onClick:()=>window.dispatchEvent(new Event(`super-pi-open-server-management`)),children:`查看服务器连接`})]})]}):null,(0,F.jsx)(`div`,{className:`settings-agents-header`,children:(0,F.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,F.jsx)(`strong`,{children:`设置新建会话的默认模型。`}),`这里的选择适用于「`,s,`」上的工作区。工作区自己的默认模型优先,两者都没有时跟随 Pi 的默认模型。 默认值只在会话创建时复制一次,之后改这里不会改动已经存在的会话。`]})}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`当前默认模型`}),(0,F.jsx)(`div`,{className:`settings-model-current`,"data-model-current":`1`,children:l?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`span`,{className:`settings-model-current-name`,children:l.label}),(0,F.jsxs)(`code`,{className:`settings-model-current-pair`,children:[l.provider,`/`,l.modelId]})]}):(0,F.jsx)(`span`,{className:`settings-model-current-none`,children:`跟随 Pi 默认模型`})}),l&&!w&&(0,F.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ Pi 当前不再提供这个模型,新会话会改用 Pi 的默认模型。`})]}),(0,F.jsxs)(`section`,{className:`settings-section`,children:[(0,F.jsx)(`h4`,{className:`settings-section-title`,children:`修改默认模型`}),D?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`正在读取 Pi 的模型列表…`}):O?(0,F.jsx)(`div`,{className:`settings-empty-hint`,children:`无法读取 Pi 的模型列表,暂时不能设置默认模型。`}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`settings-model-grid`,children:[(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`供应商`}),(0,F.jsx)(`select`,{"data-model-provider":`1`,className:`settings-model-select`,value:b,disabled:e.pendingSettings||y.length===0,onChange:e=>j(e.target.value),children:y.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))})]}),(0,F.jsxs)(`label`,{className:`settings-model-group`,children:[(0,F.jsx)(`span`,{className:`settings-model-label`,children:`模型`}),(0,F.jsx)(`select`,{"data-model-select":`1`,className:`settings-model-select`,value:C,disabled:e.pendingSettings||S.length===0,onChange:e=>_(e.target.value),children:S.map(e=>(0,F.jsx)(`option`,{value:e.modelId,children:e.label},e.modelId))})]})]}),(0,F.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,F.jsx)(`button`,{type:`button`,"data-model-save":`1`,className:`settings-dir-add-btn`,disabled:!E||e.pendingSettings||!T,onClick:()=>{let t=d.find(e=>e.provider===b&&e.modelId===C);t&&e.onSetDefaultModel?.({provider:t.provider,modelId:t.modelId,label:t.label})},children:`保存默认模型`}),(0,F.jsx)(`button`,{type:`button`,"data-model-clear":`1`,className:`settings-dir-cancel-btn`,disabled:!l||e.pendingSettings,onClick:()=>e.onSetDefaultModel?.(null),children:`清除默认模型`})]})]})]}),!o&&e.modelCatalog?.configError&&(0,F.jsxs)(`div`,{className:`settings-provider-note settings-provider-note-warn settings-provider-config-error`,"data-provider-config-error":`1`,children:[(0,F.jsx)(`div`,{children:`Pi 拒绝了自己的模型配置,因此它不提供文件里的任何自定义供应商:`}),(0,F.jsx)(`pre`,{className:`settings-provider-config-error-text`,children:e.modelCatalog.configError}),(0,F.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-repair":`1`,onClick:()=>e.onRepairProviders?.(),children:`修好这个文件`})]}),(0,F.jsx)(Nh,{}),!o&&(0,F.jsxs)(`section`,{className:`settings-section`,"data-model-route":`independent`,children:[(0,F.jsxs)(`h4`,{className:`settings-section-title`,children:[`供应商连接 · `,s]}),(0,F.jsxs)(`p`,{children:[`模型请求由「`,s,`」上的 Super Pi 服务发出,使用这台机器的登录和代理设置。`,n===`entry`&&`通过入口调用模型的托管服务器也使用这组供应商连接。`]})]}),!o&&(0,F.jsx)(dg,{context:e,externalEditModel:k,offered:new Set((e.modelCatalog?.models??[]).map(e=>e.provider))}),(0,F.jsx)(lg,{catalog:e.modelCatalog,customProviders:e.providers,onEditModel:o?void 0:(e,t,n)=>A({provider:e,modelId:t,label:n})}),(0,F.jsx)(`div`,{className:`picker-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}var mg=[{id:`appearance`,label:`外观`,render:eg},{id:`general`,label:`通用`,render:tg},{id:`desktop`,label:`桌面与后台`,render:()=>(0,F.jsx)(bh,{})},{id:`notifications`,label:`通知`,render:ng},{id:`memory`,label:`主动记忆`,render:e=>(0,F.jsx)(Sh,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`knowledge`,label:`知识库`,render:e=>(0,F.jsx)(wh,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`feishu`,label:`飞书`,render:()=>(0,F.jsx)(xh,{name:`飞书`,children:(0,F.jsx)(Th,{})})},{id:`tavily`,label:`Tavily 搜索`,render:()=>(0,F.jsx)(xh,{name:`Tavily`,children:(0,F.jsx)(jh,{})})},{id:`servers`,label:`服务器连接`,render:()=>(0,F.jsx)(Mn,{})},{id:`agents`,label:`智能体`,render:og},{id:`model`,label:`模型`,render:e=>(0,F.jsx)(pg,{context:e})},{id:`native-tools`,label:`外部工具`,render:e=>(0,F.jsx)(Rh,{workspaceId:e.workspaceId})},{id:`model-rules`,label:`模型过滤`,render:e=>(0,F.jsx)(cg,{context:e})},{id:`terminal`,label:`终端`,render:e=>(0,F.jsx)(sg,{context:e})}],hg=mg[0]?.id;function gg({initialCategory:e,workspaceId:t,theme:n,onChooseTheme:r,onClose:i,agentCatalog:a,subagentCatalog:o,modelFilterRules:s,onSetModelRules:c,defaultModel:l,modelCatalog:d,onSetDefaultModel:f,providers:p,providerApis:m,onSetProvider:h,onRemoveProvider:g,onToggleProvider:_,onRepairProviders:v,onRemoveProviderModel:y,customAgentDirs:b,pendingSettings:x,onSetCustomAgentDirs:S,onRescanAgents:C,userNickname:w,onSetUserNickname:T,terminalShell:E,onSetTerminalShell:D,browserNotificationsEnabled:O,browserNotificationPermission:k,onSetBrowserNotifications:A,onCheckBrowserNotifications:j}){let[ee,M]=(0,u.useState)(e??hg);(0,u.useEffect)(()=>{let e=()=>M(`servers`);return window.addEventListener(`super-pi-open-server-management`,e),()=>window.removeEventListener(`super-pi-open-server-management`,e)},[]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]);let{settingsServer:te}=ue();(0,u.useEffect)(()=>{let e=()=>{me(`entry`),M(`model`)};return window.addEventListener(`super-pi-open-local-model-settings`,e),()=>window.removeEventListener(`super-pi-open-local-model-settings`,e)},[]);let N=mg.find(e=>e.id===ee)??mg[0];return(0,F.jsx)(`div`,{className:`overlay`,onClick:i,children:(0,F.jsxs)(`div`,{className:`picker settings-window`,"data-theme-dialog":`1`,"data-settings-window":`1`,onClick:e=>e.stopPropagation(),children:[(0,F.jsxs)(`div`,{className:`settings-window-head`,children:[(0,F.jsx)(`h2`,{children:`设置`}),(0,F.jsx)(An,{})]}),(0,F.jsxs)(`div`,{className:`settings-window-body`,children:[(0,F.jsxs)(`nav`,{className:`settings-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`设置分类`,"data-settings-nav":`1`,children:[(0,F.jsx)(`div`,{className:`settings-nav-label`,children:`分类`}),mg.map(e=>(0,F.jsx)(`button`,{type:`button`,id:`settings-tab-${e.id}`,className:`settings-category`,role:`tab`,"aria-selected":e.id===N?.id,"aria-controls":`settings-panel`,tabIndex:e.id===N?.id?0:-1,"data-settings-category":e.id,onClick:()=>M(e.id),children:e.label},e.id))]}),N&&(0,F.jsxs)(`div`,{className:`settings-panel`,id:`settings-panel`,role:`tabpanel`,"aria-labelledby":`settings-tab-${N.id}`,"data-settings-panel":N.id,children:[(0,F.jsx)(`h3`,{className:`settings-panel-title`,"data-settings-panel-title":N.id,children:N.label}),N.render({workspaceId:t&&de(t)===te?t:void 0,theme:n,onChooseTheme:r,onClose:i,agentCatalog:a,subagentCatalog:o,modelFilterRules:s,onSetModelRules:c,defaultModel:l,modelCatalog:d,onSetDefaultModel:f,providers:p,providerApis:m,onSetProvider:h,onRemoveProvider:g,onToggleProvider:_,onRepairProviders:v,onRemoveProviderModel:y,customAgentDirs:b,pendingSettings:x,onSetCustomAgentDirs:S,onRescanAgents:C,userNickname:w,onSetUserNickname:T,terminalShell:E,onSetTerminalShell:D,browserNotificationsEnabled:O,browserNotificationPermission:k,onSetBrowserNotifications:A,onCheckBrowserNotifications:j})]},te)]})]})})}var _g=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,yg=(e,t)=>{for(var n in t)_g(e,n,{get:t[n],enumerable:!0})},bg=(e,t,n,r)=>{for(var i=r>1?void 0:r?vg(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&_g(t,n,i),i},xg=(e,t)=>(n,r)=>t(n,r,e),Sg=`Terminal input`,Cg={get:()=>Sg,set:e=>Sg=e},wg=`Too much output to announce, navigate to rows manually to read`,Tg={get:()=>wg,set:e=>wg=e};function Eg(e){return e.replace(/\r?\n/g,`\r`)}function Dg(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function Og(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function kg(e,t,n,r){e.stopPropagation(),e.clipboardData&&Ag(e.clipboardData.getData(`text/plain`),t,n,r)}function Ag(e,t,n,r){e=Eg(e),e=Dg(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function jg(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Mg(e,t,n,r,i){jg(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Ng(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Pg(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Fg=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},Ig=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Lg=``,Rg=` `,zg=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Bg}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Bg=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Vg=class e extends zg{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Bg,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ng(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Hg=`di$target`,Ug=`di$dependencies`,Wg=new Map;function Gg(e){return e[Ug]||[]}function Kg(e){if(Wg.has(e))return Wg.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);qg(t,e,r)};return t._id=e,Wg.set(e,t),t}function qg(e,t,n){t[Hg]===t?t[Ug].push({id:e,index:n}):(t[Ug]=[{id:e,index:n}],t[Hg]=t)}var Jg=Kg(`BufferService`),Yg=Kg(`CoreMouseService`),Xg=Kg(`CoreService`),Zg=Kg(`CharsetService`),Qg=Kg(`InstantiationService`),$g=Kg(`LogService`),e_=Kg(`OptionsService`),t_=Kg(`OscLinkService`),n_=Kg(`UnicodeService`),r_=Kg(`DecorationService`),i_=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Vg,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):a_(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};i_=bg([xg(0,Jg),xg(1,e_),xg(2,t_)],i_);function a_(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
316
316
|
|
|
317
|
-
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var
|
|
317
|
+
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var o_=Kg(`CharSizeService`),s_=Kg(`CoreBrowserService`),c_=Kg(`MouseService`),l_=Kg(`RenderService`),u_=Kg(`SelectionService`),d_=Kg(`CharacterJoinerService`),f_=Kg(`ThemeService`),p_=Kg(`LinkProviderService`),m_=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?b_.isErrorNoTelemetry(e)?new b_(e.message+`
|
|
318
318
|
|
|
319
319
|
`+e.stack):Error(e.message+`
|
|
320
320
|
|
|
321
|
-
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function m_(e){g_(e)||p_.onUnexpectedError(e)}var h_=`Canceled`;function g_(e){return e instanceof __||e instanceof Error&&e.name===h_&&e.message===h_}var __=class extends Error{constructor(){super(h_),this.name=this.message}};function v_(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var y_=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},b_=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function x_(e,t=0){return e[e.length-(1+t)]}var S_;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(S_||={});var C_=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||S_.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};C_.empty=new C_(e=>{});function w_(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var T_;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(T_||={});var E_=null;function D_(e){return E_?.trackDisposable(e),e}function O_(e){E_?.markAsDisposed(e)}function k_(e,t){E_?.setParent(e,t)}function A_(e){return E_?.markAsSingleton(e),e}function j_(e){if(T_.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function M_(...e){return N_(()=>j_(e))}function N_(e){let t=D_({dispose:w_(()=>{O_(t),e()})});return t}var P_=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,D_(this)}dispose(){this._isDisposed||(O_(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{j_(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return k_(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),k_(e,null))}};P_.DISABLE_DISPOSED_WARNING=!1;var F_=P_,I_=class{constructor(){this._store=new F_,D_(this),k_(this._store,this)}dispose(){O_(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};I_.None=Object.freeze({dispose(){}});var L_=class{constructor(){this._isDisposed=!1,D_(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&k_(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,O_(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&k_(e,null),e}},R_=typeof window==`object`?window:globalThis,z_=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};z_.Undefined=new z_(void 0);var B_=z_,V_=class{constructor(){this._first=B_.Undefined,this._last=B_.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===B_.Undefined}clear(){let e=this._first;for(;e!==B_.Undefined;){let t=e.next;e.prev=B_.Undefined,e.next=B_.Undefined,e=t}this._first=B_.Undefined,this._last=B_.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new B_(e);if(this._first===B_.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==B_.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==B_.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==B_.Undefined&&e.next!==B_.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===B_.Undefined&&e.next===B_.Undefined?(this._first=B_.Undefined,this._last=B_.Undefined):e.next===B_.Undefined?(this._last=this._last.prev,this._last.next=B_.Undefined):e.prev===B_.Undefined&&(this._first=this._first.next,this._first.prev=B_.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==B_.Undefined;)yield e.element,e=e.next}},H_=globalThis.performance&&typeof globalThis.performance.now==`function`,U_=class e{static create(t){return new e(t)}constructor(e){this._now=H_&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},W_;(e=>{e.None=()=>I_.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(M_(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new Q({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new Q({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new Q({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Q({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Q({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new Q;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Q(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof F_?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(W_||={});var G_=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new U_,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};G_.all=new Set,G_._idPool=0;var K_=G_,q_=-1,J_=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Z_(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};J_._idPool=1;var Y_=J_,X_=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
|
|
321
|
+
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function h_(e){__(e)||m_.onUnexpectedError(e)}var g_=`Canceled`;function __(e){return e instanceof v_||e instanceof Error&&e.name===g_&&e.message===g_}var v_=class extends Error{constructor(){super(g_),this.name=this.message}};function y_(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var b_=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},x_=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function S_(e,t=0){return e[e.length-(1+t)]}var C_;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(C_||={});var w_=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||C_.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};w_.empty=new w_(e=>{});function T_(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var E_;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(E_||={});var D_=null;function O_(e){return D_?.trackDisposable(e),e}function k_(e){D_?.markAsDisposed(e)}function A_(e,t){D_?.setParent(e,t)}function j_(e){return D_?.markAsSingleton(e),e}function M_(e){if(E_.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function N_(...e){return P_(()=>M_(e))}function P_(e){let t=O_({dispose:T_(()=>{k_(t),e()})});return t}var F_=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,O_(this)}dispose(){this._isDisposed||(k_(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{M_(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return A_(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),A_(e,null))}};F_.DISABLE_DISPOSED_WARNING=!1;var I_=F_,L_=class{constructor(){this._store=new I_,O_(this),A_(this._store,this)}dispose(){k_(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};L_.None=Object.freeze({dispose(){}});var R_=class{constructor(){this._isDisposed=!1,O_(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&A_(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,k_(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&A_(e,null),e}},z_=typeof window==`object`?window:globalThis,B_=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};B_.Undefined=new B_(void 0);var V_=B_,H_=class{constructor(){this._first=V_.Undefined,this._last=V_.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===V_.Undefined}clear(){let e=this._first;for(;e!==V_.Undefined;){let t=e.next;e.prev=V_.Undefined,e.next=V_.Undefined,e=t}this._first=V_.Undefined,this._last=V_.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new V_(e);if(this._first===V_.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==V_.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==V_.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==V_.Undefined&&e.next!==V_.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===V_.Undefined&&e.next===V_.Undefined?(this._first=V_.Undefined,this._last=V_.Undefined):e.next===V_.Undefined?(this._last=this._last.prev,this._last.next=V_.Undefined):e.prev===V_.Undefined&&(this._first=this._first.next,this._first.prev=V_.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==V_.Undefined;)yield e.element,e=e.next}},U_=globalThis.performance&&typeof globalThis.performance.now==`function`,W_=class e{static create(t){return new e(t)}constructor(e){this._now=U_&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},G_;(e=>{e.None=()=>L_.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(N_(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new Q({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new Q({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new Q({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Q({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Q({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new Q;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Q(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof I_?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(G_||={});var K_=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new W_,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};K_.all=new Set,K_._idPool=0;var q_=K_,J_=-1,Y_=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Q_(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Y_._idPool=1;var X_=Y_,Z_=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
|
|
322
322
|
`).slice(2).join(`
|
|
323
|
-
`))}},Z_=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Q_=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},$_=0,ev=class{constructor(e){this.value=e,this.id=$_++}},tv=2,Q=class{constructor(e){this._size=0,this._options=e,this._leakageMon=q_>0||this._options?.leakWarningThreshold?new Y_(e?.onListenerError??m_,this._options?.leakWarningThreshold??q_):void 0,this._perfMon=this._options?._profName?new K_(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Q_(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||m_)(n),I_.None}if(this._disposed)return I_.None;t&&(e=e.bind(t));let r=new ev(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=X_.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ev?(this._deliveryQueue??=new nv,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=N_(()=>{i?.(),this._removeListener(r)});return n instanceof F_?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*tv<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||m_;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof ev)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},nv=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},rv=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Q,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Q,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};rv.INSTANCE=new rv;var iv=rv;function av(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}iv.INSTANCE.onDidChangeZoomLevel;function ov(e){return iv.INSTANCE.getZoomFactor(e)}iv.INSTANCE.onDidChangeFullscreen;var sv=typeof navigator==`object`?navigator.userAgent:``,cv=sv.indexOf(`Firefox`)>=0,lv=sv.indexOf(`AppleWebKit`)>=0,uv=sv.indexOf(`Chrome`)>=0,dv=!uv&&sv.indexOf(`Safari`)>=0;sv.indexOf(`Electron/`),sv.indexOf(`Android`);var fv=!1;if(typeof R_.matchMedia==`function`){let e=R_.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=R_.matchMedia(`(display-mode: fullscreen)`);fv=e.matches,av(R_,e,({matches:e})=>{fv&&t.matches||(fv=e)})}function pv(){return fv}var mv=`en`,hv=!1,gv=!1,_v=!1,vv=!1,yv=!1,bv=mv,xv,Sv=globalThis,Cv;typeof Sv.vscode<`u`&&typeof Sv.vscode.process<`u`?Cv=Sv.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(Cv=process);var wv=typeof Cv?.versions?.electron==`string`&&Cv?.type===`renderer`;if(typeof Cv==`object`){hv=Cv.platform===`win32`,gv=Cv.platform===`darwin`,_v=Cv.platform===`linux`,_v&&Cv.env.SNAP&&Cv.env.SNAP_REVISION,Cv.env.CI||Cv.env.BUILD_ARTIFACTSTAGINGDIRECTORY,bv=mv;let e=Cv.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,bv=t.resolvedLanguage||mv,t.languagePack?.translationsConfigFile}catch{}vv=!0}else typeof navigator==`object`&&!wv?(xv=navigator.userAgent,hv=xv.indexOf(`Windows`)>=0,gv=xv.indexOf(`Macintosh`)>=0,(xv.indexOf(`Macintosh`)>=0||xv.indexOf(`iPad`)>=0||xv.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,_v=xv.indexOf(`Linux`)>=0,xv?.indexOf(`Mobi`),yv=!0,bv=globalThis._VSCODE_NLS_LANGUAGE||mv,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var Tv=hv,Ev=gv,Dv=_v,Ov=vv;yv&&typeof Sv.importScripts==`function`&&Sv.origin;var kv=xv,Av=bv,jv;(e=>{function t(){return Av}e.value=t;function n(){return Av.length===2?Av===`en`:Av.length>=3&&Av[0]===`e`&&Av[1]===`n`&&Av[2]===`-`}e.isDefaultVariant=n;function r(){return Av===`en`}e.isDefault=r})(jv||={});var Mv=typeof Sv.postMessage==`function`&&!Sv.importScripts;(()=>{if(Mv){let e=[];Sv.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),Sv.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var Nv=!!(kv&&kv.indexOf(`Chrome`)>=0);kv&&kv.indexOf(`Firefox`),!Nv&&kv&&kv.indexOf(`Safari`),kv&&kv.indexOf(`Edg/`),kv&&kv.indexOf(`Android`);var Pv=typeof navigator==`object`?navigator:{};Ov||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Pv&&Pv.clipboard&&Pv.clipboard.writeText,Ov||Pv&&Pv.clipboard&&Pv.clipboard.readText,Ov||pv()||Pv.keyboard,`ontouchstart`in R_||Pv.maxTouchPoints,R_.PointerEvent&&(`ontouchstart`in R_||navigator.maxTouchPoints);var Fv=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Iv=new Fv,Lv=new Fv,Rv=new Fv,zv=Array(230),Bv;(e=>{function t(e){return Iv.keyCodeToStr(e)}e.toString=t;function n(e){return Iv.strToKeyCode(e)}e.fromString=n;function r(e){return Lv.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Rv.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Lv.strToKeyCode(e)||Rv.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Iv.keyCodeToStr(e)}e.toElectronAccelerator=o})(Bv||={});var Vv=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Hv([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Hv=class{constructor(e){if(e.length===0)throw v_(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Uv(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Bv.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(cv)switch(t){case 59:return 85;case 60:if(Dv)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Ev)return 57}else if(lv&&(Ev&&t===93||!Ev&&t===92))return 57;return zv[t]||0}var Wv=Ev?256:2048,Gv=512,Kv=1024,qv=Ev?2048:256,Jv=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=Uv(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Wv),this.altKey&&(t|=Gv),this.shiftKey&&(t|=Kv),this.metaKey&&(t|=qv),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new Vv(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Yv=new WeakMap;function Xv(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var Zv=class{static getSameOriginWindowChain(e){let t=Yv.get(e);if(!t){t=[],Yv.set(e,t);let n=e,r;do r=Xv(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Qv=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=Zv.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},$v=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(uv){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?cv&&!Ev?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=dv&&Tv?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?cv&&!Ev?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},ey=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),ty;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof ny?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:W_.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ey})})(ty||={});var ny=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?ey:(this._emitter||=new Q,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},ry=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new b_(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new b_(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},iy=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new b_(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=N_(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var ay;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(ay||={});var oy=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Q,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await W_.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};oy.EMPTY=oy.fromArray([]);function sy(e){return cy(e,0)}function cy(e,t){switch(typeof e){case`object`:return e===null?ly(349,t):Array.isArray(e)?fy(e,t):py(e,t);case`string`:return dy(e,t);case`boolean`:return uy(e,t);case`number`:return ly(e,t);case`undefined`:return ly(937,t);default:return ly(617,t)}}function ly(e,t){return(t<<5)-t+e|0}function uy(e,t){return ly(e?433:863,t)}function dy(e,t){t=ly(149417,t);for(let n=0,r=e.length;n<r;n++)t=ly(e.charCodeAt(n),t);return t}function fy(e,t){return t=ly(104579,t),e.reduce((e,t)=>cy(t,e),t)}function py(e,t){return t=ly(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=dy(n,t),cy(e[n],t)),t)}var{registerWindow:my,getWindow:hy,getDocument:gy,getWindows:_y,getWindowsCount:vy,getWindowId:yy,getWindowById:by,hasWindow:xy,onDidRegisterWindow:Sy,onWillUnregisterWindow:Cy,onDidUnregisterWindow:wy}=function(){let e=new Map,t={window:R_,disposables:new F_};e.set(R_.vscodeWindowId,t);let n=new Q,r=new Q,i=new Q;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return I_.None;let a=new F_,o={window:t,disposables:a.add(new F_)};return e.set(t.vscodeWindowId,o),a.add(N_(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(Ey(t,Fy.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:R_},getDocument(e){return hy(e).document}}}(),Ty=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function Ey(e,t,n,r){return new Ty(e,t,n,r)}function Dy(e,t){return function(n){return t(new Qv(e,n))}}function Oy(e){return function(t){return e(new Jv(t))}}var ky=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Dy(hy(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=Oy(n)),Ey(e,t,i,r)},Ay,jy=class extends iy{constructor(e){super(),this.defaultTarget=e&&hy(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},My=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){m_(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(My.sort),a.shift().execute();r.set(i,!1)};Ay=(t,r,a=0)=>{let o=yy(t),s=new My(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var Ny=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};Ny.None=new Ny(0,0);function Py(e){let t=e.getBoundingClientRect(),n=hy(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=sy(n),a=r.get(i);if(a)a.users+=1;else{let o=new Q,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(N_(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var Fy={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:lv?`webkitAnimationStart`:`animationstart`,ANIMATION_END:lv?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:lv?`webkitAnimationIteration`:`animationiteration`},Iy=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=Ly(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Ly(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Ly(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Ly(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Ly(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Ly(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Ly(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Ly(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Ly(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Ly(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Ly(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Ly(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Ly(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Ly(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Ly(e){return typeof e==`number`?`${e}px`:e}function Ry(e){return new Iy(e)}var zy=class{constructor(){this._hooks=new F_,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(N_(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=hy(e)}this._hooks.add(Ey(a,Fy.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(Ey(a,Fy.POINTER_UP,e=>this.stopMonitoring(!0)))}};function By(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Vy;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Vy||={});var Hy=class e extends I_{constructor(){super(),this.dispatched=!1,this.targets=new V_,this.ignoreTargets=new V_,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(W_.runAndSubscribe(Sy,({window:e,disposables:t})=>{t.add(Ey(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(Ey(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(Ey(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:R_,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=A_(new e),N_(e.INSTANCE.targets.push(t))):I_.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=A_(new e),N_(e.INSTANCE.ignoreTargets.push(t))):I_.None}static isTouchDevice(){return`ontouchstart`in R_||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Vy.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-x_(s.rollingPageX))<30&&Math.abs(s.initialPageY-x_(s.rollingPageY))<30){let e=this.newGestureEvent(Vy.Tap,s.initialTarget);e.pageX=x_(s.rollingPageX),e.pageY=x_(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-x_(s.rollingPageX))<30&&Math.abs(s.initialPageY-x_(s.rollingPageY))<30){let e=this.newGestureEvent(Vy.Contextmenu,s.initialTarget);e.pageX=x_(s.rollingPageX),e.pageY=x_(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=x_(s.rollingPageX),n=x_(s.rollingPageY),i=x_(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Vy.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Vy.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Vy.Change||t.type===Vy.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=Ay(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Vy.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Vy.Change,i.initialTarget);a.translationX=r.pageX-x_(i.rollingPageX),a.translationY=r.pageY-x_(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Hy.SCROLL_FRICTION=-.005,Hy.HOLD_DELAY=700,Hy.CLEAR_TAP_COUNT_TIME=400,yg([By],Hy,`isTouchDevice`,1);var Uy=Hy,Wy=class extends I_{onclick(e,t){this._register(Ey(e,Fy.CLICK,n=>t(new Qv(hy(e),n))))}onmousedown(e,t){this._register(Ey(e,Fy.MOUSE_DOWN,n=>t(new Qv(hy(e),n))))}onmouseover(e,t){this._register(Ey(e,Fy.MOUSE_OVER,n=>t(new Qv(hy(e),n))))}onmouseleave(e,t){this._register(Ey(e,Fy.MOUSE_LEAVE,n=>t(new Qv(hy(e),n))))}onkeydown(e,t){this._register(Ey(e,Fy.KEY_DOWN,e=>t(new Jv(e))))}onkeyup(e,t){this._register(Ey(e,Fy.KEY_UP,e=>t(new Jv(e))))}oninput(e,t){this._register(Ey(e,Fy.INPUT,t))}onblur(e,t){this._register(Ey(e,Fy.BLUR,t))}onfocus(e,t){this._register(Ey(e,Fy.FOCUS,t))}onchange(e,t){this._register(Ey(e,Fy.CHANGE,t))}ignoreGesture(e){return Uy.ignoreTarget(e)}},Gy=11,Ky=class extends Wy{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Gy+`px`,this.domNode.style.height=Gy+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new zy),this._register(ky(this.bgDomNode,Fy.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(ky(this.domNode,Fy.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new jy),this._pointerdownScheduleRepeatTimer=this._register(new ry)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,hy(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},qy=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Jy=class extends I_{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new qy(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Qy(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Qy.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Yy=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Xy(e,t){let n=t-e;return function(t){return e+n*eb(t)}}function Zy(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Qy=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),Zy(Xy(e,r),Xy(i,t),.33)}return Xy(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Yy(this.scrollLeft(t),this.scrollTop(t),!1):new Yy(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function $y(e){return e**3}function eb(e){return 1-$y(1-e)}var tb=class extends I_{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new ry)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},nb=140,rb=class extends Wy{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new tb(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new zy),this._shouldRender=!0,this.domNode=Ry(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(Ey(this.domNode.domNode,Fy.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Ky(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Ry(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ey(this.slider.domNode,Fy.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=Py(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(Tv&&a>nb){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},ib=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},ab=class extends rb{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new ib(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},ob=class extends rb{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new ib(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},sb=500,cb=50,lb=!0,ub=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},db=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(uv){let t=ov(hy(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new ub(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};db.INSTANCE=new db;var fb=db,pb=class extends Wy{constructor(e,t,n){super(),this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Q),this.onWillScroll=this._onWillScroll.event,this._options=hb(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new ob(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ab(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ry(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ry(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ry(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new ry),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=j_(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Ev&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new $v(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=j_(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(Ey(this._listenOnDomNode,Fy.MOUSE_WHEEL,e=>{this._onMouseWheel(new $v(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=fb.INSTANCE;lb&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!Ev&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=cb*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=cb*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(lb&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),sb)}},mb=class extends pb{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function hb(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,Ev&&(t.className+=` mac`),t}var gb=class extends I_{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Jy({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>Ay(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new mb(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(W_.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(N_(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(N_(()=>this._styleElement.remove())),this._register(W_.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
|
|
324
|
-
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};gb=yg([bg(2,qg),bg(3,o_),bg(4,Jg),bg(5,d_),bg(6,$g),bg(7,c_)],gb);var _b=class extends I_{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(N_(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};_b=yg([bg(1,qg),bg(2,o_),bg(3,n_),bg(4,c_)],_b);var vb=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},yb={full:0,left:0,center:0,right:0},bb={full:0,left:0,center:0,right:0},xb={full:0,left:0,center:0,right:0},Sb=class extends I_{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new vb,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(N_(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);bb.full=this._canvas.width,bb.left=e,bb.center=t,bb.right=e,this._refreshDrawHeightConstants(),xb.full=1,xb.left=1,xb.center=1+bb.left,xb.right=1+bb.left+bb.center}_refreshDrawHeightConstants(){yb.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);yb.left=t,yb.center=t,yb.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yb.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yb.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yb.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*yb.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(xb[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-yb[e.position||`full`]/2),bb[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+yb[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Sb=yg([bg(2,qg),bg(3,n_),bg(4,c_),bg(5,$g),bg(6,d_),bg(7,o_)],Sb);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
325
|
-
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var Cb;(e=>(e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``))(Cb||={});var wb;(e=>e.ST=`${$.ESC}\\`)(wb||={});var Tb=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};Tb=yg([bg(2,qg),bg(3,$g),bg(4,Yg),bg(5,c_)],Tb);var Eb=0,Db=0,Ob=0,kb=0,Ab={css:`#00000000`,rgba:0},jb;(e=>{function t(e,t,n,r){return r===void 0?`#${Ib(e)}${Ib(t)}${Ib(n)}`:`#${Ib(e)}${Ib(t)}${Ib(n)}${Ib(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(jb||={});var Mb;(e=>{function t(e,t){if(kb=(t.rgba&255)/255,kb===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Eb=a+Math.round((n-a)*kb),Db=o+Math.round((r-o)*kb),Ob=s+Math.round((i-s)*kb),{css:jb.toCss(Eb,Db,Ob),rgba:jb.toRgba(Eb,Db,Ob)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=Fb.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return jb.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Eb,Db,Ob]=Fb.toChannels(t),{css:jb.toCss(Eb,Db,Ob),rgba:t}}e.opaque=i;function a(e,t){return kb=Math.round(t*255),[Eb,Db,Ob]=Fb.toChannels(e.rgba),{css:jb.toCss(Eb,Db,Ob,kb),rgba:jb.toRgba(Eb,Db,Ob,kb)}}e.opacity=a;function o(e,t){return kb=e.rgba&255,a(e,kb*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Mb||={});var Nb;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Eb=parseInt(e.slice(1,2).repeat(2),16),Db=parseInt(e.slice(2,3).repeat(2),16),Ob=parseInt(e.slice(3,4).repeat(2),16),jb.toColor(Eb,Db,Ob);case 5:return Eb=parseInt(e.slice(1,2).repeat(2),16),Db=parseInt(e.slice(2,3).repeat(2),16),Ob=parseInt(e.slice(3,4).repeat(2),16),kb=parseInt(e.slice(4,5).repeat(2),16),jb.toColor(Eb,Db,Ob,kb);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Eb=parseInt(r[1]),Db=parseInt(r[2]),Ob=parseInt(r[3]),kb=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),jb.toColor(Eb,Db,Ob,kb);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Eb,Db,Ob,kb]=t.getImageData(0,0,1,1).data,kb!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:jb.toRgba(Eb,Db,Ob,kb),css:e}}e.toColor=r})(Nb||={});var Pb;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(Pb||={});var Fb;(e=>{function t(e,t){if(kb=(t&255)/255,kb===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Eb=a+Math.round((n-a)*kb),Db=o+Math.round((r-o)*kb),Ob=s+Math.round((i-s)*kb),jb.toRgba(Eb,Db,Ob)}e.blend=t;function n(e,t,n){let a=Pb.relativeLuminance(e>>8),o=Pb.relativeLuminance(t>>8);if(Lb(a,o)<n){if(o<a){let o=r(e,t,n),s=Lb(a,Pb.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Lb(a,Pb.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Lb(a,Pb.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Lb(a,Pb.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Lb(Pb.relativeLuminance2(o,s,c),Pb.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Lb(Pb.relativeLuminance2(o,s,c),Pb.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Lb(Pb.relativeLuminance2(o,s,c),Pb.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Lb(Pb.relativeLuminance2(o,s,c),Pb.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(Fb||={});function Ib(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Lb(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var Rb=class extends Rg{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},zb=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Bg}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||Lg.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)zb._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||Lg.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};zb=yg([bg(0,qg)],zb);function Bb(e){return 57508<=e&&e<=57558}function Vb(e){return 9472<=e&&e<=9631}function Hb(e){return Bb(e)||Vb(e)}function Ub(){return{css:{canvas:Wb(),cell:Wb()},device:{canvas:Wb(),cell:Wb(),char:{width:0,height:0,left:0,top:0}}}}function Wb(){return{width:0,height:0}}var Gb=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Bg,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,j=k>=E,ee=k,M=this._workCell;if(f.length>0&&k===f[0][0]&&j){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)j&&=i===this._isCellInSelection(v,t);j&&=!n||a<r[0]||a>=r[1],j?(A=!0,M=new Rb(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),ee=r[1]-1,m=M.getWidth()):E=r[1]}let te=this._isCellInSelection(k,t),N=n&&k===a,ne=O&&k>=l&&k<=u,re=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{re=!0});let ie=M.getChars()||Lg;if(ie===` `&&(M.isUnderline()||M.isOverline())&&(ie=`\xA0`),T=m*s-c.get(ie,M.isBold(),M.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(te&&w||!te&&!w&&M.bg===y)&&(te&&w&&p.selectionForeground||M.fg===b)&&M.extended.ext===x&&ne===S&&T===C&&!N&&!A&&!re&&j){M.isInvisible()?_+=Lg:_+=ie,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=M.bg,b=M.fg,x=M.extended.ext,S=ne,C=T,w=te,A&&a>=k&&a<=ee&&(a=k),!this._coreService.isCursorHidden&&N&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`)}}if(M.isBold()&&D.push(`xterm-bold`),M.isItalic()&&D.push(`xterm-italic`),M.isDim()&&D.push(`xterm-dim`),_=M.isInvisible()?Lg:M.getChars()||Lg,M.isUnderline()&&(D.push(`xterm-underline-${M.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!M.isUnderlineColorDefault())){if(M.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Rg.toColorRGB(M.getUnderlineColor()).join(`,`)})`;else{let e=M.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&M.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}M.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),M.isStrikethrough()&&D.push(`xterm-strikethrough`),ne&&(h.style.textDecoration=`underline`);let ae=M.getFgColor(),oe=M.getFgColorMode(),se=M.getBgColor(),ce=M.getBgColorMode(),le=!!M.isInverse();if(le){let e=ae;ae=se,se=e;let t=oe;oe=ce,ce=t}let ue,de,fe=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&fe||(e.backgroundColorRGB&&(ce=50331648,se=e.backgroundColorRGB.rgba>>8&16777215,ue=e.backgroundColorRGB),e.foregroundColorRGB&&(oe=50331648,ae=e.foregroundColorRGB.rgba>>8&16777215,de=e.foregroundColorRGB),fe=e.options.layer===`top`)}),!fe&&te&&(ue=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,se=ue.rgba>>8&16777215,ce=50331648,fe=!0,p.selectionForeground&&(oe=50331648,ae=p.selectionForeground.rgba>>8&16777215,de=p.selectionForeground)),fe&&D.push(`xterm-decoration-top`);let pe;switch(ce){case 16777216:case 33554432:pe=p.ansi[se],D.push(`xterm-bg-${se}`);break;case 50331648:pe=jb.toColor(se>>16,se>>8&255,se&255),this._addStyle(h,`background-color:#${Kb((se>>>0).toString(16),`0`,6)}`);break;default:le?(pe=p.foreground,D.push(`xterm-bg-257`)):pe=p.background}switch(ue||M.isDim()&&(ue=Mb.multiplyOpacity(pe,.5)),oe){case 16777216:case 33554432:M.isBold()&&ae<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ae+=8),this._applyMinimumContrast(h,pe,p.ansi[ae],M,ue,void 0)||D.push(`xterm-fg-${ae}`);break;case 50331648:let e=jb.toColor(ae>>16&255,ae>>8&255,ae&255);this._applyMinimumContrast(h,pe,e,M,ue,de)||this._addStyle(h,`color:#${Kb(ae.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,pe,p.foreground,M,ue,de)||le&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!N&&!A&&!re&&j?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=ee}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Hb(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=Mb.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Gb=yg([bg(1,u_),bg(2,$g),bg(3,o_),bg(4,Yg),bg(5,n_),bg(6,d_)],Gb);function Kb(e,t,n){for(;e.length<n;)e=t+e;return e}var qb=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.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`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.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(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Jb=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Yb(){return new Jb}var Xb=`xterm-dom-renderer-owner-`,Zb=`xterm-rows`,Qb=`xterm-fg-`,$b=`xterm-bg-`,ex=`xterm-focus`,tx=`xterm-selection`,nx=1,rx=class extends I_{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=nx++,this._rowElements=[],this._selectionRenderModel=Yb(),this.onRequestRedraw=this._register(new Q).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(Zb),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(tx),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=Ub(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Gb,document),this._element.classList.add(Xb+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(N_(()=>{this._element.classList.remove(Xb+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new qb(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Zb} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Zb} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Zb} .xterm-dim { color: ${Mb.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Zb}.${ex} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Zb}.${ex} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Zb}.${ex} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Zb} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Zb} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Zb} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Zb} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Zb} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${tx} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${tx} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${tx} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${Qb}${n} { color: ${r.css}; }${this._terminalSelector} .${Qb}${n}.xterm-dim { color: ${Mb.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${$b}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${Qb}257 { color: ${Mb.opaque(e.background).css}; }${this._terminalSelector} .${Qb}257.xterm-dim { color: ${Mb.multiplyOpacity(Mb.opaque(e.background),.5).css}; }${this._terminalSelector} .${$b}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ex),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ex),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Xb}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};rx=yg([bg(7,Zg),bg(8,a_),bg(9,$g),bg(10,qg),bg(11,Yg),bg(12,o_),bg(13,d_)],rx);var ix=class extends I_{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Q),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new sx(this._optionsService))}catch{this._measureStrategy=this._register(new ox(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};ix=yg([bg(2,$g)],ix);var ax=class extends I_{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},ox=class extends ax{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},sx=class extends ax{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},cx=class extends I_{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new lx(this._window)),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Q),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(W_.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ey(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(Ey(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},lx=class extends I_{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new L_),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(N_(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ey(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},ux=class extends I_{constructor(){super(),this.linkProviders=[],this._register(N_(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function dx(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function fx(e,t,n,r,i,a,o,s,c){if(!a)return;let l=dx(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var px=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return fx(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=dx(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};px=yg([bg(0,c_),bg(1,a_)],px);var mx=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},hx={};vg(hx,{getSafariVersion:()=>Sx,isChromeOS:()=>Ox,isFirefox:()=>yx,isIpad:()=>wx,isIphone:()=>Tx,isLegacyEdge:()=>bx,isLinux:()=>Dx,isMac:()=>Cx,isNode:()=>gx,isSafari:()=>xx,isWindows:()=>Ex});var gx=typeof process<`u`&&`title`in process,_x=gx?`node`:navigator.userAgent,vx=gx?`node`:navigator.platform,yx=_x.includes(`Firefox`),bx=_x.includes(`Edge`),xx=/^((?!chrome|android).)*safari/i.test(_x);function Sx(){if(!xx)return 0;let e=_x.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Cx=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(vx),wx=vx===`iPad`,Tx=vx===`iPhone`,Ex=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(vx),Dx=vx.indexOf(`Linux`)>=0,Ox=/\bCrOS\b/.test(_x),kx=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},Ax=class extends kx{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},jx=class extends kx{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Mx=!gx&&`requestIdleCallback`in window?jx:Ax,Nx=class{constructor(){this._queue=new Mx}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Px=class extends I_{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new L_),this._pausedResizeTask=new Nx,this._observerDisposable=this._register(new L_),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 Q),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Q),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Q),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new mx((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Fx(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(N_(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=N_(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Px=yg([bg(2,$g),bg(3,a_),bg(4,Yg),bg(5,n_),bg(6,qg),bg(7,o_),bg(8,d_)],Px);var Fx=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Ix(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return zx(i,a,e,t,n,r)+Bx(a,t,n,r)+Vx(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,Jx(Math.abs(i-e),qx(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return Jx(Rx(a>t?e:i,n)+(s-1)*n.cols+1+Lx(a>t?i:e,n),qx(o,r))}function Lx(e,t){return e-1}function Rx(e,t){return t.cols-e}function zx(e,t,n,r,i,a){return Bx(t,r,i,a).length===0?``:Jx(Kx(e,t,e,t-Ux(t,i),!1,i).length,qx(`D`,a))}function Bx(e,t,n,r){let i=e-Ux(e,n),a=t-Ux(t,n);return Jx(Math.abs(i-a)-Hx(e,t,n),qx(Gx(e,t),r))}function Vx(e,t,n,r,i,a){let o;o=Bx(t,r,i,a).length>0?r-Ux(r,i):t;let s=r,c=Wx(e,t,n,r,i,a);return Jx(Kx(e,o,n,s,c===`C`,i).length,qx(c,a))}function Hx(e,t,n){let r=0,i=e-Ux(e,n),a=t-Ux(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Gx(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function Ux(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Wx(e,t,n,r,i,a){let o;return o=Bx(n,r,i,a).length>0?r-Ux(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Gx(e,t){return e>t?`A`:`B`}function Kx(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function qx(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function Jx(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var Yx=class{constructor(e){this._bufferService=e,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.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()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Xx(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Zx=50,Qx=15,$x=50,eS=500,tS=RegExp(`\xA0`,`g`),nS=class extends I_{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Bg,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Q),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Q),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new Yx(this._bufferService),this._activeSelectionMode=0,this._register(N_(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(tS,` `)).join(Ex?`\r
|
|
323
|
+
`))}},Q_=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},$_=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},ev=0,tv=class{constructor(e){this.value=e,this.id=ev++}},nv=2,Q=class{constructor(e){this._size=0,this._options=e,this._leakageMon=J_>0||this._options?.leakWarningThreshold?new X_(e?.onListenerError??h_,this._options?.leakWarningThreshold??J_):void 0,this._perfMon=this._options?._profName?new q_(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new $_(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||h_)(n),L_.None}if(this._disposed)return L_.None;t&&(e=e.bind(t));let r=new tv(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Z_.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof tv?(this._deliveryQueue??=new rv,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=P_(()=>{i?.(),this._removeListener(r)});return n instanceof I_?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*nv<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||h_;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof tv)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},rv=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},iv=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Q,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Q,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};iv.INSTANCE=new iv;var av=iv;function ov(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}av.INSTANCE.onDidChangeZoomLevel;function sv(e){return av.INSTANCE.getZoomFactor(e)}av.INSTANCE.onDidChangeFullscreen;var cv=typeof navigator==`object`?navigator.userAgent:``,lv=cv.indexOf(`Firefox`)>=0,uv=cv.indexOf(`AppleWebKit`)>=0,dv=cv.indexOf(`Chrome`)>=0,fv=!dv&&cv.indexOf(`Safari`)>=0;cv.indexOf(`Electron/`),cv.indexOf(`Android`);var pv=!1;if(typeof z_.matchMedia==`function`){let e=z_.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=z_.matchMedia(`(display-mode: fullscreen)`);pv=e.matches,ov(z_,e,({matches:e})=>{pv&&t.matches||(pv=e)})}function mv(){return pv}var hv=`en`,gv=!1,_v=!1,vv=!1,yv=!1,bv=!1,xv=hv,Sv,Cv=globalThis,wv;typeof Cv.vscode<`u`&&typeof Cv.vscode.process<`u`?wv=Cv.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(wv=process);var Tv=typeof wv?.versions?.electron==`string`&&wv?.type===`renderer`;if(typeof wv==`object`){gv=wv.platform===`win32`,_v=wv.platform===`darwin`,vv=wv.platform===`linux`,vv&&wv.env.SNAP&&wv.env.SNAP_REVISION,wv.env.CI||wv.env.BUILD_ARTIFACTSTAGINGDIRECTORY,xv=hv;let e=wv.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,xv=t.resolvedLanguage||hv,t.languagePack?.translationsConfigFile}catch{}yv=!0}else typeof navigator==`object`&&!Tv?(Sv=navigator.userAgent,gv=Sv.indexOf(`Windows`)>=0,_v=Sv.indexOf(`Macintosh`)>=0,(Sv.indexOf(`Macintosh`)>=0||Sv.indexOf(`iPad`)>=0||Sv.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,vv=Sv.indexOf(`Linux`)>=0,Sv?.indexOf(`Mobi`),bv=!0,xv=globalThis._VSCODE_NLS_LANGUAGE||hv,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var Ev=gv,Dv=_v,Ov=vv,kv=yv;bv&&typeof Cv.importScripts==`function`&&Cv.origin;var Av=Sv,jv=xv,Mv;(e=>{function t(){return jv}e.value=t;function n(){return jv.length===2?jv===`en`:jv.length>=3&&jv[0]===`e`&&jv[1]===`n`&&jv[2]===`-`}e.isDefaultVariant=n;function r(){return jv===`en`}e.isDefault=r})(Mv||={});var Nv=typeof Cv.postMessage==`function`&&!Cv.importScripts;(()=>{if(Nv){let e=[];Cv.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),Cv.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var Pv=!!(Av&&Av.indexOf(`Chrome`)>=0);Av&&Av.indexOf(`Firefox`),!Pv&&Av&&Av.indexOf(`Safari`),Av&&Av.indexOf(`Edg/`),Av&&Av.indexOf(`Android`);var Fv=typeof navigator==`object`?navigator:{};kv||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Fv&&Fv.clipboard&&Fv.clipboard.writeText,kv||Fv&&Fv.clipboard&&Fv.clipboard.readText,kv||mv()||Fv.keyboard,`ontouchstart`in z_||Fv.maxTouchPoints,z_.PointerEvent&&(`ontouchstart`in z_||navigator.maxTouchPoints);var Iv=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Lv=new Iv,Rv=new Iv,zv=new Iv,Bv=Array(230),Vv;(e=>{function t(e){return Lv.keyCodeToStr(e)}e.toString=t;function n(e){return Lv.strToKeyCode(e)}e.fromString=n;function r(e){return Rv.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return zv.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Rv.strToKeyCode(e)||zv.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Lv.keyCodeToStr(e)}e.toElectronAccelerator=o})(Vv||={});var Hv=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Uv([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Uv=class{constructor(e){if(e.length===0)throw y_(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Wv(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Vv.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(lv)switch(t){case 59:return 85;case 60:if(Ov)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Dv)return 57}else if(uv&&(Dv&&t===93||!Dv&&t===92))return 57;return Bv[t]||0}var Gv=Dv?256:2048,Kv=512,qv=1024,Jv=Dv?2048:256,Yv=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=Wv(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Gv),this.altKey&&(t|=Kv),this.shiftKey&&(t|=qv),this.metaKey&&(t|=Jv),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new Hv(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Xv=new WeakMap;function Zv(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var Qv=class{static getSameOriginWindowChain(e){let t=Xv.get(e);if(!t){t=[],Xv.set(e,t);let n=e,r;do r=Zv(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},$v=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=Qv.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},ey=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(dv){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?lv&&!Dv?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=fv&&Ev?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?lv&&!Dv?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},ty=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),ny;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof ry?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:G_.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ty})})(ny||={});var ry=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?ty:(this._emitter||=new Q,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},iy=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new x_(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new x_(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},ay=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new x_(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=P_(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var oy;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(oy||={});var sy=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Q,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await G_.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};sy.EMPTY=sy.fromArray([]);function cy(e){return ly(e,0)}function ly(e,t){switch(typeof e){case`object`:return e===null?uy(349,t):Array.isArray(e)?py(e,t):my(e,t);case`string`:return fy(e,t);case`boolean`:return dy(e,t);case`number`:return uy(e,t);case`undefined`:return uy(937,t);default:return uy(617,t)}}function uy(e,t){return(t<<5)-t+e|0}function dy(e,t){return uy(e?433:863,t)}function fy(e,t){t=uy(149417,t);for(let n=0,r=e.length;n<r;n++)t=uy(e.charCodeAt(n),t);return t}function py(e,t){return t=uy(104579,t),e.reduce((e,t)=>ly(t,e),t)}function my(e,t){return t=uy(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=fy(n,t),ly(e[n],t)),t)}var{registerWindow:hy,getWindow:gy,getDocument:_y,getWindows:vy,getWindowsCount:yy,getWindowId:by,getWindowById:xy,hasWindow:Sy,onDidRegisterWindow:Cy,onWillUnregisterWindow:wy,onDidUnregisterWindow:Ty}=function(){let e=new Map,t={window:z_,disposables:new I_};e.set(z_.vscodeWindowId,t);let n=new Q,r=new Q,i=new Q;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return L_.None;let a=new I_,o={window:t,disposables:a.add(new I_)};return e.set(t.vscodeWindowId,o),a.add(P_(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(Dy(t,Iy.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:z_},getDocument(e){return gy(e).document}}}(),Ey=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function Dy(e,t,n,r){return new Ey(e,t,n,r)}function Oy(e,t){return function(n){return t(new $v(e,n))}}function ky(e){return function(t){return e(new Yv(t))}}var Ay=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=Oy(gy(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=ky(n)),Dy(e,t,i,r)},jy,My=class extends ay{constructor(e){super(),this.defaultTarget=e&&gy(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Ny=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){h_(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Ny.sort),a.shift().execute();r.set(i,!1)};jy=(t,r,a=0)=>{let o=by(t),s=new Ny(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var Py=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};Py.None=new Py(0,0);function Fy(e){let t=e.getBoundingClientRect(),n=gy(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=cy(n),a=r.get(i);if(a)a.users+=1;else{let o=new Q,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(P_(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var Iy={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:uv?`webkitAnimationStart`:`animationstart`,ANIMATION_END:uv?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:uv?`webkitAnimationIteration`:`animationiteration`},Ly=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=Ry(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Ry(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Ry(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Ry(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Ry(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Ry(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Ry(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Ry(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Ry(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Ry(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Ry(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Ry(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Ry(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Ry(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Ry(e){return typeof e==`number`?`${e}px`:e}function zy(e){return new Ly(e)}var By=class{constructor(){this._hooks=new I_,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(P_(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=gy(e)}this._hooks.add(Dy(a,Iy.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(Dy(a,Iy.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Vy(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Hy;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Hy||={});var Uy=class e extends L_{constructor(){super(),this.dispatched=!1,this.targets=new H_,this.ignoreTargets=new H_,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(G_.runAndSubscribe(Cy,({window:e,disposables:t})=>{t.add(Dy(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(Dy(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(Dy(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:z_,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=j_(new e),P_(e.INSTANCE.targets.push(t))):L_.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=j_(new e),P_(e.INSTANCE.ignoreTargets.push(t))):L_.None}static isTouchDevice(){return`ontouchstart`in z_||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Hy.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-S_(s.rollingPageX))<30&&Math.abs(s.initialPageY-S_(s.rollingPageY))<30){let e=this.newGestureEvent(Hy.Tap,s.initialTarget);e.pageX=S_(s.rollingPageX),e.pageY=S_(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-S_(s.rollingPageX))<30&&Math.abs(s.initialPageY-S_(s.rollingPageY))<30){let e=this.newGestureEvent(Hy.Contextmenu,s.initialTarget);e.pageX=S_(s.rollingPageX),e.pageY=S_(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=S_(s.rollingPageX),n=S_(s.rollingPageY),i=S_(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Hy.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Hy.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Hy.Change||t.type===Hy.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=jy(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Hy.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Hy.Change,i.initialTarget);a.translationX=r.pageX-S_(i.rollingPageX),a.translationY=r.pageY-S_(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Uy.SCROLL_FRICTION=-.005,Uy.HOLD_DELAY=700,Uy.CLEAR_TAP_COUNT_TIME=400,bg([Vy],Uy,`isTouchDevice`,1);var Wy=Uy,Gy=class extends L_{onclick(e,t){this._register(Dy(e,Iy.CLICK,n=>t(new $v(gy(e),n))))}onmousedown(e,t){this._register(Dy(e,Iy.MOUSE_DOWN,n=>t(new $v(gy(e),n))))}onmouseover(e,t){this._register(Dy(e,Iy.MOUSE_OVER,n=>t(new $v(gy(e),n))))}onmouseleave(e,t){this._register(Dy(e,Iy.MOUSE_LEAVE,n=>t(new $v(gy(e),n))))}onkeydown(e,t){this._register(Dy(e,Iy.KEY_DOWN,e=>t(new Yv(e))))}onkeyup(e,t){this._register(Dy(e,Iy.KEY_UP,e=>t(new Yv(e))))}oninput(e,t){this._register(Dy(e,Iy.INPUT,t))}onblur(e,t){this._register(Dy(e,Iy.BLUR,t))}onfocus(e,t){this._register(Dy(e,Iy.FOCUS,t))}onchange(e,t){this._register(Dy(e,Iy.CHANGE,t))}ignoreGesture(e){return Wy.ignoreTarget(e)}},Ky=11,qy=class extends Gy{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Ky+`px`,this.domNode.style.height=Ky+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new By),this._register(Ay(this.bgDomNode,Iy.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(Ay(this.domNode,Iy.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new My),this._pointerdownScheduleRepeatTimer=this._register(new iy)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,gy(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Jy=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Yy=class extends L_{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Jy(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new $y(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=$y.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Xy=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Zy(e,t){let n=t-e;return function(t){return e+n*tb(t)}}function Qy(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var $y=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),Qy(Zy(e,r),Zy(i,t),.33)}return Zy(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Xy(this.scrollLeft(t),this.scrollTop(t),!1):new Xy(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function eb(e){return e**3}function tb(e){return 1-eb(1-e)}var nb=class extends L_{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new iy)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},rb=140,ib=class extends Gy{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new nb(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new By),this._shouldRender=!0,this.domNode=zy(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(Dy(this.domNode.domNode,Iy.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new qy(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=zy(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Dy(this.slider.domNode,Iy.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=Fy(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(Ev&&a>rb){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},ab=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},ob=class extends ib{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new ab(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},sb=class extends ib{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new ab(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},cb=500,lb=50,ub=!0,db=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},fb=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(dv){let t=sv(gy(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new db(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};fb.INSTANCE=new fb;var pb=fb,mb=class extends Gy{constructor(e,t,n){super(),this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Q),this.onWillScroll=this._onWillScroll.event,this._options=gb(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new sb(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new ob(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=zy(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=zy(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=zy(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new iy),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=M_(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Dv&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new ey(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=M_(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(Dy(this._listenOnDomNode,Iy.MOUSE_WHEEL,e=>{this._onMouseWheel(new ey(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=pb.INSTANCE;ub&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!Dv&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=lb*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=lb*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(ub&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),cb)}},hb=class extends mb{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function gb(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,Dv&&(t.className+=` mac`),t}var _b=class extends L_{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Yy({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>jy(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new hb(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(G_.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(P_(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(P_(()=>this._styleElement.remove())),this._register(G_.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
|
|
324
|
+
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};_b=bg([xg(2,Jg),xg(3,s_),xg(4,Yg),xg(5,f_),xg(6,e_),xg(7,l_)],_b);var vb=class extends L_{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(P_(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};vb=bg([xg(1,Jg),xg(2,s_),xg(3,r_),xg(4,l_)],vb);var yb=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},bb={full:0,left:0,center:0,right:0},xb={full:0,left:0,center:0,right:0},Sb={full:0,left:0,center:0,right:0},Cb=class extends L_{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new yb,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(P_(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);xb.full=this._canvas.width,xb.left=e,xb.center=t,xb.right=e,this._refreshDrawHeightConstants(),Sb.full=1,Sb.left=1,Sb.center=1+xb.left,Sb.right=1+xb.left+xb.center}_refreshDrawHeightConstants(){bb.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);bb.left=t,bb.center=t,bb.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*bb.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*bb.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*bb.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*bb.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Sb[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-bb[e.position||`full`]/2),xb[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+bb[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Cb=bg([xg(2,Jg),xg(3,r_),xg(4,l_),xg(5,e_),xg(6,f_),xg(7,s_)],Cb);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
325
|
+
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var wb;(e=>(e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``))(wb||={});var Tb;(e=>e.ST=`${$.ESC}\\`)(Tb||={});var Eb=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};Eb=bg([xg(2,Jg),xg(3,e_),xg(4,Xg),xg(5,l_)],Eb);var Db=0,Ob=0,kb=0,Ab=0,jb={css:`#00000000`,rgba:0},Mb;(e=>{function t(e,t,n,r){return r===void 0?`#${Lb(e)}${Lb(t)}${Lb(n)}`:`#${Lb(e)}${Lb(t)}${Lb(n)}${Lb(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(Mb||={});var Nb;(e=>{function t(e,t){if(Ab=(t.rgba&255)/255,Ab===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return Db=a+Math.round((n-a)*Ab),Ob=o+Math.round((r-o)*Ab),kb=s+Math.round((i-s)*Ab),{css:Mb.toCss(Db,Ob,kb),rgba:Mb.toRgba(Db,Ob,kb)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=Ib.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return Mb.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[Db,Ob,kb]=Ib.toChannels(t),{css:Mb.toCss(Db,Ob,kb),rgba:t}}e.opaque=i;function a(e,t){return Ab=Math.round(t*255),[Db,Ob,kb]=Ib.toChannels(e.rgba),{css:Mb.toCss(Db,Ob,kb,Ab),rgba:Mb.toRgba(Db,Ob,kb,Ab)}}e.opacity=a;function o(e,t){return Ab=e.rgba&255,a(e,Ab*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(Nb||={});var Pb;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return Db=parseInt(e.slice(1,2).repeat(2),16),Ob=parseInt(e.slice(2,3).repeat(2),16),kb=parseInt(e.slice(3,4).repeat(2),16),Mb.toColor(Db,Ob,kb);case 5:return Db=parseInt(e.slice(1,2).repeat(2),16),Ob=parseInt(e.slice(2,3).repeat(2),16),kb=parseInt(e.slice(3,4).repeat(2),16),Ab=parseInt(e.slice(4,5).repeat(2),16),Mb.toColor(Db,Ob,kb,Ab);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return Db=parseInt(r[1]),Ob=parseInt(r[2]),kb=parseInt(r[3]),Ab=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Mb.toColor(Db,Ob,kb,Ab);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[Db,Ob,kb,Ab]=t.getImageData(0,0,1,1).data,Ab!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:Mb.toRgba(Db,Ob,kb,Ab),css:e}}e.toColor=r})(Pb||={});var Fb;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(Fb||={});var Ib;(e=>{function t(e,t){if(Ab=(t&255)/255,Ab===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return Db=a+Math.round((n-a)*Ab),Ob=o+Math.round((r-o)*Ab),kb=s+Math.round((i-s)*Ab),Mb.toRgba(Db,Ob,kb)}e.blend=t;function n(e,t,n){let a=Fb.relativeLuminance(e>>8),o=Fb.relativeLuminance(t>>8);if(Rb(a,o)<n){if(o<a){let o=r(e,t,n),s=Rb(a,Fb.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>Rb(a,Fb.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=Rb(a,Fb.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>Rb(a,Fb.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Rb(Fb.relativeLuminance2(o,s,c),Fb.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=Rb(Fb.relativeLuminance2(o,s,c),Fb.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=Rb(Fb.relativeLuminance2(o,s,c),Fb.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=Rb(Fb.relativeLuminance2(o,s,c),Fb.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(Ib||={});function Lb(e){let t=e.toString(16);return t.length<2?`0`+t:t}function Rb(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var zb=class extends zg{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Bb=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Vg}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||Rg.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)Bb._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||Rg.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};Bb=bg([xg(0,Jg)],Bb);function Vb(e){return 57508<=e&&e<=57558}function Hb(e){return 9472<=e&&e<=9631}function Ub(e){return Vb(e)||Hb(e)}function Wb(){return{css:{canvas:Gb(),cell:Gb()},device:{canvas:Gb(),cell:Gb(),char:{width:0,height:0,left:0,top:0}}}}function Gb(){return{width:0,height:0}}var Kb=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Vg,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,j=k>=E,ee=k,M=this._workCell;if(f.length>0&&k===f[0][0]&&j){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)j&&=i===this._isCellInSelection(v,t);j&&=!n||a<r[0]||a>=r[1],j?(A=!0,M=new zb(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),ee=r[1]-1,m=M.getWidth()):E=r[1]}let te=this._isCellInSelection(k,t),N=n&&k===a,ne=O&&k>=l&&k<=u,re=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{re=!0});let ie=M.getChars()||Rg;if(ie===` `&&(M.isUnderline()||M.isOverline())&&(ie=`\xA0`),T=m*s-c.get(ie,M.isBold(),M.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(te&&w||!te&&!w&&M.bg===y)&&(te&&w&&p.selectionForeground||M.fg===b)&&M.extended.ext===x&&ne===S&&T===C&&!N&&!A&&!re&&j){M.isInvisible()?_+=Rg:_+=ie,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=M.bg,b=M.fg,x=M.extended.ext,S=ne,C=T,w=te,A&&a>=k&&a<=ee&&(a=k),!this._coreService.isCursorHidden&&N&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`)}}if(M.isBold()&&D.push(`xterm-bold`),M.isItalic()&&D.push(`xterm-italic`),M.isDim()&&D.push(`xterm-dim`),_=M.isInvisible()?Rg:M.getChars()||Rg,M.isUnderline()&&(D.push(`xterm-underline-${M.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!M.isUnderlineColorDefault())){if(M.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${zg.toColorRGB(M.getUnderlineColor()).join(`,`)})`;else{let e=M.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&M.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}M.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),M.isStrikethrough()&&D.push(`xterm-strikethrough`),ne&&(h.style.textDecoration=`underline`);let ae=M.getFgColor(),oe=M.getFgColorMode(),se=M.getBgColor(),ce=M.getBgColorMode(),le=!!M.isInverse();if(le){let e=ae;ae=se,se=e;let t=oe;oe=ce,ce=t}let ue,de,fe=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&fe||(e.backgroundColorRGB&&(ce=50331648,se=e.backgroundColorRGB.rgba>>8&16777215,ue=e.backgroundColorRGB),e.foregroundColorRGB&&(oe=50331648,ae=e.foregroundColorRGB.rgba>>8&16777215,de=e.foregroundColorRGB),fe=e.options.layer===`top`)}),!fe&&te&&(ue=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,se=ue.rgba>>8&16777215,ce=50331648,fe=!0,p.selectionForeground&&(oe=50331648,ae=p.selectionForeground.rgba>>8&16777215,de=p.selectionForeground)),fe&&D.push(`xterm-decoration-top`);let pe;switch(ce){case 16777216:case 33554432:pe=p.ansi[se],D.push(`xterm-bg-${se}`);break;case 50331648:pe=Mb.toColor(se>>16,se>>8&255,se&255),this._addStyle(h,`background-color:#${qb((se>>>0).toString(16),`0`,6)}`);break;default:le?(pe=p.foreground,D.push(`xterm-bg-257`)):pe=p.background}switch(ue||M.isDim()&&(ue=Nb.multiplyOpacity(pe,.5)),oe){case 16777216:case 33554432:M.isBold()&&ae<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ae+=8),this._applyMinimumContrast(h,pe,p.ansi[ae],M,ue,void 0)||D.push(`xterm-fg-${ae}`);break;case 50331648:let e=Mb.toColor(ae>>16&255,ae>>8&255,ae&255);this._applyMinimumContrast(h,pe,e,M,ue,de)||this._addStyle(h,`color:#${qb(ae.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,pe,p.foreground,M,ue,de)||le&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!N&&!A&&!re&&j?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=ee}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Ub(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=Nb.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Kb=bg([xg(1,d_),xg(2,e_),xg(3,s_),xg(4,Xg),xg(5,r_),xg(6,f_)],Kb);function qb(e,t,n){for(;e.length<n;)e=t+e;return e}var Jb=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.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`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.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(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},Yb=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Xb(){return new Yb}var Zb=`xterm-dom-renderer-owner-`,Qb=`xterm-rows`,$b=`xterm-fg-`,ex=`xterm-bg-`,tx=`xterm-focus`,nx=`xterm-selection`,rx=1,ix=class extends L_{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=rx++,this._rowElements=[],this._selectionRenderModel=Xb(),this.onRequestRedraw=this._register(new Q).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(Qb),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(nx),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=Wb(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Kb,document),this._element.classList.add(Zb+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(P_(()=>{this._element.classList.remove(Zb+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Jb(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Qb} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Qb} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Qb} .xterm-dim { color: ${Nb.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Qb}.${tx} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Qb}.${tx} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Qb}.${tx} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Qb} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Qb} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Qb} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Qb} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Qb} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${nx} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${nx} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${nx} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${$b}${n} { color: ${r.css}; }${this._terminalSelector} .${$b}${n}.xterm-dim { color: ${Nb.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${ex}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${$b}257 { color: ${Nb.opaque(e.background).css}; }${this._terminalSelector} .${$b}257.xterm-dim { color: ${Nb.multiplyOpacity(Nb.opaque(e.background),.5).css}; }${this._terminalSelector} .${ex}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(tx),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(tx),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Zb}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};ix=bg([xg(7,Qg),xg(8,o_),xg(9,e_),xg(10,Jg),xg(11,Xg),xg(12,s_),xg(13,f_)],ix);var ax=class extends L_{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Q),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new cx(this._optionsService))}catch{this._measureStrategy=this._register(new sx(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};ax=bg([xg(2,e_)],ax);var ox=class extends L_{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},sx=class extends ox{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},cx=class extends ox{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},lx=class extends L_{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new ux(this._window)),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Q),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(G_.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Dy(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(Dy(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},ux=class extends L_{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new R_),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(P_(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Dy(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},dx=class extends L_{constructor(){super(),this.linkProviders=[],this._register(P_(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function fx(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function px(e,t,n,r,i,a,o,s,c){if(!a)return;let l=fx(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var mx=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return px(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=fx(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};mx=bg([xg(0,l_),xg(1,o_)],mx);var hx=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},gx={};yg(gx,{getSafariVersion:()=>Cx,isChromeOS:()=>kx,isFirefox:()=>bx,isIpad:()=>Tx,isIphone:()=>Ex,isLegacyEdge:()=>xx,isLinux:()=>Ox,isMac:()=>wx,isNode:()=>_x,isSafari:()=>Sx,isWindows:()=>Dx});var _x=typeof process<`u`&&`title`in process,vx=_x?`node`:navigator.userAgent,yx=_x?`node`:navigator.platform,bx=vx.includes(`Firefox`),xx=vx.includes(`Edge`),Sx=/^((?!chrome|android).)*safari/i.test(vx);function Cx(){if(!Sx)return 0;let e=vx.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var wx=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(yx),Tx=yx===`iPad`,Ex=yx===`iPhone`,Dx=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(yx),Ox=yx.indexOf(`Linux`)>=0,kx=/\bCrOS\b/.test(vx),Ax=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},jx=class extends Ax{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},Mx=class extends Ax{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Nx=!_x&&`requestIdleCallback`in window?Mx:jx,Px=class{constructor(){this._queue=new Nx}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},Fx=class extends L_{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new R_),this._pausedResizeTask=new Px,this._observerDisposable=this._register(new R_),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 Q),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Q),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Q),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new hx((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new Ix(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(P_(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=P_(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Fx=bg([xg(2,e_),xg(3,o_),xg(4,Xg),xg(5,r_),xg(6,Jg),xg(7,s_),xg(8,f_)],Fx);var Ix=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Lx(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return Bx(i,a,e,t,n,r)+Vx(a,t,n,r)+Hx(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,Yx(Math.abs(i-e),Jx(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return Yx(zx(a>t?e:i,n)+(s-1)*n.cols+1+Rx(a>t?i:e,n),Jx(o,r))}function Rx(e,t){return e-1}function zx(e,t){return t.cols-e}function Bx(e,t,n,r,i,a){return Vx(t,r,i,a).length===0?``:Yx(qx(e,t,e,t-Wx(t,i),!1,i).length,Jx(`D`,a))}function Vx(e,t,n,r){let i=e-Wx(e,n),a=t-Wx(t,n);return Yx(Math.abs(i-a)-Ux(e,t,n),Jx(Kx(e,t),r))}function Hx(e,t,n,r,i,a){let o;o=Vx(t,r,i,a).length>0?r-Wx(r,i):t;let s=r,c=Gx(e,t,n,r,i,a);return Yx(qx(e,o,n,s,c===`C`,i).length,Jx(c,a))}function Ux(e,t,n){let r=0,i=e-Wx(e,n),a=t-Wx(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Kx(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function Wx(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Gx(e,t,n,r,i,a){let o;return o=Vx(n,r,i,a).length>0?r-Wx(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Kx(e,t){return e>t?`A`:`B`}function qx(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Jx(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function Yx(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var Xx=class{constructor(e){this._bufferService=e,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.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()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Zx(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Qx=50,$x=15,eS=50,tS=500,nS=RegExp(`\xA0`,`g`),rS=class extends L_{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Vg,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Q),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Q),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new Xx(this._bufferService),this._activeSelectionMode=0,this._register(P_(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(nS,` `)).join(Dx?`\r
|
|
326
326
|
`:`
|
|
327
|
-
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Dx&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Xx(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=dx(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Zx),Zx),t/=Zx,t/Math.abs(t)+Math.round(t*(Qx-1)))}shouldForceSelection(e){return Cx?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),$x)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Cx&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<eS&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=Ix(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Xx(n,this._bufferService.cols)}};nS=yg([bg(3,qg),bg(4,Yg),bg(5,s_),bg(6,$g),bg(7,c_),bg(8,o_)],nS);var rS=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},iS=class{constructor(){this._color=new rS,this._css=new rS}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},aS=Object.freeze((()=>{let e=[Nb.toColor(`#2e3436`),Nb.toColor(`#cc0000`),Nb.toColor(`#4e9a06`),Nb.toColor(`#c4a000`),Nb.toColor(`#3465a4`),Nb.toColor(`#75507b`),Nb.toColor(`#06989a`),Nb.toColor(`#d3d7cf`),Nb.toColor(`#555753`),Nb.toColor(`#ef2929`),Nb.toColor(`#8ae234`),Nb.toColor(`#fce94f`),Nb.toColor(`#729fcf`),Nb.toColor(`#ad7fa8`),Nb.toColor(`#34e2e2`),Nb.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:jb.toCss(r,i,a),rgba:jb.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:jb.toCss(n,n,n),rgba:jb.toRgba(n,n,n)})}return e})()),oS=Nb.toColor(`#ffffff`),sS=Nb.toColor(`#000000`),cS=Nb.toColor(`#ffffff`),lS=sS,uS={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},dS=oS,fS=class extends I_{constructor(e){super(),this._optionsService=e,this._contrastCache=new iS,this._halfContrastCache=new iS,this._onChangeColors=this._register(new Q),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:oS,background:sS,cursor:cS,cursorAccent:lS,selectionForeground:void 0,selectionBackgroundTransparent:uS,selectionBackgroundOpaque:Mb.blend(sS,uS),selectionInactiveBackgroundTransparent:uS,selectionInactiveBackgroundOpaque:Mb.blend(sS,uS),scrollbarSliderBackground:Mb.opacity(oS,.2),scrollbarSliderHoverBackground:Mb.opacity(oS,.4),scrollbarSliderActiveBackground:Mb.opacity(oS,.5),overviewRulerBorder:oS,ansi:aS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=pS(e.foreground,oS),t.background=pS(e.background,sS),t.cursor=Mb.blend(t.background,pS(e.cursor,cS)),t.cursorAccent=Mb.blend(t.background,pS(e.cursorAccent,lS)),t.selectionBackgroundTransparent=pS(e.selectionBackground,uS),t.selectionBackgroundOpaque=Mb.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=pS(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Mb.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?pS(e.selectionForeground,Ab):void 0,t.selectionForeground===Ab&&(t.selectionForeground=void 0),Mb.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Mb.opacity(t.selectionBackgroundTransparent,.3)),Mb.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Mb.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=pS(e.scrollbarSliderBackground,Mb.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=pS(e.scrollbarSliderHoverBackground,Mb.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=pS(e.scrollbarSliderActiveBackground,Mb.opacity(t.foreground,.5)),t.overviewRulerBorder=pS(e.overviewRulerBorder,dS),t.ansi=aS.slice(),t.ansi[0]=pS(e.black,aS[0]),t.ansi[1]=pS(e.red,aS[1]),t.ansi[2]=pS(e.green,aS[2]),t.ansi[3]=pS(e.yellow,aS[3]),t.ansi[4]=pS(e.blue,aS[4]),t.ansi[5]=pS(e.magenta,aS[5]),t.ansi[6]=pS(e.cyan,aS[6]),t.ansi[7]=pS(e.white,aS[7]),t.ansi[8]=pS(e.brightBlack,aS[8]),t.ansi[9]=pS(e.brightRed,aS[9]),t.ansi[10]=pS(e.brightGreen,aS[10]),t.ansi[11]=pS(e.brightYellow,aS[11]),t.ansi[12]=pS(e.brightBlue,aS[12]),t.ansi[13]=pS(e.brightMagenta,aS[13]),t.ansi[14]=pS(e.brightCyan,aS[14]),t.ansi[15]=pS(e.brightWhite,aS[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=pS(e.extendedAnsi[r],aS[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};fS=yg([bg(0,$g)],fS);function pS(e,t){if(e!==void 0)try{return Nb.toColor(e)}catch{}return t}var mS=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},hS=class{constructor(){this._services=new mS,this._services.set(Zg,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Wg(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},gS={trace:0,debug:1,info:2,warn:3,error:4,off:5},_S=`xterm.js: `,vS=class extends I_{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),yS=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=gS[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:_S)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};vS=yg([bg(0,$g)],vS);var yS,bS=class extends I_{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Q),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Q),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Q),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},xS=3,SS=Object.freeze(new Rg),CS=0,wS=2,TS=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*xS);let r=t||Bg.fromCharData([0,Ig,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*xS+0],n=t&2097151;return[this._data[e*xS+1],t&2097152?this._combined[e]:n?Mg(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*xS+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*xS+0]=e|2097152|t[2]<<22):this._data[e*xS+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*xS+0]>>22}hasWidth(e){return this._data[e*xS+0]&12582912}getFg(e){return this._data[e*xS+1]}getBg(e){return this._data[e*xS+2]}hasContent(e){return this._data[e*xS+0]&4194303}getCodePoint(e){let t=this._data[e*xS+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*xS+0]&2097152}getString(e){let t=this._data[e*xS+0];return t&2097152?this._combined[e]:t&2097151?Mg(t&2097151):``}isProtected(e){return this._data[e*xS+2]&536870912}loadCell(e,t){return CS=e*xS,t.content=this._data[CS+0],t.fg=this._data[CS+1],t.bg=this._data[CS+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*xS+0]=t.content,this._data[e*xS+1]=t.fg,this._data[e*xS+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*xS+0]=t|n<<22,this._data[e*xS+1]=r.fg,this._data[e*xS+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*xS+0];r&2097152?this._combined[e]+=Mg(t):r&2097151?(this._combined[e]=Mg(r&2097151)+Mg(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*xS+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Bg;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Bg;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*wS<this._data.buffer.byteLength;let n=e*xS;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*wS<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*wS<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*xS+0]&4194303)return e+(this._data[e*xS+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*xS+0]&4194303||this._data[e*xS+2]&50331648)return e+(this._data[e*xS+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<xS;e++)this._data[(n+i)*xS+e]=a[(t+i)*xS+e];a[(t+i)*xS+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<xS;e++)this._data[(n+i)*xS+e]=a[(t+i)*xS+e];a[(t+i)*xS+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*xS+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Mg(n):Lg;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function ES(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=AS(u,d,t),p=1,m=0;for(;p<u.length;){let e=AS(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function DS(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function OS(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function kS(e,t,n){let r=[],i=e.map((n,r)=>AS(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=AS(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function AS(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var jS=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Q),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),j_(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};jS._nextId=1;var MS=jS,NS={},PS=NS.B;NS[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:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},NS.A={"#":`£`},NS.B=void 0,NS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},NS.C=NS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},NS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},NS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},NS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},NS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},NS.E=NS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},NS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},NS.H=NS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},NS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var FS=4294967295,IS=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=SS.clone(),this.savedCharset=PS,this.markers=[],this._nullCell=Bg.fromCharData([0,Ig,1,0]),this._whitespaceCell=Bg.fromCharData([0,Lg,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Mx,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new bS(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new zg),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new zg),this._whitespaceCell}getBlankLine(e,t){return new TS(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>FS?FS:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=SS);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new bS(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(SS),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new TS(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new TS(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=ES(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(SS),n);if(r.length>0){let n=DS(this.lines,r);OS(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(SS),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new TS(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(SS),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=kS(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(SS,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=AS(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new MS(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},LS=class extends I_{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Q),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 IS(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new IS(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},RS=2,zS=1,BS=class extends I_{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,RS),this.rows=Math.max(e.rawOptions.rows||0,zS),this.buffers=this._register(new LS(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};BS=yg([bg(0,$g)],BS);var VS={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Cx,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},HS=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],US=class extends I_{constructor(e){super(),this._onOptionChange=this._register(new Q),this.onOptionChange=this._onOptionChange.event;let t={...VS};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(N_(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in VS))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in VS))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=VS[e],!WS(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=VS[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=HS.includes(t)?t:VS[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function WS(e){return e===`block`||e===`underline`||e===`bar`}function GS(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&GS(e[r],t-1);return n}var KS=Object.freeze({insertMode:!1}),qS=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),JS=class extends I_{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Q),this.onData=this._onData.event,this._onUserInput=this._register(new Q),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Q),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=GS(KS),this.decPrivateModes=GS(qS)}reset(){this.modes=GS(KS),this.decPrivateModes=GS(qS)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};JS=yg([bg(0,qg),bg(1,Qg),bg(2,$g)],JS);var YS={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function XS(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var ZS=String.fromCharCode,QS={DEFAULT:e=>{let t=[XS(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${ZS(t[0])}${ZS(t[1])}${ZS(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${XS(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${XS(e,!0)};${e.x};${e.y}${t}`}},$S=class extends I_{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Q),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(YS))this.addProtocol(e,YS[e]);for(let e of Object.keys(QS))this.addEncoding(e,QS[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};$S=yg([bg(0,qg),bg(1,Yg),bg(2,$g)],$S);var eC=[[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]],tC=[[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]],nC;function rC(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var iC=class{constructor(){if(this.version=`6`,!nC){nC=new Uint8Array(65536),nC.fill(1),nC[0]=0,nC.fill(0,1,32),nC.fill(0,127,160),nC.fill(2,4352,4448),nC[9001]=2,nC[9002]=2,nC.fill(2,11904,42192),nC[12351]=1,nC.fill(2,44032,55204),nC.fill(2,63744,64256),nC.fill(2,65040,65050),nC.fill(2,65072,65136),nC.fill(2,65280,65377),nC.fill(2,65504,65511);for(let e=0;e<eC.length;++e)nC.fill(0,eC[e][0],eC[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?nC[e]:rC(e,tC)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=aC.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return aC.createPropertyValue(0,n,r)}},aC=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Q,this.onChange=this._onChange.event;let e=new iC;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},oC=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function sC(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var cC=2147483647,lC=256,uC=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>lC)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>cC?cC:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>cC?cC:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,cC):e}},dC=[],fC=class{constructor(){this._state=0,this._active=dC,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=dC}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=dC,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||dC,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,Ng(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=dC,this._id=-1,this._state=0}}},pC=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Ng(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},mC=[],hC=class{constructor(){this._handlers=Object.create(null),this._active=mC,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=mC}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=mC,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||mC,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,Ng(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=mC,this._ident=0}},gC=new uC;gC.addParam(0);var _C=class{constructor(e){this._handler=e,this._data=``,this._params=gC,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():gC,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Ng(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=gC,this._data=``,this._hitLimit=!1,e));return this._params=gC,this._data=``,this._hitLimit=!1,t}},vC=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},yC=160,bC=function(){let e=new vC(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(yC,0,2,0),e.add(yC,8,5,8),e.add(yC,6,0,6),e.add(yC,11,0,11),e.add(yC,13,13,13),e}(),xC=class extends I_{constructor(e=bC){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new uC,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(N_(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new fC),this._dcsParser=this._register(new hC),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:yC)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<yC||++i>=t||(r=e[i])<32||r>126&&r<yC||++i>=t||(r=e[i])<32||r>126&&r<yC||++i>=t||(r=e[i])<32||r>126&&r<yC){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<yC){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<yC){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},SC=/^([\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})$/,CC=/^[\da-f]+$/;function wC(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=SC.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),CC.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function TC(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function EC(e,t=16){let[n,r,i]=e;return`rgb:${TC(n,t)}/${TC(r,t)}/${TC(i,t)}`}var DC={"(":0,")":1,"*":2,"+":3,"-":1,".":2},OC=131072,kC=10;function AC(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var jC=5e3,MC=0,NC=class extends I_{constructor(e,t,n,r,i,a,o,s,c=new xC){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Pg,this._utf8Decoder=new Fg,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=SS.clone(),this._eraseAttrDataInternal=SS.clone(),this._onRequestBell=this._register(new Q),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Q),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Q),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Q),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Q),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Q),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Q),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Q),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Q),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 PC(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Cb.IND,()=>this.index()),this._parser.setExecuteHandler(Cb.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Cb.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new pC(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new pC(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new pC(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new pC(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new pC(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new pC(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new pC(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new pC(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new pC(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new pC(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new pC(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new pC(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in NS)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new _C((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),jC))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${jC} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>OC&&(a=this._parseStack.position+OC)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<OC&&(this._parseBuffer=new Uint32Array(Math.min(e.length,OC))),o||this._dirtyRowTracker.clearRange(),e.length>OC)for(let t=a;t<e.length;t+=OC){let a=t+OC<e.length?t+OC:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=aC.extractWidth(t);let n=aC.extractShouldJoin(t),m=n?aC.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Mg(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof TS&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!AC(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new _C(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new pC(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(SS));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=aC.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,PS),this._charsetService.setgCharset(1,PS),this._charsetService.setgCharset(2,PS),this._charsetService.setgCharset(3,PS);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Rg.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=SS.fg,e.bg=SS.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=SS.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=SS.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=SS.fg&16777215,r.bg&=-67108864,r.bg|=SS.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=SS.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!AC(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>kC&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>kC&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(FC(n)){if(r===`?`)t.push({type:0,index:n});else{let e=wC(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=wC(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);FC(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,PS),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(DC[e[0]],NS[e[1]]||PS),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),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._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=SS.clone(),this._eraseAttrDataInternal=SS.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Bg;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},PC=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(MC=e,e=t,t=MC),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};PC=yg([bg(0,qg)],PC);function FC(e){return 0<=e&&e<256}var IC=5e7,LC=12,RC=50,zC=class extends I_{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>IC)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=LC?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=LC)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>RC&&(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()}},BC=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};BC=yg([bg(0,qg)],BC);var VC=!1,HC=class extends I_{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new L_),this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onData=this._register(new Q),this.onData=this._onData.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Q),this._instantiationService=new hS,this.optionsService=this._register(new US(e)),this._instantiationService.setService($g,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(BS)),this._instantiationService.setService(qg,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(vS)),this._instantiationService.setService(Qg,this._logService),this.coreService=this._register(this._instantiationService.createInstance(JS)),this._instantiationService.setService(Yg,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance($S)),this._instantiationService.setService(Jg,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(aC)),this._instantiationService.setService(t_,this.unicodeService),this._charsetService=this._instantiationService.createInstance(oC),this._instantiationService.setService(Xg,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(BC),this._instantiationService.setService(e_,this._oscLinkService),this._inputHandler=this._register(new NC(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(W_.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(W_.forward(this._bufferService.onResize,this._onResize)),this._register(W_.forward(this.coreService.onData,this._onData)),this._register(W_.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new zC((e,t)=>this._inputHandler.parse(e,t))),this._register(W_.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Q),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!VC&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),VC=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,RS),t=Math.max(t,zS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(sC.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(sC(this._bufferService),!1))),this._windowsWrappingHeuristics.value=N_(()=>{for(let t of e)t.dispose()})}}},UC={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function WC(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=UC[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var GC=0,KC=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Mx,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Mx,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(GC=this._search(t),GC===-1)||this._getKey(this._array[GC])!==t)return!1;do if(this._array[GC]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(GC),!0;while(++GC<this._array.length&&this._getKey(this._array[GC])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(GC=this._search(e),!(GC<0||GC>=this._array.length)&&this._getKey(this._array[GC])===e))do yield this._array[GC];while(++GC<this._array.length&&this._getKey(this._array[GC])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(GC=this._search(e),!(GC<0||GC>=this._array.length)&&this._getKey(this._array[GC])===e))do t(this._array[GC]);while(++GC<this._array.length&&this._getKey(this._array[GC])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},qC=0,JC=0,YC=class extends I_{constructor(){super(),this._decorations=new KC(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Q),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Q),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(N_(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new XC(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{qC=t.options.x??0,JC=qC+(t.options.width??1),e>=qC&&e<JC&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},XC=class extends F_{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Q),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Q),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?Nb.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?Nb.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},ZC=1e3,QC=class{constructor(e,t=ZC){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},$C=20,ew=class extends I_{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new QC(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
328
|
-
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(
|
|
329
|
-
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===$C+1&&(this._liveRegion.textContent+=wg.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};ew=yg([bg(1,Zg),bg(2,o_),bg(3,c_)],ew);var tw=class extends I_{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Q),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Q),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(N_(()=>{j_(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ey(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ey(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Ey(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Ey(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&nw(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,j_(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};tw=yg([bg(1,s_),bg(2,c_),bg(3,qg),bg(4,f_)],tw);function nw(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var rw=class extends HC{constructor(e={}){super(e),this._linkifier=this._register(new L_),this.browser=hx,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new L_),this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Q),this.onKey=this._onKey.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Q),this.onBell=this._onBell.event,this._onFocus=this._register(new Q),this._onBlur=this._register(new Q),this._onA11yCharEmitter=this._register(new Q),this._onA11yTabEmitter=this._register(new Q),this._onWillOpen=this._register(new Q),this._setup(),this._decorationService=this._instantiationService.createInstance(YC),this._instantiationService.setService(n_,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(ux),this._instantiationService.setService(f_,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(r_)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(W_.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(W_.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(W_.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(W_.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(N_(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=Mb.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${EC(r)}${wb.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=jb.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=jb.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(ew,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(Ey(this.element,`copy`,e=>{this.hasSelection()&&Dg(e,this._selectionService)}));let e=e=>Og(e,this.textarea,this.coreService,this.optionsService);this._register(Ey(this.textarea,`paste`,e)),this._register(Ey(this.element,`paste`,e)),yx?this._register(Ey(this.element,`mousedown`,e=>{e.button===2&&jg(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ey(this.element,`contextmenu`,e=>{jg(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Dx&&this._register(Ey(this.element,`auxclick`,e=>{e.button===1&&Ag(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ey(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Ey(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Ey(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Ey(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Ey(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Ey(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Ey(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(Ey(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,Sg.get()),Ox||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(cx,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(o_,this._coreBrowserService),this._register(Ey(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Ey(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ix,this._document,this._helperContainer),this._instantiationService.setService(a_,this._charSizeService),this._themeService=this._instantiationService.createInstance(fS),this._instantiationService.setService(d_,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(zb),this._instantiationService.setService(u_,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Px,this.rows,this.screenElement)),this._instantiationService.setService(c_,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(Tb,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(px),this._instantiationService.setService(s_,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(tw,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(gb,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(nS,this.element,this.screenElement,r)),this._instantiationService.setService(l_,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(W_.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(_b,this.screenElement)),this._register(Ey(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),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(ew,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Sb,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Sb,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(rx,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),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()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ey(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(Ey(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){kg(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=WC(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(iw(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(SS));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function iw(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var aw=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},ow=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Bg)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},sw=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new ow(t)}getNullCell(){return new Bg}},cw=class extends I_{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Q),this.onBufferChange=this._onBufferChange.event,this._normal=new sw(this._core.buffers.normal,`normal`),this._alternate=new sw(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 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)}},lw=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},uw=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},dw=[`cols`,`rows`],fw=0,pw=class extends I_{constructor(e){super(),this._core=this._register(new rw(e)),this._addonManager=this._register(new aw),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(dw.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw 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||=new lw(this._core),this._parser}get unicode(){return this._checkProposedApi(),new uw(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._register(new cw(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
330
|
-
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Sg.get()},set promptLabel(e){Sg.set(e)},get tooMuchOutput(){return wg.get()},set tooMuchOutput(e){wg.set(e)}}}_verifyIntegers(...e){for(fw of e)if(fw===1/0||isNaN(fw)||fw%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(fw of e)if(fw&&(fw===1/0||isNaN(fw)||fw%1!=0||fw<0))throw Error(`This API only accepts positive integers`)}},mw=2,hw=1,gw=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(mw,Math.floor(u/e.css.cell.width)),rows:Math.max(hw,Math.floor(l/e.css.cell.height))}}},_w=`super-pi.terminal-owner.v1`,vw=`super-pi.terminal-selection.v1.`,yw=20,bw=5,xw=240,Sw=120,Cw={checking:`正在连接`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`,empty:`没有打开的终端`},ww;function Tw(){if(ww)return ww;try{let e=window.localStorage.getItem(_w);if(e&&/^[0-9a-f]{32}$/.test(e))return ww=e}catch{}ww=Array.from(window.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(_w,ww)}catch{}return ww}function Ew(e){try{return window.sessionStorage.getItem(e)??void 0}catch{return}}function Dw({workspaceId:e,workspaceLabel:t,cwd:n=``,connected:r,sendCommand:i,registerSink:a,conversationId:o,terminalShell:s}){let c=vw+JSON.stringify([e,o]),[l,d]=(0,u.useState)([]),[f,p]=(0,u.useState)(()=>Ew(c)??``),[m,h]=(0,u.useState)(!1),[g,_]=(0,u.useState)(),[v,y]=(0,u.useState)(``),[b,x]=(0,u.useState)(``),S=(0,u.useRef)(new Map),C=(0,u.useRef)(new Map),w=(0,u.useRef)(new Map),T=(0,u.useRef)(new Map),E=(0,u.useRef)(!1),D=(0,u.useRef)(f);D.current=f;let O=(0,u.useRef)(!1),k=(0,u.useRef)(void 0),A=(0,u.useCallback)(e=>{let t=C.current.get(e);if(!t||!t.host.clientWidth||!t.host.clientHeight||T.current.has(e))return;let{terminal:n,fitAddon:r}=t,a=r.proposeDimensions();if(!a||!Number.isFinite(a.cols)||!Number.isFinite(a.rows))return;let o=Math.max(yw,Math.min(xw,a.cols)),s=Math.max(bw,Math.min(Sw,a.rows));(n.cols!==o||n.rows!==s)&&n.resize(o,s);let c=S.current.get(e);E.current&&c&&c.exitCode===void 0&&(c.cols!==o||c.rows!==s)&&i({type:`terminal.resize`,sessionId:e,cols:o,rows:s})},[i]),j=(0,u.useCallback)((e,t)=>{let n=e.sessionId;if(e.type===`terminal.output`){t.write(e.data);return}let r=S.current.get(n),i=T.current.get(n);r&&t.resize(r.cols,r.rows),t.write(`\x1Bc\x1B[3J`+e.data,()=>{T.current.get(n)===i&&(T.current.delete(n),D.current===n&&A(n))})},[A]),ee=(0,u.useCallback)((e,t)=>{if(!t||C.current.has(e))return;let n=getComputedStyle(t),r=(e,t)=>n.getPropertyValue(e).trim()||t,a=S.current.get(e),o=new pw({cols:a?.cols,rows:a?.rows,cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:r(`--term-fg`,`#dbe4f0`),cursor:r(`--term-fg`,`#dbe4f0`),selectionBackground:r(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),s=new gw;o.loadAddon(s),o.open(t),o.onData(t=>{E.current&&!T.current.has(e)&&S.current.get(e)?.exitCode===void 0&&i({type:`terminal.input`,sessionId:e,data:t})}),C.current.set(e,{terminal:o,fitAddon:s,host:t});for(let t of w.current.get(e)??[])j(t,o);w.current.delete(e),requestAnimationFrame(()=>A(e))},[A,i,j]),M=(0,u.useCallback)(t=>{if(t.type===`terminal.sessions`){if(t.workspaceId!==e||t.conversationId!==o)return;let n=new Map(t.sessions.map(e=>[e.id,e]));for(let[e,r]of C.current)n.has(e)?!t.replay&&S.current.get(e)?.exitCode!==void 0&&n.get(e)?.exitCode===void 0&&r.terminal.write(`\x1Bc\x1B[3J`):(r.terminal.dispose(),C.current.delete(e));for(let e of w.current.keys())(!n.has(e)||t.replay)&&w.current.delete(e);if(t.replay){T.current.clear();for(let e of n.keys())T.current.set(e,Symbol())}!t.replay&&O.current&&t.activate&&n.has(t.activate)&&(k.current=t.activate,O.current=!1),S.current=n,E.current=!0,d(t.sessions),p(e=>t.activate??(n.has(e)?e:t.sessions[0]?.id??``)),_(void 0),h(!0)}else if(t.type===`terminal.output`||t.type===`terminal.replay`){if(!S.current.has(t.sessionId))return;let e=C.current.get(t.sessionId)?.terminal;if(e)j(t,e);else{let e=w.current.get(t.sessionId)??[];e.push(t),w.current.set(t.sessionId,e)}}else if(t.type===`terminal.size`){let e=S.current.get(t.sessionId);e&&(Object.assign(e,{cols:t.cols,rows:t.rows}),C.current.get(e.id)?.terminal.resize(e.cols,e.rows))}else if(t.type===`terminal.exit`){let e=S.current.get(t.sessionId);if(!e)return;let n={...e,exitCode:t.exitCode,reason:t.reason};S.current.set(n.id,n),d(e=>e.map(e=>e.id===n.id?n:e))}else(t.type===`terminal.error`||t.type===`terminal.status`&&!t.enabled)&&(O.current=!1,_(void 0),y(t.type===`terminal.error`?t.message:t.reason||`终端未启用`))},[o,e,j]);(0,u.useEffect)(()=>(a(M),()=>a(void 0)),[M,a]);let te=(0,u.useCallback)(()=>{E.current=!1,h(!1),_(void 0),y(``),r&&e&&i({type:`terminal.sync`,ownerId:Tw(),workspaceId:e,conversationId:o,cwd:n,initialize:Ew(c)===void 0})},[r,e,o,n,c,i]);(0,u.useEffect)(()=>(te(),()=>{r&&i({type:`terminal.detach`})}),[r,i,te]),(0,u.useEffect)(()=>()=>{for(let e of C.current.values())e.terminal.dispose();C.current.clear()},[]),(0,u.useEffect)(()=>{if(m)try{window.sessionStorage.setItem(c,f)}catch{}},[f,m,c]),(0,u.useEffect)(()=>{let e=!1;return Ne(`/api/terminal-shell`).then(e=>e.json()).then(t=>{let n=t.shell;!e&&n&&x(n.file+(n.args.length?` `+n.args.join(` `):``)+`(`+(t.source??``)+`)`)}).catch(()=>void 0),()=>{e=!0}},[s?.file,s?.args.join(`\0`)]),(0,u.useLayoutEffect)(()=>{let e=C.current.get(f);if(!e)return;let t=new ResizeObserver(()=>A(f));if(t.observe(e.host),A(f),k.current===f){let e=f;requestAnimationFrame(()=>{k.current===e&&(C.current.get(e)?.terminal.focus(),k.current=void 0)})}return()=>t.disconnect()},[f,A,l]);let N=e=>!r||!m||g?!1:i(e)?(y(``),_(e.type===`terminal.open`?`open`:`close`),!0):!1,ne=e=>{let t=C.current.get(f)?.terminal;O.current=!0,N({type:`terminal.open`,sessionId:e,cols:t?.cols,rows:t?.rows})||(O.current=!1)},re=l.find(e=>e.id===f),ie=r&&m&&!g,ae=e?r?m?g===`open`?`starting`:re?re.exitCode===void 0?`running`:`exited`:`empty`:v?`unavailable`:`checking`:`checking`:`unavailable`,oe=v||re?.reason;return(0,F.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":ae,children:[(0,F.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[l.map(e=>(0,F.jsxs)(`div`,{className:`terminal-tab${e.id===f?` is-active`:``}`,children:[(0,F.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===f,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>p(e.id),title:Cw[e.exitCode===void 0?`running`:`exited`],children:[(0,F.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.exitCode===void 0?`running`:`exited`}`,"aria-hidden":`true`}),e.title]}),(0,F.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,disabled:!ie,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>N({type:`terminal.close`,sessionId:e.id}),children:`×`})]},e.id)),l.length<5&&(0,F.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,disabled:!ie,"data-terminal-add":`1`,onClick:()=>ne(),title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,F.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,F.jsxs)(`span`,{className:`terminal-status terminal-status-${ae}`,"data-terminal-status":ae,children:[(0,F.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),Cw[ae]]}),(0,F.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[b&&(0,F.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-shell-hint":`1`,title:b,children:b}),t&&(0,F.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),re?.exitCode!==void 0&&(0,F.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,disabled:!ie,onClick:()=>ne(re.id),children:`重新打开`}),!m&&v&&r&&(0,F.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,onClick:te,children:`重试连接`})]})]}),oe&&(0,F.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,title:kr(oe),children:Or(oe,`终端出错了。`)}),re?.exitCode!==void 0&&re.exitCode!==0&&(0,F.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,re.exitCode,`。`]}),(0,F.jsxs)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:[l.map(e=>(0,F.jsx)(`div`,{ref:t=>ee(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===f?`block`:`none`}},e.id)),ae===`empty`&&(0,F.jsx)(`div`,{className:`terminal-surface-empty`,"data-terminal-empty":`1`,children:(0,F.jsx)(`p`,{className:`rail-empty`,children:Cw.empty})}),!re&&ae===`checking`&&(0,F.jsx)(`p`,{className:`rail-empty terminal-surface-message`,"data-terminal-phase":`checking`,children:`正在连接终端…`}),!e&&(0,F.jsx)(`p`,{className:`rail-empty terminal-surface-message`,children:`选择一个工作区后即可打开终端。`})]})]})}function Ow({id:e,title:t,icon:n,count:r,actions:i,children:a}){let o=(0,u.useId)();return(0,F.jsxs)(`section`,{className:`rail-card`,"data-rail-section":e,"aria-labelledby":o,children:[(0,F.jsxs)(`div`,{className:`rail-section-head`,children:[(0,F.jsxs)(`h2`,{className:`rail-section-title`,id:o,children:[(0,F.jsx)(kw,{kind:n}),t]}),r&&(0,F.jsx)(`span`,{className:`rail-section-count`,children:r}),i]}),(0,F.jsx)(`div`,{className:`rail-card-body`,children:a})]})}function kw({kind:e}){return(0,F.jsx)(`svg`,{className:`rail-section-icon`,viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:e===`tasks`?(0,F.jsx)(F.Fragment,{children:(0,F.jsx)(`path`,{d:`m3 6 2 2 3-4M11 6h10M3 13h5m3 0h10M3 20h5m3 0h10`})}):e===`clock`?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,F.jsx)(`path`,{d:`M12 7v5l3 2`})]}):(0,F.jsx)(F.Fragment,{children:(0,F.jsx)(`path`,{d:`M3 12h4l3-7 4 14 3-7h4`})})})}var Aw=[{day:1,label:`一`},{day:2,label:`二`},{day:3,label:`三`},{day:4,label:`四`},{day:5,label:`五`},{day:6,label:`六`},{day:0,label:`日`}];function jw(e){return e.kind===`interval`?`每隔 ${e.everyMinutes} 分钟`:e.kind===`daily`?`每天 ${e.time}`:e.kind===`weekly`?`每周${e.weekdays.map(e=>Aw.find(t=>t.day===e)?.label??`?`).join(`、`)} ${e.time}`:`仅一次:${Mw(e.at)}`}function Mw(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Nw(){return typeof Intl<`u`?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Pw(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())} ${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`year`)}-${i(`month`)}-${i(`day`)} ${i(`hour`)}:${i(`minute`)}`}function Fw(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-GB`,{timeZone:t,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`hour`)}:${i(`minute`)}`}function Iw(e,t){if(!e)return``;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).formatToParts(t).find(e=>e.type===`timeZoneName`)?.value??e}catch{return e}}function Lw(e,t,n){let r=Fw(e,n),i=Rw(e,t,n);return i===0?`今天 ${r}`:i===1?`明天 ${r}`:Pw(e,n)}function Rw(e,t,n){let r=e=>{let[t]=Pw(e,n).split(` `),[r,i,a]=t.split(`-`).map(Number);return Date.UTC(r,i-1,a)},i=Math.round((r(e)-r(t))/864e5);return Number.isFinite(i)?i:0}function zw(e,t,n){if(!e||!t||e===t)return``;let r=Iw(e,n),i=Iw(t,n);return Fw(n,e)===Fw(n,t)?`服务器在 ${r} 时区,你的时区也是 ${i},下面的时间按你的时区显示`:`服务器在 ${r} 时区,下面的时间按你的时区(${i})显示`}function Bw(e,t,n){return e.enabled?e.nextRunAt===void 0?{glyph:`✓`,word:`已结束`,detail:``}:{glyph:`●`,word:`启用中`,detail:`下次 ${Lw(e.nextRunAt,t,n)}`}:e.schedule.kind===`once`&&e.lastRunAt!==void 0?{glyph:`✓`,word:`已结束`,detail:e.lastRunAt?`上次 ${Pw(e.lastRunAt,n)}`:``}:{glyph:`○`,word:`已停用`,detail:``}}function Vw(e,t){if(e.lastRunAt===void 0)return``;let n=Pw(e.lastRunAt,t);return e.lastRunStatus===`failed`?`上次 ${n} · 失败${e.lastRunMessage?`:${e.lastRunMessage}`:``}`:`上次 ${n} · 成功`}function Hw({tasks:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,serverTimeZone:o}){let[s,c]=(0,u.useState)(()=>Date.now()),[l,d]=(0,u.useState)();(0,u.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let f=Nw(),p=zw(o,f,s),m=e=>{i({type:`scheduledTask.toggle`,id:e.id,enabled:!e.enabled})},h=e=>{i({type:`scheduledTask.trigger`,id:e.id}),a(`已触发「${e.name}」,结果会出现在它自己的会话里。`,`info`)},g=e=>{i({type:`scheduledTask.delete`,id:e.id}),a(`已删除定时任务「${e.name}」,它的会话和结果保留着。`,`info`)};return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(Ow,{id:`scheduled`,title:`定时任务`,icon:`clock`,count:(0,F.jsx)(`span`,{"data-sched-count":`1`,children:e.length?`${e.length} 个`:`0 个`}),actions:(0,F.jsx)(`button`,{type:`button`,className:`scheduled-add`,"data-sched-add":`1`,title:`新建定时任务`,onClick:()=>d(`new`),children:`+ 新建`}),children:[p&&(0,F.jsx)(`p`,{className:`scheduled-zone-note`,"data-sched-zone-note":`1`,children:p}),e.length>0?(0,F.jsx)(`ul`,{className:`scheduled-list`,"data-sched-list":`1`,children:e.map(e=>{let t=Bw(e,s,f),n=Vw(e,f);return(0,F.jsxs)(`li`,{className:`scheduled-item`,"data-scheduled-task":e.id,children:[(0,F.jsx)(`button`,{type:`button`,className:`scheduled-toggle`,"data-sched-toggle":`1`,title:e.enabled?`点击停用`:`点击启用`,"aria-label":e.enabled?`停用 ${e.name}`:`启用 ${e.name}`,onClick:()=>m(e),children:t.glyph}),(0,F.jsxs)(`div`,{className:`scheduled-main`,children:[(0,F.jsxs)(`div`,{className:`scheduled-name-row`,children:[(0,F.jsx)(`span`,{className:`scheduled-name`,children:e.name}),(0,F.jsx)(`span`,{className:`scheduled-status-word`,"data-sched-word":`1`,children:t.word}),e.createdBy===`agent`&&(0,F.jsx)(`span`,{className:`scheduled-by`,title:`这个定时任务是 agent 创建的,你可以像编辑自己建的一样编辑它`,children:`agent`})]}),(0,F.jsxs)(`div`,{className:`scheduled-meta`,"data-sched-meta":`1`,children:[jw(e.schedule),t.detail?` · ${t.detail}`:``]}),n&&(0,F.jsx)(`div`,{className:`scheduled-last`,"data-sched-last":`1`,children:n})]}),(0,F.jsxs)(`div`,{className:`scheduled-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-trigger":`1`,title:`立即执行一次(不改变周期)`,"aria-label":`立即执行 ${e.name}`,onClick:()=>h(e),children:`⚡`}),(0,F.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-edit":`1`,title:`编辑`,"aria-label":`编辑 ${e.name}`,onClick:()=>d(e),children:`✎`}),(0,F.jsx)(`button`,{type:`button`,className:`scheduled-action scheduled-action-danger`,"data-sched-delete":`1`,title:`删除(会话与结果保留)`,"aria-label":`删除 ${e.name}`,onClick:()=>g(e),children:`✕`})]})]},e.id)})}):(0,F.jsx)(`p`,{className:`rail-empty`,"data-sched-empty":`1`,children:`还没有定时任务。可以新建周期任务,或让 AI 安排。`})]}),l!==void 0&&(0,F.jsx)(Kw,{task:l===`new`?void 0:l,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:()=>d(void 0)},l===`new`?`new`:l.id)]})}function Uw(e){let t=e?.schedule;return{name:e?.name??``,prompt:e?.prompt??``,kind:t?.kind??`daily`,everyMinutes:t?.kind===`interval`?String(t.everyMinutes):`30`,time:t&&(t.kind===`daily`||t.kind===`weekly`)?t.time:`09:00`,weekdays:t?.kind===`weekly`?[...t.weekdays]:[1],onceAt:t?.kind===`once`?Ww(t.at):``,modelKey:e?.model?`${e.model.provider}/${e.model.modelId}`:``,agentId:e?.agentId??``}}function Ww(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Gw(e){if(e.kind===`interval`){let t=Number(e.everyMinutes);return!Number.isInteger(t)||t<1||t>10080?{ok:!1,reason:`间隔分钟数要是一个 1 到 10080 之间的整数。`}:{ok:!0,schedule:{kind:`interval`,everyMinutes:t}}}if(e.kind===`daily`||e.kind===`weekly`){let t=/^(\d{1,2}):(\d{2})$/.exec(e.time.trim()),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||n>23||r>59)return{ok:!1,reason:`触发时刻要写成 HH:MM,比如 09:00。`};let i=`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`;return e.kind===`daily`?{ok:!0,schedule:{kind:`daily`,time:i}}:e.weekdays.length?{ok:!0,schedule:{kind:`weekly`,weekdays:[...e.weekdays].sort((e,t)=>e-t),time:i}}:{ok:!1,reason:`每周任务至少要选一天。`}}if(!e.onceAt)return{ok:!1,reason:`选一下这一次的运行时刻。`};let t=new Date(e.onceAt).getTime();return Number.isNaN(t)?{ok:!1,reason:`这一次的运行时刻不是有效时间。`}:{ok:!0,schedule:{kind:`once`,at:t}}}function Kw({task:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:o}){let[s,c]=(0,u.useState)(()=>Uw(e)),[l,d]=(0,u.useState)();(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let f=e=>{c(t=>({...t,...e})),d(void 0)};return(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay`,"data-sched-dialog-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&o()},children:(0,F.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`scheduled-dialog-title`,"data-sched-dialog":`1`,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsx)(`h2`,{className:`tool-dialog-title`,id:`scheduled-dialog-title`,children:e?`编辑定时任务`:`新建定时任务`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-sched-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭定时任务编辑`,onClick:o,children:`✕`})]}),(0,F.jsxs)(`div`,{className:`tool-dialog-body scheduled-form`,children:[(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`名称`}),(0,F.jsx)(`input`,{className:`scheduled-input`,"data-sched-field":`name`,value:s.name,placeholder:`留空则取提示词首句`,onChange:e=>f({name:e.target.value})})]}),(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`提示词`}),(0,F.jsx)(`textarea`,{className:`scheduled-textarea`,"data-sched-field":`prompt`,rows:5,value:s.prompt,placeholder:`到点时这段话会作为用户消息发给 agent,所以它要是一条完整、自包含的指令`,onChange:e=>f({prompt:e.target.value})})]}),(0,F.jsxs)(`div`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`周期`}),(0,F.jsx)(`div`,{className:`scheduled-kind-row`,role:`radiogroup`,"aria-label":`周期类型`,children:[[`interval`,`每隔 N 分钟`],[`daily`,`每天`],[`weekly`,`每周`],[`once`,`仅一次`]].map(([e,t])=>(0,F.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":s.kind===e,className:`scheduled-kind${s.kind===e?` scheduled-kind-active`:``}`,"data-sched-kind":e,onClick:()=>f({kind:e}),children:t},e))})]}),s.kind===`interval`&&(0,F.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`间隔`}),(0,F.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`everyMinutes`,inputMode:`numeric`,value:s.everyMinutes,onChange:e=>f({everyMinutes:e.target.value})}),(0,F.jsx)(`span`,{className:`scheduled-hint`,children:`分钟(1 – 10080)`})]}),(s.kind===`daily`||s.kind===`weekly`)&&(0,F.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,F.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`time`,inputMode:`numeric`,placeholder:`09:00`,value:s.time,onChange:e=>f({time:e.target.value})}),(0,F.jsx)(`span`,{className:`scheduled-hint`,children:`服务器本地时间,每天/每周的这一天到点触发`})]}),s.kind===`weekly`&&(0,F.jsxs)(`div`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`星期`}),(0,F.jsx)(`div`,{className:`scheduled-weekdays`,children:Aw.map(({day:e,label:t})=>{let n=s.weekdays.includes(e);return(0,F.jsx)(`button`,{type:`button`,"aria-pressed":n,className:`scheduled-weekday${n?` scheduled-weekday-on`:``}`,"data-sched-weekday":e,onClick:()=>f({weekdays:n?s.weekdays.filter(t=>t!==e):[...s.weekdays,e]}),children:t},e)})})]}),s.kind===`once`&&(0,F.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,F.jsx)(`input`,{className:`scheduled-input`,type:`datetime-local`,"data-sched-field":`onceAt`,value:s.onceAt,onChange:e=>f({onceAt:e.target.value})}),(0,F.jsx)(`span`,{className:`scheduled-hint`,children:`这一次运行之后就结束`})]}),(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`模型`}),(0,F.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`model`,value:s.modelKey,onChange:e=>f({modelKey:e.target.value}),children:[(0,F.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(n?.models??[]).map(e=>(0,F.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,`(`,e.detail,`)`]},`${e.provider}/${e.modelId}`))]})]}),(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`Agent`}),(0,F.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`agent`,value:s.agentId,onChange:e=>f({agentId:e.target.value}),children:[(0,F.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(r?.agents??[]).map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name??e.id},e.id))]})]}),l&&(0,F.jsx)(`p`,{className:`scheduled-error`,"data-sched-error":`1`,role:`alert`,children:l}),(0,F.jsxs)(`div`,{className:`scheduled-actions-row`,children:[(0,F.jsx)(`button`,{type:`button`,className:`scheduled-cancel`,onClick:o,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`scheduled-save`,"data-sched-save":`1`,onClick:()=>{let r=s.prompt.trim();if(!r){d(`定时任务需要一段提示词:到点时这段话会被当作用户消息发给 agent。`);return}if(!t){d(`先选一个工作区,再建定时任务。`);return}let c=Gw(s);if(!c.ok){d(c.reason);return}let l=n?.models.find(e=>`${e.provider}/${e.modelId}`===s.modelKey),u=l?{provider:l.provider,modelId:l.modelId,label:l.label}:null,f=s.agentId||null,p=s.name.trim()||void 0;i(e?{type:`scheduledTask.update`,id:e.id,name:p,prompt:r,schedule:c.schedule,model:u,agentId:f}:{type:`scheduledTask.create`,name:p,prompt:r,schedule:c.schedule,workspaceId:t,model:u,agentId:f})?(a(e?`已保存对「${s.name.trim()||e.name}」的修改。`:`定时任务已创建,到点会自动运行。`,`info`),o()):d(`连接已断开,没能保存。等重连后再试一次。`)},children:e?`保存修改`:`创建任务`})]})]})]})}),document.body)}function qw(e){return e.status===`open`&&(e.audience===`boss`||e.audience===void 0)}function Jw(e){return(e.escalations??[]).filter(qw)}function Yw(e){let t=e.filter(e=>Jw(e).length>0);return{projects:t.length,cases:t.reduce((e,t)=>e+Jw(t).length,0)}}function Xw(e,t=!1){return[`cancelled`,`failed`].includes(e.status??``)?!0:t}function Zw(e,t,n){let r=Xw(e,t),i=Jw(e).length>0;return n===`history`?r&&!i:!r||i}function Qw(e){return(e.reports??[]).filter(t=>!t.taskId&&[`progress`,`delivery`].includes(t.kind??``)&&(t.authorConversationId===e.ownerConversationId&&!!e.ownerConversationId||t.kind===`delivery`&&!t.authorConversationId))}function $w(e){return[...e.reports??[]].reverse().find(t=>t.kind===`delivery`&&!t.taskId&&(!t.authorConversationId||t.authorConversationId===e.ownerConversationId))}function eT(e){let t=Jw(e),n=[...Qw(e)].reverse().find(e=>e.kind===`progress`),r=$w(e),i=[`cancelled`,`failed`].includes(e.status),a=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),o=(e.resources?.activeWorkers??0)>0||[`running`,`waiting`,`awaiting_background`].includes(a?.status??``);return{label:e.status===`cancelled`?`已取消`:e.status===`failed`?`执行暂停`:t.length?`需要你决定`:o?`正在推进`:e.ownerConversationId?[`failed`,`stopped`].includes(a?.status??``)?`执行暂停`:r?`待继续`:`未交付`:`待启动`,summary:n?.progress?.trim()||n?.summary?.trim()||(i?`项目已结束,已有记录会保留。`:r?`可继续安排新任务或追加验证。`:`已交由负责人推进,进展和成果会在这里汇总。`),progress:n,delivery:r,decisions:t,ended:i,deliveryLabel:e.mode===`lightweight`?`自评交付`:`交付成果`}}var tT=/\.[A-Za-z][A-Za-z0-9]{0,9}$/,nT=new Set([`makefile`,`dockerfile`,`license`,`readme`,`changelog`]),rT=/^[A-Za-z]:/;function iT(e){let t=(e??``).trim();if(!t||/\s/.test(t)||t.includes(`://`)||t.startsWith(`/`)||t.startsWith(`\\`)||rT.test(t))return;let n=t.split(/[\\/]/);if(n.some(e=>e===``||e===`.`||e===`..`))return;let r=n[n.length-1];if(tT.test(r)||nT.has(r.toLowerCase()))return n.join(`/`)}function aT(e){return/\s/.test(e)||e.includes(`://`)||e.startsWith(`/`)||e.startsWith(`\\`)||rT.test(e)?!1:!e.split(/[\\/]/).some(e=>e===``||e===`.`||e===`..`)}function oT(e){let t=e.split(/[\\/]/);return t[t.length-1]||e}function sT(e,t){let n=iT(e);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(aT(r))return n===r||n.startsWith(`${r}/`)?n:`${r}/${n}`}function cT(e,t){let n=(e??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(n!==r&&n.startsWith(`${r}/`))return n.slice(r.length+1)}function lT(e){return[`cancelled`,`failed`].includes(e.status??``)}function uT(e,t){return e.filter(e=>Zw(e,e.ownerArchived===!0,t?`history`:`current`))}function dT(e){let[t,n]=(0,u.useState)(0),r=(0,u.useRef)(null),i=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let e=()=>{let e=r.current,t=i.current;if(!e||!t)return;let a=getComputedStyle(e),o=Number.parseFloat(a.lineHeight)||Number.parseFloat(a.fontSize)*1.6||16,s=t.getBoundingClientRect().height;n(Math.max(1,Math.round(s/o)))};e();let t=typeof ResizeObserver==`function`?new ResizeObserver(()=>e()):null;return t&&(r.current&&t.observe(r.current),i.current&&t.observe(i.current)),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[e]),{lines:t,visible:r,measured:i}}function fT({text:e,what:t}){let[n,r]=(0,u.useState)(!1),{lines:i,visible:a,measured:o}=dT(e),s=Math.max(0,i-2);return e?(0,F.jsxs)(`div`,{className:`project-prose-wrap`,children:[(0,F.jsx)(`p`,{className:`project-prose${n?` project-prose-open`:``}`,"data-prose-text":!0,ref:a,children:e}),(0,F.jsx)(`span`,{className:`project-prose-measure`,"aria-hidden":`true`,ref:o,children:e}),s>0?(0,F.jsx)(`button`,{type:`button`,className:`project-prose-expand`,"data-prose-expand":!0,"aria-expanded":n,onClick:()=>r(e=>!e),children:n?`收起${t}`:`展开完整${t}(还有 ${s} 行)`}):null]}):null}function pT({refs:e,baseCwd:t,cwd:n,onOpenFile:r}){return(0,F.jsx)(`ul`,{children:e.map((e,i)=>{let a=sT(e,t),o=a?cT(a,n):void 0;return(0,F.jsx)(`li`,{children:o&&r?(0,F.jsx)(`button`,{type:`button`,className:`project-evidence-path`,"data-team-evidence-file":o,onClick:()=>r({path:o,name:oT(o),text:null}),children:e}):e},i)})})}function mT(e){if(!e)return``;let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));return n<60?`刚刚`:n<3600?`${Math.floor(n/60)} 分钟前`:n<86400?`${Math.floor(n/3600)} 小时前`:`${Math.floor(n/86400)} 天前`}async function hT(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`请求失败(${e.status})`);return t}async function gT(e){let t=(await e.text().catch(()=>``)).trim();if(!t)return`报告打不开(${e.status})`;try{let n=JSON.parse(t);return n&&typeof n==`object`&&typeof n.error==`string`&&n.error.trim()?n.error.trim():`报告打不开(${e.status})`}catch{return t}}function _T(e,t){return`/api/projects/${encodeURIComponent(e)}/report?workspaceId=${encodeURIComponent(t??``)}`}function vT(e,t=60){let n=(e??``).replace(/\s+/g,` `).trim();return n?n.length<=t?n:`${n.slice(0,t-1)}…`:``}function yT(e){let t=(e.title??``).trim();if(t)return t;let n=(e.reason??``).trim();return n?n.match(/^[\s\S]*?[。!?!?]/)?.[0]?.trim()||n:`需要处理`}var bT={decision:0,delivery:1},xT=5;function ST(e,t){let n=Jw(e)[0],r={projectId:e.id,projectTitle:e.title,updatedAt:Date.parse(e.updatedAt??``)||0};if(n)return{...r,reminderId:`${e.id}:decision:${Jw(e).map(e=>e.id).join(`,`)}`,kind:`decision`,label:`要你决定`,detail:vT(n.title||n.reason||`需要你的决定`,lT(e)?36:60)+(lT(e)?`(项目已结束:记录后不会唤醒任何人)`:``),actionLabel:`去看看`,target:{kind:`exception`,escalationId:n.id}};let i=eT(e).delivery,a=Date.parse(i?.createdAt??``);return!i||!Number.isFinite(a)||t-a>864e5?null:{...r,updatedAt:a,reminderId:`${e.id}:delivery:${i.id}`,kind:`delivery`,label:`阶段交付`,detail:vT(i.progress||i.summary||`已提交阶段成果`),actionLabel:`查看交付`,target:{kind:`top`}}}function CT({text:e}){let[t,n]=(0,u.useState)(!1),{lines:r,visible:i,measured:a}=dT(e),o=Math.max(0,r-2);return e?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`project-exception-reason-wrap`,children:[(0,F.jsx)(`p`,{className:`project-exception-reason${t?` project-exception-reason-open`:``}`,"data-project-exception-reason":!0,ref:i,children:e}),(0,F.jsx)(`span`,{className:`project-exception-reason-measure`,"aria-hidden":`true`,ref:a,children:e})]}),o>0&&(0,F.jsx)(`button`,{type:`button`,className:`project-exception-expand`,"data-project-exception-expand":!0,"aria-expanded":t,onClick:()=>n(e=>!e),children:t?`收起理由`:`展开完整理由(还有 ${o} 行)`})]}):null}function wT({item:e,project:t,busy:n,onResolve:r,onReturn:i}){let[a,o]=(0,u.useState)(``),s=lT(t);return(0,F.jsxs)(`li`,{className:`project-exception`,"data-project-exception":e.id,children:[(0,F.jsx)(`strong`,{className:`project-exception-title`,"data-project-exception-title":!0,children:yT(e)}),e.reason&&(0,F.jsx)(CT,{text:e.reason}),s&&(0,F.jsx)(`p`,{className:`project-exception-ended`,"data-project-exception-ended":!0,"data-project-exception-ended-note":!0,children:`项目已结束:你的处理意见会记进项目记录,但不会唤醒任何人。`}),(0,F.jsxs)(`label`,{className:`project-decision-label`,children:[`你的决定`,(0,F.jsx)(`textarea`,{"data-project-decision":e.id,"data-project-exception-decision":!0,value:a,onChange:e=>o(e.target.value),disabled:n})]}),(0,F.jsxs)(`div`,{className:`project-detail-actions`,children:[(0,F.jsx)(`button`,{type:`button`,"data-project-decision-submit":e.id,"data-project-exception-resolve":!0,disabled:n||!a.trim(),onClick:()=>r(a.trim()),children:s?`记录处理意见`:`记录决定并答复主会话`}),(0,F.jsx)(`button`,{type:`button`,"data-project-decision-return":e.id,"data-project-exception-return":!0,disabled:n||!a.trim(),onClick:()=>i(a.trim()),children:`退回补充`})]})]})}function TT({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o}){let s=eT(e),[c,l]=(0,u.useState)(!1),[d,f]=(0,u.useState)(``),[p,m]=(0,u.useState)(!1),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(``),y=(0,u.useRef)(``);(0,u.useEffect)(()=>()=>{y.current&&URL.revokeObjectURL(y.current)},[]);let b=async(r,i,a={})=>{if(t&&!c){l(!0),f(``);try{await Ne(`/api/projects/${encodeURIComponent(e.id)}/${r}`,{method:i,headers:{"content-type":`application/json`},body:JSON.stringify({...a,workspaceId:t})}).then(hT),await o?.(),n?.(`已记录并交给负责人`,`info`)}catch(e){f(e instanceof Error?e.message:`操作失败`)}finally{l(!1)}}},x=async()=>{if(t&&!p){m(!0),g(``);try{let n=await Ne(_T(e.id,t));if(!n.ok){g(await gT(n));return}let r=await n.text();y.current&&URL.revokeObjectURL(y.current);let i=URL.createObjectURL(new Blob([r],{type:`text/plain;charset=utf-8`}));y.current=i,v(i),window.open(i,`_blank`,`noopener`)}catch(e){g(e instanceof Error?e.message:`报告打不开`)}finally{m(!1)}}},S=e.resources?.usage,C=s.delivery?.evidenceRefs??[],w=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),T=!e.ownerConversationId||!!(w&&[`failed`,`stopped`].includes(w.status??``)&&!e.resources?.activeWorkers);return(0,F.jsxs)(`div`,{className:`project-detail project-overview`,"data-project-detail":e.id,children:[e.objective&&(0,F.jsxs)(`div`,{className:`project-goal`,children:[(0,F.jsx)(`span`,{children:`项目目标`}),(0,F.jsx)(`p`,{className:`project-detail-objective`,children:e.objective})]}),(0,F.jsxs)(`section`,{className:`project-section`,"data-project-owner-summary":!0,children:[(0,F.jsx)(`h3`,{children:`当前进展`}),(0,F.jsx)(fT,{text:s.summary,what:`进展`}),e.updatedAt&&(0,F.jsxs)(`p`,{className:`project-overview-time`,children:[mT(e.updatedAt),`更新`]})]}),s.delivery&&(0,F.jsxs)(`section`,{className:`project-section`,"data-project-stage-delivery":!0,children:[(0,F.jsx)(`h3`,{children:s.deliveryLabel}),(0,F.jsx)(fT,{text:s.delivery.progress||s.delivery.summary||`已提交阶段成果`,what:`交付`}),C.length?(0,F.jsx)(pT,{refs:C,baseCwd:e.resources?.ownerCwd??w?.cwd,cwd:a,onOpenFile:i}):(0,F.jsx)(`p`,{"data-project-no-evidence":!0,children:`未附可核对的交付证据。`})]}),s.decisions.length>0&&(0,F.jsxs)(`section`,{className:`project-section`,"data-project-exception-section":!0,children:[(0,F.jsx)(`h3`,{"data-project-exception-heading":!0,children:`需要你决定`}),(0,F.jsx)(`ul`,{className:`project-exception-list`,children:s.decisions.map(t=>(0,F.jsx)(wT,{item:t,project:e,busy:c,onResolve:e=>void b(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`resolved`}),onReturn:e=>void b(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`returned`})},t.id))})]}),d&&(0,F.jsx)(`p`,{className:`project-error`,role:`alert`,children:d}),(0,F.jsxs)(`div`,{className:`project-detail-actions project-overview-actions`,children:[w&&r&&(0,F.jsx)(`button`,{type:`button`,className:T&&!s.ended?``:`project-primary-action`,"data-project-open-owner":!0,onClick:()=>r(w.id),children:`查看负责人会话`}),!s.ended&&T&&(0,F.jsx)(`button`,{type:`button`,className:`project-primary-action`,disabled:c,"data-project-resume":!0,onClick:()=>void b(`start`,`POST`),children:`让负责人继续`}),!s.ended&&(0,F.jsx)(`button`,{type:`button`,className:`project-stop-action`,disabled:c,"data-project-stop":!0,onClick:()=>void b(``,`PATCH`,{status:`cancelled`}),children:`停止项目`}),(0,F.jsx)(`button`,{type:`button`,disabled:p,"data-project-report":e.id,onClick:()=>void x(),children:p?`正在读取…`:`导出记录`})]}),h&&(0,F.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-report-error":!0,children:h}),_&&(0,F.jsx)(`a`,{href:_,target:`_blank`,rel:`noopener noreferrer`,"data-project-report-link":!0,children:`打开已读取的记录`}),e.resources&&(0,F.jsxs)(`details`,{className:`project-section project-secondary`,"data-project-usage":!0,children:[(0,F.jsx)(`summary`,{children:`查看用量`}),(0,F.jsxs)(`div`,{"data-project-budget":e.id,children:[(0,F.jsxs)(`p`,{"data-project-budget-used":e.id,children:[`等效 Token `,e.resources.usageKnown?e.resources.tokens.toLocaleString():`未知`]}),S&&(0,F.jsxs)(`p`,{"data-project-budget-raw":e.id,children:[`原始口径 `,(e.resources.rawTokens??S.input+S.output+S.cacheRead+S.cacheWrite).toLocaleString(),`;输入 `,S.input.toLocaleString(),`;输出 `,S.output.toLocaleString(),`;缓存写入 `,S.cacheWrite.toLocaleString(),`;缓存读取 `,S.cacheRead.toLocaleString()]}),(0,F.jsx)(`p`,{"data-project-budget-basis":`1`,children:`等效 Token = 输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1`})]})]})]})}function ET({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o,onClose:s}){let c=(0,u.useId)(),l=(0,u.useRef)(null),d=(0,u.useRef)(s);return d.current=s,(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),d.current())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,u.useEffect)(()=>{l.current?.focus({preventScroll:!0})},[e.id]),(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay project-dialog-overlay`,"data-project-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&s()},children:(0,F.jsxs)(`div`,{ref:l,className:`tool-dialog project-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":c,"data-project-dialog":e.id,tabIndex:-1,onKeyDown:e=>{if(e.key!==`Tab`)return;let t=l.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), input:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex='-1'])`)).filter(e=>e.offsetParent!==null||e.getClientRects().length>0);if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?(document.activeElement===r||document.activeElement===t)&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head project-dialog-head`,children:[(0,F.jsxs)(`div`,{className:`project-dialog-title-group`,children:[(0,F.jsx)(`h2`,{className:`tool-dialog-title project-dialog-title`,id:c,children:e.title}),(0,F.jsx)(`span`,{className:`project-detail-flags`,children:(0,F.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:eT(e).label})})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close project-dialog-close`,"data-project-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭 ${e.title}`,onClick:s,children:`✕`})]}),(0,F.jsx)(`div`,{className:`tool-dialog-body project-dialog-body`,children:(0,F.jsx)(TT,{project:e,workspaceId:t,notify:n,onOpenSession:r?e=>{s(),r(e)}:void 0,onOpenFile:i?e=>{s(),i(e)}:void 0,cwd:a,onChanged:o})})]})}),document.body)}function DT({workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i}){let[a,o]=(0,u.useState)([]),[s,c]=(0,u.useState)(!1),l=(0,u.useMemo)(()=>uT(a,s),[a,s]),[d,f]=(0,u.useState)(!1),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(null),_=(0,u.useRef)(null),[v,y]=(0,u.useState)([]),b=(0,u.useCallback)(async t=>{if(!e)o([]);else{m(``);try{let n=await Ne(`/api/projects?workspaceId=${encodeURIComponent(e)}${s?`&view=history`:``}`,{signal:t}).then(hT),r=Array.isArray(n)?n:Array.isArray(n.projects)?n.projects:[];o(r)}catch(e){e.name!==`AbortError`&&m(e instanceof Error?e.message:`项目列表加载失败`)}finally{t?.aborted||f(!0)}}},[e,s]);(0,u.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]),(0,u.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>void b(),5e3);return()=>window.clearInterval(t)},[b,e]);let x=(0,u.useMemo)(()=>{let e=Date.now();return l.map(t=>ST(t,e)).filter(e=>!!e).filter(e=>!v.includes(e.reminderId)).sort((e,t)=>bT[e.kind]-bT[t.kind]||t.updatedAt-e.updatedAt)},[l,v]),S=(0,u.useMemo)(()=>l.flatMap(e=>Jw(e).map(t=>({project:e,decision:t}))),[l]),C=(0,u.useMemo)(()=>Yw(l).projects,[l]),w=(0,u.useMemo)(()=>x.slice(0,xT),[x]),T=x.length-w.length,[E,D]=(0,u.useState)(!1),O=E?x:w,[k,A]=(0,u.useState)(!1),j=(0,u.useMemo)(()=>{let e=new Set;for(let t of x)e.add(t.projectId);return e},[l,x]),ee=(0,u.useMemo)(()=>k?l.filter(e=>j.has(e.id)):l,[k,l,j]),M=(0,u.useMemo)(()=>h?l.find(e=>e.id===h)??null:null,[l,h]),te=(0,u.useRef)(null),[N,ne]=(0,u.useState)(0),re=(0,u.useCallback)((e,t,n)=>{_.current=t??document.querySelector(`[data-project-row="${e}"]`),g(e),n&&(te.current={projectId:e,target:n},ne(e=>e+1))},[]),ie=(0,u.useCallback)(()=>{let e=h,t=_.current;_.current=null,g(null),window.requestAnimationFrame(()=>{(t?.isConnected?t:e?document.querySelector(`[data-project-row="${e}"]`):null)?.focus()})},[h]),ae=e=>{let t=document.querySelector(`[data-project-row="${e.projectId}"]`);re(e.projectId,t,e.target)};return(0,u.useEffect)(()=>{if(!N)return;let e=te.current;if(te.current=null,!e)return;let t=document.querySelector(`[data-project-detail="${e.projectId}"]`);if(!t)return;let n=null;if(e.target.kind===`exception`){let e=t.querySelector(`[data-project-exception-section]`);e&&(e.open=!0,n=e.querySelector(`[data-project-exception-heading]`)??e)}let r=n??t,i=window.requestAnimationFrame(()=>{r.scrollIntoView({block:e.target.kind===`top`?`start`:`center`,inline:`nearest`})});return()=>window.cancelAnimationFrame(i)},[N,M?.id]),(0,F.jsxs)(`section`,{className:`project-panel`,"data-project-panel":`1`,children:[(0,F.jsx)(`div`,{className:`rail-section-head project-panel-head`,children:(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`项目进展`}),(0,F.jsx)(`p`,{className:`project-panel-subtitle`,children:`查看负责人汇总的进展、成果和需要你决定的事。`})]})}),S.length>0&&(0,F.jsxs)(`div`,{className:`warning`,role:`status`,"data-project-team-notice":`1`,"data-project-team-notice-count":C,children:[(0,F.jsxs)(`span`,{"data-project-team-notice-text":!0,children:[C===1?`有 1 个项目的事需要你决定`:`有 ${C} 个项目的事需要你决定`,`:`,vT(yT(S[0].decision),48)]}),(0,F.jsx)(`button`,{type:`button`,"data-project-team-notice-action":`1`,onClick:()=>re(S[0].project.id,void 0,{kind:`exception`,escalationId:S[0].decision.id}),children:`去看看`})]}),x.length>0&&(0,F.jsxs)(`div`,{className:`project-pending`,"data-project-pending":`1`,"data-project-pending-count":x.length,children:[O.map(e=>(0,F.jsxs)(`div`,{className:`project-pending-item`,"data-project-pending-item":e.projectId,"data-project-pending-kind":e.kind,children:[(0,F.jsxs)(`div`,{className:`project-pending-row`,children:[(0,F.jsx)(`span`,{className:`project-pending-kind project-pending-kind-${e.kind}`,"data-project-pending-label":e.kind,children:e.label}),(0,F.jsx)(`span`,{className:`project-pending-title`,"data-project-pending-title":e.projectId,children:e.projectTitle}),(0,F.jsx)(`button`,{type:`button`,className:`project-pending-action`,"data-project-pending-action":e.projectId,onClick:()=>ae(e),children:e.actionLabel}),(0,F.jsx)(`button`,{type:`button`,className:`project-pending-close`,"data-project-pending-dismiss":e.projectId,"aria-label":`关闭「${e.projectTitle}」的这条提醒`,title:`关闭这条提醒(不改变项目状态)`,onClick:()=>y(t=>[...t,e.reminderId]),children:`×`})]}),(0,F.jsx)(`p`,{className:`project-pending-detail`,"data-project-pending-detail":e.projectId,children:e.detail})]},`${e.projectId}:${e.kind}`)),T>0&&(0,F.jsx)(`button`,{type:`button`,className:`project-pending-more`,"data-project-pending-more":`1`,"aria-expanded":E,onClick:()=>D(e=>!e),children:E?`收起`:`还有 ${T} 个`})]}),(0,F.jsxs)(`label`,{className:`project-pending-filter`,"data-project-pending-only-label":`1`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-project-pending-only":`1`,checked:k,onChange:e=>A(e.target.checked)}),(0,F.jsx)(`span`,{className:`project-pending-filter-name`,children:`只看提醒`}),(0,F.jsx)(`span`,{className:`project-pending-filter-state`,"data-project-pending-only-state":k?`on`:`off`,children:k?`已开启`:`已关闭`})]}),(0,F.jsxs)(`label`,{className:`project-pending-filter`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-project-history":`1`,checked:s,onChange:e=>{c(e.target.checked),A(!1),g(null)}}),(0,F.jsx)(`span`,{className:`project-pending-filter-name`,children:`查看历史项目`})]}),p&&(0,F.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-error":`1`,children:p}),e?!d&&l.length===0?(0,F.jsx)(`p`,{className:`rail-empty`,children:`正在加载项目…`}):l.length===0?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{className:`rail-empty`,"data-project-empty":`1`,children:s?`没有已结束的项目。`:`当前没有进行中的项目。`}),(0,F.jsx)(`p`,{className:`project-empty-hint`,"data-project-empty-hint":`1`,children:`在对话里告诉 AI 你要完成什么,负责人会推进工作并向你交付。`})]}):ee.length===0?(0,F.jsx)(`p`,{className:`rail-empty`,"data-project-pending-empty":`1`,children:`没有需要关注的项目。`}):(0,F.jsx)(F.Fragment,{children:(0,F.jsx)(`div`,{className:`project-list`,"data-project-count":ee.length,children:ee.map(e=>{let t=M?.id===e.id;return(0,F.jsxs)(`button`,{type:`button`,className:`project-row`,"data-project-row":e.id,"data-project-block":e.id,"data-project-summary":e.id,"aria-haspopup":`dialog`,"aria-expanded":t,onClick:t=>re(e.id,t.currentTarget),children:[(0,F.jsx)(`span`,{className:`project-list-title`,title:e.title,children:e.title}),(0,F.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:eT(e).label}),(0,F.jsx)(`span`,{className:`project-row-summary`,children:eT(e).summary}),e.updatedAt&&(0,F.jsxs)(`span`,{className:`project-row-updated`,children:[mT(e.updatedAt),`更新`]})]},e.id)})})}):(0,F.jsx)(`p`,{className:`rail-empty`,children:`请先选择工作区。`}),M?(0,F.jsx)(ET,{project:M,workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i,onChanged:()=>b(),onClose:ie}):null]})}var OT=()=>({text:``,mentions:[],files:[]}),kT=(e,t)=>`super-pi.group-draft.v1:${JSON.stringify([e,t])}`;function AT(e,t){try{let n=JSON.parse(localStorage.getItem(kT(e,t))??`null`);return!n||typeof n.text!=`string`?OT():{text:n.text.slice(0,32e3),replyTo:typeof n.replyTo==`string`?n.replyTo:void 0,mentions:Array.isArray(n.mentions)?n.mentions.filter(e=>typeof e?.memberId==`string`&&typeof e.text==`string`):[],files:Array.isArray(n.files)?n.files.filter(e=>typeof e?.path==`string`&&typeof e.text==`string`):[]}}catch{return OT()}}function jT(e,t,n){try{let r=kT(e,t);!n.text&&!n.replyTo?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(n))}catch{}}function MT(e,t,n){AT(e,t).text===n&&jT(e,t,OT())}var NT=`super-pi.group-presets.v1`;function PT(){try{let e=JSON.parse(localStorage.getItem(`super-pi.group-presets.v1`)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e?.id==`string`&&typeof e.name==`string`&&Array.isArray(e.memberIds)&&e.memberIds.every(e=>typeof e==`string`)&&e.memberModels&&typeof e.memberModels==`object`&&!Array.isArray(e.memberModels)&&typeof e.moderator?.prompt==`string`).slice(0,100):[]}catch{return[]}}var FT=e=>JSON.stringify([e.provider,e.modelId]);function IT({value:e,models:t,onChange:n,label:r,inheritLabel:i}){let[a,o]=(0,u.useState)(``),[s,c]=(0,u.useState)(``),l=(0,u.useRef)(null),d=t.find(t=>FT(t)===e),f=t.filter(e=>(!a||e.provider===a)&&`${e.label} ${e.modelId}`.toLocaleLowerCase().includes(s.toLocaleLowerCase())),p=e=>{n(e),l.current&&(l.current.open=!1)};return(0,F.jsxs)(`details`,{className:`group-model-picker`,ref:l,onKeyDown:e=>{e.key===`Escape`&&l.current&&(l.current.open=!1,l.current.querySelector(`summary`)?.focus())},children:[(0,F.jsxs)(`summary`,{"aria-label":r,title:d?`${d.provider} / ${d.modelId}`:void 0,children:[(0,F.jsx)(`span`,{children:e?d?.label??`当前模型不可用,请重新选择`:i??`继承 Agent / 工作区模型`}),(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]}),(0,F.jsxs)(`div`,{className:`group-model-popup`,children:[(0,F.jsxs)(`select`,{"aria-label":`${r} Provider`,value:a,onChange:e=>o(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`全部 Provider`}),[...new Set(t.map(e=>e.provider))].sort().map(e=>(0,F.jsx)(`option`,{children:e},e))]}),(0,F.jsx)(`input`,{"aria-label":`${r} 筛选`,placeholder:`筛选模型…`,value:s,onChange:e=>c(e.target.value)}),(0,F.jsxs)(`div`,{className:`group-model-options`,role:`group`,"aria-label":r,children:[(0,F.jsx)(`button`,{type:`button`,"aria-pressed":!e,onClick:()=>p(``),children:i??`继承默认模型`}),f.map(t=>(0,F.jsxs)(`button`,{type:`button`,"aria-pressed":e===FT(t),onClick:()=>p(FT(t)),children:[(0,F.jsx)(`span`,{children:t.label}),(0,F.jsx)(`small`,{children:t.provider})]},FT(t))),!f.length&&(0,F.jsx)(`p`,{children:`没有匹配的模型`})]})]})]})}var LT={division:`分工`,prompt:`Prompt`,tools:`工具`,mechanism:`协作机制`,execution:`执行策略`};function RT({value:e}){if(/(?:^|\n)\s*(?:[-*+] |\d+[.)] |#{1,4} |```)/.test(e))return(0,F.jsx)(`div`,{className:`rsi-prose`,children:(0,F.jsx)(ef,{source:e,handoffs:!1})});let t=e.split(/\n+/).map(e=>e.trim()).filter(Boolean),n=t.length>1?t:e.length>100?e.split(/(?<=[。;!?])\s*/u).filter(Boolean):t;return(0,F.jsx)(`ul`,{className:`rsi-points`,children:n.map((e,t)=>(0,F.jsx)(`li`,{children:(0,F.jsx)(tf,{source:e})},t))})}function zT({state:e,models:t,archived:n,onAction:r,onClose:i,extra:a}){let[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(e?.enabled!==!1),[d,f]=(0,u.useState)(e?.automaticImprovements!==!1),[p,m]=(0,u.useState)(e?.prompt??``),[h,g]=(0,u.useState)(e?.model?FT(e.model):``),[_,v]=(0,u.useState)({}),[y,b]=(0,u.useState)(!1),[x,S]=(0,u.useState)(``),C=e?.reports??[],w=C.find(e=>e.id===o)??C.at(-1),T=async e=>{if(!y){b(!0),S(``);try{await r(e)}catch(e){S(e instanceof Error?e.message:`RSI 操作失败`)}finally{b(!1)}}};return(0,F.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,"aria-label":`RSI 观察与建议`,children:[(0,F.jsxs)(`header`,{children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,F.jsx)(`span`,{role:`status`,children:e?.enabled===!1?`已暂停`:e?.status===`running`?`后台观察中`:e?.status===`failed`?`观察失败`:e?.pending?`有新过程,等待更新观察`:w?`观察已更新`:`等待任务产生可观察的过程`})]}),(0,F.jsx)(`button`,{type:`button`,"aria-label":`关闭 RSI 面板`,onClick:i,children:`关闭`})]}),(0,F.jsxs)(`div`,{className:`group-rsi-body`,children:[(0,F.jsx)(`p`,{className:`rsi-intro`,children:`观察任务效率和交付质量。通用缺口归平台,企业专用能力在用户侧开发、验证并复用。`}),!n&&(0,F.jsx)(`button`,{type:`button`,"data-rsi-refresh":!0,disabled:y||e?.status===`running`||e?.enabled===!1,onClick:()=>void T({action:`rsi.refresh`}),children:`更新观察`}),(x||e?.error)&&(0,F.jsx)(`p`,{role:`alert`,children:x||e?.error}),C.length>0&&(0,F.jsxs)(`label`,{children:[`观察记录`,(0,F.jsx)(`select`,{"aria-label":`RSI 观察记录`,value:w?.id,onChange:e=>s(e.target.value),children:[...C].reverse().map(e=>(0,F.jsx)(`option`,{value:e.id,children:new Date(e.createdAt).toLocaleString()},e.id))})]}),w&&(0,F.jsxs)(`section`,{"data-rsi-report":w.id,children:[(0,F.jsxs)(`div`,{className:`rsi-report-meta`,children:[(0,F.jsxs)(`span`,{children:[w.observedMessages,` / `,w.totalMessages,` 条发言`]}),(0,F.jsxs)(`span`,{children:[w.findings.length,` 条建议`]}),w.model&&(0,F.jsx)(`span`,{title:`观察模型`,children:w.model.label||w.model.modelId})]}),w.compressed&&(0,F.jsx)(`p`,{className:`group-rsi-coverage`,children:`部分历史或执行摘要已压缩;下列结论仅基于可见过程。`}),!!w.artifactReads?.length&&(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsxs)(`summary`,{children:[`本轮实际读取的产物证据 · `,w.artifactReads.length]}),(0,F.jsx)(`ul`,{children:w.artifactReads.map((e,t)=>(0,F.jsx)(`li`,{children:e},t))})]}),!!w.runEvidence?.length&&(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsx)(`summary`,{children:`实际运行用时(含工具及等人)`}),(0,F.jsx)(`ul`,{children:w.runEvidence.map((e,t)=>(0,F.jsxs)(`li`,{children:[Math.round(e.elapsedMs/1e3),` 秒 · `,new Date(e.finishedAt).toLocaleTimeString()]},t))}),(0,F.jsx)(`p`,{children:`这是完整运行用时,不能直接当作模型思考耗时。`})]}),(0,F.jsxs)(`section`,{className:`rsi-overview`,children:[(0,F.jsx)(`h4`,{children:`本轮结论`}),(0,F.jsx)(RT,{value:w.summary})]}),w.retrospective&&(0,F.jsxs)(`details`,{className:`rsi-retrospective`,children:[(0,F.jsx)(`summary`,{children:`前次建议的后续观察`}),(0,F.jsx)(RT,{value:w.retrospective})]}),!w.findings.length&&(0,F.jsx)(`p`,{children:`当前证据未形成具体改进建议。`}),[...w.findings].sort((e,t)=>({high:0,medium:1,low:2})[e.priority]-{high:0,medium:1,low:2}[t.priority]).map((e,t)=>(0,F.jsxs)(`article`,{className:`group-rsi-finding`,"data-rsi-finding":e.id,children:[(0,F.jsxs)(`header`,{className:`rsi-finding-heading`,children:[(0,F.jsxs)(`h4`,{children:[(0,F.jsx)(`span`,{className:`rsi-finding-number`,children:String(t+1).padStart(2,`0`)}),LT[e.category]]}),(0,F.jsx)(`span`,{className:`rsi-priority`,"data-priority":e.priority,children:{high:`优先处理`,medium:`建议改进`,low:`可选优化`}[e.priority]})]}),(0,F.jsxs)(`p`,{className:`rsi-ownership`,"data-rsi-ownership":e.ownership??`unclassified`,children:[(0,F.jsx)(`strong`,{children:{platform:`平台通用能力`,user:`用户专用能力`,mixed:`通用底座与专用适配需拆分`,unclassified:`归属待澄清`}[e.ownership??`unclassified`]}),e.ownershipReason&&` · ${e.ownershipReason}`]}),(0,F.jsxs)(`section`,{className:`rsi-finding-observation`,children:[(0,F.jsx)(`h5`,{children:`观察到的问题`}),(0,F.jsx)(RT,{value:e.observation})]}),(0,F.jsxs)(`section`,{className:`rsi-recommendation`,children:[(0,F.jsx)(`h5`,{children:`改进建议`}),(0,F.jsx)(RT,{value:e.recommendation})]}),(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsxs)(`summary`,{children:[`证据 · `,e.evidence.length,` 处关联发言`]}),e.evidence.map((e,t)=>(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`button`,{type:`button`,onClick:()=>{[...document.querySelectorAll(`[data-group-post-id]`)].find(t=>t.dataset.groupPostId===e.messageId)?.scrollIntoView({block:`center`,behavior:`smooth`})},children:`定位发言`}),e.quote&&(0,F.jsx)(`blockquote`,{children:e.quote})]},t))]}),(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsx)(`summary`,{children:`适用范围与验证办法`}),(0,F.jsx)(`h5`,{children:`适用范围`}),(0,F.jsx)(RT,{value:e.applicability}),(0,F.jsx)(`h5`,{children:`验证办法`}),(0,F.jsx)(RT,{value:e.verification})]}),e.disposition&&(0,F.jsxs)(`p`,{role:`status`,children:[e.disposition===`accepted`?`已标记采纳 · 待后续过程验证`:`已标记不适用`,e.feedback&&` · ${e.feedback}`]}),!n&&(0,F.jsxs)(`div`,{className:`group-rsi-feedback`,children:[e.ownership===`user`&&e.capability&&(0,F.jsxs)(`button`,{type:`button`,disabled:y,"data-rsi-improve":e.id,onClick:()=>void T({action:`rsi.improve`,reportId:w.id,findingId:e.id}),children:[`开发并验证 · `,e.capability.name]}),(0,F.jsx)(`textarea`,{"aria-label":`RSI 建议反馈`,placeholder:`说明适用差异或实际效果,供下一轮观察参考`,value:_[e.id]??e.feedback??``,onChange:t=>v(n=>({...n,[e.id]:t.target.value})),maxLength:2e3}),(0,F.jsx)(`div`,{children:[`accepted`,`dismissed`].map(t=>(0,F.jsx)(`button`,{type:`button`,disabled:y,"aria-pressed":e.disposition===t,onClick:()=>void T({action:`rsi.feedback`,reportId:w.id,findingId:e.id,disposition:t,feedback:_[e.id]??e.feedback??``}),children:t===`accepted`?`标记采纳`:`不适用`},t))})]})]},e.id))]}),a,!n&&(0,F.jsxs)(`details`,{className:`group-rsi-settings`,children:[(0,F.jsx)(`summary`,{children:`RSI 设置`}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:c,onChange:e=>l(e.target.checked)}),`自动观察`]}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`自动开发符合条件的用户专用能力`]}),(0,F.jsx)(`p`,{children:`观察会产生独立模型请求与费用,可随时暂停。每个来源至少间隔一分钟,每次最多 90 秒、12 次只读检查;同一工作区同时最多一个能力开发,预算十分钟。未指定模型时跟随来源会话、主持人或工作区。`}),(0,F.jsx)(IT,{value:h,models:t,label:`RSI 模型`,inheritLabel:`跟随主持人 / 工作区模型`,onChange:g}),(0,F.jsxs)(`label`,{children:[`补充观察要求`,(0,F.jsx)(`textarea`,{"aria-label":`RSI 补充要求`,value:p,onChange:e=>m(e.target.value),maxLength:8e3})]}),(0,F.jsx)(`button`,{type:`button`,"data-rsi-save":!0,disabled:y,onClick:()=>void T({action:`rsi.configure`,enabled:c,automaticImprovements:d,model:t.find(e=>FT(e)===h)??null,prompt:p}),children:`保存 RSI 设置`})]})]})]})}function BT({source:e,models:t,archived:n=!1,onClose:r}){let[i,a]=(0,u.useState)(),[o,s]=(0,u.useState)(``),c=`/api/rsi?${new URLSearchParams({kind:e.kind,workspaceId:e.workspaceId,id:e.id})}`;(0,u.useEffect)(()=>{let e=!1,t=new AbortController,n=async()=>{try{let n=await Ne(c,{signal:t.signal}),r=await n.json();if(!n.ok)throw Error(r.error??`RSI 暂时不可用。`);e||(a(r),s(``))}catch(t){e||s(t instanceof Error?t.message:String(t))}};n();let r=setInterval(()=>void n(),3e3);return()=>{e=!0,t.abort(),clearInterval(r)}},[c]);let l=async e=>{let t=await Ne(c,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();if(!t.ok)throw Error(n.error??`RSI 操作失败。`);a(n)};return i?(0,F.jsx)(zT,{state:i?.state,models:t,archived:n,onClose:r,onAction:l,extra:(0,F.jsxs)(`section`,{className:`rsi-work`,"data-rsi-work":!0,children:[o&&(0,F.jsx)(`p`,{role:`alert`,children:o}),(0,F.jsx)(`h4`,{children:`能力改进`}),!i?.improvements.length&&(0,F.jsx)(`p`,{children:`符合条件的用户侧建议会在后台开发;平台建议保留在报告中。`}),i?.improvements.map(e=>(0,F.jsxs)(`article`,{"data-rsi-job":e.id,children:[(0,F.jsxs)(`h5`,{children:[e.name,` · `,{queued:`等待开发`,running:`开发与验证中`,available:`已注册可用 · 收益待验证`,failed:`开发未通过`,interrupted:`已中断`,cancelled:`已取消`}[e.status]]}),(0,F.jsxs)(`p`,{children:[e.slug,e.version?` · v${e.version}`:``]}),e.error&&(0,F.jsx)(`p`,{role:`alert`,children:e.error}),e.conversationId&&(0,F.jsx)(`button`,{type:`button`,"data-rsi-open-work":e.id,onClick:()=>{window.dispatchEvent(new CustomEvent(`super-pi-open-rsi-work`,{detail:e.conversationId})),r()},children:`查看开发过程`}),[`running`,`queued`].includes(e.status)&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>void l({action:`rsi.cancel`,jobId:e.id}).catch(e=>s(String(e))),children:`取消改进`})]},e.id)),!!i?.usage.length&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`h4`,{children:`实际复用记录`}),(0,F.jsx)(`ul`,{children:i.usage.slice(-8).reverse().map((e,t)=>(0,F.jsxs)(`li`,{children:[e.slug,` v`,e.version,` · `,e.status,` · `,e.durationMs,` ms`]},t))}),(0,F.jsx)(`p`,{children:`调用成功仅表示执行成功,不能单独证明整个任务更快或质量更好。`})]})]})},c):(0,F.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,children:[(0,F.jsxs)(`header`,{children:[(0,F.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,F.jsx)(`button`,{type:`button`,onClick:r,children:`关闭`})]}),(0,F.jsx)(`div`,{className:`group-rsi-body`,children:(0,F.jsx)(`p`,{role:o?`alert`:`status`,children:o||`正在读取观察与能力改进记录…`})})]})}function VT({id:e,workspaceId:t,models:n}){let[r,i]=(0,u.useState)(!1),a=(0,u.useRef)(null);return(0,u.useEffect)(()=>i(!1),[e]),(0,u.useEffect)(()=>{if(!r)return;let e=e=>{e.key===`Escape`&&i(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]),(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{ref:a,type:`button`,"data-session-rsi":e,"aria-expanded":r,title:`RSI:任务效率与能力改进`,onClick:()=>i(e=>!e),children:`RSI`}),r&&(0,Re.createPortal)((0,F.jsx)(`div`,{className:`session-rsi-dock`,role:`region`,"aria-label":`会话 RSI`,children:(0,F.jsx)(BT,{source:{kind:`session`,id:e,workspaceId:t},models:n,onClose:()=>{i(!1),a.current?.focus()}})}),a.current?.closest(`.workbench-main-panes`)??document.body)]})}var HT={queued:`排队中`,running:`进行中`,completed:`已完成`,failed:`失败`,cancelled:`已停止`,interrupted:`已中断`},UT=new Map([[`read`,`读取文件`],[`write`,`写入文件`],[`edit`,`编辑文件`],[`grep`,`搜索内容`],[`find`,`查找文件`],[`ls`,`列出目录`],[`bash`,`运行命令`],[`powershell`,`运行命令`]]),WT=new Map([[`solution-designer`,`案`],[`code-designer`,`码`],[`code-auditor`,`审`],[`document-organizer`,`文`]]),GT=e=>e.status===`queued`||e.status===`running`,KT=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),qT=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`});function JT(e,t=!1){let n=Date.parse(e);return Number.isFinite(n)?(t?qT:KT).format(n):``}function YT({name:e,memberId:t,busy:n}){let r=e.trim(),i=t&&WT.get(t)||(/\p{Script=Han}/u.test(r)?Array.from(r).slice(-2).join(``):r.split(/\s+/u).filter(Boolean).map(e=>Array.from(e)[0]).slice(0,2).join(``).toUpperCase())||`?`,a=Wn.findIndex(e=>e===t),o=a>=0?a:Array.from(t??``).reduce((e,t)=>(e*31+(t.codePointAt(0)??0))%4,0);return(0,F.jsx)(`span`,{className:`group-avatar`,"data-avatar-tone":t?o:`self`,"data-avatar-busy":n||void 0,"aria-hidden":`true`,children:i})}function XT({step:e}){return e.kind===`thinking`?(0,F.jsxs)(`details`,{className:`group-execution-step`,"data-execution-kind":`thinking`,"data-execution-status":e.status,open:!0,children:[(0,F.jsxs)(`summary`,{children:[(0,F.jsx)(`span`,{children:e.status===`running`?`正在思考`:`思考摘要`}),(0,F.jsx)(`time`,{dateTime:e.startedAt,children:JT(e.startedAt,!0)})]}),e.text?(0,F.jsx)(`div`,{className:`message-body`,children:(0,F.jsx)(ef,{source:e.text,handoffs:!1})}):(0,F.jsx)(`p`,{className:`group-execution-muted`,children:e.status===`running`?`正在等待模型返回摘要。`:`模型未提供可显示的摘要。`}),e.status===`interrupted`&&(0,F.jsx)(`p`,{className:`group-execution-muted`,children:`思考已中断`})]}):(0,F.jsxs)(`li`,{className:`group-execution-step`,"data-execution-kind":`tool`,"data-execution-status":e.status,children:[(0,F.jsxs)(`div`,{className:`group-execution-tool`,children:[(0,F.jsx)(`strong`,{children:UT.get(e.name)??`工具调用`}),(0,F.jsx)(`code`,{children:e.name}),(0,F.jsx)(`span`,{className:`group-execution-step-status`,children:HT[e.status]})]}),e.detail&&(0,F.jsx)(`p`,{className:`group-execution-target`,children:(0,F.jsx)(`code`,{children:e.detail})}),(0,F.jsxs)(`div`,{className:`group-execution-muted`,children:[(0,F.jsx)(`time`,{dateTime:e.startedAt,children:JT(e.startedAt,!0)}),e.durationMs===void 0?e.status===`running`&&e.lastUpdateAt?` · 最近更新 ${JT(e.lastUpdateAt,!0)}`:null:` · ${(e.durationMs/1e3).toFixed(1)} 秒`]})]})}function ZT({workspaceId:e,roomId:t,memberId:n,name:r,runs:i,postId:a,onSelect:o,onClose:s,onStop:c,models:l,memberModel:d,onModelChange:f,onRetry:p}){let m=(0,u.useId)(),h=(0,u.useRef)(null),[g,_]=(0,u.useState)(),[v,y]=(0,u.useState)(),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)(``),[w,T]=(0,u.useState)(!1),E=i.find(e=>e.id===a)??i.find(e=>e.status===`running`)??i[0],D=E?.id,O=g?.id===D?g?.value:void 0,k=v?.id===D?v?.message:void 0;return(0,u.useLayoutEffect)(()=>{h.current?.focus()},[]),(0,u.useEffect)(()=>{if(!D)return;let n=new AbortController,r,i,a=!1,o=async()=>{try{let r=await nr(er(e,t,i,D),{signal:n.signal});if(n.signal.aborted)return;y(void 0),r&&(i=r.revision,a=!GT(r),_({id:D,value:r}))}catch(e){n.signal.aborted||y({id:D,message:e instanceof Error?e.message:`暂时无法读取执行记录。`})}finally{!n.signal.aborted&&!a&&(r=window.setTimeout(o,500))}};return o(),()=>{n.abort(),window.clearTimeout(r)}},[D,e,t]),(0,F.jsxs)(`aside`,{className:`group-execution`,"aria-labelledby":m,"data-group-execution":n,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),s())},children:[(0,F.jsxs)(`header`,{className:`group-execution-header`,children:[(0,F.jsx)(YT,{name:r,memberId:n,busy:i.some(GT)}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`h2`,{id:m,children:r}),(0,F.jsx)(`p`,{children:`执行详情`})]}),(0,F.jsx)(`button`,{ref:h,type:`button`,className:`group-close-execution`,"data-close-group-execution":!0,"aria-label":`关闭执行详情`,title:`关闭执行详情`,onClick:s,children:(0,F.jsx)(Gr,{name:`close`})})]}),f&&(0,F.jsxs)(`div`,{className:`group-execution-model-settings`,"aria-busy":b,children:[(0,F.jsx)(`span`,{children:`该成员后续使用的模型`}),(0,F.jsx)(IT,{label:`${r} 后续使用的模型`,value:d?FT(d):``,models:l,onChange:e=>{b||(x(!0),C(``),f(e).catch(e=>C(String(e.message??e))).finally(()=>x(!1)))}}),(0,F.jsx)(`small`,{children:b?`正在保存…`:`当前执行使用原模型。如需立即切换,请先停止再重试。`}),S&&(0,F.jsx)(`p`,{className:`group-error`,role:`alert`,children:S})]}),E?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`group-execution-summary`,children:[i.length>1&&(0,F.jsx)(`select`,{"aria-label":`选择执行记录`,value:D,onChange:e=>o(e.target.value),children:i.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[JT(e.createdAt,!0),` · `,e.assignment??HT[e.status]]},e.id))}),(0,F.jsx)(`div`,{"aria-live":`polite`,"data-execution-run-status":O?.status??E.status,children:HT[O?.status??E.status]}),E.assignment&&(0,F.jsx)(`p`,{children:E.assignment}),(0,F.jsx)(`p`,{"data-group-execution-model":!0,children:E.model?`${E.model.label} · ${E.model.provider}`:`模型尚未记录`}),GT(E)&&c&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>c(E.id),children:`停止这次执行`}),[`failed`,`cancelled`,`interrupted`].includes(E.status)&&p&&(0,F.jsx)(`button`,{type:`button`,"data-group-retry":!0,disabled:w||b,onClick:()=>{T(!0),C(``),p(E.id).catch(e=>C(String(e.message??e))).finally(()=>T(!1))},children:w?`正在提交重试…`:`用当前模型继续任务`}),E.error&&(0,F.jsx)(`p`,{className:`group-error`,children:E.error})]}),(0,F.jsxs)(`div`,{className:`group-execution-scroll`,children:[k&&(0,F.jsx)(`p`,{className:`group-error`,role:`alert`,children:k}),O?.steps.length?(0,F.jsx)(`ol`,{className:`group-execution-steps`,children:O.steps.map(e=>e.kind===`thinking`?(0,F.jsx)(`li`,{children:(0,F.jsx)(XT,{step:e})},e.id):(0,F.jsx)(XT,{step:e},e.id))}):!k&&(0,F.jsx)(`p`,{className:`group-execution-muted`,children:O?GT(O)?`等待模型或工具事件。`:`这次发言没有可查看的执行明细。`:`正在读取执行记录…`}),O?.truncated&&(0,F.jsx)(`p`,{className:`group-execution-muted`,children:`部分执行记录超过保留长度,已省略。`})]})]}):(0,F.jsx)(`p`,{className:`group-execution-scroll group-execution-muted`,children:`该成员还没有执行记录。`})]})}var QT=e=>JSON.stringify([e.provider,e.modelId]),$T=`super-pi.group-moderator-prompt-presets.v1`;function eE(){try{let e=JSON.parse(localStorage.getItem($T)??`[]`);return Array.isArray(e)?e.filter(e=>e&&typeof e.id==`string`&&typeof e.name==`string`&&typeof e.prompt==`string`).slice(0,100).map(e=>({id:e.id.slice(0,100),name:e.name.slice(0,80),prompt:e.prompt.slice(0,8e3)})):[]}catch{return[]}}var tE=e=>/\s/u.test(e)?`@"${e}"`:`@${e}`,nE=e=>new Set([...e.matchAll(/(?:^|[\s([{])(@(?:"(?:[^"\\]|\\.)+"|[^\s,。;、!?,::;!?,)\]}]+))/gu)].map(e=>e[1])),rE=rr;function iE({workspaceId:e,roomId:t,agents:n,catalog:r,userLabel:i,archivedAt:a,restoring:o,onRestore:s,onRoomSeen:c,onRoomRead:l,onRoomMissing:d,onCreated:f,onCancelCreate:p,onEnableNotifications:m,composerResize:h,sourceLink:g}){let[_,v]=(0,u.useState)(),[y,b]=(0,u.useState)(!1),[x,S]=(0,u.useState)(!1);(0,u.useEffect)(()=>{let e=e=>{e.detail?.roomId===t&&b(!0)};return window.addEventListener(`super-pi-status-group-models`,e),()=>window.removeEventListener(`super-pi-status-group-models`,e)},[t]);let[C,w]=(0,u.useState)(``),[T,E]=(0,u.useState)(``),[D,O]=(0,u.useState)(!1),[k,A]=(0,u.useState)({}),[j,ee]=(0,u.useState)(),[M,te]=(0,u.useState)(``),[N]=(0,u.useState)(()=>AT(e,t)),[ne,re]=(0,u.useState)(N.text),[ie,ae]=(0,u.useState)(N.replyTo),[oe,se]=(0,u.useState)(),[ce,le]=(0,u.useState)(N.mentions),[ue,de]=(0,u.useState)(N.files),[fe,pe]=(0,u.useState)([]),[me,he]=(0,u.useState)(0),[ge,P]=(0,u.useState)(),_e=(0,u.useRef)(null),ve=(0,u.useRef)(null),ye=(0,u.useRef)(void 0),be=(0,u.useRef)(null),xe=(0,u.useRef)(!0),Se=(0,u.useRef)(void 0),Ce=(0,u.useRef)(!1),we=(0,u.useRef)(void 0),Te=(0,u.useRef)(new Map),Ee=_?.id===t?_:void 0,De=!!(a||Ee?.archivedAt),Oe=Ee?.messages.find(e=>e.id===ie),ke=e=>Ee?.members.find(t=>t.id===e)?.name??e,Ae=e=>e.role===`user`?i:e.memberName??ke(e.memberId),je=De?void 0:oe?.query,Me=oe?[...(Ee?.members??[]).filter(e=>`${e.name} ${e.id}`.toLocaleLowerCase().includes(oe.query.toLocaleLowerCase())).map(e=>({kind:`member`,member:e})),...fe.map(e=>({kind:`file`,file:e}))]:[];(0,u.useEffect)(()=>{jT(e,t,{text:ne,replyTo:ie,mentions:ce,files:ue})},[e,t,ne,ie,ce,ue]);let Ne=e=>{if(e.id!==t)return;let n=Se.current;if(n?.id===e.id){let[t,r]=n.revision.split(`:`).map(Number),[i,a]=e.revision.split(`:`).map(Number);if(t>i||t===i&&r>a)return}Se.current=e,v(e),e.archivedAt&&b(!1),(n?.title!==e.title||n?.archivedAt!==e.archivedAt||n?.activity.status!==e.activity.status||n?.activity.lastReplyAt!==e.activity.lastReplyAt)&&c(e)};(0,u.useEffect)(()=>{let e=be.current;if(!Ee||y||!e)return;let t=!0,n=()=>{let n=e.getBoundingClientRect();t&&document.visibilityState===`visible`&&getComputedStyle(e).visibility===`visible`&&n.width>0&&n.height>0&&n.bottom>0&&n.top<window.innerHeight&&n.right>0&&n.left<window.innerWidth&&l(Ee)};n();let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()});return r.observe(e),document.addEventListener(`visibilitychange`,n),()=>{t=!1,r.disconnect(),document.removeEventListener(`visibilitychange`,n)}},[Ee?.id,Ee?.activity.lastReplyAt,y,ge?.memberId,ge?.postId,l]),(0,u.useEffect)(()=>(Ce.current=!0,()=>{Ce.current=!1}),[]),(0,u.useEffect)(()=>{if(!t)return;let n=new AbortController,r,i=!1,a=async()=>{try{let r=await nr(er(e,t,Se.current?.revision),{signal:n.signal});n.signal.aborted||(E(``),r&&Ne(r))}catch(r){n.signal.aborted||(r instanceof tr&&r.status===404?(i=!0,d({workspaceId:e,roomId:t})):E(Se.current?`群聊连接暂时中断,正在重试。`:String(r.message??r)))}finally{!n.signal.aborted&&!i&&(r=window.setTimeout(a,Se.current?.messages.some(GT)?450:1600))}};return a(),()=>{n.abort(),window.clearTimeout(r)}},[e,t,d]),(0,u.useEffect)(()=>{if(pe([]),!je)return;let t=new AbortController,n,r=()=>{nr(`/api/files/mentions?${new URLSearchParams({workspaceId:e,cwd:``,q:je})}`,{signal:t.signal}).then(e=>{!t.signal.aborted&&e&&(pe(e.hits.filter(e=>e.kind===`file`).slice(0,8)),e.indexed||(n=window.setTimeout(r,650)))}).catch(()=>{})};return n=window.setTimeout(r,160),()=>{window.clearTimeout(n),t.abort()}},[je,e]),(0,u.useLayoutEffect)(()=>{be.current&&xe.current&&(be.current.scrollTop=be.current.scrollHeight)},[Ee?.revision]),(0,u.useLayoutEffect)(()=>{let e=ye.current;e!==void 0&&ve.current&&(ye.current=void 0,ve.current.focus(),ve.current.setSelectionRange(e,e))},[ne]);async function Pe(n){O(!0),w(``);try{let r=await rE(er(e,t),t?{action:`configure`,memberIds:n.memberIds,memberModels:n.memberModels,...n.moderator,model:n.moderator.model??null,cloneLimit:n.moderator.cloneLimit??null}:n);if(!r)throw Error(`服务没有返回群聊。`);t?(Ne(r),b(!1)):f(r,Ce.current)}catch(e){w(String(e.message??e))}finally{O(!1)}}async function Fe(n){if(n.preventDefault(),!Ee||De||!ne.trim()||D)return;let r=ne.trim(),i=nE(r),a=ce.filter(e=>i.has(e.text)),o=Ee.members.filter(e=>a.some(t=>t.memberId===e.id)||i.has(tE(e.name))&&Ee.members.filter(t=>t.name===e.name).length===1).map(e=>e.id),s=ue.filter(e=>i.has(e.text)).map(e=>e.path),c=JSON.stringify([Ee.id,r,o,ie,s]);we.current?.signature!==c&&(we.current={signature:c,clientId:Wt()}),O(!0),w(``);try{let n=await rE(er(e,Ee.id),{action:`send`,content:r,memberIds:o,replyTo:ie,filePaths:s,clientId:we.current.clientId});if(!n)throw Error(`服务没有确认收到消息。`);MT(e,t,ne),xe.current=!0,Ne(n),Ce.current&&t===n.id&&(re(``),ae(void 0),le([]),de([]),se(void 0)),we.current=void 0}catch(e){w(String(e.message??e))}finally{O(!1)}}function Ie(e){if(!oe)return;let t;if(e.kind===`member`){let n=e.member,r=tE(n.name);re(ne.slice(0,oe.start)+r+` `+ne.slice(oe.end)),le(e=>[...e.filter(e=>e.text!==r),{memberId:n.id,text:r}]),t=oe.start+r.length+1}else{let n=e.file,r=_f(ne,oe,n),i=r.text.slice(oe.start,r.caret).trimEnd();re(r.text),de(e=>[...e.filter(e=>e.path!==n.path),{path:n.path,text:i}]),t=r.caret}ye.current=t,se(void 0)}async function Le(n){try{let r=await rE(er(e,t),{action:`stop`,postId:n});r&&Ne(r)}catch(e){w(String(e.message??e))}}async function Re(n,i){let a=r?.models.find(e=>QT(e)===i);if(i&&!a)throw Error(`所选模型不可用,请刷新模型列表后重试。`);if(!Ee)throw Error(`群聊尚未加载,请稍后重试。`);let o=await rE(er(e,t),{action:`configure`,memberModels:{[n]:a??null},...Ee.moderator,model:Ee.moderator.model??null,cloneLimit:Ee.moderator.cloneLimit??null});if(!o)throw Error(`服务没有确认模型更改。`);Ne(o);let s=o.members.find(e=>e.id===n)?.model;if((s?QT(s):``)!==i)throw Error(`目标服务端没有应用成员模型设置,可能版本过旧。请先升级目标服务端后重试;群聊历史仍保留。`)}async function ze(n){let r=Ee?.messages.find(e=>e.id===n&&e.role===`assistant`),i=r&&Ee?.messages.find(e=>e.id===r.topicId);if(!r||!i||![`failed`,`interrupted`,`cancelled`].includes(r.status))throw Error(`只能重试已失败或停止的执行。`);let a=Te.current.get(n)??Wt();Te.current.set(n,a);let o=`请使用当前模型继续这次未完成的任务。先检查已有产物,避免重复执行。\n原分工:${r.assignment??`按原请求完成工作`}\n原请求:${i.content}`.slice(0,32e3),s=await rE(er(e,t),{action:`send`,content:o,memberIds:[r.memberId],replyTo:r.id,clientId:a,filePaths:i.role===`user`?i.files?.map(e=>e.path):void 0});if(!s)throw Error(`服务没有确认重试请求。`);Ne(s),Te.current.delete(n)}async function Be(n,r,i){ee(n),w(``);try{let a=await rE(er(e,t),{action:`clone.resolve`,requestId:n,choice:r,name:i});a&&Ne(a)}catch(e){w(e instanceof Error?e.message:String(e))}finally{ee(void 0)}}function Ve(e,t,n,r){S(!1);let i=n.closest(`[data-group-post-id]`)?.querySelector(`[data-group-message-avatar]`)??void 0;_e.current={origin:n,avatar:i},P({memberId:e,name:t,postId:r})}function He(){let e=ge?.memberId;P(void 0);let t=_e.current;requestAnimationFrame(()=>{let n=[...document.querySelectorAll(`[data-group-message-avatar]`)].filter(t=>t.dataset.groupMessageAvatar===e).at(-1);(t?.origin.isConnected?t.origin:t?.avatar?.isConnected?t.avatar:n)?.focus({preventScroll:!0})})}let Ue=Ee?.messages??[],We=Kn(Ue),Ge=Ue.filter(e=>e.role===`assistant`&>(e)).filter((e,t,n)=>n.findIndex(t=>t.memberId===e.memberId)===t),Ke=new Map(Ue.map(e=>[e.id,e])),qe=new Set(Ue.flatMap(e=>e.role===`assistant`&>(e)?[e.memberId]:[])),Je=ge?Ue.filter(e=>e.role===`assistant`&&e.memberId===ge.memberId).reverse():[],Ye;return(0,F.jsxs)(`section`,{className:`group-chat`,"data-group-chat":t,children:[(C||T)&&(0,F.jsx)(`div`,{className:`group-error`,role:`alert`,children:C||T}),!t||y&&!De?(0,F.jsx)(aE,{room:y?Ee:void 0,agents:n,catalog:r,saving:D,onSave:Pe,onCancel:t?()=>b(!1):p}):Ee?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`group-members`,children:[(0,F.jsx)(`div`,{className:`group-roster`,"aria-label":`群成员`,children:Ee.members.map(e=>(0,F.jsxs)(`button`,{type:`button`,className:`group-roster-member`,"data-group-member-avatar":e.id,"aria-label":`查看 ${e.name} 的执行详情${qe.has(e.id)?`,工作中`:``}`,title:`${e.name}${e.agentId?` · 分身 · ${e.worktreePath??e.agentId}`:``}`,"aria-pressed":ge?.memberId===e.id,onClick:t=>Ve(e.id,e.name,t.currentTarget),children:[(0,F.jsx)(YT,{name:e.name,memberId:e.id,busy:qe.has(e.id)}),(0,F.jsxs)(`span`,{children:[e.name,e.agentId?` · 分身`:``]})]},e.id))}),!De&&(0,F.jsx)(`button`,{type:`button`,"data-group-settings":!0,disabled:D,onClick:()=>{w(``),P(void 0),b(!0)},children:`群聊设置`}),(0,F.jsxs)(`button`,{type:`button`,"data-group-rsi":!0,"aria-pressed":x,onClick:()=>{S(e=>!e),P(void 0)},children:[`RSI`,Ee.rsi?.status===`running`?` · 观察中`:Ee.rsi?.status===`failed`?` · 需处理`:``]}),(0,F.jsx)(`button`,{type:`button`,onClick:()=>{m?m():na().then(e=>te(e===`granted`?`系统通知已开启`:`请在浏览器站点设置中允许通知`))},children:`系统通知`})]}),M&&(0,F.jsx)(`p`,{role:`status`,children:M}),(Ee.cloneRequests??[]).filter((e,t,n)=>e.status===`pending`||t>=n.length-3).map(e=>{let t=Ee.members.find(t=>t.id===e.memberId),n=2;for(;Ee.members.some(e=>e.name===`${t?.name??`Agent`} ${n}`);)n+=1;let r=k[e.id]??`${t?.name??`Agent`} ${n}`;return(0,F.jsx)(`section`,{className:`group-clone-request`,"data-clone-request":e.id,"aria-label":`创建 Agent 分身`,children:e.status===`pending`&&e.automatic?(0,F.jsx)(`span`,{children:`主持人正在准备独立分身…`}):e.status===`pending`&&!De?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`strong`,{children:[t?.name??`Agent`,` 正在工作,是否创建分身?`]}),(0,F.jsx)(`p`,{children:e.reason}),(0,F.jsx)(`p`,{children:e.assignment}),(0,F.jsxs)(`form`,{onSubmit:t=>{t.preventDefault(),Be(e.id,`create`,r)},children:[(0,F.jsxs)(`label`,{children:[`分身名字`,(0,F.jsx)(`input`,{maxLength:80,required:!0,value:r,onChange:t=>A(n=>({...n,[e.id]:t.target.value}))})]}),(0,F.jsx)(`button`,{disabled:!!j||!r.trim(),children:j===e.id?`正在准备…`:`创建分身并处理`}),(0,F.jsx)(`button`,{type:`button`,disabled:!!j,onClick:()=>void Be(e.id,`wait`,``),children:`等待空闲`})]}),(0,F.jsx)(`small`,{children:`分身共享源 Agent 的能力与经验,在独立 Git 工作树处理此 case。`})]}):(0,F.jsx)(`span`,{children:e.status===`created`?`已安排 ${Ee.members.find(t=>t.id===e.cloneId)?.name??`分身`}`:e.status===`waiting`?`已选择等待原成员`:`成员或任务状态已变化,无需创建分身`})},e.id)}),(0,F.jsxs)(`div`,{className:`group-stage${ge?` group-stage-inspecting`:``}${x?` group-stage-rsi`:``}`,children:[(0,F.jsxs)(`div`,{className:`group-dialogue`,children:[(0,F.jsxs)(`div`,{className:`group-thread`,ref:be,onScroll:e=>{let t=e.currentTarget;xe.current=t.scrollHeight-t.clientHeight-t.scrollTop<64},children:[!Ue.length&&(0,F.jsx)(`p`,{className:`group-empty`,children:De?`这个群聊没有消息。`:`发条消息开始讨论。用 @ 点名一个或多个成员。`}),We.map(e=>{let t=e.replyTo?Ke.get(e.replyTo):void 0;e.role===`user`&&(Ye=e.id);let n=t&&(e.role===`user`||t.id!==e.topicId||e.topicId!==Ye)?t:void 0,r=Ae(e),i=e.role===`assistant`&&e.background&&e.status===`running`?`后台进行中`:HT[e.status],a=e.role===`assistant`&&ge?.postId===e.id;return(0,F.jsxs)(`article`,{className:`group-post group-post-${e.role}`,"data-group-post":e.role,"data-group-status":e.status,"data-group-post-id":e.id,children:[e.role===`assistant`?(0,F.jsx)(`button`,{className:`group-post-avatar`,type:`button`,"data-group-message-avatar":e.memberId,"aria-label":`查看 ${r} 这次发言的执行详情`,title:`${r} · 执行详情`,"aria-pressed":a,onClick:t=>Ve(e.memberId,r,t.currentTarget,e.id),children:(0,F.jsx)(YT,{name:r,memberId:e.memberId,busy:GT(e)})}):(0,F.jsx)(YT,{name:r}),(0,F.jsxs)(`div`,{className:`group-post-content`,children:[(0,F.jsxs)(`div`,{className:`group-post-head`,children:[(0,F.jsx)(`strong`,{children:r}),e.role===`assistant`&&(0,F.jsx)(`span`,{className:`group-message-model`,"data-group-message-model":e.model?QT(e.model):`unknown`,title:e.model?`${e.model.provider} / ${e.model.modelId}`:`这条历史消息没有记录使用的模型`,children:e.model?`${e.model.label} · ${e.model.provider}`:`模型未记录`}),e.status!==`completed`&&(0,F.jsx)(`span`,{className:`group-post-state`,children:i}),(0,F.jsx)(`time`,{dateTime:Gn(e),children:JT(Gn(e))}),!De&&(0,F.jsxs)(`div`,{className:`group-post-actions`,children:[!GT(e)&&(0,F.jsx)(`button`,{type:`button`,className:`group-reply-action`,disabled:D,onClick:()=>{ae(e.id),ve.current?.focus()},children:`回复`}),GT(e)&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>void Le(e.id),children:`停止`})]})]}),(n||e.content||e.error||e.role===`user`&&e.memoryNotice)&&(0,F.jsxs)(`div`,{className:`group-bubble`,children:[n&&(0,F.jsxs)(`div`,{className:`group-quote`,children:[Ae(n),` · `,n.content.slice(0,120)]}),e.content&&(0,F.jsx)(`div`,{className:`message-body`,children:(0,F.jsx)(ef,{source:e.content,handoffs:!1,sourceLink:e.role===`assistant`&&_?.members.some(t=>t.id===e.memberId&&!t.worktreePath)?g:void 0})}),e.role===`user`&&e.memoryNotice&&(0,F.jsx)(`div`,{className:`group-route`,children:e.memoryNotice}),e.error&&(0,F.jsx)(`p`,{className:`group-error`,children:e.error})]}),e.role===`assistant`&&e.routeReason&&(0,F.jsxs)(`details`,{className:`group-route group-post-footer`,children:[(0,F.jsx)(`summary`,{children:`接话原因`}),e.routeReason]})]})]},e.id)})]}),Ge.length>0&&(0,F.jsx)(`div`,{className:`group-preparing`,"data-group-preparing":!0,role:`group`,"aria-label":`正在准备回复的成员`,children:Ge.map(e=>(0,F.jsx)(`button`,{type:`button`,"data-group-preparing-avatar":e.memberId,title:`${Ae(e)} · 正在准备回复`,"aria-label":`查看 ${Ae(e)} 的准备详情`,"aria-pressed":ge?.memberId===e.memberId,onClick:t=>Ve(e.memberId,Ae(e),t.currentTarget,e.id),children:(0,F.jsx)(YT,{name:Ae(e),memberId:e.memberId,busy:!0})},e.memberId))}),De?(0,F.jsxs)(`div`,{className:`group-archive-notice`,"data-group-archive-notice":!0,children:[(0,F.jsx)(`p`,{children:`群聊已归档。恢复后可继续发消息。`}),(0,F.jsx)(`button`,{type:`button`,"data-group-restore":!0,disabled:o,onClick:()=>s(Ee),children:`恢复群聊`})]}):(0,F.jsxs)(`form`,{className:`group-composer`,onSubmit:Fe,children:[h,Oe&&(0,F.jsxs)(`div`,{className:`group-quote`,children:[`回复 `,Ae(Oe),` · `,Oe.content.slice(0,60),` `,(0,F.jsx)(`button`,{type:`button`,onClick:()=>ae(void 0),"aria-label":`取消引用`,children:`×`})]}),Me.length>0&&(0,F.jsx)(`div`,{className:`group-suggestions`,role:`listbox`,"aria-label":`点名群成员或引用文件`,children:Me.map((e,t)=>(0,F.jsx)(`button`,{type:`button`,role:`option`,"aria-selected":t===me,"data-group-member-option":e.kind===`member`?e.member.id:void 0,onMouseDown:e=>e.preventDefault(),onClick:()=>Ie(e),children:e.kind===`member`?e.member.name:`文件 · ${e.file.path}`},e.kind===`member`?`member:${e.member.id}`:`file:${e.file.path}`))}),(0,F.jsx)(`textarea`,{ref:ve,"data-group-composer":!0,"aria-label":`群聊消息`,placeholder:`输入消息,@ 点名或引用文件`,value:ne,maxLength:32e3,readOnly:D,onChange:e=>{re(e.target.value),se(gf(e.target.value,e.target.selectionStart,e.target.selectionEnd)),he(0)},onSelect:e=>{let t=e.currentTarget;se(gf(t.value,t.selectionStart,t.selectionEnd))},onKeyDown:e=>{e.nativeEvent.isComposing||(Me.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)?(e.preventDefault(),he(t=>(t+Me.length+(e.key===`ArrowDown`?1:-1))%Me.length)):Me.length&&(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey?(e.preventDefault(),Ie(Me[me]??Me[0])):e.key===`Escape`?se(void 0):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit()))}}),(0,F.jsx)(`button`,{type:`submit`,"data-group-send":!0,disabled:!ne.trim()||D,children:`发送`})]})]}),x&&(0,F.jsx)(BT,{source:{kind:`group`,workspaceId:e,id:t},models:r?.models??[],archived:De,onClose:()=>S(!1)}),!x&&ge&&(0,F.jsx)(ZT,{workspaceId:e,roomId:t,memberId:ge.memberId,name:ge.name,runs:Je,postId:ge.postId,onStop:e=>void Le(e),onSelect:e=>P({...ge,postId:e}),onClose:He,models:r?.models??[],memberModel:Ee.members.find(e=>e.id===ge.memberId)?.model,onModelChange:De?void 0:e=>Re(ge.memberId,e),onRetry:De?void 0:ze},ge.memberId)]})]}):!T&&(0,F.jsx)(`p`,{className:`group-empty`,children:`正在加载群聊…`})]})}function aE({room:e,agents:t,catalog:n,saving:r,onSave:i,onCancel:a}){let[o,s]=(0,u.useState)(e?.title??``),[c,l]=(0,u.useState)({}),d=t.filter(e=>e.mode===`primary`&&!e.hidden),f=[...d,...e?.members.filter(e=>!d.some(t=>t.id===e.id))??[]],p=e?.members.map(e=>e.id)??Wn,m=[...new Set([...p,...f.map(e=>e.id)])].filter(e=>f.some(t=>t.id===e)&&(c[e]??p.includes(e))),[h,g]=(0,u.useState)(e?.moderator.model?QT(e.moderator.model):``),[_,v]=(0,u.useState)(e?.moderator.prompt??``),[y,b]=(0,u.useState)(e?.moderator.cloneLimit??0),[x,S]=(0,u.useState)(()=>Object.fromEntries((e?.members??[]).map(e=>[e.id,e.model?QT(e.model):``]))),[C,w]=(0,u.useState)(PT),[T,E]=(0,u.useState)(``),[D,O]=(0,u.useState)(``),[k,A]=(0,u.useState)(``),[j,ee]=(0,u.useState)(eE),[M,te]=(0,u.useState)(``),[N,ne]=(0,u.useState)(``),[re,ie]=(0,u.useState)(``);(0,u.useEffect)(()=>{try{localStorage.setItem($T,JSON.stringify(j))}catch{ie(`浏览器无法保存预设,请检查本地存储空间或隐私设置。`)}},[j]);let ae=[...n?.models??[]];if(e?.moderator.model&&!ae.some(t=>QT(t)===QT(e.moderator.model))){let t=e.moderator.model;n||ae.push(t)}let oe=()=>Object.fromEntries(m.map(e=>[e,ae.find(t=>QT(t)===x[e])??null])),se=()=>({prompt:_,cloneLimit:y||void 0,model:ae.find(e=>QT(e)===h)}),ce=!(!h||ae.some(e=>QT(e)===h))||m.some(e=>x[e]&&!ae.some(t=>QT(t)===x[e])),le=e=>{try{return localStorage.setItem(NT,JSON.stringify(e)),w(e),!0}catch{return A(`浏览器无法保存群聊预设,请检查本地存储空间或隐私设置。`),!1}};return(0,F.jsxs)(`form`,{className:`group-settings`,onSubmit:e=>{e.preventDefault();let t=ae.find(e=>QT(e)===h);h&&!t||ce||i({title:o,memberIds:m,memberModels:oe(),moderator:se()})},children:[(0,F.jsxs)(`div`,{className:`group-settings-heading`,children:[(0,F.jsx)(`h2`,{children:e?`群聊设置`:`创建群聊`}),(0,F.jsx)(`p`,{children:`安排成员与模型,让主持人协调讨论和执行。`})]}),(0,F.jsxs)(`section`,{className:`group-settings-card`,"data-group-presets":!0,children:[(0,F.jsx)(`h3`,{children:`群聊预设`}),(0,F.jsx)(`p`,{className:`group-settings-hint`,children:`一并保存成员、各自模型和主持人设置。`}),(0,F.jsxs)(`label`,{children:[`加载群聊预设`,(0,F.jsxs)(`select`,{"aria-label":`加载群聊预设`,value:T,onChange:e=>{E(e.target.value);let t=C.find(t=>t.id===e.target.value);if(!t)return;O(t.name),l(Object.fromEntries([...new Set([...p,...f.map(e=>e.id),...t.memberIds])].map(e=>[e,t.memberIds.includes(e)]))),S(Object.fromEntries(Object.entries(t.memberModels).map(([e,t])=>[e,t?QT(t):``]))),v(t.moderator.prompt),g(t.moderator.model?QT(t.moderator.model):``),b(t.moderator.cloneLimit??0);let n=t.memberIds.filter(e=>!f.some(t=>t.id===e));A(n.length?`已加载「${t.name}」。${n.length} 位成员在当前服务端不可用,请检查成员列表后保存。`:`已加载「${t.name}」。可继续调整,不影响其他群聊。`)},children:[(0,F.jsx)(`option`,{value:``,children:`选择预设…`}),C.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,F.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,F.jsx)(`input`,{"aria-label":`群聊预设名称`,placeholder:`例如:日常开发评审`,value:D,maxLength:80,onChange:e=>O(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,disabled:!D.trim()||m.length<2||ce,onClick:()=>{let t=D.trim(),n=C.find(e=>e.name.toLocaleLowerCase()===t.toLocaleLowerCase()),r=m.map(t=>e?.members.find(e=>e.id===t)?.agentId??t),i=oe(),a={id:n?.id??Wt(),name:t,memberIds:[...new Set(r)],memberModels:Object.fromEntries(r.map((e,t)=>[e,i[m[t]]])),moderator:se()};le(n?C.map(e=>e.id===n.id?a:e):[a,...C].slice(0,100))&&(E(a.id),A(`已保存群聊预设「${t}」。`))},children:`保存预设`}),T&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>{le(C.filter(e=>e.id!==T))&&(E(``),A(`群聊预设已删除。`))},children:`删除`})]}),k&&(0,F.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:k})]}),!e&&(0,F.jsxs)(`label`,{children:[`群名`,(0,F.jsx)(`input`,{autoFocus:!0,value:o,onChange:e=>s(e.target.value),maxLength:100,required:!0})]}),(0,F.jsxs)(`fieldset`,{className:`group-member-settings`,children:[(0,F.jsx)(`legend`,{children:`群成员与模型`}),f.map(e=>(0,F.jsxs)(`div`,{className:`group-member-card`,"data-selected":m.includes(e.id),children:[(0,F.jsxs)(`label`,{className:`group-choice`,title:e.description,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-group-member-choice":e.id,checked:m.includes(e.id),disabled:!m.includes(e.id)&&m.length>=8,onChange:t=>{let n=t.target.checked;l(t=>({...t,[e.id]:n}))}}),(0,F.jsx)(YT,{name:e.name,memberId:e.id}),(0,F.jsxs)(`span`,{children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{children:e.description})]})]}),m.includes(e.id)&&(0,F.jsx)(IT,{label:`${e.name} 的模型`,value:x[e.id]??``,models:ae,onChange:t=>S(n=>({...n,[e.id]:t}))})]},e.id))]}),(0,F.jsx)(`p`,{className:`group-settings-hint`,children:`取消勾选可移除成员。请选择 2 到 8 位主 Agent。`}),(0,F.jsxs)(`details`,{className:`group-settings-card`,open:!0,children:[(0,F.jsx)(`summary`,{children:`主持人设置`}),(0,F.jsxs)(`label`,{children:[`同类 Agent 分身`,(0,F.jsxs)(`select`,{value:y,onChange:e=>b(Number(e.target.value)),children:[(0,F.jsx)(`option`,{value:0,children:`创建前询问我`}),[2,3,4,8].map(e=>(0,F.jsxs)(`option`,{value:e,children:[`允许自动创建 · 同类最多 `,e,` 人`]},e))]})]}),(0,F.jsxs)(`div`,{className:`group-model-field`,children:[(0,F.jsx)(`span`,{children:`主持人模型`}),(0,F.jsx)(IT,{label:`主持人模型`,value:h,models:ae,onChange:g})]}),(0,F.jsxs)(`label`,{children:[`主持人 Prompt`,(0,F.jsx)(`textarea`,{value:_,maxLength:8e3,onChange:e=>v(e.target.value),placeholder:`例如:先请最熟悉模块的成员回答,结论足够时结束。`})]}),(0,F.jsxs)(`details`,{className:`group-prompt-presets`,"data-moderator-prompt-presets":!0,children:[(0,F.jsx)(`summary`,{children:`旧版 Prompt 预设`}),(0,F.jsxs)(`label`,{children:[`加载已保存的 Prompt`,(0,F.jsxs)(`select`,{"aria-label":`加载主持人 Prompt 预设`,value:M,onChange:e=>{let t=j.find(t=>t.id===e.target.value);te(e.target.value),t?(v(t.prompt),ne(t.name),ie(`已加载「${t.name}」,可继续修改后用于当前群聊。`)):ie(``)},children:[(0,F.jsx)(`option`,{value:``,children:`选择预设…`}),j.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,F.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,F.jsx)(`input`,{"aria-label":`Prompt 预设名称`,value:N,maxLength:80,onChange:e=>ne(e.target.value),placeholder:`预设名称`}),(0,F.jsx)(`button`,{type:`button`,disabled:!N.trim()||!_.trim(),onClick:()=>{let e=N.trim(),t=j.find(t=>t.name.toLocaleLowerCase()===e.toLocaleLowerCase()),n={id:t?.id??Wt(),name:e,prompt:_};ee(e=>t?e.map(e=>e.id===t.id?n:e):[n,...e].slice(0,100)),te(n.id),ie(`已保存「${e}」。`)},children:`保存预设`}),M&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>{let e=j.find(e=>e.id===M);ee(e=>e.filter(e=>e.id!==M)),te(``),ne(``),ie(e?`已删除「${e.name}」。`:`预设已删除。`)},children:`删除预设`})]}),re&&(0,F.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:re})]})]}),(0,F.jsxs)(`div`,{className:`group-settings-actions`,children:[(0,F.jsx)(`button`,{type:`button`,disabled:r,onClick:a,children:`取消`}),(0,F.jsx)(`button`,{type:`submit`,disabled:r||!o.trim()||m.length<2||m.length>8||ce,children:e?`保存`:`创建群聊`})]})]})}var oE=`__pi_default__`;function sE({workspaces:e,catalog:t,onClose:n,onSave:r}){let[i,a]=(0,u.useState)(oE),[o,s]=(0,u.useState)(oE);(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]);let c=t.models.find(e=>`${e.provider}/${e.modelId}`===i),l=c?.provider===t.defaultModel?.provider&&c?.modelId===t.defaultModel?.modelId,d=c?.thinkingLevels??(l?t.levels:[]),f=c?{provider:c.provider,modelId:c.modelId,label:c.label}:void 0;return(0,F.jsx)(`div`,{className:`overlay`,onClick:n,children:(0,F.jsxs)(`div`,{className:`picker settings-dialog bulk-workspace-settings`,"data-bulk-workspace-settings":`1`,onClick:e=>e.stopPropagation(),children:[(0,F.jsx)(`h2`,{children:`批量设置工作区`}),(0,F.jsxs)(`div`,{className:`settings-scope`,children:[`将统一修改 `,e.length,` 个现存工作区的默认模型与思考等级,只影响之后新建的会话。`]}),(0,F.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,F.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认模型`,value:i,disabled:t.source!==`pi`,onChange:e=>{a(e.target.value),s(oE)},children:[(0,F.jsx)(`option`,{value:oE,children:`跟随 Pi 默认`}),t.models.map(e=>(0,F.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,` · `,e.provider]},`${e.provider}/${e.modelId}`))]})]}),(0,F.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认思考等级`}),(0,F.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认思考等级`,value:o,disabled:!c||t.source!==`pi`,onChange:e=>s(e.target.value),children:[(0,F.jsx)(`option`,{value:oE,children:`跟随 Pi 默认`}),d.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))]})]}),c&&d.length===0&&(0,F.jsx)(`p`,{className:`bulk-settings-note`,children:`Pi 没有为此模型提供可选择的思考等级;新会话会使用 Pi 默认值。`}),(0,F.jsxs)(`div`,{className:`bulk-settings-workspaces`,"aria-label":`将被更新的工作区`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`应用到`}),(0,F.jsx)(`div`,{children:e.map(e=>(0,F.jsx)(`span`,{children:e.name},e.id))})]}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!e.length||t.source!==`pi`,onClick:()=>r(f,o===oE?void 0:o),children:`应用到全部工作区`})]})]})})}function cE({glyph:e,className:t}){return(0,F.jsx)(`span`,{className:t,"data-tool-glyph-length":Math.min(4,Math.max(1,Array.from(e).length)),"aria-hidden":`true`,children:e})}function lE(e){if(e!==void 0){if(typeof e!=`string`||!e.trim()||Array.from(e.trim()).length>4||/[<>\u0000-\u001f\u007f]/.test(e))throw Error(`工具图标须为 1 至 4 个字符的文字或符号`);return e.trim()}}function uE(e){try{let t=lE(e.glyph);if(t)return t}catch{}let t=`${e.name} ${e.slug??``}`.toLowerCase();return[[/json/,`{}`],[/正则|regex/,`.*`],[/计算|calc/,`∑`],[/时间|timestamp|date/,`◷`],[/差异|diff/,`±`],[/markdown/,`M↓`],[/图像|图片|image/,`▧`],[/表格|csv|excel/,`▦`],[/颜色|color/,`◐`],[/base64/,`64`],[/hash|哈希/,`#`],[/git/,`⑂`]].find(([e])=>e.test(t))?.[1]??(Array.from(e.name.trim()).slice(0,2).join(``)||`◇`)}function dE(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function fE(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}function pE(e){let t=new Map;for(let[n,r]of e.entries())t.has(r.id)||t.set(r.id,n);return t}function mE(e,t){if(!t||t.length===0)return e;let n=new Map(t.map((e,t)=>[e,t])),r=e.filter(e=>n.has(e.id)).sort((e,t)=>(n.get(e.id)??0)-(n.get(t.id)??0));return[...e.filter(e=>!n.has(e.id)),...r]}function hE(e,t,n){if(e.indexOf(t)<0)return[...e];let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(n,r.length));return[...r.slice(0,i),t,...r.slice(i)]}var gE=`super-pi.session-order.v1`;function _E(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.session-order.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.filter(e=>typeof e==`string`));return t}catch{return{}}}function vE(e){try{typeof window<`u`&&window.localStorage.setItem(gE,JSON.stringify(e))}catch{}}function yE(e,t,n){let r=new Set(e.map(e=>e.id)),i=pE(e),a=(e,t)=>(i.get(e.id)??2**53-1)-(i.get(t.id)??2**53-1),o=new Map,s=[];for(let t of e){let e=t.parentConversationId;if(e&&r.has(e)){let n=o.get(e);n?n.push(t):o.set(e,[t])}else s.push(t)}for(let e of o.values())e.sort(a);let c=mE(s.sort(a),n?.manualRoots),l=[],u=new Set,d=(e,n,r,i=!0)=>{if(u.has(e.id))return;u.add(e.id);let a=o.get(e.id)??[];i&&l.push({conversation:e,depth:Math.min(n,8),childCount:a.length,isLastSibling:r});let s=!i||t.has(e.id);for(let[e,t]of a.entries())d(t,n+1,e===a.length-1,!s)};for(let e of c)d(e,0,!1);let f=e.filter(e=>!u.has(e.id)).sort(a);for(let e of f)d(e,0,!1);return l}var bE=`super-pi:tool-shortcuts:v1`,xE=new Set([`Control`,`Alt`,`Shift`,`Meta`,`AltGraph`,`CapsLock`,`Fn`,`FnLock`,`Hyper`,`Super`,`Symbol`,`SymbolLock`]),SE=new Set([`Escape`]),CE=new Set([`Enter`,` `,`Tab`]),wE={" ":`Space`,ArrowUp:`↑`,ArrowDown:`↓`,ArrowLeft:`←`,ArrowRight:`→`,Escape:`Esc`},TE={ctrl:`⌃`,alt:`⌥`,shift:`⇧`,meta:`⌘`};function EE(e){if(e===` `)return` `;let t=e.trim();return t?t.length===1?t.toLowerCase():t:``}function DE(e){return xE.has(e)}function OE(e){let t=e.key;if(!t||t===`Unidentified`||t===`Dead`||DE(t))return;let n=EE(t);if(!n)return;let r=!!e.shiftKey;if(r&&n.length===1&&!/[a-z]/.test(n)){let t=/^Digit([0-9])$/.exec(e.code??``);t&&(n=t[1])}let i={key:n};return e.ctrlKey&&(i.ctrl=!0),e.altKey&&(i.alt=!0),r&&(i.shift=!0),e.metaKey&&(i.meta=!0),i}function kE(e){return wE[e]||(e.length===1||/^f\d{1,2}$/.test(e)?e.toUpperCase():e)}function AE(e){let t=[];return e.ctrl&&t.push(`Ctrl`),e.alt&&t.push(`Alt`),e.shift&&t.push(`Shift`),e.meta&&t.push(`Meta`),t.push(kE(e.key)),t.join(`+`)}function jE(e){let t=``;return e.ctrl&&(t+=TE.ctrl),e.alt&&(t+=TE.alt),e.shift&&(t+=TE.shift),e.meta&&(t+=TE.meta),t+kE(e.key)}function ME(e,t){return e.key===t.key&&!!e.ctrl==!!t.ctrl&&!!e.alt==!!t.alt&&!!e.shift==!!t.shift&&!!e.meta==!!t.meta}function NE(e){return!!(e.ctrl||e.alt||e.shift||e.meta)}function PE(e){return e.key?SE.has(e.key)?{ok:!1,reason:`Esc 是所有弹窗的退出键,不能拿来当工具快捷键。`}:!NE(e)&&CE.has(e.key)?{ok:!1,reason:`「${FE(e.key)}」是当前焦点控件的激活键,加一个修饰键(Ctrl / Alt / Shift)才能当快捷键用。`}:{ok:!0}:{ok:!1,reason:`这个组合键不完整,请按一个具体的键。`}}function FE(e){return kE(e)}function IE(e){let t=e;if(!t||typeof t!=`object`)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable===!0}function LE(e,t){if(t.isComposing||t.defaultPrevented)return!1;let n=OE(t);return!(!n||!ME(e,n)||!NE(e)&&IE(t.target??null))}function RE(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){if(!e||typeof r!=`object`||!r)continue;let t=r,i=EE(typeof t.key==`string`?t.key:``);if(!i)continue;let a={key:i};t.ctrl===!0&&(a.ctrl=!0),t.alt===!0&&(a.alt=!0),t.shift===!0&&(a.shift=!0),t.meta===!0&&(a.meta=!0),PE(a).ok&&(n[e]=a)}return n}function zE(e){let t={};for(let n of Object.keys(e).sort()){let r=e[n];if(!r)continue;let i={key:r.key};r.ctrl&&(i.ctrl=!0),r.alt&&(i.alt=!0),r.shift&&(i.shift=!0),r.meta&&(i.meta=!0),t[n]=i}return JSON.stringify(t)}function BE(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&ME(i,t))return r}var VE=`super-pi:tool-settings-size:v1`,HE={width:480,height:320};function UE(){try{if(typeof window>`u`)return It.slice();let e=Ht(window.localStorage.getItem(zt));return window.localStorage.getItem(`super-pi:tools:v1`)===null?It.slice():e}catch{return It.slice()}}function WE(e){try{if(typeof window>`u`)return;window.localStorage.setItem(zt,Ut(e))}catch{}}function GE(){try{return typeof window>`u`?{}:RE(window.localStorage.getItem(bE))}catch{return{}}}function KE(e){try{if(typeof window>`u`)return;window.localStorage.setItem(bE,zE(e))}catch{}}function qE(e,t,n){let r={};for(let n of t)e[n.id]&&(r[n.id]=e[n.id]);for(let e of n)e.shortcut&&(r[e.id]=e.shortcut);return r}function JE(){try{if(typeof window>`u`)return;let e=window.localStorage.getItem(VE);if(!e)return;let t=JSON.parse(e);return typeof t?.width!=`number`||typeof t?.height!=`number`||!Number.isFinite(t.width)||!Number.isFinite(t.height)||t.width<HE.width||t.height<HE.height?void 0:{width:Math.round(t.width),height:Math.round(t.height)}}catch{return}}function YE(e){try{if(typeof window>`u`)return;e?window.localStorage.setItem(VE,JSON.stringify({width:Math.round(e.width),height:Math.round(e.height)})):window.localStorage.removeItem(VE)}catch{}}function XE(e,t,n){let r=Math.max(HE.width,t-32),i=Math.max(HE.height,n-32);return{width:Math.round(Math.min(Math.max(e.width,HE.width),r)),height:Math.round(Math.min(Math.max(e.height,HE.height),i))}}var ZE=GE(),QE={tools:UE(),mountedTools:[],settingsOpen:!1,shortcuts:{}};QE.shortcuts=qE(ZE,QE.tools,QE.mountedTools);var $E=new Set;function eD(e){QE={...QE,...e};for(let e of $E)e()}function tD(e){return $E.add(e),()=>{$E.delete(e)}}var nD=()=>QE;function rD(){return(0,u.useSyncExternalStore)(tD,nD,nD)}var iD={setTools(e){WE(e);let t=new Set(e.map(e=>e.id));ZE=Object.fromEntries(Object.entries(ZE).filter(([e])=>t.has(e))),KE(ZE),eD({tools:e,shortcuts:qE(ZE,e,QE.mountedTools)})},removeTool(e){let t=qt(QE.tools,e);ZE[e]&&(ZE={...ZE},delete ZE[e],KE(ZE)),WE(t),eD({tools:t,shortcuts:qE(ZE,t,QE.mountedTools),openToolId:QE.openToolId===e?void 0:QE.openToolId})},setMountedTools(e){let t=new Set(QE.tools.map(e=>e.id));ZE=Object.fromEntries(Object.entries(ZE).filter(([e])=>t.has(e))),KE(ZE),eD({mountedTools:e,shortcuts:qE(ZE,QE.tools,e)})},openTool(e){eD({openToolId:e,settingsOpen:!1})},closeTool(){eD({openToolId:void 0})},toggleTool(e){QE.openToolId===e?iD.closeTool():iD.openTool(e)},openSettings(){eD({settingsOpen:!0,openToolId:void 0})},closeSettings(){eD({settingsOpen:!1})},async setShortcut(e,t){let n=QE.mountedTools.find(t=>t.id===e);if(n){try{let e=await Ne(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:n.slug,shortcut:t})}),r=await e.json();if(!e.ok)return r.error??`快捷键保存失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}eD({mountedTools:QE.mountedTools.map(n=>n.id===e?{...n,shortcut:t}:n),shortcuts:{...QE.shortcuts,[e]:t}})}else ZE={...ZE,[e]:t},KE(ZE),eD({shortcuts:qE(ZE,QE.tools,QE.mountedTools)})},async clearShortcut(e){if(!QE.shortcuts[e])return;let t=QE.mountedTools.find(t=>t.id===e);if(t){try{let e=await Ne(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:t.slug,shortcut:null})}),n=await e.json();if(!e.ok)return n.error??`快捷键清除失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}eD({mountedTools:QE.mountedTools.map(t=>t.id===e?{...t,shortcut:void 0}:t),shortcuts:Object.fromEntries(Object.entries(QE.shortcuts).filter(([t])=>t!==e))})}else ZE={...ZE},delete ZE[e],KE(ZE),eD({shortcuts:qE(ZE,QE.tools,QE.mountedTools)})},persistTools(){WE(QE.tools)}};async function aD(){let e=fe();try{let t=await Ne(`/api/tools`),n=await t.json();fe()===e&&t.ok&&Array.isArray(n.tools)&&iD.setMountedTools(n.tools.filter(e=>e.enabled))}catch{}}async function oD(e){try{let t=await Ne(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);iD.closeTool(),await aD();return}catch(e){return e instanceof Error?e.message:String(e)}}var sD=`.super-pi-tool.json`,cD=512e3,lD=/^[a-z0-9][a-z0-9-]{0,63}$/,uD=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function dD(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${sD})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i;try{i=lE(r.glyph)}catch{return{ok:!1,reason:`工具图标须为 1 至 4 个字符的文字或符号。`}}let a=typeof r.format==`string`?r.format:void 0;if(a!==void 0&&a!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${a})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let o=typeof r.slug==`string`?r.slug.trim():``,s=typeof r.name==`string`?r.name.trim():``;if(!o)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!s)return{ok:!1,reason:`这个工具包里没有名字。`};if(!Array.isArray(r.files)||!r.files.length)return{ok:!1,reason:`这个工具包里没有文件。`};if(r.files.length>32)return{ok:!1,reason:`文件太多了:${r.files.length} 个,上限 32 个。`};let c=[],l=0;for(let e of r.files){let t=e;if(!t||typeof t.path!=`string`||typeof t.content!=`string`)return{ok:!1,reason:`工具包里的文件项格式不对(每一项都要有 path 和 content)。`};let n=t.path.trim();if(!n||n.startsWith(`/`)||n.includes(`\\`)||n.includes(`\0`)||n.split(`/`).includes(`..`))return{ok:!1,reason:`文件路径「${n}」不合法:不能是绝对路径,也不能跳出工具自己的目录。`};if(c.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(l+=new TextEncoder().encode(t.content).length,l>512e3)return{ok:!1,reason:`工具文件合计超过 ${yD(cD)} 的上限。`};c.push({path:n,content:t.content})}let u=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!u.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!c.some(e=>e.path===u))return{ok:!1,reason:`工具包里没有包含入口文件 ${u}。`};let d;if(r.script!==void 0&&r.script!==null){let e=r.script,t=typeof e.path==`string`?e.path.trim():``;if(!t.endsWith(`.py`))return{ok:!1,reason:`工具包声明的脚本必须是一个 .py 文件。`};if(!c.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};d={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let f;if(r.environment!==void 0&&r.environment!==null){let e=r.environment,t=e.requires;if(t!==void 0&&!Array.isArray(t))return{ok:!1,reason:`工具包声明的依赖列表格式不对(requires 必须是数组)。`};if(Array.isArray(t)){for(let e of t)if(typeof e!=`string`||!uD.test(e.trim()))return{ok:!1,reason:`依赖必须钉死到精确版本(写成 pkg==version):${String(e).slice(0,60)}。`}}let n=e.fingerprint&&typeof e.fingerprint==`object`?e.fingerprint:void 0;f={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let p=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:a===void 0,bundle:{...a===void 0?{}:{format:a},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:o,name:s,...i?{glyph:i}:{},...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:u,files:c,script:d,environment:f,...p?{permissions:p}:{}}}}function fD(e){let t=e.trim().toLowerCase();return t?lD.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function pD(e,t){let n=e.trim().toLowerCase().slice(0,60).replace(/[^a-z0-9-]+/g,`-`).replace(/^-+|-+$/g,``)||`tool`;if(!t.includes(n))return n;for(let e=2;e<100;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return n}function mD(e){return`${e.slug}${sD}`}function hD(e){let t=e.trim().replace(/[\\/:*?"<>|]/g,``).replace(/\.+$/,``).trim();return t?t.length>80?{ok:!1,reason:`文件名太长了,请控制在 80 个字符以内。`}:{ok:!0,name:t.endsWith(`.super-pi-tool.json`)?t:`${t}${sD}`}:{ok:!1,reason:`请填写文件名。`}}function gD(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function _D(e){let t=e.environment?.requires??[];return!e.script&&t.length===0?{tone:`ok`,text:`纯页面工具 · 导入即用,不需要 Python`}:t.length===0?{tone:`ok`,text:`只用 Python 标准库 · 导入即用,不需要安装任何包${e.environment?.requiresPython?`(需要 Python ${e.environment.requiresPython})`:``}`}:{tone:`warn`,text:`首次运行时会安装 ${t.length} 个依赖:${t.join(`、`)}(装进这个工具自己的虚拟环境)${e.environment?.requiresPython?` · 需要 Python ${e.environment.requiresPython}`:``}`}}function vD(e){if(e)return e.state===`zero-deps`?{text:`零依赖`,warn:!1}:e.state===`ready`?{text:`环境就绪`,warn:!1}:e.state===`needs-env`?{text:`首次运行时安装依赖`,warn:!1}:e.state===`needs-python`?{text:`缺少可用的 Python`,warn:!0}:{text:`与导出方环境不一致`,warn:!0}}function yD(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function bD(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var xD=`请基于上面的请求、已输出的内容和已完成的操作继续完成任务。优先给出简洁结论或执行必要的小步骤,不要重复已有内容或已成功的写入。`;function SD(e){return/^\s*<continue_output>([\s\S]*?)<\/continue_output>\s*$/.exec(e)?.[1].trim()}function CD(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function wD(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function TD(e,t){if(!e)return 0;let n=0;for(let r of t)n+=e[r]??0;return n}var ED=128e3;function DD(e){let t=[[]],n=0,r=0,i=[0,0],a=e=>{for(;t.length<=e;)t.push([])},o=e=>{let i=t[n];for(;i.length<r;)i.push(` `);for(let t of e)i[r]=t,r+=1},s=e=>e.replace(/^[?>!]/u,``).split(`;`).map(e=>Number.parseInt(e,10)||0),c=(e,o)=>{let c=s(e),l=Math.max(1,c[0]||1);switch(o){case`A`:n=Math.max(0,n-l);break;case`B`:case`e`:n+=l,a(n);break;case`C`:case`a`:r+=l;break;case`D`:r=Math.max(0,r-l);break;case`E`:n+=l,a(n),r=0;break;case`F`:n=Math.max(0,n-l),r=0;break;case`G`:case"`":r=Math.max(0,l-1);break;case`d`:n=Math.max(0,l-1),a(n);break;case`H`:case`f`:n=Math.max(0,l-1),a(n),r=Math.max(0,(c[1]||1)-1);break;case`K`:{let e=t[n];(c[0]??0)===2?t[n]=[]:(c[0]??0)===1?t[n]=[...Array.from({length:Math.min(r+1,e.length)},()=>` `),...e.slice(r+1)]:e.splice(r);break}case`J`:(c[0]??0)===2||(c[0]??0)===3?(t.splice(0,t.length,[]),n=0,r=0):(c[0]??0)===0?t.splice(n+1):(c[0]??0)===1&&(t.splice(0,n),n=0,t[0]=[]);break;case`s`:i=[n,r];break;case`u`:[n,r]=i,a(n);break;case`P`:t[n].splice(r,l);break;case`X`:{let e=t[n];for(let t=r;t<Math.min(e.length,r+l);t+=1)e[t]=` `;break}case`@`:t[n].splice(r,0,...Array.from({length:l},()=>` `))}},l=t=>{for(let n=t;n<e.length;n+=1){if(e[n]===`\x07`)return n+1;if(e[n]===`\x1B`&&e[n+1]===`\\`)return n+2}return e.length};for(let t=0;t<e.length;){let i=e[t];if(i===``||i===``||i===``||i===``){t=l(t+1);continue}if(i===`\x1B`||i===``){let n=e[t+1];if(i===`\x1B`&&(n===`]`||n===`P`||n===`^`||n===`_`)){t=l(t+2);continue}if(i===`\x1B`&&n===`[`||i===``){let n=t+(i===``?1:2),r=n;for(;r<e.length&&!(e.charCodeAt(r)>=64&&e.charCodeAt(r)<=126);)r+=1;r<e.length&&c(e.slice(n,r),e[r]),t=Math.min(e.length,r+1);continue}t+=n===void 0?1:2;continue}if(i===`\r`){t+=1,r=0;continue}if(i===`
|
|
327
|
+
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Ox&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Zx(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=fx(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Qx),Qx),t/=Qx,t/Math.abs(t)+Math.round(t*($x-1)))}shouldForceSelection(e){return wx?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),eS)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(wx&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<tS&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=Lx(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Zx(n,this._bufferService.cols)}};rS=bg([xg(3,Jg),xg(4,Xg),xg(5,c_),xg(6,e_),xg(7,l_),xg(8,s_)],rS);var iS=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},aS=class{constructor(){this._color=new iS,this._css=new iS}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},oS=Object.freeze((()=>{let e=[Pb.toColor(`#2e3436`),Pb.toColor(`#cc0000`),Pb.toColor(`#4e9a06`),Pb.toColor(`#c4a000`),Pb.toColor(`#3465a4`),Pb.toColor(`#75507b`),Pb.toColor(`#06989a`),Pb.toColor(`#d3d7cf`),Pb.toColor(`#555753`),Pb.toColor(`#ef2929`),Pb.toColor(`#8ae234`),Pb.toColor(`#fce94f`),Pb.toColor(`#729fcf`),Pb.toColor(`#ad7fa8`),Pb.toColor(`#34e2e2`),Pb.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Mb.toCss(r,i,a),rgba:Mb.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Mb.toCss(n,n,n),rgba:Mb.toRgba(n,n,n)})}return e})()),sS=Pb.toColor(`#ffffff`),cS=Pb.toColor(`#000000`),lS=Pb.toColor(`#ffffff`),uS=cS,dS={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},fS=sS,pS=class extends L_{constructor(e){super(),this._optionsService=e,this._contrastCache=new aS,this._halfContrastCache=new aS,this._onChangeColors=this._register(new Q),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:sS,background:cS,cursor:lS,cursorAccent:uS,selectionForeground:void 0,selectionBackgroundTransparent:dS,selectionBackgroundOpaque:Nb.blend(cS,dS),selectionInactiveBackgroundTransparent:dS,selectionInactiveBackgroundOpaque:Nb.blend(cS,dS),scrollbarSliderBackground:Nb.opacity(sS,.2),scrollbarSliderHoverBackground:Nb.opacity(sS,.4),scrollbarSliderActiveBackground:Nb.opacity(sS,.5),overviewRulerBorder:sS,ansi:oS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=mS(e.foreground,sS),t.background=mS(e.background,cS),t.cursor=Nb.blend(t.background,mS(e.cursor,lS)),t.cursorAccent=Nb.blend(t.background,mS(e.cursorAccent,uS)),t.selectionBackgroundTransparent=mS(e.selectionBackground,dS),t.selectionBackgroundOpaque=Nb.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=mS(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Nb.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?mS(e.selectionForeground,jb):void 0,t.selectionForeground===jb&&(t.selectionForeground=void 0),Nb.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Nb.opacity(t.selectionBackgroundTransparent,.3)),Nb.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Nb.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=mS(e.scrollbarSliderBackground,Nb.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=mS(e.scrollbarSliderHoverBackground,Nb.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=mS(e.scrollbarSliderActiveBackground,Nb.opacity(t.foreground,.5)),t.overviewRulerBorder=mS(e.overviewRulerBorder,fS),t.ansi=oS.slice(),t.ansi[0]=mS(e.black,oS[0]),t.ansi[1]=mS(e.red,oS[1]),t.ansi[2]=mS(e.green,oS[2]),t.ansi[3]=mS(e.yellow,oS[3]),t.ansi[4]=mS(e.blue,oS[4]),t.ansi[5]=mS(e.magenta,oS[5]),t.ansi[6]=mS(e.cyan,oS[6]),t.ansi[7]=mS(e.white,oS[7]),t.ansi[8]=mS(e.brightBlack,oS[8]),t.ansi[9]=mS(e.brightRed,oS[9]),t.ansi[10]=mS(e.brightGreen,oS[10]),t.ansi[11]=mS(e.brightYellow,oS[11]),t.ansi[12]=mS(e.brightBlue,oS[12]),t.ansi[13]=mS(e.brightMagenta,oS[13]),t.ansi[14]=mS(e.brightCyan,oS[14]),t.ansi[15]=mS(e.brightWhite,oS[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=mS(e.extendedAnsi[r],oS[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};pS=bg([xg(0,e_)],pS);function mS(e,t){if(e!==void 0)try{return Pb.toColor(e)}catch{}return t}var hS=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},gS=class{constructor(){this._services=new hS,this._services.set(Qg,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Gg(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},_S={trace:0,debug:1,info:2,warn:3,error:4,off:5},vS=`xterm.js: `,yS=class extends L_{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),bS=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=_S[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:vS)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};yS=bg([xg(0,e_)],yS);var bS,xS=class extends L_{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Q),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Q),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Q),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},SS=3,CS=Object.freeze(new zg),wS=0,TS=2,ES=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*SS);let r=t||Vg.fromCharData([0,Lg,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*SS+0],n=t&2097151;return[this._data[e*SS+1],t&2097152?this._combined[e]:n?Ng(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*SS+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*SS+0]=e|2097152|t[2]<<22):this._data[e*SS+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*SS+0]>>22}hasWidth(e){return this._data[e*SS+0]&12582912}getFg(e){return this._data[e*SS+1]}getBg(e){return this._data[e*SS+2]}hasContent(e){return this._data[e*SS+0]&4194303}getCodePoint(e){let t=this._data[e*SS+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*SS+0]&2097152}getString(e){let t=this._data[e*SS+0];return t&2097152?this._combined[e]:t&2097151?Ng(t&2097151):``}isProtected(e){return this._data[e*SS+2]&536870912}loadCell(e,t){return wS=e*SS,t.content=this._data[wS+0],t.fg=this._data[wS+1],t.bg=this._data[wS+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*SS+0]=t.content,this._data[e*SS+1]=t.fg,this._data[e*SS+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*SS+0]=t|n<<22,this._data[e*SS+1]=r.fg,this._data[e*SS+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*SS+0];r&2097152?this._combined[e]+=Ng(t):r&2097151?(this._combined[e]=Ng(r&2097151)+Ng(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*SS+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Vg;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Vg;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*TS<this._data.buffer.byteLength;let n=e*SS;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*TS<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*TS<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*SS+0]&4194303)return e+(this._data[e*SS+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*SS+0]&4194303||this._data[e*SS+2]&50331648)return e+(this._data[e*SS+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<SS;e++)this._data[(n+i)*SS+e]=a[(t+i)*SS+e];a[(t+i)*SS+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<SS;e++)this._data[(n+i)*SS+e]=a[(t+i)*SS+e];a[(t+i)*SS+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*SS+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Ng(n):Rg;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function DS(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=jS(u,d,t),p=1,m=0;for(;p<u.length;){let e=jS(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function OS(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function kS(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function AS(e,t,n){let r=[],i=e.map((n,r)=>jS(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=jS(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function jS(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var MS=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Q),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),M_(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};MS._nextId=1;var NS=MS,PS={},FS=PS.B;PS[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:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},PS.A={"#":`£`},PS.B=void 0,PS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},PS.C=PS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},PS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},PS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},PS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},PS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},PS.E=PS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},PS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},PS.H=PS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},PS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var IS=4294967295,LS=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=CS.clone(),this.savedCharset=FS,this.markers=[],this._nullCell=Vg.fromCharData([0,Lg,1,0]),this._whitespaceCell=Vg.fromCharData([0,Rg,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Nx,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new xS(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Bg),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Bg),this._whitespaceCell}getBlankLine(e,t){return new ES(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>IS?IS:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=CS);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new xS(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(CS),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new ES(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new ES(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=DS(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(CS),n);if(r.length>0){let n=OS(this.lines,r);kS(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(CS),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new ES(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(CS),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=AS(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(CS,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=jS(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new NS(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},RS=class extends L_{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Q),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 LS(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new LS(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},zS=2,BS=1,VS=class extends L_{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,zS),this.rows=Math.max(e.rawOptions.rows||0,BS),this.buffers=this._register(new RS(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};VS=bg([xg(0,e_)],VS);var HS={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:wx,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},US=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],WS=class extends L_{constructor(e){super(),this._onOptionChange=this._register(new Q),this.onOptionChange=this._onOptionChange.event;let t={...HS};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(P_(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in HS))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in HS))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=HS[e],!GS(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=HS[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=US.includes(t)?t:HS[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function GS(e){return e===`block`||e===`underline`||e===`bar`}function KS(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&KS(e[r],t-1);return n}var qS=Object.freeze({insertMode:!1}),JS=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),YS=class extends L_{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Q),this.onData=this._onData.event,this._onUserInput=this._register(new Q),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Q),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=KS(qS),this.decPrivateModes=KS(JS)}reset(){this.modes=KS(qS),this.decPrivateModes=KS(JS)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};YS=bg([xg(0,Jg),xg(1,$g),xg(2,e_)],YS);var XS={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function ZS(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var QS=String.fromCharCode,$S={DEFAULT:e=>{let t=[ZS(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${QS(t[0])}${QS(t[1])}${QS(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${ZS(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${ZS(e,!0)};${e.x};${e.y}${t}`}},eC=class extends L_{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Q),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(XS))this.addProtocol(e,XS[e]);for(let e of Object.keys($S))this.addEncoding(e,$S[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};eC=bg([xg(0,Jg),xg(1,Xg),xg(2,e_)],eC);var tC=[[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]],nC=[[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]],rC;function iC(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var aC=class{constructor(){if(this.version=`6`,!rC){rC=new Uint8Array(65536),rC.fill(1),rC[0]=0,rC.fill(0,1,32),rC.fill(0,127,160),rC.fill(2,4352,4448),rC[9001]=2,rC[9002]=2,rC.fill(2,11904,42192),rC[12351]=1,rC.fill(2,44032,55204),rC.fill(2,63744,64256),rC.fill(2,65040,65050),rC.fill(2,65072,65136),rC.fill(2,65280,65377),rC.fill(2,65504,65511);for(let e=0;e<tC.length;++e)rC.fill(0,tC[e][0],tC[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?rC[e]:iC(e,nC)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=oC.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return oC.createPropertyValue(0,n,r)}},oC=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Q,this.onChange=this._onChange.event;let e=new aC;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},sC=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function cC(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var lC=2147483647,uC=256,dC=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>uC)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>lC?lC:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>lC?lC:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,lC):e}},fC=[],pC=class{constructor(){this._state=0,this._active=fC,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=fC}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=fC,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||fC,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,Pg(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=fC,this._id=-1,this._state=0}}},mC=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Pg(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},hC=[],gC=class{constructor(){this._handlers=Object.create(null),this._active=hC,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=hC}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=hC,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||hC,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,Pg(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=hC,this._ident=0}},_C=new dC;_C.addParam(0);var vC=class{constructor(e){this._handler=e,this._data=``,this._params=_C,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():_C,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Pg(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=_C,this._data=``,this._hitLimit=!1,e));return this._params=_C,this._data=``,this._hitLimit=!1,t}},yC=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},bC=160,xC=function(){let e=new yC(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(bC,0,2,0),e.add(bC,8,5,8),e.add(bC,6,0,6),e.add(bC,11,0,11),e.add(bC,13,13,13),e}(),SC=class extends L_{constructor(e=xC){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new dC,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(P_(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new pC),this._dcsParser=this._register(new gC),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:bC)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<bC||++i>=t||(r=e[i])<32||r>126&&r<bC||++i>=t||(r=e[i])<32||r>126&&r<bC||++i>=t||(r=e[i])<32||r>126&&r<bC){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<bC){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<bC){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},CC=/^([\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})$/,wC=/^[\da-f]+$/;function TC(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=CC.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),wC.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function EC(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function DC(e,t=16){let[n,r,i]=e;return`rgb:${EC(n,t)}/${EC(r,t)}/${EC(i,t)}`}var OC={"(":0,")":1,"*":2,"+":3,"-":1,".":2},kC=131072,AC=10;function jC(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var MC=5e3,NC=0,PC=class extends L_{constructor(e,t,n,r,i,a,o,s,c=new SC){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Fg,this._utf8Decoder=new Ig,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=CS.clone(),this._eraseAttrDataInternal=CS.clone(),this._onRequestBell=this._register(new Q),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Q),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Q),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Q),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Q),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Q),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Q),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Q),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Q),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 FC(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(wb.IND,()=>this.index()),this._parser.setExecuteHandler(wb.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(wb.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new mC(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new mC(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new mC(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new mC(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new mC(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new mC(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new mC(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new mC(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new mC(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new mC(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new mC(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new mC(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in PS)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new vC((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),MC))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${MC} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>kC&&(a=this._parseStack.position+kC)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<kC&&(this._parseBuffer=new Uint32Array(Math.min(e.length,kC))),o||this._dirtyRowTracker.clearRange(),e.length>kC)for(let t=a;t<e.length;t+=kC){let a=t+kC<e.length?t+kC:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=oC.extractWidth(t);let n=oC.extractShouldJoin(t),m=n?oC.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Ng(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof ES&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!jC(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new vC(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new mC(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(CS));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=oC.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,FS),this._charsetService.setgCharset(1,FS),this._charsetService.setgCharset(2,FS),this._charsetService.setgCharset(3,FS);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=zg.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=CS.fg,e.bg=CS.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=CS.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=CS.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=CS.fg&16777215,r.bg&=-67108864,r.bg|=CS.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=CS.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!jC(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>AC&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>AC&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(IC(n)){if(r===`?`)t.push({type:0,index:n});else{let e=TC(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=TC(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);IC(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,FS),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(OC[e[0]],PS[e[1]]||FS),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),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._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=CS.clone(),this._eraseAttrDataInternal=CS.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Vg;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},FC=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(NC=e,e=t,t=NC),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};FC=bg([xg(0,Jg)],FC);function IC(e){return 0<=e&&e<256}var LC=5e7,RC=12,zC=50,BC=class extends L_{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>LC)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=RC?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=RC)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>zC&&(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()}},VC=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};VC=bg([xg(0,Jg)],VC);var HC=!1,UC=class extends L_{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new R_),this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onData=this._register(new Q),this.onData=this._onData.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Q),this._instantiationService=new gS,this.optionsService=this._register(new WS(e)),this._instantiationService.setService(e_,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(VS)),this._instantiationService.setService(Jg,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(yS)),this._instantiationService.setService($g,this._logService),this.coreService=this._register(this._instantiationService.createInstance(YS)),this._instantiationService.setService(Xg,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(eC)),this._instantiationService.setService(Yg,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(oC)),this._instantiationService.setService(n_,this.unicodeService),this._charsetService=this._instantiationService.createInstance(sC),this._instantiationService.setService(Zg,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(VC),this._instantiationService.setService(t_,this._oscLinkService),this._inputHandler=this._register(new PC(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(G_.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(G_.forward(this._bufferService.onResize,this._onResize)),this._register(G_.forward(this.coreService.onData,this._onData)),this._register(G_.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new BC((e,t)=>this._inputHandler.parse(e,t))),this._register(G_.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Q),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!HC&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),HC=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,zS),t=Math.max(t,BS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(cC.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(cC(this._bufferService),!1))),this._windowsWrappingHeuristics.value=P_(()=>{for(let t of e)t.dispose()})}}},WC={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function GC(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=WC[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var KC=0,qC=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Nx,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Nx,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(KC=this._search(t),KC===-1)||this._getKey(this._array[KC])!==t)return!1;do if(this._array[KC]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(KC),!0;while(++KC<this._array.length&&this._getKey(this._array[KC])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(KC=this._search(e),!(KC<0||KC>=this._array.length)&&this._getKey(this._array[KC])===e))do yield this._array[KC];while(++KC<this._array.length&&this._getKey(this._array[KC])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(KC=this._search(e),!(KC<0||KC>=this._array.length)&&this._getKey(this._array[KC])===e))do t(this._array[KC]);while(++KC<this._array.length&&this._getKey(this._array[KC])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},JC=0,YC=0,XC=class extends L_{constructor(){super(),this._decorations=new qC(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Q),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Q),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(P_(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new ZC(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{JC=t.options.x??0,YC=JC+(t.options.width??1),e>=JC&&e<YC&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},ZC=class extends I_{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Q),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Q),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?Pb.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?Pb.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},QC=1e3,$C=class{constructor(e,t=QC){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},ew=20,tw=class extends L_{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new $C(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
328
|
+
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Dy(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(P_(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<ew+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
329
|
+
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===ew+1&&(this._liveRegion.textContent+=Tg.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};tw=bg([xg(1,Qg),xg(2,s_),xg(3,l_)],tw);var nw=class extends L_{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Q),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Q),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(P_(()=>{M_(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Dy(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Dy(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Dy(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Dy(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&rw(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,M_(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};nw=bg([xg(1,c_),xg(2,l_),xg(3,Jg),xg(4,p_)],nw);function rw(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var iw=class extends UC{constructor(e={}){super(e),this._linkifier=this._register(new R_),this.browser=gx,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new R_),this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Q),this.onKey=this._onKey.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Q),this.onBell=this._onBell.event,this._onFocus=this._register(new Q),this._onBlur=this._register(new Q),this._onA11yCharEmitter=this._register(new Q),this._onA11yTabEmitter=this._register(new Q),this._onWillOpen=this._register(new Q),this._setup(),this._decorationService=this._instantiationService.createInstance(XC),this._instantiationService.setService(r_,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(dx),this._instantiationService.setService(p_,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(i_)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(G_.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(G_.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(G_.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(G_.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(P_(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=Nb.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${DC(r)}${Tb.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Mb.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Mb.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(tw,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(Dy(this.element,`copy`,e=>{this.hasSelection()&&Og(e,this._selectionService)}));let e=e=>kg(e,this.textarea,this.coreService,this.optionsService);this._register(Dy(this.textarea,`paste`,e)),this._register(Dy(this.element,`paste`,e)),bx?this._register(Dy(this.element,`mousedown`,e=>{e.button===2&&Mg(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Dy(this.element,`contextmenu`,e=>{Mg(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Ox&&this._register(Dy(this.element,`auxclick`,e=>{e.button===1&&jg(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Dy(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Dy(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Dy(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Dy(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Dy(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Dy(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Dy(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(Dy(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,Cg.get()),kx||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(lx,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(s_,this._coreBrowserService),this._register(Dy(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Dy(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ax,this._document,this._helperContainer),this._instantiationService.setService(o_,this._charSizeService),this._themeService=this._instantiationService.createInstance(pS),this._instantiationService.setService(f_,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Bb),this._instantiationService.setService(d_,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Fx,this.rows,this.screenElement)),this._instantiationService.setService(l_,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(Eb,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(mx),this._instantiationService.setService(c_,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(nw,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(_b,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(rS,this.element,this.screenElement,r)),this._instantiationService.setService(u_,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(G_.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(vb,this.screenElement)),this._register(Dy(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),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(tw,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cb,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Cb,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ix,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),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()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Dy(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(Dy(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Ag(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=GC(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(aw(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(CS));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function aw(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var ow=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},sw=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Vg)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},cw=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new sw(t)}getNullCell(){return new Vg}},lw=class extends L_{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Q),this.onBufferChange=this._onBufferChange.event,this._normal=new cw(this._core.buffers.normal,`normal`),this._alternate=new cw(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 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)}},uw=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},dw=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},fw=[`cols`,`rows`],pw=0,mw=class extends L_{constructor(e){super(),this._core=this._register(new iw(e)),this._addonManager=this._register(new ow),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(fw.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw 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||=new uw(this._core),this._parser}get unicode(){return this._checkProposedApi(),new dw(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._register(new lw(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
330
|
+
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Cg.get()},set promptLabel(e){Cg.set(e)},get tooMuchOutput(){return Tg.get()},set tooMuchOutput(e){Tg.set(e)}}}_verifyIntegers(...e){for(pw of e)if(pw===1/0||isNaN(pw)||pw%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(pw of e)if(pw&&(pw===1/0||isNaN(pw)||pw%1!=0||pw<0))throw Error(`This API only accepts positive integers`)}},hw=2,gw=1,_w=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(hw,Math.floor(u/e.css.cell.width)),rows:Math.max(gw,Math.floor(l/e.css.cell.height))}}},vw=`super-pi.terminal-owner.v1`,yw=`super-pi.terminal-selection.v1.`,bw=20,xw=5,Sw=240,Cw=120,ww={checking:`正在连接`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`,empty:`没有打开的终端`},Tw;function Ew(){if(Tw)return Tw;try{let e=window.localStorage.getItem(vw);if(e&&/^[0-9a-f]{32}$/.test(e))return Tw=e}catch{}Tw=Array.from(window.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(vw,Tw)}catch{}return Tw}function Dw(e){try{return window.sessionStorage.getItem(e)??void 0}catch{return}}function Ow({workspaceId:e,workspaceLabel:t,cwd:n=``,connected:r,sendCommand:i,registerSink:a,conversationId:o,terminalShell:s}){let c=yw+JSON.stringify([e,o]),[l,d]=(0,u.useState)([]),[f,p]=(0,u.useState)(()=>Dw(c)??``),[m,h]=(0,u.useState)(!1),[g,_]=(0,u.useState)(),[v,y]=(0,u.useState)(``),[b,x]=(0,u.useState)(``),S=(0,u.useRef)(new Map),C=(0,u.useRef)(new Map),w=(0,u.useRef)(new Map),T=(0,u.useRef)(new Map),E=(0,u.useRef)(!1),D=(0,u.useRef)(f);D.current=f;let O=(0,u.useRef)(!1),k=(0,u.useRef)(void 0),A=(0,u.useCallback)(e=>{let t=C.current.get(e);if(!t||!t.host.clientWidth||!t.host.clientHeight||T.current.has(e))return;let{terminal:n,fitAddon:r}=t,a=r.proposeDimensions();if(!a||!Number.isFinite(a.cols)||!Number.isFinite(a.rows))return;let o=Math.max(bw,Math.min(Sw,a.cols)),s=Math.max(xw,Math.min(Cw,a.rows));(n.cols!==o||n.rows!==s)&&n.resize(o,s);let c=S.current.get(e);E.current&&c&&c.exitCode===void 0&&(c.cols!==o||c.rows!==s)&&i({type:`terminal.resize`,sessionId:e,cols:o,rows:s})},[i]),j=(0,u.useCallback)((e,t)=>{let n=e.sessionId;if(e.type===`terminal.output`){t.write(e.data);return}let r=S.current.get(n),i=T.current.get(n);r&&t.resize(r.cols,r.rows),t.write(`\x1Bc\x1B[3J`+e.data,()=>{T.current.get(n)===i&&(T.current.delete(n),D.current===n&&A(n))})},[A]),ee=(0,u.useCallback)((e,t)=>{if(!t||C.current.has(e))return;let n=getComputedStyle(t),r=(e,t)=>n.getPropertyValue(e).trim()||t,a=S.current.get(e),o=new mw({cols:a?.cols,rows:a?.rows,cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:r(`--term-fg`,`#dbe4f0`),cursor:r(`--term-fg`,`#dbe4f0`),selectionBackground:r(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),s=new _w;o.loadAddon(s),o.open(t),o.onData(t=>{E.current&&!T.current.has(e)&&S.current.get(e)?.exitCode===void 0&&i({type:`terminal.input`,sessionId:e,data:t})}),C.current.set(e,{terminal:o,fitAddon:s,host:t});for(let t of w.current.get(e)??[])j(t,o);w.current.delete(e),requestAnimationFrame(()=>A(e))},[A,i,j]),M=(0,u.useCallback)(t=>{if(t.type===`terminal.sessions`){if(t.workspaceId!==e||t.conversationId!==o)return;let n=new Map(t.sessions.map(e=>[e.id,e]));for(let[e,r]of C.current)n.has(e)?!t.replay&&S.current.get(e)?.exitCode!==void 0&&n.get(e)?.exitCode===void 0&&r.terminal.write(`\x1Bc\x1B[3J`):(r.terminal.dispose(),C.current.delete(e));for(let e of w.current.keys())(!n.has(e)||t.replay)&&w.current.delete(e);if(t.replay){T.current.clear();for(let e of n.keys())T.current.set(e,Symbol())}!t.replay&&O.current&&t.activate&&n.has(t.activate)&&(k.current=t.activate,O.current=!1),S.current=n,E.current=!0,d(t.sessions),p(e=>t.activate??(n.has(e)?e:t.sessions[0]?.id??``)),_(void 0),h(!0)}else if(t.type===`terminal.output`||t.type===`terminal.replay`){if(!S.current.has(t.sessionId))return;let e=C.current.get(t.sessionId)?.terminal;if(e)j(t,e);else{let e=w.current.get(t.sessionId)??[];e.push(t),w.current.set(t.sessionId,e)}}else if(t.type===`terminal.size`){let e=S.current.get(t.sessionId);e&&(Object.assign(e,{cols:t.cols,rows:t.rows}),C.current.get(e.id)?.terminal.resize(e.cols,e.rows))}else if(t.type===`terminal.exit`){let e=S.current.get(t.sessionId);if(!e)return;let n={...e,exitCode:t.exitCode,reason:t.reason};S.current.set(n.id,n),d(e=>e.map(e=>e.id===n.id?n:e))}else(t.type===`terminal.error`||t.type===`terminal.status`&&!t.enabled)&&(O.current=!1,_(void 0),y(t.type===`terminal.error`?t.message:t.reason||`终端未启用`))},[o,e,j]);(0,u.useEffect)(()=>(a(M),()=>a(void 0)),[M,a]);let te=(0,u.useCallback)(()=>{E.current=!1,h(!1),_(void 0),y(``),r&&e&&i({type:`terminal.sync`,ownerId:Ew(),workspaceId:e,conversationId:o,cwd:n,initialize:Dw(c)===void 0})},[r,e,o,n,c,i]);(0,u.useEffect)(()=>(te(),()=>{r&&i({type:`terminal.detach`})}),[r,i,te]),(0,u.useEffect)(()=>()=>{for(let e of C.current.values())e.terminal.dispose();C.current.clear()},[]),(0,u.useEffect)(()=>{if(m)try{window.sessionStorage.setItem(c,f)}catch{}},[f,m,c]),(0,u.useEffect)(()=>{let e=!1;return Ne(`/api/terminal-shell`).then(e=>e.json()).then(t=>{let n=t.shell;!e&&n&&x(n.file+(n.args.length?` `+n.args.join(` `):``)+`(`+(t.source??``)+`)`)}).catch(()=>void 0),()=>{e=!0}},[s?.file,s?.args.join(`\0`)]),(0,u.useLayoutEffect)(()=>{let e=C.current.get(f);if(!e)return;let t=new ResizeObserver(()=>A(f));if(t.observe(e.host),A(f),k.current===f){let e=f;requestAnimationFrame(()=>{k.current===e&&(C.current.get(e)?.terminal.focus(),k.current=void 0)})}return()=>t.disconnect()},[f,A,l]);let N=e=>!r||!m||g?!1:i(e)?(y(``),_(e.type===`terminal.open`?`open`:`close`),!0):!1,ne=e=>{let t=C.current.get(f)?.terminal;O.current=!0,N({type:`terminal.open`,sessionId:e,cols:t?.cols,rows:t?.rows})||(O.current=!1)},re=l.find(e=>e.id===f),ie=r&&m&&!g,ae=e?r?m?g===`open`?`starting`:re?re.exitCode===void 0?`running`:`exited`:`empty`:v?`unavailable`:`checking`:`checking`:`unavailable`,oe=v||re?.reason;return(0,F.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":ae,children:[(0,F.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[l.map(e=>(0,F.jsxs)(`div`,{className:`terminal-tab${e.id===f?` is-active`:``}`,children:[(0,F.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===f,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>p(e.id),title:ww[e.exitCode===void 0?`running`:`exited`],children:[(0,F.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.exitCode===void 0?`running`:`exited`}`,"aria-hidden":`true`}),e.title]}),(0,F.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,disabled:!ie,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>N({type:`terminal.close`,sessionId:e.id}),children:`×`})]},e.id)),l.length<5&&(0,F.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,disabled:!ie,"data-terminal-add":`1`,onClick:()=>ne(),title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,F.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,F.jsxs)(`span`,{className:`terminal-status terminal-status-${ae}`,"data-terminal-status":ae,children:[(0,F.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),ww[ae]]}),(0,F.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[b&&(0,F.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-shell-hint":`1`,title:b,children:b}),t&&(0,F.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),re?.exitCode!==void 0&&(0,F.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,disabled:!ie,onClick:()=>ne(re.id),children:`重新打开`}),!m&&v&&r&&(0,F.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,onClick:te,children:`重试连接`})]})]}),oe&&(0,F.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,title:kr(oe),children:Or(oe,`终端出错了。`)}),re?.exitCode!==void 0&&re.exitCode!==0&&(0,F.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,re.exitCode,`。`]}),(0,F.jsxs)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:[l.map(e=>(0,F.jsx)(`div`,{ref:t=>ee(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===f?`block`:`none`}},e.id)),ae===`empty`&&(0,F.jsx)(`div`,{className:`terminal-surface-empty`,"data-terminal-empty":`1`,children:(0,F.jsx)(`p`,{className:`rail-empty`,children:ww.empty})}),!re&&ae===`checking`&&(0,F.jsx)(`p`,{className:`rail-empty terminal-surface-message`,"data-terminal-phase":`checking`,children:`正在连接终端…`}),!e&&(0,F.jsx)(`p`,{className:`rail-empty terminal-surface-message`,children:`选择一个工作区后即可打开终端。`})]})]})}function kw({id:e,title:t,icon:n,count:r,actions:i,children:a}){let o=(0,u.useId)();return(0,F.jsxs)(`section`,{className:`rail-card`,"data-rail-section":e,"aria-labelledby":o,children:[(0,F.jsxs)(`div`,{className:`rail-section-head`,children:[(0,F.jsxs)(`h2`,{className:`rail-section-title`,id:o,children:[(0,F.jsx)(Aw,{kind:n}),t]}),r&&(0,F.jsx)(`span`,{className:`rail-section-count`,children:r}),i]}),(0,F.jsx)(`div`,{className:`rail-card-body`,children:a})]})}function Aw({kind:e}){return(0,F.jsx)(`svg`,{className:`rail-section-icon`,viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:e===`tasks`?(0,F.jsx)(F.Fragment,{children:(0,F.jsx)(`path`,{d:`m3 6 2 2 3-4M11 6h10M3 13h5m3 0h10M3 20h5m3 0h10`})}):e===`clock`?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,F.jsx)(`path`,{d:`M12 7v5l3 2`})]}):(0,F.jsx)(F.Fragment,{children:(0,F.jsx)(`path`,{d:`M3 12h4l3-7 4 14 3-7h4`})})})}var jw=[{day:1,label:`一`},{day:2,label:`二`},{day:3,label:`三`},{day:4,label:`四`},{day:5,label:`五`},{day:6,label:`六`},{day:0,label:`日`}];function Mw(e){return e.kind===`interval`?`每隔 ${e.everyMinutes} 分钟`:e.kind===`daily`?`每天 ${e.time}`:e.kind===`weekly`?`每周${e.weekdays.map(e=>jw.find(t=>t.day===e)?.label??`?`).join(`、`)} ${e.time}`:`仅一次:${Nw(e.at)}`}function Nw(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Pw(){return typeof Intl<`u`?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function Fw(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())} ${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`year`)}-${i(`month`)}-${i(`day`)} ${i(`hour`)}:${i(`minute`)}`}function Iw(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-GB`,{timeZone:t,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`hour`)}:${i(`minute`)}`}function Lw(e,t){if(!e)return``;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).formatToParts(t).find(e=>e.type===`timeZoneName`)?.value??e}catch{return e}}function Rw(e,t,n){let r=Iw(e,n),i=zw(e,t,n);return i===0?`今天 ${r}`:i===1?`明天 ${r}`:Fw(e,n)}function zw(e,t,n){let r=e=>{let[t]=Fw(e,n).split(` `),[r,i,a]=t.split(`-`).map(Number);return Date.UTC(r,i-1,a)},i=Math.round((r(e)-r(t))/864e5);return Number.isFinite(i)?i:0}function Bw(e,t,n){if(!e||!t||e===t)return``;let r=Lw(e,n),i=Lw(t,n);return Iw(n,e)===Iw(n,t)?`服务器在 ${r} 时区,你的时区也是 ${i},下面的时间按你的时区显示`:`服务器在 ${r} 时区,下面的时间按你的时区(${i})显示`}function Vw(e,t,n){return e.enabled?e.nextRunAt===void 0?{glyph:`✓`,word:`已结束`,detail:``}:{glyph:`●`,word:`启用中`,detail:`下次 ${Rw(e.nextRunAt,t,n)}`}:e.schedule.kind===`once`&&e.lastRunAt!==void 0?{glyph:`✓`,word:`已结束`,detail:e.lastRunAt?`上次 ${Fw(e.lastRunAt,n)}`:``}:{glyph:`○`,word:`已停用`,detail:``}}function Hw(e,t){if(e.lastRunAt===void 0)return``;let n=Fw(e.lastRunAt,t);return e.lastRunStatus===`failed`?`上次 ${n} · 失败${e.lastRunMessage?`:${e.lastRunMessage}`:``}`:`上次 ${n} · 成功`}function Uw({tasks:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,serverTimeZone:o}){let[s,c]=(0,u.useState)(()=>Date.now()),[l,d]=(0,u.useState)();(0,u.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let f=Pw(),p=Bw(o,f,s),m=e=>{i({type:`scheduledTask.toggle`,id:e.id,enabled:!e.enabled})},h=e=>{i({type:`scheduledTask.trigger`,id:e.id}),a(`已触发「${e.name}」,结果会出现在它自己的会话里。`,`info`)},g=e=>{i({type:`scheduledTask.delete`,id:e.id}),a(`已删除定时任务「${e.name}」,它的会话和结果保留着。`,`info`)};return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(kw,{id:`scheduled`,title:`定时任务`,icon:`clock`,count:(0,F.jsx)(`span`,{"data-sched-count":`1`,children:e.length?`${e.length} 个`:`0 个`}),actions:(0,F.jsx)(`button`,{type:`button`,className:`scheduled-add`,"data-sched-add":`1`,title:`新建定时任务`,onClick:()=>d(`new`),children:`+ 新建`}),children:[p&&(0,F.jsx)(`p`,{className:`scheduled-zone-note`,"data-sched-zone-note":`1`,children:p}),e.length>0?(0,F.jsx)(`ul`,{className:`scheduled-list`,"data-sched-list":`1`,children:e.map(e=>{let t=Vw(e,s,f),n=Hw(e,f);return(0,F.jsxs)(`li`,{className:`scheduled-item`,"data-scheduled-task":e.id,children:[(0,F.jsx)(`button`,{type:`button`,className:`scheduled-toggle`,"data-sched-toggle":`1`,title:e.enabled?`点击停用`:`点击启用`,"aria-label":e.enabled?`停用 ${e.name}`:`启用 ${e.name}`,onClick:()=>m(e),children:t.glyph}),(0,F.jsxs)(`div`,{className:`scheduled-main`,children:[(0,F.jsxs)(`div`,{className:`scheduled-name-row`,children:[(0,F.jsx)(`span`,{className:`scheduled-name`,children:e.name}),(0,F.jsx)(`span`,{className:`scheduled-status-word`,"data-sched-word":`1`,children:t.word}),e.createdBy===`agent`&&(0,F.jsx)(`span`,{className:`scheduled-by`,title:`这个定时任务是 agent 创建的,你可以像编辑自己建的一样编辑它`,children:`agent`})]}),(0,F.jsxs)(`div`,{className:`scheduled-meta`,"data-sched-meta":`1`,children:[Mw(e.schedule),t.detail?` · ${t.detail}`:``]}),n&&(0,F.jsx)(`div`,{className:`scheduled-last`,"data-sched-last":`1`,children:n})]}),(0,F.jsxs)(`div`,{className:`scheduled-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-trigger":`1`,title:`立即执行一次(不改变周期)`,"aria-label":`立即执行 ${e.name}`,onClick:()=>h(e),children:`⚡`}),(0,F.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-edit":`1`,title:`编辑`,"aria-label":`编辑 ${e.name}`,onClick:()=>d(e),children:`✎`}),(0,F.jsx)(`button`,{type:`button`,className:`scheduled-action scheduled-action-danger`,"data-sched-delete":`1`,title:`删除(会话与结果保留)`,"aria-label":`删除 ${e.name}`,onClick:()=>g(e),children:`✕`})]})]},e.id)})}):(0,F.jsx)(`p`,{className:`rail-empty`,"data-sched-empty":`1`,children:`还没有定时任务。可以新建周期任务,或让 AI 安排。`})]}),l!==void 0&&(0,F.jsx)(qw,{task:l===`new`?void 0:l,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:()=>d(void 0)},l===`new`?`new`:l.id)]})}function Ww(e){let t=e?.schedule;return{name:e?.name??``,prompt:e?.prompt??``,kind:t?.kind??`daily`,everyMinutes:t?.kind===`interval`?String(t.everyMinutes):`30`,time:t&&(t.kind===`daily`||t.kind===`weekly`)?t.time:`09:00`,weekdays:t?.kind===`weekly`?[...t.weekdays]:[1],onceAt:t?.kind===`once`?Gw(t.at):``,modelKey:e?.model?`${e.model.provider}/${e.model.modelId}`:``,agentId:e?.agentId??``}}function Gw(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Kw(e){if(e.kind===`interval`){let t=Number(e.everyMinutes);return!Number.isInteger(t)||t<1||t>10080?{ok:!1,reason:`间隔分钟数要是一个 1 到 10080 之间的整数。`}:{ok:!0,schedule:{kind:`interval`,everyMinutes:t}}}if(e.kind===`daily`||e.kind===`weekly`){let t=/^(\d{1,2}):(\d{2})$/.exec(e.time.trim()),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||n>23||r>59)return{ok:!1,reason:`触发时刻要写成 HH:MM,比如 09:00。`};let i=`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`;return e.kind===`daily`?{ok:!0,schedule:{kind:`daily`,time:i}}:e.weekdays.length?{ok:!0,schedule:{kind:`weekly`,weekdays:[...e.weekdays].sort((e,t)=>e-t),time:i}}:{ok:!1,reason:`每周任务至少要选一天。`}}if(!e.onceAt)return{ok:!1,reason:`选一下这一次的运行时刻。`};let t=new Date(e.onceAt).getTime();return Number.isNaN(t)?{ok:!1,reason:`这一次的运行时刻不是有效时间。`}:{ok:!0,schedule:{kind:`once`,at:t}}}function qw({task:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:o}){let[s,c]=(0,u.useState)(()=>Ww(e)),[l,d]=(0,u.useState)();(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let f=e=>{c(t=>({...t,...e})),d(void 0)};return(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay`,"data-sched-dialog-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&o()},children:(0,F.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`scheduled-dialog-title`,"data-sched-dialog":`1`,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsx)(`h2`,{className:`tool-dialog-title`,id:`scheduled-dialog-title`,children:e?`编辑定时任务`:`新建定时任务`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-sched-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭定时任务编辑`,onClick:o,children:`✕`})]}),(0,F.jsxs)(`div`,{className:`tool-dialog-body scheduled-form`,children:[(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`名称`}),(0,F.jsx)(`input`,{className:`scheduled-input`,"data-sched-field":`name`,value:s.name,placeholder:`留空则取提示词首句`,onChange:e=>f({name:e.target.value})})]}),(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`提示词`}),(0,F.jsx)(`textarea`,{className:`scheduled-textarea`,"data-sched-field":`prompt`,rows:5,value:s.prompt,placeholder:`到点时这段话会作为用户消息发给 agent,所以它要是一条完整、自包含的指令`,onChange:e=>f({prompt:e.target.value})})]}),(0,F.jsxs)(`div`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`周期`}),(0,F.jsx)(`div`,{className:`scheduled-kind-row`,role:`radiogroup`,"aria-label":`周期类型`,children:[[`interval`,`每隔 N 分钟`],[`daily`,`每天`],[`weekly`,`每周`],[`once`,`仅一次`]].map(([e,t])=>(0,F.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":s.kind===e,className:`scheduled-kind${s.kind===e?` scheduled-kind-active`:``}`,"data-sched-kind":e,onClick:()=>f({kind:e}),children:t},e))})]}),s.kind===`interval`&&(0,F.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`间隔`}),(0,F.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`everyMinutes`,inputMode:`numeric`,value:s.everyMinutes,onChange:e=>f({everyMinutes:e.target.value})}),(0,F.jsx)(`span`,{className:`scheduled-hint`,children:`分钟(1 – 10080)`})]}),(s.kind===`daily`||s.kind===`weekly`)&&(0,F.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,F.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`time`,inputMode:`numeric`,placeholder:`09:00`,value:s.time,onChange:e=>f({time:e.target.value})}),(0,F.jsx)(`span`,{className:`scheduled-hint`,children:`服务器本地时间,每天/每周的这一天到点触发`})]}),s.kind===`weekly`&&(0,F.jsxs)(`div`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`星期`}),(0,F.jsx)(`div`,{className:`scheduled-weekdays`,children:jw.map(({day:e,label:t})=>{let n=s.weekdays.includes(e);return(0,F.jsx)(`button`,{type:`button`,"aria-pressed":n,className:`scheduled-weekday${n?` scheduled-weekday-on`:``}`,"data-sched-weekday":e,onClick:()=>f({weekdays:n?s.weekdays.filter(t=>t!==e):[...s.weekdays,e]}),children:t},e)})})]}),s.kind===`once`&&(0,F.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,F.jsx)(`input`,{className:`scheduled-input`,type:`datetime-local`,"data-sched-field":`onceAt`,value:s.onceAt,onChange:e=>f({onceAt:e.target.value})}),(0,F.jsx)(`span`,{className:`scheduled-hint`,children:`这一次运行之后就结束`})]}),(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`模型`}),(0,F.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`model`,value:s.modelKey,onChange:e=>f({modelKey:e.target.value}),children:[(0,F.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(n?.models??[]).map(e=>(0,F.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,`(`,e.detail,`)`]},`${e.provider}/${e.modelId}`))]})]}),(0,F.jsxs)(`label`,{className:`scheduled-field`,children:[(0,F.jsx)(`span`,{className:`scheduled-label`,children:`Agent`}),(0,F.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`agent`,value:s.agentId,onChange:e=>f({agentId:e.target.value}),children:[(0,F.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(r?.agents??[]).map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name??e.id},e.id))]})]}),l&&(0,F.jsx)(`p`,{className:`scheduled-error`,"data-sched-error":`1`,role:`alert`,children:l}),(0,F.jsxs)(`div`,{className:`scheduled-actions-row`,children:[(0,F.jsx)(`button`,{type:`button`,className:`scheduled-cancel`,onClick:o,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`scheduled-save`,"data-sched-save":`1`,onClick:()=>{let r=s.prompt.trim();if(!r){d(`定时任务需要一段提示词:到点时这段话会被当作用户消息发给 agent。`);return}if(!t){d(`先选一个工作区,再建定时任务。`);return}let c=Kw(s);if(!c.ok){d(c.reason);return}let l=n?.models.find(e=>`${e.provider}/${e.modelId}`===s.modelKey),u=l?{provider:l.provider,modelId:l.modelId,label:l.label}:null,f=s.agentId||null,p=s.name.trim()||void 0;i(e?{type:`scheduledTask.update`,id:e.id,name:p,prompt:r,schedule:c.schedule,model:u,agentId:f}:{type:`scheduledTask.create`,name:p,prompt:r,schedule:c.schedule,workspaceId:t,model:u,agentId:f})?(a(e?`已保存对「${s.name.trim()||e.name}」的修改。`:`定时任务已创建,到点会自动运行。`,`info`),o()):d(`连接已断开,没能保存。等重连后再试一次。`)},children:e?`保存修改`:`创建任务`})]})]})]})}),document.body)}function Jw(e){return e.status===`open`&&(e.audience===`boss`||e.audience===void 0)}function Yw(e){return(e.escalations??[]).filter(Jw)}function Xw(e){let t=e.filter(e=>Yw(e).length>0);return{projects:t.length,cases:t.reduce((e,t)=>e+Yw(t).length,0)}}function Zw(e,t=!1){return[`cancelled`,`failed`].includes(e.status??``)?!0:t}function Qw(e,t,n){let r=Zw(e,t),i=Yw(e).length>0;return n===`history`?r&&!i:!r||i}function $w(e){return(e.reports??[]).filter(t=>!t.taskId&&[`progress`,`delivery`].includes(t.kind??``)&&(t.authorConversationId===e.ownerConversationId&&!!e.ownerConversationId||t.kind===`delivery`&&!t.authorConversationId))}function eT(e){return[...e.reports??[]].reverse().find(t=>t.kind===`delivery`&&!t.taskId&&(!t.authorConversationId||t.authorConversationId===e.ownerConversationId))}function tT(e){let t=Yw(e),n=[...$w(e)].reverse().find(e=>e.kind===`progress`),r=eT(e),i=[`cancelled`,`failed`].includes(e.status),a=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),o=(e.resources?.activeWorkers??0)>0||[`running`,`waiting`,`awaiting_background`].includes(a?.status??``);return{label:e.status===`cancelled`?`已取消`:e.status===`failed`?`执行暂停`:t.length?`需要你决定`:o?`正在推进`:e.ownerConversationId?[`failed`,`stopped`].includes(a?.status??``)?`执行暂停`:r?`待继续`:`未交付`:`待启动`,summary:n?.progress?.trim()||n?.summary?.trim()||(i?`项目已结束,已有记录会保留。`:r?`可继续安排新任务或追加验证。`:`已交由负责人推进,进展和成果会在这里汇总。`),progress:n,delivery:r,decisions:t,ended:i,deliveryLabel:e.mode===`lightweight`?`自评交付`:`交付成果`}}var nT=/\.[A-Za-z][A-Za-z0-9]{0,9}$/,rT=new Set([`makefile`,`dockerfile`,`license`,`readme`,`changelog`]),iT=/^[A-Za-z]:/;function aT(e){let t=(e??``).trim();if(!t||/\s/.test(t)||t.includes(`://`)||t.startsWith(`/`)||t.startsWith(`\\`)||iT.test(t))return;let n=t.split(/[\\/]/);if(n.some(e=>e===``||e===`.`||e===`..`))return;let r=n[n.length-1];if(nT.test(r)||rT.has(r.toLowerCase()))return n.join(`/`)}function oT(e){return/\s/.test(e)||e.includes(`://`)||e.startsWith(`/`)||e.startsWith(`\\`)||iT.test(e)?!1:!e.split(/[\\/]/).some(e=>e===``||e===`.`||e===`..`)}function sT(e){let t=e.split(/[\\/]/);return t[t.length-1]||e}function cT(e,t){let n=aT(e);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(oT(r))return n===r||n.startsWith(`${r}/`)?n:`${r}/${n}`}function lT(e,t){let n=(e??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(n!==r&&n.startsWith(`${r}/`))return n.slice(r.length+1)}function uT(e){return[`cancelled`,`failed`].includes(e.status??``)}function dT(e,t){return e.filter(e=>Qw(e,e.ownerArchived===!0,t?`history`:`current`))}function fT(e){let[t,n]=(0,u.useState)(0),r=(0,u.useRef)(null),i=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let e=()=>{let e=r.current,t=i.current;if(!e||!t)return;let a=getComputedStyle(e),o=Number.parseFloat(a.lineHeight)||Number.parseFloat(a.fontSize)*1.6||16,s=t.getBoundingClientRect().height;n(Math.max(1,Math.round(s/o)))};e();let t=typeof ResizeObserver==`function`?new ResizeObserver(()=>e()):null;return t&&(r.current&&t.observe(r.current),i.current&&t.observe(i.current)),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[e]),{lines:t,visible:r,measured:i}}function pT({text:e,what:t}){let[n,r]=(0,u.useState)(!1),{lines:i,visible:a,measured:o}=fT(e),s=Math.max(0,i-2);return e?(0,F.jsxs)(`div`,{className:`project-prose-wrap`,children:[(0,F.jsx)(`p`,{className:`project-prose${n?` project-prose-open`:``}`,"data-prose-text":!0,ref:a,children:e}),(0,F.jsx)(`span`,{className:`project-prose-measure`,"aria-hidden":`true`,ref:o,children:e}),s>0?(0,F.jsx)(`button`,{type:`button`,className:`project-prose-expand`,"data-prose-expand":!0,"aria-expanded":n,onClick:()=>r(e=>!e),children:n?`收起${t}`:`展开完整${t}(还有 ${s} 行)`}):null]}):null}function mT({refs:e,baseCwd:t,cwd:n,onOpenFile:r}){return(0,F.jsx)(`ul`,{children:e.map((e,i)=>{let a=cT(e,t),o=a?lT(a,n):void 0;return(0,F.jsx)(`li`,{children:o&&r?(0,F.jsx)(`button`,{type:`button`,className:`project-evidence-path`,"data-team-evidence-file":o,onClick:()=>r({path:o,name:sT(o),text:null}),children:e}):e},i)})})}function hT(e){if(!e)return``;let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));return n<60?`刚刚`:n<3600?`${Math.floor(n/60)} 分钟前`:n<86400?`${Math.floor(n/3600)} 小时前`:`${Math.floor(n/86400)} 天前`}async function gT(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`请求失败(${e.status})`);return t}async function _T(e){let t=(await e.text().catch(()=>``)).trim();if(!t)return`报告打不开(${e.status})`;try{let n=JSON.parse(t);return n&&typeof n==`object`&&typeof n.error==`string`&&n.error.trim()?n.error.trim():`报告打不开(${e.status})`}catch{return t}}function vT(e,t){return`/api/projects/${encodeURIComponent(e)}/report?workspaceId=${encodeURIComponent(t??``)}`}function yT(e,t=60){let n=(e??``).replace(/\s+/g,` `).trim();return n?n.length<=t?n:`${n.slice(0,t-1)}…`:``}function bT(e){let t=(e.title??``).trim();if(t)return t;let n=(e.reason??``).trim();return n?n.match(/^[\s\S]*?[。!?!?]/)?.[0]?.trim()||n:`需要处理`}var xT={decision:0,delivery:1},ST=5;function CT(e,t){let n=Yw(e)[0],r={projectId:e.id,projectTitle:e.title,updatedAt:Date.parse(e.updatedAt??``)||0};if(n)return{...r,reminderId:`${e.id}:decision:${Yw(e).map(e=>e.id).join(`,`)}`,kind:`decision`,label:`要你决定`,detail:yT(n.title||n.reason||`需要你的决定`,uT(e)?36:60)+(uT(e)?`(项目已结束:记录后不会唤醒任何人)`:``),actionLabel:`去看看`,target:{kind:`exception`,escalationId:n.id}};let i=tT(e).delivery,a=Date.parse(i?.createdAt??``);return!i||!Number.isFinite(a)||t-a>864e5?null:{...r,updatedAt:a,reminderId:`${e.id}:delivery:${i.id}`,kind:`delivery`,label:`阶段交付`,detail:yT(i.progress||i.summary||`已提交阶段成果`),actionLabel:`查看交付`,target:{kind:`top`}}}function wT({text:e}){let[t,n]=(0,u.useState)(!1),{lines:r,visible:i,measured:a}=fT(e),o=Math.max(0,r-2);return e?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`project-exception-reason-wrap`,children:[(0,F.jsx)(`p`,{className:`project-exception-reason${t?` project-exception-reason-open`:``}`,"data-project-exception-reason":!0,ref:i,children:e}),(0,F.jsx)(`span`,{className:`project-exception-reason-measure`,"aria-hidden":`true`,ref:a,children:e})]}),o>0&&(0,F.jsx)(`button`,{type:`button`,className:`project-exception-expand`,"data-project-exception-expand":!0,"aria-expanded":t,onClick:()=>n(e=>!e),children:t?`收起理由`:`展开完整理由(还有 ${o} 行)`})]}):null}function TT({item:e,project:t,busy:n,onResolve:r,onReturn:i}){let[a,o]=(0,u.useState)(``),s=uT(t);return(0,F.jsxs)(`li`,{className:`project-exception`,"data-project-exception":e.id,children:[(0,F.jsx)(`strong`,{className:`project-exception-title`,"data-project-exception-title":!0,children:bT(e)}),e.reason&&(0,F.jsx)(wT,{text:e.reason}),s&&(0,F.jsx)(`p`,{className:`project-exception-ended`,"data-project-exception-ended":!0,"data-project-exception-ended-note":!0,children:`项目已结束:你的处理意见会记进项目记录,但不会唤醒任何人。`}),(0,F.jsxs)(`label`,{className:`project-decision-label`,children:[`你的决定`,(0,F.jsx)(`textarea`,{"data-project-decision":e.id,"data-project-exception-decision":!0,value:a,onChange:e=>o(e.target.value),disabled:n})]}),(0,F.jsxs)(`div`,{className:`project-detail-actions`,children:[(0,F.jsx)(`button`,{type:`button`,"data-project-decision-submit":e.id,"data-project-exception-resolve":!0,disabled:n||!a.trim(),onClick:()=>r(a.trim()),children:s?`记录处理意见`:`记录决定并答复主会话`}),(0,F.jsx)(`button`,{type:`button`,"data-project-decision-return":e.id,"data-project-exception-return":!0,disabled:n||!a.trim(),onClick:()=>i(a.trim()),children:`退回补充`})]})]})}function ET({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o}){let s=tT(e),[c,l]=(0,u.useState)(!1),[d,f]=(0,u.useState)(``),[p,m]=(0,u.useState)(!1),[h,g]=(0,u.useState)(``),[_,v]=(0,u.useState)(``),y=(0,u.useRef)(``);(0,u.useEffect)(()=>()=>{y.current&&URL.revokeObjectURL(y.current)},[]);let b=async(r,i,a={})=>{if(t&&!c){l(!0),f(``);try{await Ne(`/api/projects/${encodeURIComponent(e.id)}/${r}`,{method:i,headers:{"content-type":`application/json`},body:JSON.stringify({...a,workspaceId:t})}).then(gT),await o?.(),n?.(`已记录并交给负责人`,`info`)}catch(e){f(e instanceof Error?e.message:`操作失败`)}finally{l(!1)}}},x=async()=>{if(t&&!p){m(!0),g(``);try{let n=await Ne(vT(e.id,t));if(!n.ok){g(await _T(n));return}let r=await n.text();y.current&&URL.revokeObjectURL(y.current);let i=URL.createObjectURL(new Blob([r],{type:`text/plain;charset=utf-8`}));y.current=i,v(i),window.open(i,`_blank`,`noopener`)}catch(e){g(e instanceof Error?e.message:`报告打不开`)}finally{m(!1)}}},S=e.resources?.usage,C=s.delivery?.evidenceRefs??[],w=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),T=!e.ownerConversationId||!!(w&&[`failed`,`stopped`].includes(w.status??``)&&!e.resources?.activeWorkers);return(0,F.jsxs)(`div`,{className:`project-detail project-overview`,"data-project-detail":e.id,children:[e.objective&&(0,F.jsxs)(`div`,{className:`project-goal`,children:[(0,F.jsx)(`span`,{children:`项目目标`}),(0,F.jsx)(`p`,{className:`project-detail-objective`,children:e.objective})]}),(0,F.jsxs)(`section`,{className:`project-section`,"data-project-owner-summary":!0,children:[(0,F.jsx)(`h3`,{children:`当前进展`}),(0,F.jsx)(pT,{text:s.summary,what:`进展`}),e.updatedAt&&(0,F.jsxs)(`p`,{className:`project-overview-time`,children:[hT(e.updatedAt),`更新`]})]}),s.delivery&&(0,F.jsxs)(`section`,{className:`project-section`,"data-project-stage-delivery":!0,children:[(0,F.jsx)(`h3`,{children:s.deliveryLabel}),(0,F.jsx)(pT,{text:s.delivery.progress||s.delivery.summary||`已提交阶段成果`,what:`交付`}),C.length?(0,F.jsx)(mT,{refs:C,baseCwd:e.resources?.ownerCwd??w?.cwd,cwd:a,onOpenFile:i}):(0,F.jsx)(`p`,{"data-project-no-evidence":!0,children:`未附可核对的交付证据。`})]}),s.decisions.length>0&&(0,F.jsxs)(`section`,{className:`project-section`,"data-project-exception-section":!0,children:[(0,F.jsx)(`h3`,{"data-project-exception-heading":!0,children:`需要你决定`}),(0,F.jsx)(`ul`,{className:`project-exception-list`,children:s.decisions.map(t=>(0,F.jsx)(TT,{item:t,project:e,busy:c,onResolve:e=>void b(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`resolved`}),onReturn:e=>void b(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`returned`})},t.id))})]}),d&&(0,F.jsx)(`p`,{className:`project-error`,role:`alert`,children:d}),(0,F.jsxs)(`div`,{className:`project-detail-actions project-overview-actions`,children:[w&&r&&(0,F.jsx)(`button`,{type:`button`,className:T&&!s.ended?``:`project-primary-action`,"data-project-open-owner":!0,onClick:()=>r(w.id),children:`查看负责人会话`}),!s.ended&&T&&(0,F.jsx)(`button`,{type:`button`,className:`project-primary-action`,disabled:c,"data-project-resume":!0,onClick:()=>void b(`start`,`POST`),children:`让负责人继续`}),!s.ended&&(0,F.jsx)(`button`,{type:`button`,className:`project-stop-action`,disabled:c,"data-project-stop":!0,onClick:()=>void b(``,`PATCH`,{status:`cancelled`}),children:`停止项目`}),(0,F.jsx)(`button`,{type:`button`,disabled:p,"data-project-report":e.id,onClick:()=>void x(),children:p?`正在读取…`:`导出记录`})]}),h&&(0,F.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-report-error":!0,children:h}),_&&(0,F.jsx)(`a`,{href:_,target:`_blank`,rel:`noopener noreferrer`,"data-project-report-link":!0,children:`打开已读取的记录`}),e.resources&&(0,F.jsxs)(`details`,{className:`project-section project-secondary`,"data-project-usage":!0,children:[(0,F.jsx)(`summary`,{children:`查看用量`}),(0,F.jsxs)(`div`,{"data-project-budget":e.id,children:[(0,F.jsxs)(`p`,{"data-project-budget-used":e.id,children:[`等效 Token `,e.resources.usageKnown?e.resources.tokens.toLocaleString():`未知`]}),S&&(0,F.jsxs)(`p`,{"data-project-budget-raw":e.id,children:[`原始口径 `,(e.resources.rawTokens??S.input+S.output+S.cacheRead+S.cacheWrite).toLocaleString(),`;输入 `,S.input.toLocaleString(),`;输出 `,S.output.toLocaleString(),`;缓存写入 `,S.cacheWrite.toLocaleString(),`;缓存读取 `,S.cacheRead.toLocaleString()]}),(0,F.jsx)(`p`,{"data-project-budget-basis":`1`,children:`等效 Token = 输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1`})]})]})]})}function DT({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o,onClose:s}){let c=(0,u.useId)(),l=(0,u.useRef)(null),d=(0,u.useRef)(s);return d.current=s,(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),d.current())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,u.useEffect)(()=>{l.current?.focus({preventScroll:!0})},[e.id]),(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay project-dialog-overlay`,"data-project-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&s()},children:(0,F.jsxs)(`div`,{ref:l,className:`tool-dialog project-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":c,"data-project-dialog":e.id,tabIndex:-1,onKeyDown:e=>{if(e.key!==`Tab`)return;let t=l.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), input:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex='-1'])`)).filter(e=>e.offsetParent!==null||e.getClientRects().length>0);if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?(document.activeElement===r||document.activeElement===t)&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head project-dialog-head`,children:[(0,F.jsxs)(`div`,{className:`project-dialog-title-group`,children:[(0,F.jsx)(`h2`,{className:`tool-dialog-title project-dialog-title`,id:c,children:e.title}),(0,F.jsx)(`span`,{className:`project-detail-flags`,children:(0,F.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:tT(e).label})})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close project-dialog-close`,"data-project-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭 ${e.title}`,onClick:s,children:`✕`})]}),(0,F.jsx)(`div`,{className:`tool-dialog-body project-dialog-body`,children:(0,F.jsx)(ET,{project:e,workspaceId:t,notify:n,onOpenSession:r?e=>{s(),r(e)}:void 0,onOpenFile:i?e=>{s(),i(e)}:void 0,cwd:a,onChanged:o})})]})}),document.body)}function OT({workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i}){let[a,o]=(0,u.useState)([]),[s,c]=(0,u.useState)(!1),l=(0,u.useMemo)(()=>dT(a,s),[a,s]),[d,f]=(0,u.useState)(!1),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(null),_=(0,u.useRef)(null),[v,y]=(0,u.useState)([]),b=(0,u.useCallback)(async t=>{if(!e)o([]);else{m(``);try{let n=await Ne(`/api/projects?workspaceId=${encodeURIComponent(e)}${s?`&view=history`:``}`,{signal:t}).then(gT),r=Array.isArray(n)?n:Array.isArray(n.projects)?n.projects:[];o(r)}catch(e){e.name!==`AbortError`&&m(e instanceof Error?e.message:`项目列表加载失败`)}finally{t?.aborted||f(!0)}}},[e,s]);(0,u.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]),(0,u.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>void b(),5e3);return()=>window.clearInterval(t)},[b,e]);let x=(0,u.useMemo)(()=>{let e=Date.now();return l.map(t=>CT(t,e)).filter(e=>!!e).filter(e=>!v.includes(e.reminderId)).sort((e,t)=>xT[e.kind]-xT[t.kind]||t.updatedAt-e.updatedAt)},[l,v]),S=(0,u.useMemo)(()=>l.flatMap(e=>Yw(e).map(t=>({project:e,decision:t}))),[l]),C=(0,u.useMemo)(()=>Xw(l).projects,[l]),w=(0,u.useMemo)(()=>x.slice(0,ST),[x]),T=x.length-w.length,[E,D]=(0,u.useState)(!1),O=E?x:w,[k,A]=(0,u.useState)(!1),j=(0,u.useMemo)(()=>{let e=new Set;for(let t of x)e.add(t.projectId);return e},[l,x]),ee=(0,u.useMemo)(()=>k?l.filter(e=>j.has(e.id)):l,[k,l,j]),M=(0,u.useMemo)(()=>h?l.find(e=>e.id===h)??null:null,[l,h]),te=(0,u.useRef)(null),[N,ne]=(0,u.useState)(0),re=(0,u.useCallback)((e,t,n)=>{_.current=t??document.querySelector(`[data-project-row="${e}"]`),g(e),n&&(te.current={projectId:e,target:n},ne(e=>e+1))},[]),ie=(0,u.useCallback)(()=>{let e=h,t=_.current;_.current=null,g(null),window.requestAnimationFrame(()=>{(t?.isConnected?t:e?document.querySelector(`[data-project-row="${e}"]`):null)?.focus()})},[h]),ae=e=>{let t=document.querySelector(`[data-project-row="${e.projectId}"]`);re(e.projectId,t,e.target)};return(0,u.useEffect)(()=>{if(!N)return;let e=te.current;if(te.current=null,!e)return;let t=document.querySelector(`[data-project-detail="${e.projectId}"]`);if(!t)return;let n=null;if(e.target.kind===`exception`){let e=t.querySelector(`[data-project-exception-section]`);e&&(e.open=!0,n=e.querySelector(`[data-project-exception-heading]`)??e)}let r=n??t,i=window.requestAnimationFrame(()=>{r.scrollIntoView({block:e.target.kind===`top`?`start`:`center`,inline:`nearest`})});return()=>window.cancelAnimationFrame(i)},[N,M?.id]),(0,F.jsxs)(`section`,{className:`project-panel`,"data-project-panel":`1`,children:[(0,F.jsx)(`div`,{className:`rail-section-head project-panel-head`,children:(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`项目进展`}),(0,F.jsx)(`p`,{className:`project-panel-subtitle`,children:`查看负责人汇总的进展、成果和需要你决定的事。`})]})}),S.length>0&&(0,F.jsxs)(`div`,{className:`warning`,role:`status`,"data-project-team-notice":`1`,"data-project-team-notice-count":C,children:[(0,F.jsxs)(`span`,{"data-project-team-notice-text":!0,children:[C===1?`有 1 个项目的事需要你决定`:`有 ${C} 个项目的事需要你决定`,`:`,yT(bT(S[0].decision),48)]}),(0,F.jsx)(`button`,{type:`button`,"data-project-team-notice-action":`1`,onClick:()=>re(S[0].project.id,void 0,{kind:`exception`,escalationId:S[0].decision.id}),children:`去看看`})]}),x.length>0&&(0,F.jsxs)(`div`,{className:`project-pending`,"data-project-pending":`1`,"data-project-pending-count":x.length,children:[O.map(e=>(0,F.jsxs)(`div`,{className:`project-pending-item`,"data-project-pending-item":e.projectId,"data-project-pending-kind":e.kind,children:[(0,F.jsxs)(`div`,{className:`project-pending-row`,children:[(0,F.jsx)(`span`,{className:`project-pending-kind project-pending-kind-${e.kind}`,"data-project-pending-label":e.kind,children:e.label}),(0,F.jsx)(`span`,{className:`project-pending-title`,"data-project-pending-title":e.projectId,children:e.projectTitle}),(0,F.jsx)(`button`,{type:`button`,className:`project-pending-action`,"data-project-pending-action":e.projectId,onClick:()=>ae(e),children:e.actionLabel}),(0,F.jsx)(`button`,{type:`button`,className:`project-pending-close`,"data-project-pending-dismiss":e.projectId,"aria-label":`关闭「${e.projectTitle}」的这条提醒`,title:`关闭这条提醒(不改变项目状态)`,onClick:()=>y(t=>[...t,e.reminderId]),children:`×`})]}),(0,F.jsx)(`p`,{className:`project-pending-detail`,"data-project-pending-detail":e.projectId,children:e.detail})]},`${e.projectId}:${e.kind}`)),T>0&&(0,F.jsx)(`button`,{type:`button`,className:`project-pending-more`,"data-project-pending-more":`1`,"aria-expanded":E,onClick:()=>D(e=>!e),children:E?`收起`:`还有 ${T} 个`})]}),(0,F.jsxs)(`label`,{className:`project-pending-filter`,"data-project-pending-only-label":`1`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-project-pending-only":`1`,checked:k,onChange:e=>A(e.target.checked)}),(0,F.jsx)(`span`,{className:`project-pending-filter-name`,children:`只看提醒`}),(0,F.jsx)(`span`,{className:`project-pending-filter-state`,"data-project-pending-only-state":k?`on`:`off`,children:k?`已开启`:`已关闭`})]}),(0,F.jsxs)(`label`,{className:`project-pending-filter`,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-project-history":`1`,checked:s,onChange:e=>{c(e.target.checked),A(!1),g(null)}}),(0,F.jsx)(`span`,{className:`project-pending-filter-name`,children:`查看历史项目`})]}),p&&(0,F.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-error":`1`,children:p}),e?!d&&l.length===0?(0,F.jsx)(`p`,{className:`rail-empty`,children:`正在加载项目…`}):l.length===0?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{className:`rail-empty`,"data-project-empty":`1`,children:s?`没有已结束的项目。`:`当前没有进行中的项目。`}),(0,F.jsx)(`p`,{className:`project-empty-hint`,"data-project-empty-hint":`1`,children:`在对话里告诉 AI 你要完成什么,负责人会推进工作并向你交付。`})]}):ee.length===0?(0,F.jsx)(`p`,{className:`rail-empty`,"data-project-pending-empty":`1`,children:`没有需要关注的项目。`}):(0,F.jsx)(F.Fragment,{children:(0,F.jsx)(`div`,{className:`project-list`,"data-project-count":ee.length,children:ee.map(e=>{let t=M?.id===e.id;return(0,F.jsxs)(`button`,{type:`button`,className:`project-row`,"data-project-row":e.id,"data-project-block":e.id,"data-project-summary":e.id,"aria-haspopup":`dialog`,"aria-expanded":t,onClick:t=>re(e.id,t.currentTarget),children:[(0,F.jsx)(`span`,{className:`project-list-title`,title:e.title,children:e.title}),(0,F.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:tT(e).label}),(0,F.jsx)(`span`,{className:`project-row-summary`,children:tT(e).summary}),e.updatedAt&&(0,F.jsxs)(`span`,{className:`project-row-updated`,children:[hT(e.updatedAt),`更新`]})]},e.id)})})}):(0,F.jsx)(`p`,{className:`rail-empty`,children:`请先选择工作区。`}),M?(0,F.jsx)(DT,{project:M,workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i,onChanged:()=>b(),onClose:ie}):null]})}var kT=()=>({text:``,mentions:[],files:[]}),AT=(e,t)=>`super-pi.group-draft.v1:${JSON.stringify([e,t])}`;function jT(e,t){try{let n=JSON.parse(localStorage.getItem(AT(e,t))??`null`);return!n||typeof n.text!=`string`?kT():{text:n.text.slice(0,32e3),replyTo:typeof n.replyTo==`string`?n.replyTo:void 0,mentions:Array.isArray(n.mentions)?n.mentions.filter(e=>typeof e?.memberId==`string`&&typeof e.text==`string`):[],files:Array.isArray(n.files)?n.files.filter(e=>typeof e?.path==`string`&&typeof e.text==`string`):[]}}catch{return kT()}}function MT(e,t,n){try{let r=AT(e,t);!n.text&&!n.replyTo?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(n))}catch{}}function NT(e,t,n){jT(e,t).text===n&&MT(e,t,kT())}var PT=`super-pi.group-presets.v1`;function FT(){try{let e=JSON.parse(localStorage.getItem(`super-pi.group-presets.v1`)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e?.id==`string`&&typeof e.name==`string`&&Array.isArray(e.memberIds)&&e.memberIds.every(e=>typeof e==`string`)&&e.memberModels&&typeof e.memberModels==`object`&&!Array.isArray(e.memberModels)&&typeof e.moderator?.prompt==`string`).slice(0,100):[]}catch{return[]}}var IT=e=>JSON.stringify([e.provider,e.modelId]);function LT({value:e,models:t,onChange:n,label:r,inheritLabel:i}){let[a,o]=(0,u.useState)(``),[s,c]=(0,u.useState)(``),l=(0,u.useRef)(null),d=t.find(t=>IT(t)===e),f=t.filter(e=>(!a||e.provider===a)&&`${e.label} ${e.modelId}`.toLocaleLowerCase().includes(s.toLocaleLowerCase())),p=e=>{n(e),l.current&&(l.current.open=!1)};return(0,F.jsxs)(`details`,{className:`group-model-picker`,ref:l,onKeyDown:e=>{e.key===`Escape`&&l.current&&(l.current.open=!1,l.current.querySelector(`summary`)?.focus())},children:[(0,F.jsxs)(`summary`,{"aria-label":r,title:d?`${d.provider} / ${d.modelId}`:void 0,children:[(0,F.jsx)(`span`,{children:e?d?.label??`当前模型不可用,请重新选择`:i??`继承 Agent / 工作区模型`}),(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]}),(0,F.jsxs)(`div`,{className:`group-model-popup`,children:[(0,F.jsxs)(`select`,{"aria-label":`${r} Provider`,value:a,onChange:e=>o(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`全部 Provider`}),[...new Set(t.map(e=>e.provider))].sort().map(e=>(0,F.jsx)(`option`,{children:e},e))]}),(0,F.jsx)(`input`,{"aria-label":`${r} 筛选`,placeholder:`筛选模型…`,value:s,onChange:e=>c(e.target.value)}),(0,F.jsxs)(`div`,{className:`group-model-options`,role:`group`,"aria-label":r,children:[(0,F.jsx)(`button`,{type:`button`,"aria-pressed":!e,onClick:()=>p(``),children:i??`继承默认模型`}),f.map(t=>(0,F.jsxs)(`button`,{type:`button`,"aria-pressed":e===IT(t),onClick:()=>p(IT(t)),children:[(0,F.jsx)(`span`,{children:t.label}),(0,F.jsx)(`small`,{children:t.provider})]},IT(t))),!f.length&&(0,F.jsx)(`p`,{children:`没有匹配的模型`})]})]})]})}var RT={division:`分工`,prompt:`Prompt`,tools:`工具`,mechanism:`协作机制`,execution:`执行策略`};function zT({value:e}){if(/(?:^|\n)\s*(?:[-*+] |\d+[.)] |#{1,4} |```)/.test(e))return(0,F.jsx)(`div`,{className:`rsi-prose`,children:(0,F.jsx)(ef,{source:e,handoffs:!1})});let t=e.split(/\n+/).map(e=>e.trim()).filter(Boolean),n=t.length>1?t:e.length>100?e.split(/(?<=[。;!?])\s*/u).filter(Boolean):t;return(0,F.jsx)(`ul`,{className:`rsi-points`,children:n.map((e,t)=>(0,F.jsx)(`li`,{children:(0,F.jsx)(tf,{source:e})},t))})}function BT({state:e,models:t,archived:n,onAction:r,onClose:i,extra:a}){let[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(e?.enabled!==!1),[d,f]=(0,u.useState)(e?.automaticImprovements!==!1),[p,m]=(0,u.useState)(e?.prompt??``),[h,g]=(0,u.useState)(e?.model?IT(e.model):``),[_,v]=(0,u.useState)({}),[y,b]=(0,u.useState)(!1),[x,S]=(0,u.useState)(``),C=e?.reports??[],w=C.find(e=>e.id===o)??C.at(-1),T=async e=>{if(!y){b(!0),S(``);try{await r(e)}catch(e){S(e instanceof Error?e.message:`RSI 操作失败`)}finally{b(!1)}}};return(0,F.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,"aria-label":`RSI 观察与建议`,children:[(0,F.jsxs)(`header`,{children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,F.jsx)(`span`,{role:`status`,children:e?.enabled===!1?`已暂停`:e?.status===`running`?`后台观察中`:e?.status===`failed`?`观察失败`:e?.status===`interrupted`?`观察已中断`:e?.pending&&e.requestedAt?`观察请求已排队`:e?.pending?`有新过程,等待更新观察`:w?`观察已更新`:`尚无观察报告`})]}),(0,F.jsx)(`button`,{type:`button`,"aria-label":`关闭 RSI 面板`,onClick:i,children:`关闭`})]}),(0,F.jsxs)(`div`,{className:`group-rsi-body`,children:[(0,F.jsx)(`p`,{className:`rsi-intro`,children:`观察任务效率和交付质量。通用缺口归平台,企业专用能力在用户侧开发、验证并复用。`}),!n&&(0,F.jsx)(`button`,{type:`button`,"data-rsi-refresh":!0,disabled:y||e?.status===`running`||e?.enabled===!1||!!(e?.pending&&e.requestedAt),onClick:()=>void T({action:`rsi.refresh`}),children:y?`正在提交…`:e?.status===`running`?`正在观察…`:e?.pending&&e.requestedAt?`已排队`:`更新观察`}),e?.notice&&(0,F.jsx)(`p`,{role:`status`,"data-rsi-notice":!0,children:e.notice}),!w&&!e?.notice&&e?.status!==`running`&&(0,F.jsx)(`p`,{"data-rsi-empty":!0,children:`尚无报告。更新观察后,这里会显示任务效率、工具缺口、证据及改进建议。`}),(x||e?.error)&&(0,F.jsx)(`p`,{role:`alert`,children:x||e?.error}),C.length>0&&(0,F.jsxs)(`label`,{children:[`观察记录`,(0,F.jsx)(`select`,{"aria-label":`RSI 观察记录`,value:w?.id,onChange:e=>s(e.target.value),children:[...C].reverse().map(e=>(0,F.jsx)(`option`,{value:e.id,children:new Date(e.createdAt).toLocaleString()},e.id))})]}),w&&(0,F.jsxs)(`section`,{"data-rsi-report":w.id,children:[(0,F.jsxs)(`div`,{className:`rsi-report-meta`,children:[(0,F.jsxs)(`span`,{children:[w.observedMessages,` / `,w.totalMessages,` 条发言`]}),(0,F.jsxs)(`span`,{children:[w.findings.length,` 条建议`]}),w.model&&(0,F.jsx)(`span`,{title:`观察模型`,children:w.model.label||w.model.modelId})]}),w.compressed&&(0,F.jsx)(`p`,{className:`group-rsi-coverage`,children:`部分历史或执行摘要已压缩;下列结论仅基于可见过程。`}),!!w.artifactReads?.length&&(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsxs)(`summary`,{children:[`本轮实际读取的产物证据 · `,w.artifactReads.length]}),(0,F.jsx)(`ul`,{children:w.artifactReads.map((e,t)=>(0,F.jsx)(`li`,{children:e},t))})]}),!!w.runEvidence?.length&&(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsx)(`summary`,{children:`实际运行用时(含工具及等人)`}),(0,F.jsx)(`ul`,{children:w.runEvidence.map((e,t)=>(0,F.jsxs)(`li`,{children:[Math.round(e.elapsedMs/1e3),` 秒 · `,new Date(e.finishedAt).toLocaleTimeString()]},t))}),(0,F.jsx)(`p`,{children:`这是完整运行用时,不能直接当作模型思考耗时。`})]}),(0,F.jsxs)(`section`,{className:`rsi-overview`,children:[(0,F.jsx)(`h4`,{children:`本轮结论`}),(0,F.jsx)(zT,{value:w.summary})]}),w.retrospective&&(0,F.jsxs)(`details`,{className:`rsi-retrospective`,children:[(0,F.jsx)(`summary`,{children:`前次建议的后续观察`}),(0,F.jsx)(zT,{value:w.retrospective})]}),!w.findings.length&&(0,F.jsx)(`p`,{children:`当前证据未形成具体改进建议。`}),[...w.findings].sort((e,t)=>({high:0,medium:1,low:2})[e.priority]-{high:0,medium:1,low:2}[t.priority]).map((e,t)=>(0,F.jsxs)(`article`,{className:`group-rsi-finding`,"data-rsi-finding":e.id,children:[(0,F.jsxs)(`header`,{className:`rsi-finding-heading`,children:[(0,F.jsxs)(`h4`,{children:[(0,F.jsx)(`span`,{className:`rsi-finding-number`,children:String(t+1).padStart(2,`0`)}),RT[e.category]]}),(0,F.jsx)(`span`,{className:`rsi-priority`,"data-priority":e.priority,children:{high:`优先处理`,medium:`建议改进`,low:`可选优化`}[e.priority]})]}),(0,F.jsxs)(`p`,{className:`rsi-ownership`,"data-rsi-ownership":e.ownership??`unclassified`,children:[(0,F.jsx)(`strong`,{children:{platform:`平台通用能力`,user:`用户专用能力`,mixed:`通用底座与专用适配需拆分`,unclassified:`归属待澄清`}[e.ownership??`unclassified`]}),e.ownershipReason&&` · ${e.ownershipReason}`]}),(0,F.jsxs)(`section`,{className:`rsi-finding-observation`,children:[(0,F.jsx)(`h5`,{children:`观察到的问题`}),(0,F.jsx)(zT,{value:e.observation})]}),(0,F.jsxs)(`section`,{className:`rsi-recommendation`,children:[(0,F.jsx)(`h5`,{children:`改进建议`}),(0,F.jsx)(zT,{value:e.recommendation})]}),(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsxs)(`summary`,{children:[`证据 · `,e.evidence.length,` 处关联发言`]}),e.evidence.map((e,t)=>(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`button`,{type:`button`,onClick:()=>{[...document.querySelectorAll(`[data-group-post-id]`)].find(t=>t.dataset.groupPostId===e.messageId)?.scrollIntoView({block:`center`,behavior:`smooth`})},children:`定位发言`}),e.quote&&(0,F.jsx)(`blockquote`,{children:e.quote})]},t))]}),(0,F.jsxs)(`details`,{className:`rsi-detail`,children:[(0,F.jsx)(`summary`,{children:`适用范围与验证办法`}),(0,F.jsx)(`h5`,{children:`适用范围`}),(0,F.jsx)(zT,{value:e.applicability}),(0,F.jsx)(`h5`,{children:`验证办法`}),(0,F.jsx)(zT,{value:e.verification})]}),e.disposition&&(0,F.jsxs)(`p`,{role:`status`,children:[e.disposition===`accepted`?`已标记采纳 · 待后续过程验证`:`已标记不适用`,e.feedback&&` · ${e.feedback}`]}),!n&&(0,F.jsxs)(`div`,{className:`group-rsi-feedback`,children:[e.ownership===`user`&&e.capability&&(0,F.jsxs)(`button`,{type:`button`,disabled:y,"data-rsi-improve":e.id,onClick:()=>void T({action:`rsi.improve`,reportId:w.id,findingId:e.id}),children:[`开发并验证 · `,e.capability.name]}),(0,F.jsx)(`textarea`,{"aria-label":`RSI 建议反馈`,placeholder:`说明适用差异或实际效果,供下一轮观察参考`,value:_[e.id]??e.feedback??``,onChange:t=>v(n=>({...n,[e.id]:t.target.value})),maxLength:2e3}),(0,F.jsx)(`div`,{children:[`accepted`,`dismissed`].map(t=>(0,F.jsx)(`button`,{type:`button`,disabled:y,"aria-pressed":e.disposition===t,onClick:()=>void T({action:`rsi.feedback`,reportId:w.id,findingId:e.id,disposition:t,feedback:_[e.id]??e.feedback??``}),children:t===`accepted`?`标记采纳`:`不适用`},t))})]})]},e.id))]}),a,!n&&(0,F.jsxs)(`details`,{className:`group-rsi-settings`,children:[(0,F.jsx)(`summary`,{children:`RSI 设置`}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:c,onChange:e=>l(e.target.checked)}),`自动观察`]}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`自动开发符合条件的用户专用能力`]}),(0,F.jsx)(`p`,{children:`观察会产生独立模型请求与费用,可随时暂停。自动观察至少间隔一分钟;手动更新立即排队,当前任务仍在执行时等待结束。每次最多 90 秒、12 次只读检查;同一工作区同时最多一个能力开发,预算十分钟。未指定模型时跟随来源会话、主持人或工作区。`}),(0,F.jsx)(LT,{value:h,models:t,label:`RSI 模型`,inheritLabel:`跟随会话 / 主持人 / 工作区模型`,onChange:g}),(0,F.jsxs)(`label`,{children:[`补充观察要求`,(0,F.jsx)(`textarea`,{"aria-label":`RSI 补充要求`,value:p,onChange:e=>m(e.target.value),maxLength:8e3})]}),(0,F.jsx)(`button`,{type:`button`,"data-rsi-save":!0,disabled:y,onClick:()=>void T({action:`rsi.configure`,enabled:c,automaticImprovements:d,model:t.find(e=>IT(e)===h)??null,prompt:p}),children:`保存 RSI 设置`})]})]})]})}function VT({source:e,models:t,archived:n=!1,onClose:r}){let[i,a]=(0,u.useState)(),[o,s]=(0,u.useState)(``),c=`/api/rsi?${new URLSearchParams({kind:e.kind,workspaceId:e.workspaceId,id:e.id})}`,l=(0,u.useRef)(0),d=(0,u.useRef)(0),f=(0,u.useRef)(c);f.current=c,(0,u.useEffect)(()=>{let e=!1,t=new AbortController;a(void 0),s(``);let n=async()=>{if(d.current)return;let n=l.current;try{let r=await Ne(c,{signal:t.signal}),i=await r.json();if(!r.ok)throw Error(i.error??`RSI 暂时不可用。`);!e&&n===l.current&&(a(i),s(``))}catch(t){!e&&n===l.current&&s(t instanceof Error?t.message:String(t))}};n();let r=setInterval(()=>void n(),3e3);return()=>{e=!0,t.abort(),clearInterval(r)}},[c]);let p=async e=>{let t=++l.current;d.current++;try{let n=await Ne(c,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),r=await n.json();if(!n.ok)throw Error(r.error??`RSI 操作失败。`);f.current===c&&t===l.current&&a(r)}finally{d.current--}};return i?(0,F.jsx)(BT,{state:i?.state,models:t,archived:n,onClose:r,onAction:p,extra:(0,F.jsxs)(`section`,{className:`rsi-work`,"data-rsi-work":!0,children:[o&&(0,F.jsx)(`p`,{role:`alert`,children:o}),(0,F.jsx)(`h4`,{children:`能力改进`}),!i?.improvements.length&&(0,F.jsx)(`p`,{children:`符合条件的用户侧建议会在后台开发;平台建议保留在报告中。`}),i?.improvements.map(e=>(0,F.jsxs)(`article`,{"data-rsi-job":e.id,children:[(0,F.jsxs)(`h5`,{children:[e.name,` · `,{queued:`等待开发`,running:`开发与验证中`,available:`已注册可用 · 收益待验证`,failed:`开发未通过`,interrupted:`已中断`,cancelled:`已取消`}[e.status]]}),(0,F.jsxs)(`p`,{children:[e.slug,e.version?` · v${e.version}`:``]}),e.error&&(0,F.jsx)(`p`,{role:`alert`,children:e.error}),e.conversationId&&(0,F.jsx)(`button`,{type:`button`,"data-rsi-open-work":e.id,onClick:()=>{window.dispatchEvent(new CustomEvent(`super-pi-open-rsi-work`,{detail:e.conversationId})),r()},children:`查看开发过程`}),[`running`,`queued`].includes(e.status)&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>void p({action:`rsi.cancel`,jobId:e.id}).catch(e=>s(String(e))),children:`取消改进`})]},e.id)),!!i?.usage.length&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`h4`,{children:`实际复用记录`}),(0,F.jsx)(`ul`,{children:i.usage.slice(-8).reverse().map((e,t)=>(0,F.jsxs)(`li`,{children:[e.slug,` v`,e.version,` · `,e.status,` · `,e.durationMs,` ms`]},t))}),(0,F.jsx)(`p`,{children:`调用成功仅表示执行成功,不能单独证明整个任务更快或质量更好。`})]})]})},c):(0,F.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,children:[(0,F.jsxs)(`header`,{children:[(0,F.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,F.jsx)(`button`,{type:`button`,onClick:r,children:`关闭`})]}),(0,F.jsx)(`div`,{className:`group-rsi-body`,children:(0,F.jsx)(`p`,{role:o?`alert`:`status`,children:o||`正在读取观察与能力改进记录…`})})]})}function HT({id:e,workspaceId:t,models:n}){let[r,i]=(0,u.useState)(!1),a=(0,u.useRef)(null);return(0,u.useEffect)(()=>i(!1),[e]),(0,u.useEffect)(()=>{if(!r)return;let e=e=>{e.key===`Escape`&&i(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]),(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{ref:a,type:`button`,"data-session-rsi":e,"aria-expanded":r,title:`RSI:任务效率与能力改进`,onClick:()=>i(e=>!e),children:`RSI`}),r&&(0,Re.createPortal)((0,F.jsx)(`div`,{className:`session-rsi-dock`,role:`region`,"aria-label":`会话 RSI`,children:(0,F.jsx)(VT,{source:{kind:`session`,id:e,workspaceId:t},models:n,onClose:()=>{i(!1),a.current?.focus()}})}),a.current?.closest(`.workbench-main-panes`)??document.body)]})}var UT={queued:`排队中`,running:`进行中`,completed:`已完成`,failed:`失败`,cancelled:`已停止`,interrupted:`已中断`},WT=new Map([[`read`,`读取文件`],[`write`,`写入文件`],[`edit`,`编辑文件`],[`grep`,`搜索内容`],[`find`,`查找文件`],[`ls`,`列出目录`],[`bash`,`运行命令`],[`powershell`,`运行命令`]]),GT=new Map([[`solution-designer`,`案`],[`code-designer`,`码`],[`code-auditor`,`审`],[`document-organizer`,`文`]]),KT=e=>e.status===`queued`||e.status===`running`,qT=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),JT=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`});function YT(e,t=!1){let n=Date.parse(e);return Number.isFinite(n)?(t?JT:qT).format(n):``}function XT({name:e,memberId:t,busy:n}){let r=e.trim(),i=t&>.get(t)||(/\p{Script=Han}/u.test(r)?Array.from(r).slice(-2).join(``):r.split(/\s+/u).filter(Boolean).map(e=>Array.from(e)[0]).slice(0,2).join(``).toUpperCase())||`?`,a=Wn.findIndex(e=>e===t),o=a>=0?a:Array.from(t??``).reduce((e,t)=>(e*31+(t.codePointAt(0)??0))%4,0);return(0,F.jsx)(`span`,{className:`group-avatar`,"data-avatar-tone":t?o:`self`,"data-avatar-busy":n||void 0,"aria-hidden":`true`,children:i})}function ZT({step:e}){return e.kind===`thinking`?(0,F.jsxs)(`details`,{className:`group-execution-step`,"data-execution-kind":`thinking`,"data-execution-status":e.status,open:!0,children:[(0,F.jsxs)(`summary`,{children:[(0,F.jsx)(`span`,{children:e.status===`running`?`正在思考`:`思考摘要`}),(0,F.jsx)(`time`,{dateTime:e.startedAt,children:YT(e.startedAt,!0)})]}),e.text?(0,F.jsx)(`div`,{className:`message-body`,children:(0,F.jsx)(ef,{source:e.text,handoffs:!1})}):(0,F.jsx)(`p`,{className:`group-execution-muted`,children:e.status===`running`?`正在等待模型返回摘要。`:`模型未提供可显示的摘要。`}),e.status===`interrupted`&&(0,F.jsx)(`p`,{className:`group-execution-muted`,children:`思考已中断`})]}):(0,F.jsxs)(`li`,{className:`group-execution-step`,"data-execution-kind":`tool`,"data-execution-status":e.status,children:[(0,F.jsxs)(`div`,{className:`group-execution-tool`,children:[(0,F.jsx)(`strong`,{children:WT.get(e.name)??`工具调用`}),(0,F.jsx)(`code`,{children:e.name}),(0,F.jsx)(`span`,{className:`group-execution-step-status`,children:UT[e.status]})]}),e.detail&&(0,F.jsx)(`p`,{className:`group-execution-target`,children:(0,F.jsx)(`code`,{children:e.detail})}),(0,F.jsxs)(`div`,{className:`group-execution-muted`,children:[(0,F.jsx)(`time`,{dateTime:e.startedAt,children:YT(e.startedAt,!0)}),e.durationMs===void 0?e.status===`running`&&e.lastUpdateAt?` · 最近更新 ${YT(e.lastUpdateAt,!0)}`:null:` · ${(e.durationMs/1e3).toFixed(1)} 秒`]})]})}function QT({workspaceId:e,roomId:t,memberId:n,name:r,runs:i,postId:a,onSelect:o,onClose:s,onStop:c,models:l,memberModel:d,onModelChange:f,onRetry:p}){let m=(0,u.useId)(),h=(0,u.useRef)(null),[g,_]=(0,u.useState)(),[v,y]=(0,u.useState)(),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)(``),[w,T]=(0,u.useState)(!1),E=i.find(e=>e.id===a)??i.find(e=>e.status===`running`)??i[0],D=E?.id,O=g?.id===D?g?.value:void 0,k=v?.id===D?v?.message:void 0;return(0,u.useLayoutEffect)(()=>{h.current?.focus()},[]),(0,u.useEffect)(()=>{if(!D)return;let n=new AbortController,r,i,a=!1,o=async()=>{try{let r=await nr(er(e,t,i,D),{signal:n.signal});if(n.signal.aborted)return;y(void 0),r&&(i=r.revision,a=!KT(r),_({id:D,value:r}))}catch(e){n.signal.aborted||y({id:D,message:e instanceof Error?e.message:`暂时无法读取执行记录。`})}finally{!n.signal.aborted&&!a&&(r=window.setTimeout(o,500))}};return o(),()=>{n.abort(),window.clearTimeout(r)}},[D,e,t]),(0,F.jsxs)(`aside`,{className:`group-execution`,"aria-labelledby":m,"data-group-execution":n,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),s())},children:[(0,F.jsxs)(`header`,{className:`group-execution-header`,children:[(0,F.jsx)(XT,{name:r,memberId:n,busy:i.some(KT)}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`h2`,{id:m,children:r}),(0,F.jsx)(`p`,{children:`执行详情`})]}),(0,F.jsx)(`button`,{ref:h,type:`button`,className:`group-close-execution`,"data-close-group-execution":!0,"aria-label":`关闭执行详情`,title:`关闭执行详情`,onClick:s,children:(0,F.jsx)(Gr,{name:`close`})})]}),f&&(0,F.jsxs)(`div`,{className:`group-execution-model-settings`,"aria-busy":b,children:[(0,F.jsx)(`span`,{children:`该成员后续使用的模型`}),(0,F.jsx)(LT,{label:`${r} 后续使用的模型`,value:d?IT(d):``,models:l,onChange:e=>{b||(x(!0),C(``),f(e).catch(e=>C(String(e.message??e))).finally(()=>x(!1)))}}),(0,F.jsx)(`small`,{children:b?`正在保存…`:`当前执行使用原模型。如需立即切换,请先停止再重试。`}),S&&(0,F.jsx)(`p`,{className:`group-error`,role:`alert`,children:S})]}),E?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`group-execution-summary`,children:[i.length>1&&(0,F.jsx)(`select`,{"aria-label":`选择执行记录`,value:D,onChange:e=>o(e.target.value),children:i.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[YT(e.createdAt,!0),` · `,e.assignment??UT[e.status]]},e.id))}),(0,F.jsx)(`div`,{"aria-live":`polite`,"data-execution-run-status":O?.status??E.status,children:UT[O?.status??E.status]}),E.assignment&&(0,F.jsx)(`p`,{children:E.assignment}),(0,F.jsx)(`p`,{"data-group-execution-model":!0,children:E.model?`${E.model.label} · ${E.model.provider}`:`模型尚未记录`}),KT(E)&&c&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>c(E.id),children:`停止这次执行`}),[`failed`,`cancelled`,`interrupted`].includes(E.status)&&p&&(0,F.jsx)(`button`,{type:`button`,"data-group-retry":!0,disabled:w||b,onClick:()=>{T(!0),C(``),p(E.id).catch(e=>C(String(e.message??e))).finally(()=>T(!1))},children:w?`正在提交重试…`:`用当前模型继续任务`}),E.error&&(0,F.jsx)(`p`,{className:`group-error`,children:E.error})]}),(0,F.jsxs)(`div`,{className:`group-execution-scroll`,children:[k&&(0,F.jsx)(`p`,{className:`group-error`,role:`alert`,children:k}),O?.steps.length?(0,F.jsx)(`ol`,{className:`group-execution-steps`,children:O.steps.map(e=>e.kind===`thinking`?(0,F.jsx)(`li`,{children:(0,F.jsx)(ZT,{step:e})},e.id):(0,F.jsx)(ZT,{step:e},e.id))}):!k&&(0,F.jsx)(`p`,{className:`group-execution-muted`,children:O?KT(O)?`等待模型或工具事件。`:`这次发言没有可查看的执行明细。`:`正在读取执行记录…`}),O?.truncated&&(0,F.jsx)(`p`,{className:`group-execution-muted`,children:`部分执行记录超过保留长度,已省略。`})]})]}):(0,F.jsx)(`p`,{className:`group-execution-scroll group-execution-muted`,children:`该成员还没有执行记录。`})]})}var $T=e=>JSON.stringify([e.provider,e.modelId]),eE=`super-pi.group-moderator-prompt-presets.v1`;function tE(){try{let e=JSON.parse(localStorage.getItem(eE)??`[]`);return Array.isArray(e)?e.filter(e=>e&&typeof e.id==`string`&&typeof e.name==`string`&&typeof e.prompt==`string`).slice(0,100).map(e=>({id:e.id.slice(0,100),name:e.name.slice(0,80),prompt:e.prompt.slice(0,8e3)})):[]}catch{return[]}}var nE=e=>/\s/u.test(e)?`@"${e}"`:`@${e}`,rE=e=>new Set([...e.matchAll(/(?:^|[\s([{])(@(?:"(?:[^"\\]|\\.)+"|[^\s,。;、!?,::;!?,)\]}]+))/gu)].map(e=>e[1])),iE=rr;function aE({workspaceId:e,roomId:t,agents:n,catalog:r,userLabel:i,archivedAt:a,restoring:o,onRestore:s,onRoomSeen:c,onRoomRead:l,onRoomMissing:d,onCreated:f,onCancelCreate:p,onEnableNotifications:m,composerResize:h,sourceLink:g}){let[_,v]=(0,u.useState)(),[y,b]=(0,u.useState)(!1),[x,S]=(0,u.useState)(!1);(0,u.useEffect)(()=>{let e=e=>{e.detail?.roomId===t&&b(!0)};return window.addEventListener(`super-pi-status-group-models`,e),()=>window.removeEventListener(`super-pi-status-group-models`,e)},[t]);let[C,w]=(0,u.useState)(``),[T,E]=(0,u.useState)(``),[D,O]=(0,u.useState)(!1),[k,A]=(0,u.useState)({}),[j,ee]=(0,u.useState)(),[M,te]=(0,u.useState)(``),[N]=(0,u.useState)(()=>jT(e,t)),[ne,re]=(0,u.useState)(N.text),[ie,ae]=(0,u.useState)(N.replyTo),[oe,se]=(0,u.useState)(),[ce,le]=(0,u.useState)(N.mentions),[ue,de]=(0,u.useState)(N.files),[fe,pe]=(0,u.useState)([]),[me,he]=(0,u.useState)(0),[ge,P]=(0,u.useState)(),_e=(0,u.useRef)(null),ve=(0,u.useRef)(null),ye=(0,u.useRef)(void 0),be=(0,u.useRef)(null),xe=(0,u.useRef)(!0),Se=(0,u.useRef)(void 0),Ce=(0,u.useRef)(!1),we=(0,u.useRef)(void 0),Te=(0,u.useRef)(new Map),Ee=_?.id===t?_:void 0,De=!!(a||Ee?.archivedAt),Oe=Ee?.messages.find(e=>e.id===ie),ke=e=>Ee?.members.find(t=>t.id===e)?.name??e,Ae=e=>e.role===`user`?i:e.memberName??ke(e.memberId),je=De?void 0:oe?.query,Me=oe?[...(Ee?.members??[]).filter(e=>`${e.name} ${e.id}`.toLocaleLowerCase().includes(oe.query.toLocaleLowerCase())).map(e=>({kind:`member`,member:e})),...fe.map(e=>({kind:`file`,file:e}))]:[];(0,u.useEffect)(()=>{MT(e,t,{text:ne,replyTo:ie,mentions:ce,files:ue})},[e,t,ne,ie,ce,ue]);let Ne=e=>{if(e.id!==t)return;let n=Se.current;if(n?.id===e.id){let[t,r]=n.revision.split(`:`).map(Number),[i,a]=e.revision.split(`:`).map(Number);if(t>i||t===i&&r>a)return}Se.current=e,v(e),e.archivedAt&&b(!1),(n?.title!==e.title||n?.archivedAt!==e.archivedAt||n?.activity.status!==e.activity.status||n?.activity.lastReplyAt!==e.activity.lastReplyAt)&&c(e)};(0,u.useEffect)(()=>{let e=be.current;if(!Ee||y||!e)return;let t=!0,n=()=>{let n=e.getBoundingClientRect();t&&document.visibilityState===`visible`&&getComputedStyle(e).visibility===`visible`&&n.width>0&&n.height>0&&n.bottom>0&&n.top<window.innerHeight&&n.right>0&&n.left<window.innerWidth&&l(Ee)};n();let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()});return r.observe(e),document.addEventListener(`visibilitychange`,n),()=>{t=!1,r.disconnect(),document.removeEventListener(`visibilitychange`,n)}},[Ee?.id,Ee?.activity.lastReplyAt,y,ge?.memberId,ge?.postId,l]),(0,u.useEffect)(()=>(Ce.current=!0,()=>{Ce.current=!1}),[]),(0,u.useEffect)(()=>{if(!t)return;let n=new AbortController,r,i=!1,a=async()=>{try{let r=await nr(er(e,t,Se.current?.revision),{signal:n.signal});n.signal.aborted||(E(``),r&&Ne(r))}catch(r){n.signal.aborted||(r instanceof tr&&r.status===404?(i=!0,d({workspaceId:e,roomId:t})):E(Se.current?`群聊连接暂时中断,正在重试。`:String(r.message??r)))}finally{!n.signal.aborted&&!i&&(r=window.setTimeout(a,Se.current?.messages.some(KT)?450:1600))}};return a(),()=>{n.abort(),window.clearTimeout(r)}},[e,t,d]),(0,u.useEffect)(()=>{if(pe([]),!je)return;let t=new AbortController,n,r=()=>{nr(`/api/files/mentions?${new URLSearchParams({workspaceId:e,cwd:``,q:je})}`,{signal:t.signal}).then(e=>{!t.signal.aborted&&e&&(pe(e.hits.filter(e=>e.kind===`file`).slice(0,8)),e.indexed||(n=window.setTimeout(r,650)))}).catch(()=>{})};return n=window.setTimeout(r,160),()=>{window.clearTimeout(n),t.abort()}},[je,e]),(0,u.useLayoutEffect)(()=>{be.current&&xe.current&&(be.current.scrollTop=be.current.scrollHeight)},[Ee?.revision]),(0,u.useLayoutEffect)(()=>{let e=ye.current;e!==void 0&&ve.current&&(ye.current=void 0,ve.current.focus(),ve.current.setSelectionRange(e,e))},[ne]);async function Pe(n){O(!0),w(``);try{let r=await iE(er(e,t),t?{action:`configure`,memberIds:n.memberIds,memberModels:n.memberModels,...n.moderator,model:n.moderator.model??null,cloneLimit:n.moderator.cloneLimit??null}:n);if(!r)throw Error(`服务没有返回群聊。`);t?(Ne(r),b(!1)):f(r,Ce.current)}catch(e){w(String(e.message??e))}finally{O(!1)}}async function Fe(n){if(n.preventDefault(),!Ee||De||!ne.trim()||D)return;let r=ne.trim(),i=rE(r),a=ce.filter(e=>i.has(e.text)),o=Ee.members.filter(e=>a.some(t=>t.memberId===e.id)||i.has(nE(e.name))&&Ee.members.filter(t=>t.name===e.name).length===1).map(e=>e.id),s=ue.filter(e=>i.has(e.text)).map(e=>e.path),c=JSON.stringify([Ee.id,r,o,ie,s]);we.current?.signature!==c&&(we.current={signature:c,clientId:Wt()}),O(!0),w(``);try{let n=await iE(er(e,Ee.id),{action:`send`,content:r,memberIds:o,replyTo:ie,filePaths:s,clientId:we.current.clientId});if(!n)throw Error(`服务没有确认收到消息。`);NT(e,t,ne),xe.current=!0,Ne(n),Ce.current&&t===n.id&&(re(``),ae(void 0),le([]),de([]),se(void 0)),we.current=void 0}catch(e){w(String(e.message??e))}finally{O(!1)}}function Ie(e){if(!oe)return;let t;if(e.kind===`member`){let n=e.member,r=nE(n.name);re(ne.slice(0,oe.start)+r+` `+ne.slice(oe.end)),le(e=>[...e.filter(e=>e.text!==r),{memberId:n.id,text:r}]),t=oe.start+r.length+1}else{let n=e.file,r=_f(ne,oe,n),i=r.text.slice(oe.start,r.caret).trimEnd();re(r.text),de(e=>[...e.filter(e=>e.path!==n.path),{path:n.path,text:i}]),t=r.caret}ye.current=t,se(void 0)}async function Le(n){try{let r=await iE(er(e,t),{action:`stop`,postId:n});r&&Ne(r)}catch(e){w(String(e.message??e))}}async function Re(n,i){let a=r?.models.find(e=>$T(e)===i);if(i&&!a)throw Error(`所选模型不可用,请刷新模型列表后重试。`);if(!Ee)throw Error(`群聊尚未加载,请稍后重试。`);let o=await iE(er(e,t),{action:`configure`,memberModels:{[n]:a??null},...Ee.moderator,model:Ee.moderator.model??null,cloneLimit:Ee.moderator.cloneLimit??null});if(!o)throw Error(`服务没有确认模型更改。`);Ne(o);let s=o.members.find(e=>e.id===n)?.model;if((s?$T(s):``)!==i)throw Error(`目标服务端没有应用成员模型设置,可能版本过旧。请先升级目标服务端后重试;群聊历史仍保留。`)}async function ze(n){let r=Ee?.messages.find(e=>e.id===n&&e.role===`assistant`),i=r&&Ee?.messages.find(e=>e.id===r.topicId);if(!r||!i||![`failed`,`interrupted`,`cancelled`].includes(r.status))throw Error(`只能重试已失败或停止的执行。`);let a=Te.current.get(n)??Wt();Te.current.set(n,a);let o=`请使用当前模型继续这次未完成的任务。先检查已有产物,避免重复执行。\n原分工:${r.assignment??`按原请求完成工作`}\n原请求:${i.content}`.slice(0,32e3),s=await iE(er(e,t),{action:`send`,content:o,memberIds:[r.memberId],replyTo:r.id,clientId:a,filePaths:i.role===`user`?i.files?.map(e=>e.path):void 0});if(!s)throw Error(`服务没有确认重试请求。`);Ne(s),Te.current.delete(n)}async function Be(n,r,i){ee(n),w(``);try{let a=await iE(er(e,t),{action:`clone.resolve`,requestId:n,choice:r,name:i});a&&Ne(a)}catch(e){w(e instanceof Error?e.message:String(e))}finally{ee(void 0)}}function Ve(e,t,n,r){S(!1);let i=n.closest(`[data-group-post-id]`)?.querySelector(`[data-group-message-avatar]`)??void 0;_e.current={origin:n,avatar:i},P({memberId:e,name:t,postId:r})}function He(){let e=ge?.memberId;P(void 0);let t=_e.current;requestAnimationFrame(()=>{let n=[...document.querySelectorAll(`[data-group-message-avatar]`)].filter(t=>t.dataset.groupMessageAvatar===e).at(-1);(t?.origin.isConnected?t.origin:t?.avatar?.isConnected?t.avatar:n)?.focus({preventScroll:!0})})}let Ue=Ee?.messages??[],We=Kn(Ue),Ge=Ue.filter(e=>e.role===`assistant`&&KT(e)).filter((e,t,n)=>n.findIndex(t=>t.memberId===e.memberId)===t),Ke=new Map(Ue.map(e=>[e.id,e])),qe=new Set(Ue.flatMap(e=>e.role===`assistant`&&KT(e)?[e.memberId]:[])),Je=ge?Ue.filter(e=>e.role===`assistant`&&e.memberId===ge.memberId).reverse():[],Ye;return(0,F.jsxs)(`section`,{className:`group-chat`,"data-group-chat":t,children:[(C||T)&&(0,F.jsx)(`div`,{className:`group-error`,role:`alert`,children:C||T}),!t||y&&!De?(0,F.jsx)(oE,{room:y?Ee:void 0,agents:n,catalog:r,saving:D,onSave:Pe,onCancel:t?()=>b(!1):p}):Ee?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`group-members`,children:[(0,F.jsx)(`div`,{className:`group-roster`,"aria-label":`群成员`,children:Ee.members.map(e=>(0,F.jsxs)(`button`,{type:`button`,className:`group-roster-member`,"data-group-member-avatar":e.id,"aria-label":`查看 ${e.name} 的执行详情${qe.has(e.id)?`,工作中`:``}`,title:`${e.name}${e.agentId?` · 分身 · ${e.worktreePath??e.agentId}`:``}`,"aria-pressed":ge?.memberId===e.id,onClick:t=>Ve(e.id,e.name,t.currentTarget),children:[(0,F.jsx)(XT,{name:e.name,memberId:e.id,busy:qe.has(e.id)}),(0,F.jsxs)(`span`,{children:[e.name,e.agentId?` · 分身`:``]})]},e.id))}),!De&&(0,F.jsx)(`button`,{type:`button`,"data-group-settings":!0,disabled:D,onClick:()=>{w(``),P(void 0),b(!0)},children:`群聊设置`}),(0,F.jsxs)(`button`,{type:`button`,"data-group-rsi":!0,"aria-pressed":x,onClick:()=>{S(e=>!e),P(void 0)},children:[`RSI`,Ee.rsi?.status===`running`?` · 观察中`:Ee.rsi?.status===`failed`?` · 需处理`:``]}),(0,F.jsx)(`button`,{type:`button`,onClick:()=>{m?m():na().then(e=>te(e===`granted`?`系统通知已开启`:`请在浏览器站点设置中允许通知`))},children:`系统通知`})]}),M&&(0,F.jsx)(`p`,{role:`status`,children:M}),(Ee.cloneRequests??[]).filter((e,t,n)=>e.status===`pending`||t>=n.length-3).map(e=>{let t=Ee.members.find(t=>t.id===e.memberId),n=2;for(;Ee.members.some(e=>e.name===`${t?.name??`Agent`} ${n}`);)n+=1;let r=k[e.id]??`${t?.name??`Agent`} ${n}`;return(0,F.jsx)(`section`,{className:`group-clone-request`,"data-clone-request":e.id,"aria-label":`创建 Agent 分身`,children:e.status===`pending`&&e.automatic?(0,F.jsx)(`span`,{children:`主持人正在准备独立分身…`}):e.status===`pending`&&!De?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`strong`,{children:[t?.name??`Agent`,` 正在工作,是否创建分身?`]}),(0,F.jsx)(`p`,{children:e.reason}),(0,F.jsx)(`p`,{children:e.assignment}),(0,F.jsxs)(`form`,{onSubmit:t=>{t.preventDefault(),Be(e.id,`create`,r)},children:[(0,F.jsxs)(`label`,{children:[`分身名字`,(0,F.jsx)(`input`,{maxLength:80,required:!0,value:r,onChange:t=>A(n=>({...n,[e.id]:t.target.value}))})]}),(0,F.jsx)(`button`,{disabled:!!j||!r.trim(),children:j===e.id?`正在准备…`:`创建分身并处理`}),(0,F.jsx)(`button`,{type:`button`,disabled:!!j,onClick:()=>void Be(e.id,`wait`,``),children:`等待空闲`})]}),(0,F.jsx)(`small`,{children:`分身共享源 Agent 的能力与经验,在独立 Git 工作树处理此 case。`})]}):(0,F.jsx)(`span`,{children:e.status===`created`?`已安排 ${Ee.members.find(t=>t.id===e.cloneId)?.name??`分身`}`:e.status===`waiting`?`已选择等待原成员`:`成员或任务状态已变化,无需创建分身`})},e.id)}),(0,F.jsxs)(`div`,{className:`group-stage${ge?` group-stage-inspecting`:``}${x?` group-stage-rsi`:``}`,children:[(0,F.jsxs)(`div`,{className:`group-dialogue`,children:[(0,F.jsxs)(`div`,{className:`group-thread`,ref:be,onScroll:e=>{let t=e.currentTarget;xe.current=t.scrollHeight-t.clientHeight-t.scrollTop<64},children:[!Ue.length&&(0,F.jsx)(`p`,{className:`group-empty`,children:De?`这个群聊没有消息。`:`发条消息开始讨论。用 @ 点名一个或多个成员。`}),We.map(e=>{let t=e.replyTo?Ke.get(e.replyTo):void 0;e.role===`user`&&(Ye=e.id);let n=t&&(e.role===`user`||t.id!==e.topicId||e.topicId!==Ye)?t:void 0,r=Ae(e),i=e.role===`assistant`&&e.background&&e.status===`running`?`后台进行中`:UT[e.status],a=e.role===`assistant`&&ge?.postId===e.id;return(0,F.jsxs)(`article`,{className:`group-post group-post-${e.role}`,"data-group-post":e.role,"data-group-status":e.status,"data-group-post-id":e.id,children:[e.role===`assistant`?(0,F.jsx)(`button`,{className:`group-post-avatar`,type:`button`,"data-group-message-avatar":e.memberId,"aria-label":`查看 ${r} 这次发言的执行详情`,title:`${r} · 执行详情`,"aria-pressed":a,onClick:t=>Ve(e.memberId,r,t.currentTarget,e.id),children:(0,F.jsx)(XT,{name:r,memberId:e.memberId,busy:KT(e)})}):(0,F.jsx)(XT,{name:r}),(0,F.jsxs)(`div`,{className:`group-post-content`,children:[(0,F.jsxs)(`div`,{className:`group-post-head`,children:[(0,F.jsx)(`strong`,{children:r}),e.role===`assistant`&&(0,F.jsx)(`span`,{className:`group-message-model`,"data-group-message-model":e.model?$T(e.model):`unknown`,title:e.model?`${e.model.provider} / ${e.model.modelId}`:`这条历史消息没有记录使用的模型`,children:e.model?`${e.model.label} · ${e.model.provider}`:`模型未记录`}),e.status!==`completed`&&(0,F.jsx)(`span`,{className:`group-post-state`,children:i}),(0,F.jsx)(`time`,{dateTime:Gn(e),children:YT(Gn(e))}),!De&&(0,F.jsxs)(`div`,{className:`group-post-actions`,children:[!KT(e)&&(0,F.jsx)(`button`,{type:`button`,className:`group-reply-action`,disabled:D,onClick:()=>{ae(e.id),ve.current?.focus()},children:`回复`}),KT(e)&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>void Le(e.id),children:`停止`})]})]}),(n||e.content||e.error||e.role===`user`&&e.memoryNotice)&&(0,F.jsxs)(`div`,{className:`group-bubble`,children:[n&&(0,F.jsxs)(`div`,{className:`group-quote`,children:[Ae(n),` · `,n.content.slice(0,120)]}),e.content&&(0,F.jsx)(`div`,{className:`message-body`,children:(0,F.jsx)(ef,{source:e.content,handoffs:!1,sourceLink:e.role===`assistant`&&_?.members.some(t=>t.id===e.memberId&&!t.worktreePath)?g:void 0})}),e.role===`user`&&e.memoryNotice&&(0,F.jsx)(`div`,{className:`group-route`,children:e.memoryNotice}),e.error&&(0,F.jsx)(`p`,{className:`group-error`,children:e.error})]}),e.role===`assistant`&&e.routeReason&&(0,F.jsxs)(`details`,{className:`group-route group-post-footer`,children:[(0,F.jsx)(`summary`,{children:`接话原因`}),e.routeReason]})]})]},e.id)})]}),Ge.length>0&&(0,F.jsx)(`div`,{className:`group-preparing`,"data-group-preparing":!0,role:`group`,"aria-label":`正在准备回复的成员`,children:Ge.map(e=>(0,F.jsx)(`button`,{type:`button`,"data-group-preparing-avatar":e.memberId,title:`${Ae(e)} · 正在准备回复`,"aria-label":`查看 ${Ae(e)} 的准备详情`,"aria-pressed":ge?.memberId===e.memberId,onClick:t=>Ve(e.memberId,Ae(e),t.currentTarget,e.id),children:(0,F.jsx)(XT,{name:Ae(e),memberId:e.memberId,busy:!0})},e.memberId))}),De?(0,F.jsxs)(`div`,{className:`group-archive-notice`,"data-group-archive-notice":!0,children:[(0,F.jsx)(`p`,{children:`群聊已归档。恢复后可继续发消息。`}),(0,F.jsx)(`button`,{type:`button`,"data-group-restore":!0,disabled:o,onClick:()=>s(Ee),children:`恢复群聊`})]}):(0,F.jsxs)(`form`,{className:`group-composer`,onSubmit:Fe,children:[h,Oe&&(0,F.jsxs)(`div`,{className:`group-quote`,children:[`回复 `,Ae(Oe),` · `,Oe.content.slice(0,60),` `,(0,F.jsx)(`button`,{type:`button`,onClick:()=>ae(void 0),"aria-label":`取消引用`,children:`×`})]}),Me.length>0&&(0,F.jsx)(`div`,{className:`group-suggestions`,role:`listbox`,"aria-label":`点名群成员或引用文件`,children:Me.map((e,t)=>(0,F.jsx)(`button`,{type:`button`,role:`option`,"aria-selected":t===me,"data-group-member-option":e.kind===`member`?e.member.id:void 0,onMouseDown:e=>e.preventDefault(),onClick:()=>Ie(e),children:e.kind===`member`?e.member.name:`文件 · ${e.file.path}`},e.kind===`member`?`member:${e.member.id}`:`file:${e.file.path}`))}),(0,F.jsx)(`textarea`,{ref:ve,"data-group-composer":!0,"aria-label":`群聊消息`,placeholder:`输入消息,@ 点名或引用文件`,value:ne,maxLength:32e3,readOnly:D,onChange:e=>{re(e.target.value),se(gf(e.target.value,e.target.selectionStart,e.target.selectionEnd)),he(0)},onSelect:e=>{let t=e.currentTarget;se(gf(t.value,t.selectionStart,t.selectionEnd))},onKeyDown:e=>{e.nativeEvent.isComposing||(Me.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)?(e.preventDefault(),he(t=>(t+Me.length+(e.key===`ArrowDown`?1:-1))%Me.length)):Me.length&&(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey?(e.preventDefault(),Ie(Me[me]??Me[0])):e.key===`Escape`?se(void 0):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit()))}}),(0,F.jsx)(`button`,{type:`submit`,"data-group-send":!0,disabled:!ne.trim()||D,children:`发送`})]})]}),x&&(0,F.jsx)(VT,{source:{kind:`group`,workspaceId:e,id:t},models:r?.models??[],archived:De,onClose:()=>S(!1)}),!x&&ge&&(0,F.jsx)(QT,{workspaceId:e,roomId:t,memberId:ge.memberId,name:ge.name,runs:Je,postId:ge.postId,onStop:e=>void Le(e),onSelect:e=>P({...ge,postId:e}),onClose:He,models:r?.models??[],memberModel:Ee.members.find(e=>e.id===ge.memberId)?.model,onModelChange:De?void 0:e=>Re(ge.memberId,e),onRetry:De?void 0:ze},ge.memberId)]})]}):!T&&(0,F.jsx)(`p`,{className:`group-empty`,children:`正在加载群聊…`})]})}function oE({room:e,agents:t,catalog:n,saving:r,onSave:i,onCancel:a}){let[o,s]=(0,u.useState)(e?.title??``),[c,l]=(0,u.useState)({}),d=t.filter(e=>e.mode===`primary`&&!e.hidden),f=[...d,...e?.members.filter(e=>!d.some(t=>t.id===e.id))??[]],p=e?.members.map(e=>e.id)??Wn,m=[...new Set([...p,...f.map(e=>e.id)])].filter(e=>f.some(t=>t.id===e)&&(c[e]??p.includes(e))),[h,g]=(0,u.useState)(e?.moderator.model?$T(e.moderator.model):``),[_,v]=(0,u.useState)(e?.moderator.prompt??``),[y,b]=(0,u.useState)(e?.moderator.cloneLimit??0),[x,S]=(0,u.useState)(()=>Object.fromEntries((e?.members??[]).map(e=>[e.id,e.model?$T(e.model):``]))),[C,w]=(0,u.useState)(FT),[T,E]=(0,u.useState)(``),[D,O]=(0,u.useState)(``),[k,A]=(0,u.useState)(``),[j,ee]=(0,u.useState)(tE),[M,te]=(0,u.useState)(``),[N,ne]=(0,u.useState)(``),[re,ie]=(0,u.useState)(``);(0,u.useEffect)(()=>{try{localStorage.setItem(eE,JSON.stringify(j))}catch{ie(`浏览器无法保存预设,请检查本地存储空间或隐私设置。`)}},[j]);let ae=[...n?.models??[]];if(e?.moderator.model&&!ae.some(t=>$T(t)===$T(e.moderator.model))){let t=e.moderator.model;n||ae.push(t)}let oe=()=>Object.fromEntries(m.map(e=>[e,ae.find(t=>$T(t)===x[e])??null])),se=()=>({prompt:_,cloneLimit:y||void 0,model:ae.find(e=>$T(e)===h)}),ce=!(!h||ae.some(e=>$T(e)===h))||m.some(e=>x[e]&&!ae.some(t=>$T(t)===x[e])),le=e=>{try{return localStorage.setItem(PT,JSON.stringify(e)),w(e),!0}catch{return A(`浏览器无法保存群聊预设,请检查本地存储空间或隐私设置。`),!1}};return(0,F.jsxs)(`form`,{className:`group-settings`,onSubmit:e=>{e.preventDefault();let t=ae.find(e=>$T(e)===h);h&&!t||ce||i({title:o,memberIds:m,memberModels:oe(),moderator:se()})},children:[(0,F.jsxs)(`div`,{className:`group-settings-heading`,children:[(0,F.jsx)(`h2`,{children:e?`群聊设置`:`创建群聊`}),(0,F.jsx)(`p`,{children:`安排成员与模型,让主持人协调讨论和执行。`})]}),(0,F.jsxs)(`section`,{className:`group-settings-card`,"data-group-presets":!0,children:[(0,F.jsx)(`h3`,{children:`群聊预设`}),(0,F.jsx)(`p`,{className:`group-settings-hint`,children:`一并保存成员、各自模型和主持人设置。`}),(0,F.jsxs)(`label`,{children:[`加载群聊预设`,(0,F.jsxs)(`select`,{"aria-label":`加载群聊预设`,value:T,onChange:e=>{E(e.target.value);let t=C.find(t=>t.id===e.target.value);if(!t)return;O(t.name),l(Object.fromEntries([...new Set([...p,...f.map(e=>e.id),...t.memberIds])].map(e=>[e,t.memberIds.includes(e)]))),S(Object.fromEntries(Object.entries(t.memberModels).map(([e,t])=>[e,t?$T(t):``]))),v(t.moderator.prompt),g(t.moderator.model?$T(t.moderator.model):``),b(t.moderator.cloneLimit??0);let n=t.memberIds.filter(e=>!f.some(t=>t.id===e));A(n.length?`已加载「${t.name}」。${n.length} 位成员在当前服务端不可用,请检查成员列表后保存。`:`已加载「${t.name}」。可继续调整,不影响其他群聊。`)},children:[(0,F.jsx)(`option`,{value:``,children:`选择预设…`}),C.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,F.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,F.jsx)(`input`,{"aria-label":`群聊预设名称`,placeholder:`例如:日常开发评审`,value:D,maxLength:80,onChange:e=>O(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,disabled:!D.trim()||m.length<2||ce,onClick:()=>{let t=D.trim(),n=C.find(e=>e.name.toLocaleLowerCase()===t.toLocaleLowerCase()),r=m.map(t=>e?.members.find(e=>e.id===t)?.agentId??t),i=oe(),a={id:n?.id??Wt(),name:t,memberIds:[...new Set(r)],memberModels:Object.fromEntries(r.map((e,t)=>[e,i[m[t]]])),moderator:se()};le(n?C.map(e=>e.id===n.id?a:e):[a,...C].slice(0,100))&&(E(a.id),A(`已保存群聊预设「${t}」。`))},children:`保存预设`}),T&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>{le(C.filter(e=>e.id!==T))&&(E(``),A(`群聊预设已删除。`))},children:`删除`})]}),k&&(0,F.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:k})]}),!e&&(0,F.jsxs)(`label`,{children:[`群名`,(0,F.jsx)(`input`,{autoFocus:!0,value:o,onChange:e=>s(e.target.value),maxLength:100,required:!0})]}),(0,F.jsxs)(`fieldset`,{className:`group-member-settings`,children:[(0,F.jsx)(`legend`,{children:`群成员与模型`}),f.map(e=>(0,F.jsxs)(`div`,{className:`group-member-card`,"data-selected":m.includes(e.id),children:[(0,F.jsxs)(`label`,{className:`group-choice`,title:e.description,children:[(0,F.jsx)(`input`,{type:`checkbox`,"data-group-member-choice":e.id,checked:m.includes(e.id),disabled:!m.includes(e.id)&&m.length>=8,onChange:t=>{let n=t.target.checked;l(t=>({...t,[e.id]:n}))}}),(0,F.jsx)(XT,{name:e.name,memberId:e.id}),(0,F.jsxs)(`span`,{children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{children:e.description})]})]}),m.includes(e.id)&&(0,F.jsx)(LT,{label:`${e.name} 的模型`,value:x[e.id]??``,models:ae,onChange:t=>S(n=>({...n,[e.id]:t}))})]},e.id))]}),(0,F.jsx)(`p`,{className:`group-settings-hint`,children:`取消勾选可移除成员。请选择 2 到 8 位主 Agent。`}),(0,F.jsxs)(`details`,{className:`group-settings-card`,open:!0,children:[(0,F.jsx)(`summary`,{children:`主持人设置`}),(0,F.jsxs)(`label`,{children:[`同类 Agent 分身`,(0,F.jsxs)(`select`,{value:y,onChange:e=>b(Number(e.target.value)),children:[(0,F.jsx)(`option`,{value:0,children:`创建前询问我`}),[2,3,4,8].map(e=>(0,F.jsxs)(`option`,{value:e,children:[`允许自动创建 · 同类最多 `,e,` 人`]},e))]})]}),(0,F.jsxs)(`div`,{className:`group-model-field`,children:[(0,F.jsx)(`span`,{children:`主持人模型`}),(0,F.jsx)(LT,{label:`主持人模型`,value:h,models:ae,onChange:g})]}),(0,F.jsxs)(`label`,{children:[`主持人 Prompt`,(0,F.jsx)(`textarea`,{value:_,maxLength:8e3,onChange:e=>v(e.target.value),placeholder:`例如:先请最熟悉模块的成员回答,结论足够时结束。`})]}),(0,F.jsxs)(`details`,{className:`group-prompt-presets`,"data-moderator-prompt-presets":!0,children:[(0,F.jsx)(`summary`,{children:`旧版 Prompt 预设`}),(0,F.jsxs)(`label`,{children:[`加载已保存的 Prompt`,(0,F.jsxs)(`select`,{"aria-label":`加载主持人 Prompt 预设`,value:M,onChange:e=>{let t=j.find(t=>t.id===e.target.value);te(e.target.value),t?(v(t.prompt),ne(t.name),ie(`已加载「${t.name}」,可继续修改后用于当前群聊。`)):ie(``)},children:[(0,F.jsx)(`option`,{value:``,children:`选择预设…`}),j.map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,F.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,F.jsx)(`input`,{"aria-label":`Prompt 预设名称`,value:N,maxLength:80,onChange:e=>ne(e.target.value),placeholder:`预设名称`}),(0,F.jsx)(`button`,{type:`button`,disabled:!N.trim()||!_.trim(),onClick:()=>{let e=N.trim(),t=j.find(t=>t.name.toLocaleLowerCase()===e.toLocaleLowerCase()),n={id:t?.id??Wt(),name:e,prompt:_};ee(e=>t?e.map(e=>e.id===t.id?n:e):[n,...e].slice(0,100)),te(n.id),ie(`已保存「${e}」。`)},children:`保存预设`}),M&&(0,F.jsx)(`button`,{type:`button`,onClick:()=>{let e=j.find(e=>e.id===M);ee(e=>e.filter(e=>e.id!==M)),te(``),ne(``),ie(e?`已删除「${e.name}」。`:`预设已删除。`)},children:`删除预设`})]}),re&&(0,F.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:re})]})]}),(0,F.jsxs)(`div`,{className:`group-settings-actions`,children:[(0,F.jsx)(`button`,{type:`button`,disabled:r,onClick:a,children:`取消`}),(0,F.jsx)(`button`,{type:`submit`,disabled:r||!o.trim()||m.length<2||m.length>8||ce,children:e?`保存`:`创建群聊`})]})]})}var sE=`__pi_default__`;function cE({workspaces:e,catalog:t,onClose:n,onSave:r}){let[i,a]=(0,u.useState)(sE),[o,s]=(0,u.useState)(sE);(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]);let c=t.models.find(e=>`${e.provider}/${e.modelId}`===i),l=c?.provider===t.defaultModel?.provider&&c?.modelId===t.defaultModel?.modelId,d=c?.thinkingLevels??(l?t.levels:[]),f=c?{provider:c.provider,modelId:c.modelId,label:c.label}:void 0;return(0,F.jsx)(`div`,{className:`overlay`,onClick:n,children:(0,F.jsxs)(`div`,{className:`picker settings-dialog bulk-workspace-settings`,"data-bulk-workspace-settings":`1`,onClick:e=>e.stopPropagation(),children:[(0,F.jsx)(`h2`,{children:`批量设置工作区`}),(0,F.jsxs)(`div`,{className:`settings-scope`,children:[`将统一修改 `,e.length,` 个现存工作区的默认模型与思考等级,只影响之后新建的会话。`]}),(0,F.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,F.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认模型`,value:i,disabled:t.source!==`pi`,onChange:e=>{a(e.target.value),s(sE)},children:[(0,F.jsx)(`option`,{value:sE,children:`跟随 Pi 默认`}),t.models.map(e=>(0,F.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,` · `,e.provider]},`${e.provider}/${e.modelId}`))]})]}),(0,F.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认思考等级`}),(0,F.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认思考等级`,value:o,disabled:!c||t.source!==`pi`,onChange:e=>s(e.target.value),children:[(0,F.jsx)(`option`,{value:sE,children:`跟随 Pi 默认`}),d.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))]})]}),c&&d.length===0&&(0,F.jsx)(`p`,{className:`bulk-settings-note`,children:`Pi 没有为此模型提供可选择的思考等级;新会话会使用 Pi 默认值。`}),(0,F.jsxs)(`div`,{className:`bulk-settings-workspaces`,"aria-label":`将被更新的工作区`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`应用到`}),(0,F.jsx)(`div`,{children:e.map(e=>(0,F.jsx)(`span`,{children:e.name},e.id))})]}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!e.length||t.source!==`pi`,onClick:()=>r(f,o===sE?void 0:o),children:`应用到全部工作区`})]})]})})}function lE({glyph:e,className:t}){return(0,F.jsx)(`span`,{className:t,"data-tool-glyph-length":Math.min(4,Math.max(1,Array.from(e).length)),"aria-hidden":`true`,children:e})}function uE(e){if(e!==void 0){if(typeof e!=`string`||!e.trim()||Array.from(e.trim()).length>4||/[<>\u0000-\u001f\u007f]/.test(e))throw Error(`工具图标须为 1 至 4 个字符的文字或符号`);return e.trim()}}function dE(e){try{let t=uE(e.glyph);if(t)return t}catch{}let t=`${e.name} ${e.slug??``}`.toLowerCase();return[[/json/,`{}`],[/正则|regex/,`.*`],[/计算|calc/,`∑`],[/时间|timestamp|date/,`◷`],[/差异|diff/,`±`],[/markdown/,`M↓`],[/图像|图片|image/,`▧`],[/表格|csv|excel/,`▦`],[/颜色|color/,`◐`],[/base64/,`64`],[/hash|哈希/,`#`],[/git/,`⑂`]].find(([e])=>e.test(t))?.[1]??(Array.from(e.name.trim()).slice(0,2).join(``)||`◇`)}function fE(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function pE(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}function mE(e){let t=new Map;for(let[n,r]of e.entries())t.has(r.id)||t.set(r.id,n);return t}function hE(e,t){if(!t||t.length===0)return e;let n=new Map(t.map((e,t)=>[e,t])),r=e.filter(e=>n.has(e.id)).sort((e,t)=>(n.get(e.id)??0)-(n.get(t.id)??0));return[...e.filter(e=>!n.has(e.id)),...r]}function gE(e,t,n){if(e.indexOf(t)<0)return[...e];let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(n,r.length));return[...r.slice(0,i),t,...r.slice(i)]}var _E=`super-pi.session-order.v1`;function vE(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.session-order.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.filter(e=>typeof e==`string`));return t}catch{return{}}}function yE(e){try{typeof window<`u`&&window.localStorage.setItem(_E,JSON.stringify(e))}catch{}}function bE(e,t,n){let r=new Set(e.map(e=>e.id)),i=mE(e),a=(e,t)=>(i.get(e.id)??2**53-1)-(i.get(t.id)??2**53-1),o=new Map,s=[];for(let t of e){let e=t.parentConversationId;if(e&&r.has(e)){let n=o.get(e);n?n.push(t):o.set(e,[t])}else s.push(t)}for(let e of o.values())e.sort(a);let c=hE(s.sort(a),n?.manualRoots),l=[],u=new Set,d=(e,n,r,i=!0)=>{if(u.has(e.id))return;u.add(e.id);let a=o.get(e.id)??[];i&&l.push({conversation:e,depth:Math.min(n,8),childCount:a.length,isLastSibling:r});let s=!i||t.has(e.id);for(let[e,t]of a.entries())d(t,n+1,e===a.length-1,!s)};for(let e of c)d(e,0,!1);let f=e.filter(e=>!u.has(e.id)).sort(a);for(let e of f)d(e,0,!1);return l}var xE=`super-pi:tool-shortcuts:v1`,SE=new Set([`Control`,`Alt`,`Shift`,`Meta`,`AltGraph`,`CapsLock`,`Fn`,`FnLock`,`Hyper`,`Super`,`Symbol`,`SymbolLock`]),CE=new Set([`Escape`]),wE=new Set([`Enter`,` `,`Tab`]),TE={" ":`Space`,ArrowUp:`↑`,ArrowDown:`↓`,ArrowLeft:`←`,ArrowRight:`→`,Escape:`Esc`},EE={ctrl:`⌃`,alt:`⌥`,shift:`⇧`,meta:`⌘`};function DE(e){if(e===` `)return` `;let t=e.trim();return t?t.length===1?t.toLowerCase():t:``}function OE(e){return SE.has(e)}function kE(e){let t=e.key;if(!t||t===`Unidentified`||t===`Dead`||OE(t))return;let n=DE(t);if(!n)return;let r=!!e.shiftKey;if(r&&n.length===1&&!/[a-z]/.test(n)){let t=/^Digit([0-9])$/.exec(e.code??``);t&&(n=t[1])}let i={key:n};return e.ctrlKey&&(i.ctrl=!0),e.altKey&&(i.alt=!0),r&&(i.shift=!0),e.metaKey&&(i.meta=!0),i}function AE(e){return TE[e]||(e.length===1||/^f\d{1,2}$/.test(e)?e.toUpperCase():e)}function jE(e){let t=[];return e.ctrl&&t.push(`Ctrl`),e.alt&&t.push(`Alt`),e.shift&&t.push(`Shift`),e.meta&&t.push(`Meta`),t.push(AE(e.key)),t.join(`+`)}function ME(e){let t=``;return e.ctrl&&(t+=EE.ctrl),e.alt&&(t+=EE.alt),e.shift&&(t+=EE.shift),e.meta&&(t+=EE.meta),t+AE(e.key)}function NE(e,t){return e.key===t.key&&!!e.ctrl==!!t.ctrl&&!!e.alt==!!t.alt&&!!e.shift==!!t.shift&&!!e.meta==!!t.meta}function PE(e){return!!(e.ctrl||e.alt||e.shift||e.meta)}function FE(e){return e.key?CE.has(e.key)?{ok:!1,reason:`Esc 是所有弹窗的退出键,不能拿来当工具快捷键。`}:!PE(e)&&wE.has(e.key)?{ok:!1,reason:`「${IE(e.key)}」是当前焦点控件的激活键,加一个修饰键(Ctrl / Alt / Shift)才能当快捷键用。`}:{ok:!0}:{ok:!1,reason:`这个组合键不完整,请按一个具体的键。`}}function IE(e){return AE(e)}function LE(e){let t=e;if(!t||typeof t!=`object`)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable===!0}function RE(e,t){if(t.isComposing||t.defaultPrevented)return!1;let n=kE(t);return!(!n||!NE(e,n)||!PE(e)&&LE(t.target??null))}function zE(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){if(!e||typeof r!=`object`||!r)continue;let t=r,i=DE(typeof t.key==`string`?t.key:``);if(!i)continue;let a={key:i};t.ctrl===!0&&(a.ctrl=!0),t.alt===!0&&(a.alt=!0),t.shift===!0&&(a.shift=!0),t.meta===!0&&(a.meta=!0),FE(a).ok&&(n[e]=a)}return n}function BE(e){let t={};for(let n of Object.keys(e).sort()){let r=e[n];if(!r)continue;let i={key:r.key};r.ctrl&&(i.ctrl=!0),r.alt&&(i.alt=!0),r.shift&&(i.shift=!0),r.meta&&(i.meta=!0),t[n]=i}return JSON.stringify(t)}function VE(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&NE(i,t))return r}var HE=`super-pi:tool-settings-size:v1`,UE={width:480,height:320};function WE(){try{if(typeof window>`u`)return It.slice();let e=Ht(window.localStorage.getItem(zt));return window.localStorage.getItem(`super-pi:tools:v1`)===null?It.slice():e}catch{return It.slice()}}function GE(e){try{if(typeof window>`u`)return;window.localStorage.setItem(zt,Ut(e))}catch{}}function KE(){try{return typeof window>`u`?{}:zE(window.localStorage.getItem(xE))}catch{return{}}}function qE(e){try{if(typeof window>`u`)return;window.localStorage.setItem(xE,BE(e))}catch{}}function JE(e,t,n){let r={};for(let n of t)e[n.id]&&(r[n.id]=e[n.id]);for(let e of n)e.shortcut&&(r[e.id]=e.shortcut);return r}function YE(){try{if(typeof window>`u`)return;let e=window.localStorage.getItem(HE);if(!e)return;let t=JSON.parse(e);return typeof t?.width!=`number`||typeof t?.height!=`number`||!Number.isFinite(t.width)||!Number.isFinite(t.height)||t.width<UE.width||t.height<UE.height?void 0:{width:Math.round(t.width),height:Math.round(t.height)}}catch{return}}function XE(e){try{if(typeof window>`u`)return;e?window.localStorage.setItem(HE,JSON.stringify({width:Math.round(e.width),height:Math.round(e.height)})):window.localStorage.removeItem(HE)}catch{}}function ZE(e,t,n){let r=Math.max(UE.width,t-32),i=Math.max(UE.height,n-32);return{width:Math.round(Math.min(Math.max(e.width,UE.width),r)),height:Math.round(Math.min(Math.max(e.height,UE.height),i))}}var QE=KE(),$E={tools:WE(),mountedTools:[],settingsOpen:!1,shortcuts:{}};$E.shortcuts=JE(QE,$E.tools,$E.mountedTools);var eD=new Set;function tD(e){$E={...$E,...e};for(let e of eD)e()}function nD(e){return eD.add(e),()=>{eD.delete(e)}}var rD=()=>$E;function iD(){return(0,u.useSyncExternalStore)(nD,rD,rD)}var aD={setTools(e){GE(e);let t=new Set(e.map(e=>e.id));QE=Object.fromEntries(Object.entries(QE).filter(([e])=>t.has(e))),qE(QE),tD({tools:e,shortcuts:JE(QE,e,$E.mountedTools)})},removeTool(e){let t=qt($E.tools,e);QE[e]&&(QE={...QE},delete QE[e],qE(QE)),GE(t),tD({tools:t,shortcuts:JE(QE,t,$E.mountedTools),openToolId:$E.openToolId===e?void 0:$E.openToolId})},setMountedTools(e){let t=new Set($E.tools.map(e=>e.id));QE=Object.fromEntries(Object.entries(QE).filter(([e])=>t.has(e))),qE(QE),tD({mountedTools:e,shortcuts:JE(QE,$E.tools,e)})},openTool(e){tD({openToolId:e,settingsOpen:!1})},closeTool(){tD({openToolId:void 0})},toggleTool(e){$E.openToolId===e?aD.closeTool():aD.openTool(e)},openSettings(){tD({settingsOpen:!0,openToolId:void 0})},closeSettings(){tD({settingsOpen:!1})},async setShortcut(e,t){let n=$E.mountedTools.find(t=>t.id===e);if(n){try{let e=await Ne(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:n.slug,shortcut:t})}),r=await e.json();if(!e.ok)return r.error??`快捷键保存失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}tD({mountedTools:$E.mountedTools.map(n=>n.id===e?{...n,shortcut:t}:n),shortcuts:{...$E.shortcuts,[e]:t}})}else QE={...QE,[e]:t},qE(QE),tD({shortcuts:JE(QE,$E.tools,$E.mountedTools)})},async clearShortcut(e){if(!$E.shortcuts[e])return;let t=$E.mountedTools.find(t=>t.id===e);if(t){try{let e=await Ne(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:t.slug,shortcut:null})}),n=await e.json();if(!e.ok)return n.error??`快捷键清除失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}tD({mountedTools:$E.mountedTools.map(t=>t.id===e?{...t,shortcut:void 0}:t),shortcuts:Object.fromEntries(Object.entries($E.shortcuts).filter(([t])=>t!==e))})}else QE={...QE},delete QE[e],qE(QE),tD({shortcuts:JE(QE,$E.tools,$E.mountedTools)})},persistTools(){GE($E.tools)}};async function oD(){let e=fe();try{let t=await Ne(`/api/tools`),n=await t.json();fe()===e&&t.ok&&Array.isArray(n.tools)&&aD.setMountedTools(n.tools.filter(e=>e.enabled))}catch{}}async function sD(e){try{let t=await Ne(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);aD.closeTool(),await oD();return}catch(e){return e instanceof Error?e.message:String(e)}}var cD=`.super-pi-tool.json`,lD=512e3,uD=/^[a-z0-9][a-z0-9-]{0,63}$/,dD=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function fD(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${cD})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i;try{i=uE(r.glyph)}catch{return{ok:!1,reason:`工具图标须为 1 至 4 个字符的文字或符号。`}}let a=typeof r.format==`string`?r.format:void 0;if(a!==void 0&&a!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${a})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let o=typeof r.slug==`string`?r.slug.trim():``,s=typeof r.name==`string`?r.name.trim():``;if(!o)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!s)return{ok:!1,reason:`这个工具包里没有名字。`};if(!Array.isArray(r.files)||!r.files.length)return{ok:!1,reason:`这个工具包里没有文件。`};if(r.files.length>32)return{ok:!1,reason:`文件太多了:${r.files.length} 个,上限 32 个。`};let c=[],l=0;for(let e of r.files){let t=e;if(!t||typeof t.path!=`string`||typeof t.content!=`string`)return{ok:!1,reason:`工具包里的文件项格式不对(每一项都要有 path 和 content)。`};let n=t.path.trim();if(!n||n.startsWith(`/`)||n.includes(`\\`)||n.includes(`\0`)||n.split(`/`).includes(`..`))return{ok:!1,reason:`文件路径「${n}」不合法:不能是绝对路径,也不能跳出工具自己的目录。`};if(c.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(l+=new TextEncoder().encode(t.content).length,l>512e3)return{ok:!1,reason:`工具文件合计超过 ${bD(lD)} 的上限。`};c.push({path:n,content:t.content})}let u=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!u.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!c.some(e=>e.path===u))return{ok:!1,reason:`工具包里没有包含入口文件 ${u}。`};let d;if(r.script!==void 0&&r.script!==null){let e=r.script,t=typeof e.path==`string`?e.path.trim():``;if(!t.endsWith(`.py`))return{ok:!1,reason:`工具包声明的脚本必须是一个 .py 文件。`};if(!c.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};d={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let f;if(r.environment!==void 0&&r.environment!==null){let e=r.environment,t=e.requires;if(t!==void 0&&!Array.isArray(t))return{ok:!1,reason:`工具包声明的依赖列表格式不对(requires 必须是数组)。`};if(Array.isArray(t)){for(let e of t)if(typeof e!=`string`||!dD.test(e.trim()))return{ok:!1,reason:`依赖必须钉死到精确版本(写成 pkg==version):${String(e).slice(0,60)}。`}}let n=e.fingerprint&&typeof e.fingerprint==`object`?e.fingerprint:void 0;f={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let p=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:a===void 0,bundle:{...a===void 0?{}:{format:a},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:o,name:s,...i?{glyph:i}:{},...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:u,files:c,script:d,environment:f,...p?{permissions:p}:{}}}}function pD(e){let t=e.trim().toLowerCase();return t?uD.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function mD(e,t){let n=e.trim().toLowerCase().slice(0,60).replace(/[^a-z0-9-]+/g,`-`).replace(/^-+|-+$/g,``)||`tool`;if(!t.includes(n))return n;for(let e=2;e<100;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return n}function hD(e){return`${e.slug}${cD}`}function gD(e){let t=e.trim().replace(/[\\/:*?"<>|]/g,``).replace(/\.+$/,``).trim();return t?t.length>80?{ok:!1,reason:`文件名太长了,请控制在 80 个字符以内。`}:{ok:!0,name:t.endsWith(`.super-pi-tool.json`)?t:`${t}${cD}`}:{ok:!1,reason:`请填写文件名。`}}function _D(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function vD(e){let t=e.environment?.requires??[];return!e.script&&t.length===0?{tone:`ok`,text:`纯页面工具 · 导入即用,不需要 Python`}:t.length===0?{tone:`ok`,text:`只用 Python 标准库 · 导入即用,不需要安装任何包${e.environment?.requiresPython?`(需要 Python ${e.environment.requiresPython})`:``}`}:{tone:`warn`,text:`首次运行时会安装 ${t.length} 个依赖:${t.join(`、`)}(装进这个工具自己的虚拟环境)${e.environment?.requiresPython?` · 需要 Python ${e.environment.requiresPython}`:``}`}}function yD(e){if(e)return e.state===`zero-deps`?{text:`零依赖`,warn:!1}:e.state===`ready`?{text:`环境就绪`,warn:!1}:e.state===`needs-env`?{text:`首次运行时安装依赖`,warn:!1}:e.state===`needs-python`?{text:`缺少可用的 Python`,warn:!0}:{text:`与导出方环境不一致`,warn:!0}}function bD(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function xD(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var SD=`请基于上面的请求、已输出的内容和已完成的操作继续完成任务。优先给出简洁结论或执行必要的小步骤,不要重复已有内容或已成功的写入。`;function CD(e){return/^\s*<continue_output>([\s\S]*?)<\/continue_output>\s*$/.exec(e)?.[1].trim()}function wD(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function TD(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function ED(e,t){if(!e)return 0;let n=0;for(let r of t)n+=e[r]??0;return n}var DD=128e3;function OD(e){let t=[[]],n=0,r=0,i=[0,0],a=e=>{for(;t.length<=e;)t.push([])},o=e=>{let i=t[n];for(;i.length<r;)i.push(` `);for(let t of e)i[r]=t,r+=1},s=e=>e.replace(/^[?>!]/u,``).split(`;`).map(e=>Number.parseInt(e,10)||0),c=(e,o)=>{let c=s(e),l=Math.max(1,c[0]||1);switch(o){case`A`:n=Math.max(0,n-l);break;case`B`:case`e`:n+=l,a(n);break;case`C`:case`a`:r+=l;break;case`D`:r=Math.max(0,r-l);break;case`E`:n+=l,a(n),r=0;break;case`F`:n=Math.max(0,n-l),r=0;break;case`G`:case"`":r=Math.max(0,l-1);break;case`d`:n=Math.max(0,l-1),a(n);break;case`H`:case`f`:n=Math.max(0,l-1),a(n),r=Math.max(0,(c[1]||1)-1);break;case`K`:{let e=t[n];(c[0]??0)===2?t[n]=[]:(c[0]??0)===1?t[n]=[...Array.from({length:Math.min(r+1,e.length)},()=>` `),...e.slice(r+1)]:e.splice(r);break}case`J`:(c[0]??0)===2||(c[0]??0)===3?(t.splice(0,t.length,[]),n=0,r=0):(c[0]??0)===0?t.splice(n+1):(c[0]??0)===1&&(t.splice(0,n),n=0,t[0]=[]);break;case`s`:i=[n,r];break;case`u`:[n,r]=i,a(n);break;case`P`:t[n].splice(r,l);break;case`X`:{let e=t[n];for(let t=r;t<Math.min(e.length,r+l);t+=1)e[t]=` `;break}case`@`:t[n].splice(r,0,...Array.from({length:l},()=>` `))}},l=t=>{for(let n=t;n<e.length;n+=1){if(e[n]===`\x07`)return n+1;if(e[n]===`\x1B`&&e[n+1]===`\\`)return n+2}return e.length};for(let t=0;t<e.length;){let i=e[t];if(i===``||i===``||i===``||i===``){t=l(t+1);continue}if(i===`\x1B`||i===``){let n=e[t+1];if(i===`\x1B`&&(n===`]`||n===`P`||n===`^`||n===`_`)){t=l(t+2);continue}if(i===`\x1B`&&n===`[`||i===``){let n=t+(i===``?1:2),r=n;for(;r<e.length&&!(e.charCodeAt(r)>=64&&e.charCodeAt(r)<=126);)r+=1;r<e.length&&c(e.slice(n,r),e[r]),t=Math.min(e.length,r+1);continue}t+=n===void 0?1:2;continue}if(i===`\r`){t+=1,r=0;continue}if(i===`
|
|
331
331
|
`){t+=1,n+=1,a(n),r=0;continue}if(i===`\b`){t+=1,r=Math.max(0,r-1);continue}if(i===` `){t+=1,o(` `.repeat(8-r%8));continue}let s=e.codePointAt(t)??0;if(s<32||s===127||s>=128&&s<=159){t+=s>65535?2:1;continue}let u=String.fromCodePoint(s);o(u),t+=u.length}return t.map(e=>e.join(``)).join(`
|
|
332
|
-
`).replace(/\n+$/u,``)}function
|
|
332
|
+
`).replace(/\n+$/u,``)}function kD(e){return[e.partialOutput??e.output,...(e.toolCalls??[]).map(e=>e.output)].filter(Boolean).join(`
|
|
333
333
|
|
|
334
|
-
`)}var kD=95e3;function AD(e){let t=`归档整棵会话树「${e.title}」?本次将归档 ${e.activeCount} 个会话(1 个根会话和 ${e.activeDescendants} 个活跃子孙)${e.alreadyArchived?`,跳过 ${e.alreadyArchived} 个已归档子孙`:``};恢复根会话时,整棵树会一起恢复。`;return e.pendingDecisions>0?`${t}\n还有 ${e.pendingDecisions} 个未拍板的决策,归档后它们会作废。`:t}function jD(e){return e.activeDescendants>0||e.pendingDecisions>0}var MD={workspaces:[],conversations:[],subagentRuns:[]},ND=e=>e.nativeEvent.isComposing||e.keyCode===229,PD=(e,t,n)=>{let r=e.filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),i=r.findIndex(e=>e.id===t);if(i<0||r[i].delivery===`sending`)return e;let a=r.reduce((e,t,n)=>t.delivery===`sending`?n:e,-1),o=Math.max(a+1,Math.min(n,r.length-1));if(o===i)return e;let s=[...r],[c]=s.splice(i,1);s.splice(o,0,c);let l=[...e],u=0;for(let e=0;e<l.length;e+=1)(l[e].role===`user`||l[e].role===`tool`)&&l[e].delivery&&(l[e]=s[u++]);return l},FD=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(e[n].at===t)return n;return-1},ID=(e,t,n)=>{if(t===void 0)return FD(e,n);let r=e.findIndex(e=>e.blockIndex===t);if(r>=0)return r;let i=e.findIndex(e=>e.blockIndex!==void 0);if(i<0)return FD(e,n);let a=t-((e[i].blockIndex??0)-i);return a>=0&&a<e.length?a:-1},LD=(e,t,n)=>{let r=t.at??n,i=[...e],a=ID(i,t.blockIndex,r);return a>=0?i[a]={...i[a],text:i[a].text+t.delta,blockIndex:t.blockIndex??i[a].blockIndex}:i.push({at:r,text:t.delta,blockIndex:t.blockIndex}),i},RD=(e,t)=>{let n=e??[],r=t??[];return r.length>n.length?r:e},zD=e=>{if(typeof e!=`string`||e.length===0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(t)},BD=6e4,VD=60*BD,HD=24*VD,UD=7*HD,WD=30*HD,GD=365*HD,KD=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<VD?`${Math.max(1,Math.floor(r/BD))}m ago`:r<HD?`${Math.floor(r/VD)}h ago`:r<UD?`${Math.floor(r/HD)}d ago`:r<WD?`${Math.floor(r/UD)}w ago`:r<GD?`${Math.floor(r/WD)}mo ago`:`${Math.floor(r/GD)}y ago`},qD=(e,t)=>{let n=e.find(e=>e.id===t);if(!n)return[];let r=new Map;for(let t of e){if(t.workspaceId!==n.workspaceId||!t.parentConversationId)continue;let e=r.get(t.parentConversationId);e?e.push(t):r.set(t.parentConversationId,[t])}let i=[],a=new Set,o=e=>{if(!a.has(e.id)){a.add(e.id),i.push(e);for(let t of r.get(e.id)??[])o(t)}};return o(n),i},JD=e=>{if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};function YD({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,u.useRef)(null),[o,s]=(0,u.useState)({left:t,top:n});(0,u.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let r=e.getBoundingClientRect();s({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),i())},t=e=>{a.current?.contains(e.target)||i()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&i()},o=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&i()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,o),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await Bd(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,F.jsxs)(`div`,{ref:a,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-workspace-id":e.id,style:{left:o.left,top:o.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,F.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function XD({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a,sendCommand:o,orchestrated:s,childCount:c}){let l=(0,u.useRef)(null),[d,f]=(0,u.useState)({left:t,top:n});(0,u.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let r=e.getBoundingClientRect();f({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{l.current?.contains(e.target)||a()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&a()},i=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&a()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,i),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,i)}},[a]);let p=async e=>{try{let t=await Ne(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`})}),n=await t.json();if(!t.ok)throw Error(n.error);r(`已停止会话(含排队消息)`,`info`)}catch(e){r(`停止失败:${Or(e)}`,`error`)}},m=async e=>{try{let t=await Ne(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`,subtree:!0})}),n=await t.json();if(!t.ok)throw Error(n.error);let i=typeof n.descendantCount==`number`?n.descendantCount:0;r(i>0?`已停止会话及其下属 ${i} 个`:`已停止会话(它没有下属会话)`,`info`)}catch(e){r(`停止子树失败:${Or(e)}`,`error`)}},h=async()=>{let t=await Bd(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,F.jsxs)(`div`,{ref:l,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:d.left,top:d.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void h(),children:`复制会话 ID`}),(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),![`running`,`waiting`,`awaiting_background`].includes(e.status)&&(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-save-warm-session":e.id,onClick:()=>{a();let t=window.prompt(`保存为当前工作区的预热会话。以后选用时会带上当前对话历史。`,e.title)?.trim();t&&!o({type:`conversation.warm.save`,conversationId:e.id,title:t})&&r(`连接断开,未保存预热会话`,`error`)},children:`保存为预热会话`}),(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-stop-turn-session":e.id,onClick:()=>{a(),o({type:`run.stop`,conversationId:e.id})},children:`停止当前回合`}),s&&(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-queue":e.id,onClick:()=>{a(),p(e.id)},children:`停止会话(含排队消息)`}),c>0&&(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-tree":e.id,onClick:()=>{a(),m(e.id)},children:[`停止整棵子树(`,c,` 个下属)`]}),(0,F.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var ZD={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},QD=xD,$D={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},eO={model:`没有可用的模型`,thinking:`Pi 没有给出当前模型的思考等级`,agent:`没有可用的智能体`,subagent:`没有可用的子智能体`},tO={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},nO=`图文`,rO=e=>e.imageInput?nO:void 0,iO=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),aO=(e,t)=>{let n=iO(t.trim());return n?e.filter(e=>iO(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function oO({workspaceId:e,value:t,onChange:n}){let[r,i]=(0,u.useState)([]),[a,o]=(0,u.useState)(``);(0,u.useEffect)(()=>{i([]),o(``)},[e]),(0,u.useEffect)(()=>{let n=!0;return o(``),Ne(`/api/files?workspaceId=${encodeURIComponent(e)}&path=${encodeURIComponent(t)}`).then(async e=>{let r=await e.json();if(!e.ok)throw Error(r.error??`HTTP ${e.status}`);if(!n)return;let a=(r.entries??[]).filter(e=>e.kind===`directory`).map(e=>e.path);i(e=>[...new Set([...e,t,...a])].filter(Boolean).sort())}).catch(e=>{n&&o(e instanceof Error?e.message:`子目录读取失败`)}),()=>{n=!1}},[e,t]);let s=[...new Set([...r,t])].filter(Boolean).sort();return(0,F.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,F.jsx)(`label`,{htmlFor:`empty-session-cwd`,children:`工作目录:`}),(0,F.jsxs)(`select`,{id:`empty-session-cwd`,"data-session-cwd-select":`1`,"aria-label":`会话工作目录(可选)`,value:t,onChange:e=>n(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`工作区根目录`}),s.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))]}),a&&(0,F.jsx)(`span`,{role:`status`,children:a})]})}function sO({workspace:e,onClose:t,onCreate:n}){let[r,i]=(0,u.useState)(``),a=(0,u.useRef)(null);return(0,u.useEffect)(()=>{i(``)},[e.id]),(0,u.useEffect)(()=>{let e=a.current;e&&e.focus();let n=e=>{e.key===`Escape`&&(e.preventDefault(),t())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[t]),(0,F.jsx)(`div`,{className:`overlay session-create-overlay`,onClick:t,children:(0,F.jsxs)(`div`,{className:`session-create-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`session-create-title`,tabIndex:-1,ref:a,onClick:e=>e.stopPropagation(),onKeyDown:e=>{if(e.key!==`Tab`)return;let t=a.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), select:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`));if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?document.activeElement===r&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,F.jsx)(`h2`,{id:`session-create-title`,children:`新建会话`}),(0,F.jsxs)(`p`,{className:`session-create-workspace`,children:[`工作区:`,e.name,(0,F.jsx)(`small`,{children:e.path})]}),(0,F.jsx)(oO,{workspaceId:e.id,value:r,onChange:i}),(0,F.jsxs)(`div`,{className:`session-create-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`session-create-cancel`,onClick:t,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`session-create-confirm picker-ok`,onClick:()=>n(r),children:`创建会话`})]})]})})}function cO({onClose:e,onCreate:t}){let{connections:n,activeServer:r}=ue(),i=(0,u.useRef)(0),[a,o]=(0,u.useState)(),[s,c]=(0,u.useState)(!0),[l,d]=(0,u.useState)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(``),[g,_]=(0,u.useState)(!1),v=async(e,t)=>{let n=++i.current;t===void 0&&_(!1),c(!0),d(void 0);try{let a=new URLSearchParams;e&&a.set(`path`,e),t!==void 0&&a.set(`prefix`,t);let s=await Ne(`/api/fs/dirs?${a}`,{},r),c=await s.json();if(!s.ok)throw Error(c.error??`HTTP ${s.status}`);if(n!==i.current)return;let l=c;o(l),t===void 0&&(h(l.path),p(l.suggestedName),_(!1))}catch(e){n===i.current&&d(e instanceof Error?e.message:`目录加载失败`)}finally{n===i.current&&c(!1)}};(0,u.useEffect)(()=>{o(void 0),h(``),v()},[r]),(0,u.useEffect)(()=>{if(!g||!a)return;let e=lr(m,a.path),t=window.setTimeout(()=>{v(e.path,e.prefix)},180);return()=>{window.clearTimeout(t)}},[m,g,r]),(0,u.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let y=e=>{e?.preventDefault();let t=m.trim();t&&v(t)};return(0,F.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,F.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,F.jsx)(`h2`,{children:`选择工作区目录`}),(0,F.jsxs)(`label`,{className:`server-settings-scope`,children:[`目标服务器`,(0,F.jsx)(`select`,{"aria-label":`新建工作区的服务器`,value:r,onChange:e=>ve(e.target.value),children:n.filter(e=>e.enabled).map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))})]}),(0,F.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:y,children:[(0,F.jsx)(`input`,{className:`picker-path-input`,value:m,onChange:e=>{i.current++,c(!0),h(e.target.value),_(!0)},"aria-label":`工作区目录路径`,onKeyDown:e=>{e.key===`Tab`&&!e.shiftKey&&!e.nativeEvent.isComposing&&g&&!s&&a?.entries.length===1?(e.preventDefault(),v(a.entries[0].path)):e.key===`Enter`&&(ND(e)?e.preventDefault():(e.preventDefault(),y()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,F.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!m.trim(),children:`跳转`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!a?.parent||s,onClick:()=>a?.parent&&void v(a.parent),title:`返回上一级目录`,children:`上一级`})]}),a?.drives?.length||a?.homeDir?(0,F.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,F.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),a?.homeDir&&(0,F.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void v(`~`),title:a.homeDir,children:`🏠 主目录`}),a?.drives?.map(e=>(0,F.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void v(e),children:e},e))]}):null,(0,F.jsxs)(`div`,{className:`picker-list`,children:[s&&(0,F.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!s&&l&&(0,F.jsxs)(`div`,{className:`picker-error`,children:[l,(0,F.jsx)(`button`,{onClick:()=>void v(a?.path||m),children:`重试`})]}),!s&&!l&&a?.entries.map(e=>(0,F.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void v(e.path),children:[`📁 `,e.name]},e.path)),!s&&!l&&a&&a.entries.length===0&&(0,F.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!s&&!l&&a?.truncated&&(0,F.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,F.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,F.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(ND(e)?e.preventDefault():(e.preventDefault(),f.trim()&&a&&!g&&!s&&!l&&t(f.trim(),a.path)))},placeholder:`工作区名称`})]}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,F.jsx)(`button`,{className:`picker-ok`,disabled:!f.trim()||s||!!l||!a||g,onClick:()=>a&&t(f.trim(),a.path),children:`使用这个目录`})]})]})})}var lO={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},uO=10;function dO(e,t,n=!1){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`;if(t.configError)return`Pi 拒绝了自己的模型配置,文件里的自定义供应商都没有被提供:${t.configError.split(`
|
|
335
|
-
`).find(e=>e.trim().startsWith(`-`))?.trim()??`详情见设置`}`;if(e===`模型`&&n)return`此会话已包含图片,仅显示支持图文的模型`;if(e===`思考等级`&&!t.levels.length)return`Pi 没有给出当前模型的思考等级`}function
|
|
334
|
+
`)}var AD=95e3;function jD(e){let t=`归档整棵会话树「${e.title}」?本次将归档 ${e.activeCount} 个会话(1 个根会话和 ${e.activeDescendants} 个活跃子孙)${e.alreadyArchived?`,跳过 ${e.alreadyArchived} 个已归档子孙`:``};恢复根会话时,整棵树会一起恢复。`;return e.pendingDecisions>0?`${t}\n还有 ${e.pendingDecisions} 个未拍板的决策,归档后它们会作废。`:t}function MD(e){return e.activeDescendants>0||e.pendingDecisions>0}var ND={workspaces:[],conversations:[],subagentRuns:[]},PD=e=>e.nativeEvent.isComposing||e.keyCode===229,FD=(e,t,n)=>{let r=e.filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),i=r.findIndex(e=>e.id===t);if(i<0||r[i].delivery===`sending`)return e;let a=r.reduce((e,t,n)=>t.delivery===`sending`?n:e,-1),o=Math.max(a+1,Math.min(n,r.length-1));if(o===i)return e;let s=[...r],[c]=s.splice(i,1);s.splice(o,0,c);let l=[...e],u=0;for(let e=0;e<l.length;e+=1)(l[e].role===`user`||l[e].role===`tool`)&&l[e].delivery&&(l[e]=s[u++]);return l},ID=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(e[n].at===t)return n;return-1},LD=(e,t,n)=>{if(t===void 0)return ID(e,n);let r=e.findIndex(e=>e.blockIndex===t);if(r>=0)return r;let i=e.findIndex(e=>e.blockIndex!==void 0);if(i<0)return ID(e,n);let a=t-((e[i].blockIndex??0)-i);return a>=0&&a<e.length?a:-1},RD=(e,t,n)=>{let r=t.at??n,i=[...e],a=LD(i,t.blockIndex,r);return a>=0?i[a]={...i[a],text:i[a].text+t.delta,blockIndex:t.blockIndex??i[a].blockIndex}:i.push({at:r,text:t.delta,blockIndex:t.blockIndex}),i},zD=(e,t)=>{let n=e??[],r=t??[];return r.length>n.length?r:e},BD=e=>{if(typeof e!=`string`||e.length===0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(t)},VD=6e4,HD=60*VD,UD=24*HD,WD=7*UD,GD=30*UD,KD=365*UD,qD=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<HD?`${Math.max(1,Math.floor(r/VD))}m ago`:r<UD?`${Math.floor(r/HD)}h ago`:r<WD?`${Math.floor(r/UD)}d ago`:r<GD?`${Math.floor(r/WD)}w ago`:r<KD?`${Math.floor(r/GD)}mo ago`:`${Math.floor(r/KD)}y ago`},JD=(e,t)=>{let n=e.find(e=>e.id===t);if(!n)return[];let r=new Map;for(let t of e){if(t.workspaceId!==n.workspaceId||!t.parentConversationId)continue;let e=r.get(t.parentConversationId);e?e.push(t):r.set(t.parentConversationId,[t])}let i=[],a=new Set,o=e=>{if(!a.has(e.id)){a.add(e.id),i.push(e);for(let t of r.get(e.id)??[])o(t)}};return o(n),i},YD=e=>{if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};function XD({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,u.useRef)(null),[o,s]=(0,u.useState)({left:t,top:n});(0,u.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let r=e.getBoundingClientRect();s({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),i())},t=e=>{a.current?.contains(e.target)||i()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&i()},o=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&i()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,o),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await Bd(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,F.jsxs)(`div`,{ref:a,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-workspace-id":e.id,style:{left:o.left,top:o.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,F.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function ZD({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a,sendCommand:o,orchestrated:s,childCount:c}){let l=(0,u.useRef)(null),[d,f]=(0,u.useState)({left:t,top:n});(0,u.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let r=e.getBoundingClientRect();f({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{l.current?.contains(e.target)||a()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&a()},i=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&a()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,i),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,i)}},[a]);let p=async e=>{try{let t=await Ne(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`})}),n=await t.json();if(!t.ok)throw Error(n.error);r(`已停止会话(含排队消息)`,`info`)}catch(e){r(`停止失败:${Or(e)}`,`error`)}},m=async e=>{try{let t=await Ne(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`,subtree:!0})}),n=await t.json();if(!t.ok)throw Error(n.error);let i=typeof n.descendantCount==`number`?n.descendantCount:0;r(i>0?`已停止会话及其下属 ${i} 个`:`已停止会话(它没有下属会话)`,`info`)}catch(e){r(`停止子树失败:${Or(e)}`,`error`)}},h=async()=>{let t=await Bd(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,F.jsxs)(`div`,{ref:l,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:d.left,top:d.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void h(),children:`复制会话 ID`}),(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),![`running`,`waiting`,`awaiting_background`].includes(e.status)&&(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-save-warm-session":e.id,onClick:()=>{a();let t=window.prompt(`保存为当前工作区的预热会话。以后选用时会带上当前对话历史。`,e.title)?.trim();t&&!o({type:`conversation.warm.save`,conversationId:e.id,title:t})&&r(`连接断开,未保存预热会话`,`error`)},children:`保存为预热会话`}),(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-stop-turn-session":e.id,onClick:()=>{a(),o({type:`run.stop`,conversationId:e.id})},children:`停止当前回合`}),s&&(0,F.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-queue":e.id,onClick:()=>{a(),p(e.id)},children:`停止会话(含排队消息)`}),c>0&&(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-tree":e.id,onClick:()=>{a(),m(e.id)},children:[`停止整棵子树(`,c,` 个下属)`]}),(0,F.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var QD={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},$D=SD,eO={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},tO={model:`没有可用的模型`,thinking:`Pi 没有给出当前模型的思考等级`,agent:`没有可用的智能体`,subagent:`没有可用的子智能体`},nO={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},rO=`图文`,iO=e=>e.imageInput?rO:void 0,aO=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),oO=(e,t)=>{let n=aO(t.trim());return n?e.filter(e=>aO(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function sO({workspaceId:e,value:t,onChange:n}){let[r,i]=(0,u.useState)([]),[a,o]=(0,u.useState)(``);(0,u.useEffect)(()=>{i([]),o(``)},[e]),(0,u.useEffect)(()=>{let n=!0;return o(``),Ne(`/api/files?workspaceId=${encodeURIComponent(e)}&path=${encodeURIComponent(t)}`).then(async e=>{let r=await e.json();if(!e.ok)throw Error(r.error??`HTTP ${e.status}`);if(!n)return;let a=(r.entries??[]).filter(e=>e.kind===`directory`).map(e=>e.path);i(e=>[...new Set([...e,t,...a])].filter(Boolean).sort())}).catch(e=>{n&&o(e instanceof Error?e.message:`子目录读取失败`)}),()=>{n=!1}},[e,t]);let s=[...new Set([...r,t])].filter(Boolean).sort();return(0,F.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,F.jsx)(`label`,{htmlFor:`empty-session-cwd`,children:`工作目录:`}),(0,F.jsxs)(`select`,{id:`empty-session-cwd`,"data-session-cwd-select":`1`,"aria-label":`会话工作目录(可选)`,value:t,onChange:e=>n(e.target.value),children:[(0,F.jsx)(`option`,{value:``,children:`工作区根目录`}),s.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))]}),a&&(0,F.jsx)(`span`,{role:`status`,children:a})]})}function cO({workspace:e,onClose:t,onCreate:n}){let[r,i]=(0,u.useState)(``),a=(0,u.useRef)(null);return(0,u.useEffect)(()=>{i(``)},[e.id]),(0,u.useEffect)(()=>{let e=a.current;e&&e.focus();let n=e=>{e.key===`Escape`&&(e.preventDefault(),t())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[t]),(0,F.jsx)(`div`,{className:`overlay session-create-overlay`,onClick:t,children:(0,F.jsxs)(`div`,{className:`session-create-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`session-create-title`,tabIndex:-1,ref:a,onClick:e=>e.stopPropagation(),onKeyDown:e=>{if(e.key!==`Tab`)return;let t=a.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), select:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`));if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?document.activeElement===r&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,F.jsx)(`h2`,{id:`session-create-title`,children:`新建会话`}),(0,F.jsxs)(`p`,{className:`session-create-workspace`,children:[`工作区:`,e.name,(0,F.jsx)(`small`,{children:e.path})]}),(0,F.jsx)(sO,{workspaceId:e.id,value:r,onChange:i}),(0,F.jsxs)(`div`,{className:`session-create-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`session-create-cancel`,onClick:t,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`session-create-confirm picker-ok`,onClick:()=>n(r),children:`创建会话`})]})]})})}function lO({onClose:e,onCreate:t}){let{connections:n,activeServer:r}=ue(),i=(0,u.useRef)(0),[a,o]=(0,u.useState)(),[s,c]=(0,u.useState)(!0),[l,d]=(0,u.useState)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(``),[g,_]=(0,u.useState)(!1),v=async(e,t)=>{let n=++i.current;t===void 0&&_(!1),c(!0),d(void 0);try{let a=new URLSearchParams;e&&a.set(`path`,e),t!==void 0&&a.set(`prefix`,t);let s=await Ne(`/api/fs/dirs?${a}`,{},r),c=await s.json();if(!s.ok)throw Error(c.error??`HTTP ${s.status}`);if(n!==i.current)return;let l=c;o(l),t===void 0&&(h(l.path),p(l.suggestedName),_(!1))}catch(e){n===i.current&&d(e instanceof Error?e.message:`目录加载失败`)}finally{n===i.current&&c(!1)}};(0,u.useEffect)(()=>{o(void 0),h(``),v()},[r]),(0,u.useEffect)(()=>{if(!g||!a)return;let e=lr(m,a.path),t=window.setTimeout(()=>{v(e.path,e.prefix)},180);return()=>{window.clearTimeout(t)}},[m,g,r]),(0,u.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let y=e=>{e?.preventDefault();let t=m.trim();t&&v(t)};return(0,F.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,F.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,F.jsx)(`h2`,{children:`选择工作区目录`}),(0,F.jsxs)(`label`,{className:`server-settings-scope`,children:[`目标服务器`,(0,F.jsx)(`select`,{"aria-label":`新建工作区的服务器`,value:r,onChange:e=>ve(e.target.value),children:n.filter(e=>e.enabled).map(e=>(0,F.jsx)(`option`,{value:e.id,children:e.name},e.id))})]}),(0,F.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:y,children:[(0,F.jsx)(`input`,{className:`picker-path-input`,value:m,onChange:e=>{i.current++,c(!0),h(e.target.value),_(!0)},"aria-label":`工作区目录路径`,onKeyDown:e=>{e.key===`Tab`&&!e.shiftKey&&!e.nativeEvent.isComposing&&g&&!s&&a?.entries.length===1?(e.preventDefault(),v(a.entries[0].path)):e.key===`Enter`&&(PD(e)?e.preventDefault():(e.preventDefault(),y()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,F.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!m.trim(),children:`跳转`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!a?.parent||s,onClick:()=>a?.parent&&void v(a.parent),title:`返回上一级目录`,children:`上一级`})]}),a?.drives?.length||a?.homeDir?(0,F.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,F.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),a?.homeDir&&(0,F.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void v(`~`),title:a.homeDir,children:`🏠 主目录`}),a?.drives?.map(e=>(0,F.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void v(e),children:e},e))]}):null,(0,F.jsxs)(`div`,{className:`picker-list`,children:[s&&(0,F.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!s&&l&&(0,F.jsxs)(`div`,{className:`picker-error`,children:[l,(0,F.jsx)(`button`,{onClick:()=>void v(a?.path||m),children:`重试`})]}),!s&&!l&&a?.entries.map(e=>(0,F.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void v(e.path),children:[`📁 `,e.name]},e.path)),!s&&!l&&a&&a.entries.length===0&&(0,F.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!s&&!l&&a?.truncated&&(0,F.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,F.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,F.jsx)(`input`,{value:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(PD(e)?e.preventDefault():(e.preventDefault(),f.trim()&&a&&!g&&!s&&!l&&t(f.trim(),a.path)))},placeholder:`工作区名称`})]}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,F.jsx)(`button`,{className:`picker-ok`,disabled:!f.trim()||s||!!l||!a||g,onClick:()=>a&&t(f.trim(),a.path),children:`使用这个目录`})]})]})})}var uO={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},dO=10;function fO(e,t,n=!1){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`;if(t.configError)return`Pi 拒绝了自己的模型配置,文件里的自定义供应商都没有被提供:${t.configError.split(`
|
|
335
|
+
`).find(e=>e.trim().startsWith(`-`))?.trim()??`详情见设置`}`;if(e===`模型`&&n)return`此会话已包含图片,仅显示支持图文的模型`;if(e===`思考等级`&&!t.levels.length)return`Pi 没有给出当前模型的思考等级`}function pO(e){if(!e)return`正在读取 agent 列表…`;if(e.source!==`directory`)return`读取 agent 列表失败:${e.error??`未知原因`}`;if(e.problems.length)return`${e.problems.length} 个 agent 文件无法使用:${e.problems.map(e=>e.file).join(`、`)}`;if(!e.agents.length)return`${e.directory} 下没有 primary agent`}var mO=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function hO(e){if(e===void 0||!Number.isFinite(e))return``;let t=Math.max(0,e);return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}分${Math.round(t%6e4/1e3)}秒`}var gO={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function _O(e){return e.replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,``).replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,``).replace(/\u001b[@-_]/g,``).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,``).split(/\r?\n/).map(e=>e.trim()).filter(Boolean).at(-1)??``}function vO(e,t){let[n,r]=(0,u.useState)(()=>t.get(e));return(0,u.useEffect)(()=>{r(t.get(e));let n,i=i=>{i.detail===e&&n===void 0&&(n=requestAnimationFrame(()=>{n=void 0,r(t.get(e))}))};return window.addEventListener(`super-pi-exec-output`,i),()=>{window.removeEventListener(`super-pi-exec-output`,i),n!==void 0&&cancelAnimationFrame(n)}},[e,t]),n}function yO({task:e,execOutputs:t,expanded:n}){let r=vO(e.id,t),i=e.status===`running`?r?.text||e.output:e.output??r?.text,a=i&&OD(i),o=e.status===`running`?r?.truncated??e.outputTruncated:e.outputTruncated;return(0,F.jsxs)(F.Fragment,{children:[!n&&a&&(0,F.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:_O(a)}),n&&(0,F.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:[e.reason,o?`日志仅保留最近一段。`:``,a].filter(Boolean).join(`
|
|
336
336
|
|
|
337
|
-
`)||(e.status===`running`?`等待输出…`:`任务未产生输出。`)})]})}function yO({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,F.jsxs)(`div`,{className:`call-block call-block-${e.status??`running`}`,"data-call-block":t,"data-call-tool":e.label,"data-call-detail":e.detail??void 0,"data-call-status":e.status??`running`,"data-call-expanded":n?`true`:`false`,"data-call-arg-count":o.length,"data-thinking-at":e.thinkingAt,"data-background-exec":e.backgroundTask?.id,"data-background-status":e.backgroundTask?.status,children:[(0,F.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-call-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`} ${e.label} 调用`,title:n?`折叠这次调用`:`展开这次调用`,onClick:r}),(0,F.jsxs)(`div`,{className:`call-head-row`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,F.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,F.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,F.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,F.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,F.jsx)(`span`,{className:`call-duration`,children:mO(e.durationMs)}),e.backgroundTask&&(0,F.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,JO[e.backgroundTask.status]??`未知状态`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,F.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,F.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,F.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:gO(e.live)}),n&&(0,F.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,F.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,F.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,F.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,F.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,F.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,F.jsxs)(`div`,{className:`call-result-head`,children:[(0,F.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,F.jsx)(bO,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,F.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,F.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,F.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function bO({index:e,text:t}){let[n,r]=(0,u.useState)(!1);return(0,F.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await Bd(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function xO({messageId:e,nestedCount:t,liveCall:n,liveAwaitingReader:r,liveExtra:i,preview:a,expanded:o,onToggle:s,children:c}){return(0,F.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":o?`true`:`false`,"data-thinking-calls":t,children:[(0,F.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":o,"aria-label":`${o?`折叠`:`展开`}这段思考`,title:o?`折叠这段思考`:`展开这段思考`,onClick:s}),(0,F.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":o,title:o?`折叠这段思考`:`展开这段思考`,onClick:s,children:[(0,F.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`}),(0,F.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,F.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!o&&n&&(0,F.jsxs)(`span`,{className:`thinking-live${r?` thinking-live-question`:``}`,"data-thinking-live":n,"data-thinking-live-extra":i??0,"data-thinking-awaiting-reader":r?`1`:void 0,children:[(0,F.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:r?`?`:`⚙`}),r?`等你回答`:`正在执行 ${n}`,i?` 等 ${i+1} 个`:``]}),!o&&a&&(0,F.jsx)(`span`,{className:`thinking-preview`,title:a,children:a})]}),o&&(0,F.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:c})]})}function SO({run:e,name:t,expanded:n,onToggle:r,onStop:i,stopping:a}){let o=e.toolCalls??[],s=n?o:o.slice(-10),c=o.length-s.length,l=e.status===`running`,d=e.partialOutput??e.output??``,f=e.dispatchedBy===`model`,[p,m]=(0,u.useState)(0);(0,u.useEffect)(()=>{if(!l)return;m(Date.now());let e=window.setInterval(()=>m(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let h=Date.parse(e.startedAt),g=l&&p>0&&Number.isFinite(h)?p-h:void 0,_=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,F.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${f?` subagent-by-model`:``}`,"data-subagent-card":e.id,"data-subagent-status":e.status,"data-subagent-agent":e.agentId,"data-subagent-tools":o.length,"data-subagent-dispatched-by":f?`model`:`human`,children:[(0,F.jsxs)(`div`,{className:`subagent-head`,children:[(0,F.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),f&&(0,F.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,F.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,F.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,F.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?g!==void 0&&(0,F.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":g,children:[`已运行 `,mO(g)]}):e.durationMs!==void 0&&(0,F.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,mO(e.durationMs)]}),l&&(0,F.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,F.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,F.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,F.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[f&&(0,F.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,F.jsxs)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":d.length,children:[d||(l?`…`:`(没有输出)`),e.outputTruncated&&`(输出已截断)`]}),e.failure&&(0,F.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,F.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,F.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:hO[e.failure.stage]}),e.failure.stage===`tool`&&_&&(0,F.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,_]}),o.length>0&&(0,F.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,F.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,title:kr(e.error),children:Or(e.error,`这条子任务没有完成。`)}),o.length>0&&(0,F.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,F.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,F.jsxs)(`div`,{children:[(0,F.jsxs)(`div`,{className:`subagent-tool${e.status?` subagent-tool-${e.status}`:``}`,"data-subagent-tool":e.label,"data-subagent-tool-detail":e.detail??void 0,"data-subagent-tool-status":e.status??`running`,children:[(0,F.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,F.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,F.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,F.jsx)(`span`,{className:`subagent-tool-duration`,children:mO(e.durationMs)})]}),e.output&&(0,F.jsxs)(`details`,{className:`subagent-tool-log`,children:[(0,F.jsxs)(`summary`,{children:[`命令输出`,e.outputTruncated&&`(尾部)`]}),(0,F.jsx)(`pre`,{className:`call-result-body`,"data-subagent-tool-output":!0,children:e.output})]})]},`${c&&!n?c+t:t}:${e.label}`))]}),e.usage&&(0,F.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,F.jsxs)(`span`,{children:[e.usage.turns,` 轮`]}),(0,F.jsxs)(`span`,{title:`输入 token`,children:[`↑`,pO(e.usage.input)]}),(0,F.jsxs)(`span`,{title:`输出 token`,children:[`↓`,pO(e.usage.output)]}),e.usage.cacheRead>0&&(0,F.jsxs)(`span`,{title:`缓存读取`,children:[`缓存读 `,pO(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,F.jsxs)(`span`,{title:`缓存写入`,children:[`缓存写 `,pO(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,F.jsxs)(`span`,{title:`本轮花费`,children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,F.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function CO(e,t=[]){return Array.isArray(t)?t.filter(t=>typeof t?.id==`string`&&(pf(e,t.id)||!t.id.startsWith(`skill:`)&&typeof t.name==`string`&&pf(e,t.name))):[]}function wO(e){let t=e.deliveryMode===`steer`?`steer`:`queue`;return{type:`message.send`,conversationId:e.conversationId,content:e.content,clientId:e.clientId,...e.images?.length?{images:e.images}:{},...e.attachments?.length?{attachments:e.attachments}:{},...e.inFlight&&t===`steer`?{mode:`steer`}:{}}}function TO({mode:e,onChange:t}){return(0,F.jsxs)(`div`,{className:`composer-delivery-bar`,"data-delivery-mode-bar":`1`,children:[(0,F.jsxs)(`div`,{className:`delivery-mode-group`,role:`radiogroup`,"aria-label":`运行中消息投递模式`,children:[(0,F.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`queue`,className:`delivery-mode-btn${e===`queue`?` active`:``}`,"data-delivery-mode":`queue`,title:`等待当前回合与前面排队消息完成后依次回答(默认)`,onClick:()=>t(`queue`),children:`排队`}),(0,F.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`steer`,className:`delivery-mode-btn${e===`steer`?` active`:``}`,"data-delivery-mode":`steer`,title:`在当前工具调用完成后的下一回合边界插队回复,不会强行中止正在执行的工具`,onClick:()=>t(`steer`),children:`打断`})]}),(0,F.jsx)(`span`,{className:`delivery-mode-note`,"data-delivery-mode-note":`1`,children:e===`steer`?`将在下一回合边界生效(等当前工具跑完,不强行中止工具)`:`默认排队:等当前回合及前面排队消息完成后回答`})]})}function EO({messages:e,running:t,pendingInterrupts:n=[],onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onCancelMany:s,onEdit:c}){let[l,d]=(0,u.useState)(!1),[f,p]=(0,u.useState)([]),m=(0,u.useMemo)(()=>e.filter(e=>e.delivery!==`sending`).map(e=>e.id),[e]),h=(0,u.useMemo)(()=>f.filter(e=>m.includes(e)),[f,m]);if(!e.length)return null;let g=e.filter(e=>e.delivery===`sending`).length,_=m.length>0&&h.length===m.length,v=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])};return(0,F.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-interrupt-pending":n.length,"data-queue-count":e.length,"data-queue-sending":g,"aria-label":`排队等待回答的消息`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!l,onClick:()=>d(e=>!e),children:[(0,F.jsx)(`span`,{className:`chevron`,children:l?`▸`:`▾`}),(0,F.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),g>0&&(0,F.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,g,` 条`]}),l&&(0,F.jsx)(`span`,{className:`queue-dock-preview`,children:DO(e[0])})]}),!l&&s&&(m.length>1||h.length>0)&&(0,F.jsxs)(`div`,{className:`queue-dock-toolbar`,"data-queue-bulk-toolbar":`1`,children:[(0,F.jsx)(`span`,{className:`queue-dock-selected-count`,children:h.length>0?`已选 ${h.length} 条`:`共 ${m.length} 条可多选撤回`}),(0,F.jsxs)(`div`,{className:`queue-dock-toolbar-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`queue-select-all`,"data-waiting-select-all":`1`,onClick:()=>p(_?[]:m),children:_?`取消全选`:`全选`}),(0,F.jsxs)(`button`,{type:`button`,className:`queue-cancel-selected`,"data-waiting-cancel-selected":`1`,disabled:h.length===0,onClick:()=>{h.length!==0&&(s(h),p([]))},children:[`撤回所选 (`,h.length,`)`]})]})]}),!l&&(0,F.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((l,u)=>(0,F.jsx)(kO,{message:l,order:u+1,total:e.length,interrupting:n.includes(l.id),running:t,selectable:!!(s&&l.delivery!==`sending`),selected:h.includes(l.id),onToggleSelect:v,onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:c},l.id))})]})}function DO(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function OO(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};if(!/<task id="[^"]+" state="[^"]+"/.test(e.content))return{label:(e.content.split(`
|
|
338
|
-
`).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`,state:`running`};let t=(()=>{let t=/<summary>([\s\S]*?)<\/summary>/.exec(e.content);return t?t[1].trim():`后台回传`})(),n=/<task id="[^"]+" state="([^"]+)"/.exec(e.content);return{label:t,state:n?n[1]:`completed`}}function
|
|
339
|
-
`)??``}}function MO({question:e,index:t,expanded:n,draft:r,onDraftChange:i,onToggle:a,onAnswer:o}){return(0,F.jsxs)(`div`,{className:`call-block question-block-${e.status}`,"data-call-block":t,"data-call-tool":`question`,"data-call-detail":`提问`,"data-call-status":e.status===`answered`?`ok`:e.status===`cancelled`?`error`:`running`,"data-call-expanded":n?`true`:`false`,"data-question-block":t,children:[(0,F.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:a}),(0,F.jsxs)(`div`,{className:`call-head-row`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:a,children:[(0,F.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,F.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,F.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,F.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,F.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:a,children:`收起`})]}),n&&(0,F.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,F.jsx)(NO,{question:e,draft:r,onDraftChange:i,instanceId:`inline`,onAnswer:o})})]})}function NO({question:e,draft:t,onDraftChange:n,instanceId:r,onAnswer:i}){let{picked:a,note:o}=t,s=(e,r,i)=>{let o=(()=>{let t=a,n=t[e]??[];return i?{...t,[e]:n.includes(r)?n.filter(e=>e!==r):[...n,r]}:{...t,[e]:[r]}})();n({...t,picked:o})},c=()=>{i(e.items.map(e=>({id:e.id,selected:a[e.id]??[],...e.extraNote&&o.trim()?{note:o.trim()}:{}})),!1)},l=e.items.some(e=>(a[e.id]??[]).length>0);return(0,F.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(i=>(0,F.jsxs)(`div`,{className:`question-item`,children:[(0,F.jsx)(`div`,{className:`question-text`,children:i.header?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`span`,{className:`question-header`,children:i.header}),(0,F.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,F.jsx)(ef,{source:i.question})]}):(0,F.jsx)(ef,{source:i.question})}),(0,F.jsx)(`div`,{className:`question-options`,"data-question-options":i.id,children:i.options.map(t=>{let n=e.status!==`pending`,o=(n?e.answers?.find(e=>e.id===i.id)?.selected:a[i.id])?.includes(t)??!1;return(0,F.jsxs)(`label`,{className:o?`is-chosen`:``,"data-chosen":n&&o?`1`:void 0,children:[(0,F.jsx)(`input`,{type:i.multiple?`checkbox`:`radio`,name:`q-${r}-${i.id}`,checked:o,disabled:n,onChange:()=>s(i.id,t,i.multiple)}),(0,F.jsx)(tf,{source:t}),n&&o?(0,F.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},t)})}),e.status===`pending`&&i.extraNote?(0,F.jsx)(`textarea`,{value:o,placeholder:`补充说明(可选)`,onChange:e=>n({...t,note:e.target.value})}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,F.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,F.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},i.id)),e.status===`pending`&&(0,F.jsxs)(`div`,{className:`question-actions`,children:[(0,F.jsx)(`button`,{type:`button`,onClick:c,disabled:!l,children:`提交`}),(0,F.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>i([],!0),children:`跳过`})]})]})}function PO({question:e,pendingCount:t,minimized:n,floatingRight:r,onMinimize:i,onExpand:a,onLocate:o,draft:s,onDraftChange:c,onAnswer:l}){return n?(0,Re.createPortal)((0,F.jsxs)(`button`,{type:`button`,className:`question-floating-ball`,style:{"--question-floating-right":r},"data-question-floating-ball":e.key,onClick:a,"aria-label":`展开待回答的问题${t>1?`,还有 ${t-1} 个待处理`:``}`,title:`展开待回答的问题`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`?`}),t>1&&(0,F.jsx)(`small`,{children:t})]}),document.body):(0,Re.createPortal)((0,F.jsxs)(`section`,{className:`question-floating-panel`,style:{"--question-floating-right":r},"data-question-floating-panel":e.key,role:`dialog`,"aria-labelledby":`question-floating-title`,children:[(0,F.jsxs)(`header`,{className:`question-floating-head`,children:[(0,F.jsx)(`span`,{className:`question-floating-mark`,"aria-hidden":`true`,children:`?`}),(0,F.jsxs)(`h2`,{id:`question-floating-title`,children:[`需要你回答`,t>1?` · 还有 ${t-1} 个`:``]}),(0,F.jsx)(`button`,{type:`button`,className:`question-floating-minimize`,onClick:o,title:`定位到消息上下文并最小化`,children:`查看上下文`}),(0,F.jsx)(`button`,{type:`button`,className:`question-floating-minimize-icon`,onClick:i,title:`最小化为悬浮球`,"aria-label":`最小化问题`,children:`−`})]}),(0,F.jsx)(`div`,{className:`question-floating-body`,children:(0,F.jsx)(NO,{question:e.value,draft:s,onDraftChange:c,instanceId:`floating`,onAnswer:l})})]}),document.body)}function FO({request:e,onAnswer:t,pending:n}){let[r,i]=(0,u.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,F.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,F.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,F.jsxs)(`div`,{className:`extui-head`,children:[(0,F.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,F.jsxs)(`span`,{className:`extui-deadline`,children:[Math.ceil(Math.max(0,e.deadlineAt===void 0?e.timeoutMs:e.deadlineAt-Date.now())/1e3),`s 超时`]})]}),n&&(0,F.jsx)(`p`,{className:`extui-pending`,role:`status`,children:`提交中…`}),(0,F.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,F.jsx)(`h3`,{className:`extui-title`,children:e.title||YO[e.method]}),e.method===`confirm`&&(0,F.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,F.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,F.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,F.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,F.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,F.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ND(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,F.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ND(e)&&e.preventDefault()}}),(0,F.jsxs)(`div`,{className:`extui-actions`,children:[(0,F.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,F.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,F.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,F.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function IO({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,u.useState)(e),o=(0,u.useRef)(null),s=(0,u.useRef)(!1);(0,u.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},d=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,F.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,F.jsx)(`input`,{ref:o,className:`inline-edit-input`,value:i,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{if(e.key===`Enter`){if(ND(e))return;e.preventDefault(),d()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,F.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:d,children:`✓`}),(0,F.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function LO({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c,providerOptions:l}){let[d,f]=(0,u.useState)(!1),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(0),[_,v]=(0,u.useState)(`*`),y=(0,u.useRef)(null),b=(0,u.useRef)(null),x=(0,u.useRef)(null),S=(0,u.useRef)(null),C=(0,u.useRef)([]),w=i.find(e=>e.selected),T=aO(l?i.filter(e=>_===`*`||e.key!==RO&&e.key.split(`/`)[0]===_):i,p),E=T.length===0?-1:Math.min(Math.max(h,0),T.length-1),D=E<0?void 0:T[E],O=(e=!1)=>{f(!1),e&&b.current?.focus()},k=()=>{m(``),v(`*`),g(Math.max(i.findIndex(e=>e.selected),0)),f(!0)},A=e=>g(t=>T.length?Math.min(Math.max(t+e,0),T.length-1):0);(0,u.useEffect)(()=>{if(!d)return;let e=e=>{y.current?.contains(e.target)||O()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[d]),(0,u.useEffect)(()=>{if(!d)return;let e=y.current,t=t=>{e?.contains(t.relatedTarget)||O()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[d]),(0,u.useEffect)(()=>{d&&S.current?.focus()},[d]),(0,u.useEffect)(()=>{d&&E>=0&&C.current[E]?.scrollIntoView({block:`nearest`})},[d,E]),(0,u.useLayoutEffect)(()=>{if(!d)return;let e=x.current;if(!e)return;e.style.setProperty(`--picker-nudge`,`0px`),e.style.setProperty(`--picker-drop`,`0px`);let t=e.getBoundingClientRect(),n=Math.min(window.innerWidth-8-t.right,Math.max(8-t.left,0)),r=Math.min(window.innerHeight-8-t.bottom,Math.max(8-t.top,0));e.style.setProperty(`--picker-nudge`,`${n}px`),e.style.setProperty(`--picker-drop`,`${r}px`)},[d,T.length,i.length]);let j=e=>{if(d){if(e.key===`Escape`)e.preventDefault(),O(!0);else if(e.key===`ArrowDown`)e.preventDefault(),A(1);else if(e.key===`ArrowUp`)e.preventDefault(),A(-1);else if(e.key===`Home`)e.preventDefault(),g(0);else if(e.key===`End`)e.preventDefault(),g(Math.max(T.length-1,0));else if(e.key===`Enter`){if(ND(e))return;e.preventDefault(),D&&(s(D.key),O(!0))}}},ee=`picker-list-${c??e}`,M=t=>`picker-option-${c??e}-${t}`;return(0,F.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:y,onKeyDown:d?j:void 0,children:[(0,F.jsxs)(`button`,{ref:b,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":d,title:o??`${ZD[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>d?O():k(),children:[(0,F.jsx)(`span`,{className:`session-picker-kind`,children:ZD[e]}),(0,F.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,F.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,F.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),d&&(0,F.jsxs)(`div`,{className:`picker-menu`,ref:x,"data-picker-menu":e,"data-picker-highlight":E,children:[l&&(0,F.jsxs)(`label`,{className:`picker-provider-filter`,children:[(0,F.jsx)(`span`,{children:`Provider`}),(0,F.jsxs)(`select`,{"data-picker-provider":e,"aria-label":`筛选模型 Provider`,value:_,onKeyDown:e=>e.stopPropagation(),onChange:e=>{v(e.target.value),g(0)},children:[(0,F.jsx)(`option`,{value:`*`,children:`全部 Provider`}),l.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))]})]}),(0,F.jsxs)(`div`,{className:`picker-filter`,children:[(0,F.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,F.jsx)(`input`,{ref:S,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${$D[e]}选项`,"aria-expanded":`true`,"aria-controls":ee,"aria-autocomplete":`list`,"aria-activedescendant":D?M(E):void 0,value:p,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{m(e.target.value),g(0)}}),p&&(0,F.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{m(``),g(0),S.current?.focus()},children:`✕`})]}),w&&!T.some(e=>e.key===w.key)&&(0,F.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":w.key,children:[(0,F.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,F.jsx)(`span`,{className:`picker-current-value`,children:w.label})]}),(0,F.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:ee,"aria-label":tO[e],children:[T.map((e,t)=>(0,F.jsxs)(`button`,{id:M(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{C.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===E&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===E,onClick:()=>{s(e.key),O(!0)},children:[e.color&&(0,F.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,F.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,F.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,F.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,F.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),T.length===0&&(0,F.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:i.length===0?eO[e]:`没有匹配「${p.trim()}」的${$D[e]}`})]})]})]})}var RO=`__pi_default__`;function zO({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onRemove:a,onClose:o}){let[s,c]=(0,u.useState)(e.defaultAgentId),[l,d]=(0,u.useState)(e.defaultModel),[f,p]=(0,u.useState)(e.defaultThinkingLevel);(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let m=t?.source===`pi`,h=[{key:RO,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:l===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,CD(e.contextWindow)?`${CD(e.contextWindow)} 上下文`:``,wD(e.maxTokens)?`${wD(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:rO(e),selected:l?.provider===e.provider&&l.modelId===e.modelId}))],g=t?.models.find(e=>e.provider===l?.provider&&e.modelId===l?.modelId),_=g?.thinkingLevels??t?.levels??[],v=[{key:RO,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:f===void 0},..._.map(e=>({key:e,label:e,selected:e===f}))],y=e=>{if(e===RO){d(void 0),p(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);if(n){let e=l?.provider!==n.provider||l.modelId!==n.modelId;d({provider:n.provider,modelId:n.modelId,label:n.label}),e&&p(void 0)}},b=e=>p(e===RO?void 0:e),x=[{key:RO,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:s===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:s===e.id}))];return(0,F.jsx)(`div`,{className:`overlay`,onClick:o,children:(0,F.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,F.jsx)(`h2`,{children:`工作区设置`}),(0,F.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,F.jsx)(`div`,{className:`workspace-settings-path`,children:e.path}),(0,F.jsxs)(`div`,{className:`settings-row`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,F.jsx)(LO,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===s)?.name??`跟随 Pi 默认`,value:s??RO,detail:s?`${n?.agents.find(e=>e.id===s)?.toolSummary??``}`:void 0,options:x,disabled:!n||n.source===`unavailable`,note:fO(n),onChoose:e=>c(e===RO?void 0:e)})]}),(0,F.jsxs)(`div`,{className:`settings-row`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,F.jsx)(LO,{kind:`model`,scope:`settings-model`,label:l?.label??`跟随 Pi 默认`,value:l?`${l.provider}/${l.modelId}`:RO,detail:l?`${l.provider}/${l.modelId}`:void 0,options:h,providerOptions:[...new Set((t?.models??[]).map(e=>e.provider))],disabled:!m,note:dO(`模型`,t),onChoose:y})]}),(0,F.jsxs)(`div`,{className:`settings-row`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,F.jsx)(LO,{kind:`thinking`,scope:`settings-thinking`,label:f??`跟随 Pi 默认`,value:f??RO,options:v,disabled:!m,note:dO(`思考等级`,t),onChoose:b})]}),l&&g&&_.length===0&&(0,F.jsx)(`div`,{className:`settings-scope`,children:`Pi 未提供此模型的可选等级,使用模型默认值。`}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:o,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(s,l,f),children:`保存`})]}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-delete`,onClick:a,children:`从列表移除工作区`})]})})}var BO=[{id:`main`,label:`任务`,name:`任务与后台任务`},{id:`projects`,label:`项目`,name:`项目控制面`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`terminal`,label:`终端`,name:`终端 tab`}],VO=`super-pi.right-tabs.v1`;function HO(){let e=e=>BO.some(t=>t.id===e),t={tab:BO[0].id,byConversation:{}};try{let n=JSON.parse(Pn(VO)??`null`);return!n||!e(n.tab)?t:{tab:n.tab,byConversation:Object.fromEntries(Object.entries(n.byConversation??{}).filter(t=>e(t[1])))}}catch{return t}}var UO={waiting:`⋯`,running:``,failed:``,question:`?`,completed:``,unread:`•`,idle:``,awaiting_background:`⚙`,pending_report:`↑`,awaiting_subordinates:`↓`,awaiting_decision:`▲`},WO={idle:`空闲`,running:`讨论中`,awaiting_background:`后台任务进行中`,completed:`讨论已完成`,failed:`讨论未完成`},GO={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,completed:`已完成`,unread:`有未读`,idle:`空闲`,awaiting_background:`等待后台任务`,pending_report:`待汇报`,awaiting_subordinates:`等待下级`,awaiting_decision:`等上面拍板`},KO={idle:`就绪`,waiting:`等待 LLM`,running:`正在生成`,completed:`已完成`,stopped:`已停止`,failed:`运行失败`,awaiting_background:`等待后台任务`},qO=e=>e?.status===`running`||e?.status===`waiting`,JO={running:`运行中`,completed:`已完成`,failed:`失败`,stopped:`已停止`,cancelled:`已取消`,interrupted:`已中断`},YO={select:`请选择一项`,confirm:`请确认`,input:`请输入内容`,editor:`请输入内容`,notify:`扩展通知`,setStatus:`扩展状态`,setWidget:`扩展内容`,setTitle:`扩展标题`,set_editor_text:`扩展输入`};function XO(e,t){return t.some(t=>t.conversationId===e.id)?!0:e.messagesLoaded===!1?e.hasPendingQuestion===!0:e.messages.some(e=>(e.toolCalls??[]).some(e=>e.question?.status===`pending`))}function ZO(e,t,n){let r=(t||[]).filter(t=>t.parentConversationId===e.id),i=(t||[]).find(t=>t.id===e.parentConversationId),a=n??``;return Hn({conversation:e,parent:i,directChildren:r,isTopLevelUnread:e.updatedAt>a})}function QO(e,t,n,r){let i=ZO(e,r,n);return Un({status:e.status,reportingState:i,awaitingQuestion:t,quietWhenRead:!0})}function $O(e,t){return t===`awaiting_decision`||e===`awaiting_decision`?(0,F.jsx)(`span`,{className:`conversation-status-badge badge--warning project-status-awaiting_decision`,"data-session-status":`awaiting_decision`,"data-reporting-badge":`awaiting_decision`,title:GO.awaiting_decision,children:GO.awaiting_decision}):t===`awaiting_subordinates`||e===`awaiting_subordinates`?(0,F.jsx)(`span`,{className:`conversation-status-badge project-status-awaiting_subordinates`,"data-session-status":`awaiting_subordinates`,"data-reporting-badge":`awaiting_subordinates`,title:GO.awaiting_subordinates,children:GO.awaiting_subordinates}):t===`pending_report`||e===`pending_report`?(0,F.jsx)(`span`,{className:`conversation-status-badge project-status-pending_report`,"data-session-status":`pending_report`,"data-reporting-badge":`pending_report`,title:GO.pending_report,children:GO.pending_report}):null}function ek({state:e,label:t=GO[e]}){let n=UO[e];if(e===`idle`)return null;let r=e.replace(/_/g,`-`);return(0,F.jsx)(`i`,{className:`session-state session-state-${e} session-state-${r}`,"data-session-state":e,title:t,"aria-label":t,...e===`awaiting_background`?{style:{color:`var(--accent)`}}:{},children:(0,F.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:n})})}function tk(e,t){return(0,F.jsxs)(F.Fragment,{children:[e.origin===`orchestrator`&&(0,F.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`orchestrator`,title:`编排会话:由上级智能体创建`,"aria-label":`编排会话:由上级智能体创建`,children:`编排`}),t&&(0,F.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`scheduled`,title:`定时任务会话:${t.name}`,"aria-label":`定时任务会话:${t.name}`,children:`定时`})]})}function nk(e,t){let n=[];return e.origin===`orchestrator`&&n.push(`编排会话`),t&&n.push(`定时任务会话:${t.name}`),n.length?`(${n.join(`;`)})`:``}var rk={pending:`未开始`,in_progress:`运行中`,completed:`已完成`},ik={pending:`○`,in_progress:`◐`,completed:`✓`},ak={high:`高`,medium:`中`,low:`低`};function ok(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function sk({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,F.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,title:`状态:${rk[e.status]}`,children:[(0,F.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:ik[e.status]}),(0,F.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,F.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:rk[e.status]}),e.priority&&(0,F.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:ak[e.priority]})]})}function ck(e,t){if(!e)return[];let n=t.filter(t=>t.conversationId===e.id&&t.status===`running`),r=new Set(n.map(e=>e.id));for(let t of e.messages)t.toolCalls?.forEach((i,a)=>{let o=i.backgroundTask;o&&o.status===`running`&&!r.has(o.id)&&(r.add(o.id),n.push({id:o.id,conversationId:e.id,title:i.detail?.trim()||i.label?.trim()||o.id,status:o.status,originMessageId:t.id,originCallRow:a}))});return n}function lk({tasks:e,runs:t,execOutputs:n,onStop:r}){return(0,F.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,i)=>{let a=e.id||`bg_${i}`,o=e.status?.trim()||``,s=o?JO[o]??(/[\u3400-\u9fff]/.test(o)?o:`未知状态`):`未知状态`;return(0,F.jsx)(uk,{task:e,status:s,run:t?.get(e.id),execOutputs:n,onStop:r},a)})})}function uk({task:e,status:t,run:n,execOutputs:r,onStop:i}){let[a,o]=(0,u.useState)(!1),s=_O(e.id,r),c=n?OD(n):s?.text||e.output,l=c&&DD(c),d=n?n.outputTruncated||n.toolCalls?.some(e=>e.outputTruncated):s?.truncated??e.outputTruncated;return(0,F.jsxs)(`li`,{className:`bg-item${a?` bg-item-expanded`:``}`,"data-bg-task":e.id,"data-bg-task-status":e.status??`unknown`,title:`状态:${t}`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`bg-item-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,"aria-label":`展开后台任务详情`,children:[(0,F.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务`}),(0,F.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,F.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,F.jsx)(`span`,{className:`bg-status`,children:t})]})]}),i&&(0,F.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:()=>i(e.id),children:`终止`}),a&&(0,F.jsx)(`pre`,{className:`bg-output`,"data-bg-output":e.id,children:[d?`日志仅保留最近一段。`:``,l].filter(Boolean).join(`
|
|
337
|
+
`)||(e.status===`running`?`等待输出…`:`任务未产生输出。`)})]})}function bO({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,F.jsxs)(`div`,{className:`call-block call-block-${e.status??`running`}`,"data-call-block":t,"data-call-tool":e.label,"data-call-detail":e.detail??void 0,"data-call-status":e.status??`running`,"data-call-expanded":n?`true`:`false`,"data-call-arg-count":o.length,"data-thinking-at":e.thinkingAt,"data-background-exec":e.backgroundTask?.id,"data-background-status":e.backgroundTask?.status,children:[(0,F.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-call-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`} ${e.label} 调用`,title:n?`折叠这次调用`:`展开这次调用`,onClick:r}),(0,F.jsxs)(`div`,{className:`call-head-row`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,F.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,F.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,F.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,F.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,F.jsx)(`span`,{className:`call-duration`,children:hO(e.durationMs)}),e.backgroundTask&&(0,F.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,YO[e.backgroundTask.status]??`未知状态`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,F.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,F.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,F.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:_O(e.live)}),n&&(0,F.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,F.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,F.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,F.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,F.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,F.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,F.jsxs)(`div`,{className:`call-result-head`,children:[(0,F.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,F.jsx)(xO,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,F.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,F.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,F.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function xO({index:e,text:t}){let[n,r]=(0,u.useState)(!1);return(0,F.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await Bd(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function SO({messageId:e,nestedCount:t,liveCall:n,liveAwaitingReader:r,liveExtra:i,preview:a,expanded:o,onToggle:s,children:c}){return(0,F.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":o?`true`:`false`,"data-thinking-calls":t,children:[(0,F.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":o,"aria-label":`${o?`折叠`:`展开`}这段思考`,title:o?`折叠这段思考`:`展开这段思考`,onClick:s}),(0,F.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":o,title:o?`折叠这段思考`:`展开这段思考`,onClick:s,children:[(0,F.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`}),(0,F.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,F.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!o&&n&&(0,F.jsxs)(`span`,{className:`thinking-live${r?` thinking-live-question`:``}`,"data-thinking-live":n,"data-thinking-live-extra":i??0,"data-thinking-awaiting-reader":r?`1`:void 0,children:[(0,F.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:r?`?`:`⚙`}),r?`等你回答`:`正在执行 ${n}`,i?` 等 ${i+1} 个`:``]}),!o&&a&&(0,F.jsx)(`span`,{className:`thinking-preview`,title:a,children:a})]}),o&&(0,F.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:c})]})}function CO({run:e,name:t,expanded:n,onToggle:r,onStop:i,stopping:a}){let o=e.toolCalls??[],s=n?o:o.slice(-10),c=o.length-s.length,l=e.status===`running`,d=e.partialOutput??e.output??``,f=e.dispatchedBy===`model`,[p,m]=(0,u.useState)(0);(0,u.useEffect)(()=>{if(!l)return;m(Date.now());let e=window.setInterval(()=>m(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let h=Date.parse(e.startedAt),g=l&&p>0&&Number.isFinite(h)?p-h:void 0,_=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,F.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${f?` subagent-by-model`:``}`,"data-subagent-card":e.id,"data-subagent-status":e.status,"data-subagent-agent":e.agentId,"data-subagent-tools":o.length,"data-subagent-dispatched-by":f?`model`:`human`,children:[(0,F.jsxs)(`div`,{className:`subagent-head`,children:[(0,F.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),f&&(0,F.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,F.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,F.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,F.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?g!==void 0&&(0,F.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":g,children:[`已运行 `,hO(g)]}):e.durationMs!==void 0&&(0,F.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,hO(e.durationMs)]}),l&&(0,F.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,F.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,F.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,F.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[f&&(0,F.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,F.jsxs)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":d.length,children:[d||(l?`…`:`(没有输出)`),e.outputTruncated&&`(输出已截断)`]}),e.failure&&(0,F.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,F.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,F.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:gO[e.failure.stage]}),e.failure.stage===`tool`&&_&&(0,F.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,_]}),o.length>0&&(0,F.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,F.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,title:kr(e.error),children:Or(e.error,`这条子任务没有完成。`)}),o.length>0&&(0,F.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,F.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,F.jsxs)(`div`,{children:[(0,F.jsxs)(`div`,{className:`subagent-tool${e.status?` subagent-tool-${e.status}`:``}`,"data-subagent-tool":e.label,"data-subagent-tool-detail":e.detail??void 0,"data-subagent-tool-status":e.status??`running`,children:[(0,F.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,F.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,F.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,F.jsx)(`span`,{className:`subagent-tool-duration`,children:hO(e.durationMs)})]}),e.output&&(0,F.jsxs)(`details`,{className:`subagent-tool-log`,children:[(0,F.jsxs)(`summary`,{children:[`命令输出`,e.outputTruncated&&`(尾部)`]}),(0,F.jsx)(`pre`,{className:`call-result-body`,"data-subagent-tool-output":!0,children:e.output})]})]},`${c&&!n?c+t:t}:${e.label}`))]}),e.usage&&(0,F.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,F.jsxs)(`span`,{children:[e.usage.turns,` 轮`]}),(0,F.jsxs)(`span`,{title:`输入 token`,children:[`↑`,mO(e.usage.input)]}),(0,F.jsxs)(`span`,{title:`输出 token`,children:[`↓`,mO(e.usage.output)]}),e.usage.cacheRead>0&&(0,F.jsxs)(`span`,{title:`缓存读取`,children:[`缓存读 `,mO(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,F.jsxs)(`span`,{title:`缓存写入`,children:[`缓存写 `,mO(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,F.jsxs)(`span`,{title:`本轮花费`,children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,F.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function wO(e,t=[]){return Array.isArray(t)?t.filter(t=>typeof t?.id==`string`&&(pf(e,t.id)||!t.id.startsWith(`skill:`)&&typeof t.name==`string`&&pf(e,t.name))):[]}function TO(e){let t=e.deliveryMode===`steer`?`steer`:`queue`;return{type:`message.send`,conversationId:e.conversationId,content:e.content,clientId:e.clientId,...e.images?.length?{images:e.images}:{},...e.attachments?.length?{attachments:e.attachments}:{},...e.inFlight&&t===`steer`?{mode:`steer`}:{}}}function EO({mode:e,onChange:t}){return(0,F.jsxs)(`div`,{className:`composer-delivery-bar`,"data-delivery-mode-bar":`1`,children:[(0,F.jsxs)(`div`,{className:`delivery-mode-group`,role:`radiogroup`,"aria-label":`运行中消息投递模式`,children:[(0,F.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`queue`,className:`delivery-mode-btn${e===`queue`?` active`:``}`,"data-delivery-mode":`queue`,title:`等待当前回合与前面排队消息完成后依次回答(默认)`,onClick:()=>t(`queue`),children:`排队`}),(0,F.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`steer`,className:`delivery-mode-btn${e===`steer`?` active`:``}`,"data-delivery-mode":`steer`,title:`在当前工具调用完成后的下一回合边界插队回复,不会强行中止正在执行的工具`,onClick:()=>t(`steer`),children:`打断`})]}),(0,F.jsx)(`span`,{className:`delivery-mode-note`,"data-delivery-mode-note":`1`,children:e===`steer`?`将在下一回合边界生效(等当前工具跑完,不强行中止工具)`:`默认排队:等当前回合及前面排队消息完成后回答`})]})}function DO({messages:e,running:t,pendingInterrupts:n=[],onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onCancelMany:s,onEdit:c}){let[l,d]=(0,u.useState)(!1),[f,p]=(0,u.useState)([]),m=(0,u.useMemo)(()=>e.filter(e=>e.delivery!==`sending`).map(e=>e.id),[e]),h=(0,u.useMemo)(()=>f.filter(e=>m.includes(e)),[f,m]);if(!e.length)return null;let g=e.filter(e=>e.delivery===`sending`).length,_=m.length>0&&h.length===m.length,v=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])};return(0,F.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-interrupt-pending":n.length,"data-queue-count":e.length,"data-queue-sending":g,"aria-label":`排队等待回答的消息`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!l,onClick:()=>d(e=>!e),children:[(0,F.jsx)(`span`,{className:`chevron`,children:l?`▸`:`▾`}),(0,F.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),g>0&&(0,F.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,g,` 条`]}),l&&(0,F.jsx)(`span`,{className:`queue-dock-preview`,children:OO(e[0])})]}),!l&&s&&(m.length>1||h.length>0)&&(0,F.jsxs)(`div`,{className:`queue-dock-toolbar`,"data-queue-bulk-toolbar":`1`,children:[(0,F.jsx)(`span`,{className:`queue-dock-selected-count`,children:h.length>0?`已选 ${h.length} 条`:`共 ${m.length} 条可多选撤回`}),(0,F.jsxs)(`div`,{className:`queue-dock-toolbar-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`queue-select-all`,"data-waiting-select-all":`1`,onClick:()=>p(_?[]:m),children:_?`取消全选`:`全选`}),(0,F.jsxs)(`button`,{type:`button`,className:`queue-cancel-selected`,"data-waiting-cancel-selected":`1`,disabled:h.length===0,onClick:()=>{h.length!==0&&(s(h),p([]))},children:[`撤回所选 (`,h.length,`)`]})]})]}),!l&&(0,F.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((l,u)=>(0,F.jsx)(AO,{message:l,order:u+1,total:e.length,interrupting:n.includes(l.id),running:t,selectable:!!(s&&l.delivery!==`sending`),selected:h.includes(l.id),onToggleSelect:v,onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:c},l.id))})]})}function OO(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function kO(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};if(!/<task id="[^"]+" state="[^"]+"/.test(e.content))return{label:(e.content.split(`
|
|
338
|
+
`).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`,state:`running`};let t=(()=>{let t=/<summary>([\s\S]*?)<\/summary>/.exec(e.content);return t?t[1].trim():`后台回传`})(),n=/<task id="[^"]+" state="([^"]+)"/.exec(e.content);return{label:t,state:n?n[1]:`completed`}}function AO({message:e,order:t,total:n,running:r,interrupting:i=!1,selectable:a=!1,selected:o=!1,onToggleSelect:s,onSteer:c,onInterrupt:l,onSend:d,onCancel:f,onEdit:p}){let[m,h]=(0,u.useState)(!1),[g,_]=(0,u.useState)(e.content),v=e.delivery===`sending`,y=e.source===`session-reminder`,b=e.role===`tool`&&!y,{label:x,state:S}=b?kO(e):{label:OO(e),state:`user`},C=()=>{let t=g.trim();t&&t!==e.content&&p(e.id,t),h(!1)};return(0,F.jsxs)(`li`,{className:`queue-row ${v?`queue-row-sending`:`queue-row-queued`} ${b?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":b?S:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[a&&(0,F.jsx)(`input`,{type:`checkbox`,className:`queue-select`,"data-waiting-select":e.id,checked:o,"aria-label":`选择「${x}」`,onChange:()=>s?.(e.id)}),(0,F.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),y?(0,F.jsxs)(`span`,{className:`queue-reminder`,"data-queue-reminder":!0,children:[(0,F.jsxs)(`span`,{className:`reminder-label`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`◷`}),` 定时提醒`]}),(0,F.jsx)(`span`,{className:`queue-text`,title:x,children:x})]}):b?(0,F.jsxs)(`span`,{className:`queue-bg-result`,title:x,children:[(0,F.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:S===`error`?`✕`:`↩`}),(0,F.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,F.jsx)(`span`,{className:`bg-result-summary`,children:x})]}):m?(0,F.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,F.jsx)(`textarea`,{value:g,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>_(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),_(e.content),h(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),C())}}),(0,F.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:C,children:`保存`}),(0,F.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{_(e.content),h(!1)},children:`取消`})]}):(0,F.jsx)(`span`,{className:`queue-text`,title:x,children:x}),(0,F.jsx)(`span`,{className:`queue-state`,"data-waiting-state":v?`sending`:`queued`,children:v?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),v?(0,F.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,F.jsxs)(F.Fragment,{children:[r?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,disabled:i,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${x}」`,onClick:()=>l(e.id),children:i?`◌ 打断中…`:`打断并回答`}),(0,F.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${x}」`:`让「${x}」插到最前`,onClick:()=>c(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,F.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${x}」`,onClick:()=>d(e.id),children:`现在就回答`}),e.role===`user`&&(0,F.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${x}」`,onClick:()=>{_(e.content),h(!0)},children:`改字`}),(0,F.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${x}」`,onClick:()=>f(e.id),children:`撤回`})]})]})}function jO(e,t,n){return`${e}:${t}:${n}`}function MO(e){return{picked:Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected])),note:e.answers?.map(e=>e.note??``).join(`
|
|
339
|
+
`)??``}}function NO({question:e,index:t,expanded:n,draft:r,onDraftChange:i,onToggle:a,onAnswer:o}){return(0,F.jsxs)(`div`,{className:`call-block question-block-${e.status}`,"data-call-block":t,"data-call-tool":`question`,"data-call-detail":`提问`,"data-call-status":e.status===`answered`?`ok`:e.status===`cancelled`?`error`:`running`,"data-call-expanded":n?`true`:`false`,"data-question-block":t,children:[(0,F.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:a}),(0,F.jsxs)(`div`,{className:`call-head-row`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:a,children:[(0,F.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,F.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,F.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,F.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,F.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:a,children:`收起`})]}),n&&(0,F.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,F.jsx)(PO,{question:e,draft:r,onDraftChange:i,instanceId:`inline`,onAnswer:o})})]})}function PO({question:e,draft:t,onDraftChange:n,instanceId:r,onAnswer:i}){let{picked:a,note:o}=t,s=(e,r,i)=>{let o=(()=>{let t=a,n=t[e]??[];return i?{...t,[e]:n.includes(r)?n.filter(e=>e!==r):[...n,r]}:{...t,[e]:[r]}})();n({...t,picked:o})},c=()=>{i(e.items.map(e=>({id:e.id,selected:a[e.id]??[],...e.extraNote&&o.trim()?{note:o.trim()}:{}})),!1)},l=e.items.some(e=>(a[e.id]??[]).length>0);return(0,F.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(i=>(0,F.jsxs)(`div`,{className:`question-item`,children:[(0,F.jsx)(`div`,{className:`question-text`,children:i.header?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`span`,{className:`question-header`,children:i.header}),(0,F.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,F.jsx)(ef,{source:i.question})]}):(0,F.jsx)(ef,{source:i.question})}),(0,F.jsx)(`div`,{className:`question-options`,"data-question-options":i.id,children:i.options.map(t=>{let n=e.status!==`pending`,o=(n?e.answers?.find(e=>e.id===i.id)?.selected:a[i.id])?.includes(t)??!1;return(0,F.jsxs)(`label`,{className:o?`is-chosen`:``,"data-chosen":n&&o?`1`:void 0,children:[(0,F.jsx)(`input`,{type:i.multiple?`checkbox`:`radio`,name:`q-${r}-${i.id}`,checked:o,disabled:n,onChange:()=>s(i.id,t,i.multiple)}),(0,F.jsx)(tf,{source:t}),n&&o?(0,F.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},t)})}),e.status===`pending`&&i.extraNote?(0,F.jsx)(`textarea`,{value:o,placeholder:`补充说明(可选)`,onChange:e=>n({...t,note:e.target.value})}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,F.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,F.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},i.id)),e.status===`pending`&&(0,F.jsxs)(`div`,{className:`question-actions`,children:[(0,F.jsx)(`button`,{type:`button`,onClick:c,disabled:!l,children:`提交`}),(0,F.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>i([],!0),children:`跳过`})]})]})}function FO({question:e,pendingCount:t,minimized:n,floatingRight:r,onMinimize:i,onExpand:a,onLocate:o,draft:s,onDraftChange:c,onAnswer:l}){return n?(0,Re.createPortal)((0,F.jsxs)(`button`,{type:`button`,className:`question-floating-ball`,style:{"--question-floating-right":r},"data-question-floating-ball":e.key,onClick:a,"aria-label":`展开待回答的问题${t>1?`,还有 ${t-1} 个待处理`:``}`,title:`展开待回答的问题`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`?`}),t>1&&(0,F.jsx)(`small`,{children:t})]}),document.body):(0,Re.createPortal)((0,F.jsxs)(`section`,{className:`question-floating-panel`,style:{"--question-floating-right":r},"data-question-floating-panel":e.key,role:`dialog`,"aria-labelledby":`question-floating-title`,children:[(0,F.jsxs)(`header`,{className:`question-floating-head`,children:[(0,F.jsx)(`span`,{className:`question-floating-mark`,"aria-hidden":`true`,children:`?`}),(0,F.jsxs)(`h2`,{id:`question-floating-title`,children:[`需要你回答`,t>1?` · 还有 ${t-1} 个`:``]}),(0,F.jsx)(`button`,{type:`button`,className:`question-floating-minimize`,onClick:o,title:`定位到消息上下文并最小化`,children:`查看上下文`}),(0,F.jsx)(`button`,{type:`button`,className:`question-floating-minimize-icon`,onClick:i,title:`最小化为悬浮球`,"aria-label":`最小化问题`,children:`−`})]}),(0,F.jsx)(`div`,{className:`question-floating-body`,children:(0,F.jsx)(PO,{question:e.value,draft:s,onDraftChange:c,instanceId:`floating`,onAnswer:l})})]}),document.body)}function IO({request:e,onAnswer:t,pending:n}){let[r,i]=(0,u.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,F.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,F.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,F.jsxs)(`div`,{className:`extui-head`,children:[(0,F.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,F.jsxs)(`span`,{className:`extui-deadline`,children:[Math.ceil(Math.max(0,e.deadlineAt===void 0?e.timeoutMs:e.deadlineAt-Date.now())/1e3),`s 超时`]})]}),n&&(0,F.jsx)(`p`,{className:`extui-pending`,role:`status`,children:`提交中…`}),(0,F.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,F.jsx)(`h3`,{className:`extui-title`,children:e.title||XO[e.method]}),e.method===`confirm`&&(0,F.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,F.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,F.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,F.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,F.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,F.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&PD(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,F.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&PD(e)&&e.preventDefault()}}),(0,F.jsxs)(`div`,{className:`extui-actions`,children:[(0,F.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,F.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,F.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,F.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function LO({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,u.useState)(e),o=(0,u.useRef)(null),s=(0,u.useRef)(!1);(0,u.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},d=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,F.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,F.jsx)(`input`,{ref:o,className:`inline-edit-input`,value:i,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{if(e.key===`Enter`){if(PD(e))return;e.preventDefault(),d()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,F.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:d,children:`✓`}),(0,F.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function RO({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c,providerOptions:l}){let[d,f]=(0,u.useState)(!1),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(0),[_,v]=(0,u.useState)(`*`),y=(0,u.useRef)(null),b=(0,u.useRef)(null),x=(0,u.useRef)(null),S=(0,u.useRef)(null),C=(0,u.useRef)([]),w=i.find(e=>e.selected),T=oO(l?i.filter(e=>_===`*`||e.key!==zO&&e.key.split(`/`)[0]===_):i,p),E=T.length===0?-1:Math.min(Math.max(h,0),T.length-1),D=E<0?void 0:T[E],O=(e=!1)=>{f(!1),e&&b.current?.focus()},k=()=>{m(``),v(`*`),g(Math.max(i.findIndex(e=>e.selected),0)),f(!0)},A=e=>g(t=>T.length?Math.min(Math.max(t+e,0),T.length-1):0);(0,u.useEffect)(()=>{if(!d)return;let e=e=>{y.current?.contains(e.target)||O()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[d]),(0,u.useEffect)(()=>{if(!d)return;let e=y.current,t=t=>{e?.contains(t.relatedTarget)||O()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[d]),(0,u.useEffect)(()=>{d&&S.current?.focus()},[d]),(0,u.useEffect)(()=>{d&&E>=0&&C.current[E]?.scrollIntoView({block:`nearest`})},[d,E]),(0,u.useLayoutEffect)(()=>{if(!d)return;let e=x.current;if(!e)return;e.style.setProperty(`--picker-nudge`,`0px`),e.style.setProperty(`--picker-drop`,`0px`);let t=e.getBoundingClientRect(),n=Math.min(window.innerWidth-8-t.right,Math.max(8-t.left,0)),r=Math.min(window.innerHeight-8-t.bottom,Math.max(8-t.top,0));e.style.setProperty(`--picker-nudge`,`${n}px`),e.style.setProperty(`--picker-drop`,`${r}px`)},[d,T.length,i.length]);let j=e=>{if(d){if(e.key===`Escape`)e.preventDefault(),O(!0);else if(e.key===`ArrowDown`)e.preventDefault(),A(1);else if(e.key===`ArrowUp`)e.preventDefault(),A(-1);else if(e.key===`Home`)e.preventDefault(),g(0);else if(e.key===`End`)e.preventDefault(),g(Math.max(T.length-1,0));else if(e.key===`Enter`){if(PD(e))return;e.preventDefault(),D&&(s(D.key),O(!0))}}},ee=`picker-list-${c??e}`,M=t=>`picker-option-${c??e}-${t}`;return(0,F.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:y,onKeyDown:d?j:void 0,children:[(0,F.jsxs)(`button`,{ref:b,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":d,title:o??`${QD[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>d?O():k(),children:[(0,F.jsx)(`span`,{className:`session-picker-kind`,children:QD[e]}),(0,F.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,F.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,F.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),d&&(0,F.jsxs)(`div`,{className:`picker-menu`,ref:x,"data-picker-menu":e,"data-picker-highlight":E,children:[l&&(0,F.jsxs)(`label`,{className:`picker-provider-filter`,children:[(0,F.jsx)(`span`,{children:`Provider`}),(0,F.jsxs)(`select`,{"data-picker-provider":e,"aria-label":`筛选模型 Provider`,value:_,onKeyDown:e=>e.stopPropagation(),onChange:e=>{v(e.target.value),g(0)},children:[(0,F.jsx)(`option`,{value:`*`,children:`全部 Provider`}),l.map(e=>(0,F.jsx)(`option`,{value:e,children:e},e))]})]}),(0,F.jsxs)(`div`,{className:`picker-filter`,children:[(0,F.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,F.jsx)(`input`,{ref:S,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${eO[e]}选项`,"aria-expanded":`true`,"aria-controls":ee,"aria-autocomplete":`list`,"aria-activedescendant":D?M(E):void 0,value:p,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{m(e.target.value),g(0)}}),p&&(0,F.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{m(``),g(0),S.current?.focus()},children:`✕`})]}),w&&!T.some(e=>e.key===w.key)&&(0,F.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":w.key,children:[(0,F.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,F.jsx)(`span`,{className:`picker-current-value`,children:w.label})]}),(0,F.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:ee,"aria-label":nO[e],children:[T.map((e,t)=>(0,F.jsxs)(`button`,{id:M(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{C.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===E&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===E,onClick:()=>{s(e.key),O(!0)},children:[e.color&&(0,F.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,F.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,F.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,F.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,F.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),T.length===0&&(0,F.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:i.length===0?tO[e]:`没有匹配「${p.trim()}」的${eO[e]}`})]})]})]})}var zO=`__pi_default__`;function BO({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onRemove:a,onClose:o}){let[s,c]=(0,u.useState)(e.defaultAgentId),[l,d]=(0,u.useState)(e.defaultModel),[f,p]=(0,u.useState)(e.defaultThinkingLevel);(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let m=t?.source===`pi`,h=[{key:zO,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:l===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,wD(e.contextWindow)?`${wD(e.contextWindow)} 上下文`:``,TD(e.maxTokens)?`${TD(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:iO(e),selected:l?.provider===e.provider&&l.modelId===e.modelId}))],g=t?.models.find(e=>e.provider===l?.provider&&e.modelId===l?.modelId),_=g?.thinkingLevels??t?.levels??[],v=[{key:zO,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:f===void 0},..._.map(e=>({key:e,label:e,selected:e===f}))],y=e=>{if(e===zO){d(void 0),p(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);if(n){let e=l?.provider!==n.provider||l.modelId!==n.modelId;d({provider:n.provider,modelId:n.modelId,label:n.label}),e&&p(void 0)}},b=e=>p(e===zO?void 0:e),x=[{key:zO,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:s===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:s===e.id}))];return(0,F.jsx)(`div`,{className:`overlay`,onClick:o,children:(0,F.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,F.jsx)(`h2`,{children:`工作区设置`}),(0,F.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,F.jsx)(`div`,{className:`workspace-settings-path`,children:e.path}),(0,F.jsxs)(`div`,{className:`settings-row`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,F.jsx)(RO,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===s)?.name??`跟随 Pi 默认`,value:s??zO,detail:s?`${n?.agents.find(e=>e.id===s)?.toolSummary??``}`:void 0,options:x,disabled:!n||n.source===`unavailable`,note:pO(n),onChoose:e=>c(e===zO?void 0:e)})]}),(0,F.jsxs)(`div`,{className:`settings-row`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,F.jsx)(RO,{kind:`model`,scope:`settings-model`,label:l?.label??`跟随 Pi 默认`,value:l?`${l.provider}/${l.modelId}`:zO,detail:l?`${l.provider}/${l.modelId}`:void 0,options:h,providerOptions:[...new Set((t?.models??[]).map(e=>e.provider))],disabled:!m,note:fO(`模型`,t),onChoose:y})]}),(0,F.jsxs)(`div`,{className:`settings-row`,children:[(0,F.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,F.jsx)(RO,{kind:`thinking`,scope:`settings-thinking`,label:f??`跟随 Pi 默认`,value:f??zO,options:v,disabled:!m,note:fO(`思考等级`,t),onChoose:b})]}),l&&g&&_.length===0&&(0,F.jsx)(`div`,{className:`settings-scope`,children:`Pi 未提供此模型的可选等级,使用模型默认值。`}),(0,F.jsxs)(`div`,{className:`picker-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:o,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(s,l,f),children:`保存`})]}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-delete`,onClick:a,children:`从列表移除工作区`})]})})}var VO=[{id:`main`,label:`任务`,name:`任务与后台任务`},{id:`projects`,label:`项目`,name:`项目控制面`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`terminal`,label:`终端`,name:`终端 tab`}],HO=`super-pi.right-tabs.v1`;function UO(){let e=e=>VO.some(t=>t.id===e),t={tab:VO[0].id,byConversation:{}};try{let n=JSON.parse(Pn(HO)??`null`);return!n||!e(n.tab)?t:{tab:n.tab,byConversation:Object.fromEntries(Object.entries(n.byConversation??{}).filter(t=>e(t[1])))}}catch{return t}}var WO={waiting:`⋯`,running:``,failed:``,question:`?`,completed:``,unread:`•`,idle:``,awaiting_background:`⚙`,pending_report:`↑`,awaiting_subordinates:`↓`,awaiting_decision:`▲`},GO={idle:`空闲`,running:`讨论中`,awaiting_background:`后台任务进行中`,completed:`讨论已完成`,failed:`讨论未完成`},KO={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,completed:`已完成`,unread:`有未读`,idle:`空闲`,awaiting_background:`等待后台任务`,pending_report:`待汇报`,awaiting_subordinates:`等待下级`,awaiting_decision:`等上面拍板`},qO={idle:`就绪`,waiting:`等待 LLM`,running:`正在生成`,completed:`已完成`,stopped:`已停止`,failed:`运行失败`,awaiting_background:`等待后台任务`},JO=e=>e?.status===`running`||e?.status===`waiting`,YO={running:`运行中`,completed:`已完成`,failed:`失败`,stopped:`已停止`,cancelled:`已取消`,interrupted:`已中断`},XO={select:`请选择一项`,confirm:`请确认`,input:`请输入内容`,editor:`请输入内容`,notify:`扩展通知`,setStatus:`扩展状态`,setWidget:`扩展内容`,setTitle:`扩展标题`,set_editor_text:`扩展输入`};function ZO(e,t){return t.some(t=>t.conversationId===e.id)?!0:e.messagesLoaded===!1?e.hasPendingQuestion===!0:e.messages.some(e=>(e.toolCalls??[]).some(e=>e.question?.status===`pending`))}function QO(e,t,n){let r=(t||[]).filter(t=>t.parentConversationId===e.id),i=(t||[]).find(t=>t.id===e.parentConversationId),a=n??``;return Hn({conversation:e,parent:i,directChildren:r,isTopLevelUnread:e.updatedAt>a})}function $O(e,t,n,r){let i=QO(e,r,n);return Un({status:e.status,reportingState:i,awaitingQuestion:t,quietWhenRead:!0})}function ek(e,t){return t===`awaiting_decision`||e===`awaiting_decision`?(0,F.jsx)(`span`,{className:`conversation-status-badge badge--warning project-status-awaiting_decision`,"data-session-status":`awaiting_decision`,"data-reporting-badge":`awaiting_decision`,title:KO.awaiting_decision,children:KO.awaiting_decision}):t===`awaiting_subordinates`||e===`awaiting_subordinates`?(0,F.jsx)(`span`,{className:`conversation-status-badge project-status-awaiting_subordinates`,"data-session-status":`awaiting_subordinates`,"data-reporting-badge":`awaiting_subordinates`,title:KO.awaiting_subordinates,children:KO.awaiting_subordinates}):t===`pending_report`||e===`pending_report`?(0,F.jsx)(`span`,{className:`conversation-status-badge project-status-pending_report`,"data-session-status":`pending_report`,"data-reporting-badge":`pending_report`,title:KO.pending_report,children:KO.pending_report}):null}function tk({state:e,label:t=KO[e]}){let n=WO[e];if(e===`idle`)return null;let r=e.replace(/_/g,`-`);return(0,F.jsx)(`i`,{className:`session-state session-state-${e} session-state-${r}`,"data-session-state":e,title:t,"aria-label":t,...e===`awaiting_background`?{style:{color:`var(--accent)`}}:{},children:(0,F.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:n})})}function nk(e,t){return(0,F.jsxs)(F.Fragment,{children:[e.origin===`orchestrator`&&(0,F.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`orchestrator`,title:`编排会话:由上级智能体创建`,"aria-label":`编排会话:由上级智能体创建`,children:`编排`}),t&&(0,F.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`scheduled`,title:`定时任务会话:${t.name}`,"aria-label":`定时任务会话:${t.name}`,children:`定时`})]})}function rk(e,t){let n=[];return e.origin===`orchestrator`&&n.push(`编排会话`),t&&n.push(`定时任务会话:${t.name}`),n.length?`(${n.join(`;`)})`:``}var ik={pending:`未开始`,in_progress:`运行中`,completed:`已完成`},ak={pending:`○`,in_progress:`◐`,completed:`✓`},ok={high:`高`,medium:`中`,low:`低`};function sk(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function ck({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,F.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,title:`状态:${ik[e.status]}`,children:[(0,F.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:ak[e.status]}),(0,F.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,F.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:ik[e.status]}),e.priority&&(0,F.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:ok[e.priority]})]})}function lk(e,t){if(!e)return[];let n=t.filter(t=>t.conversationId===e.id&&t.status===`running`),r=new Set(n.map(e=>e.id));for(let t of e.messages)t.toolCalls?.forEach((i,a)=>{let o=i.backgroundTask;o&&o.status===`running`&&!r.has(o.id)&&(r.add(o.id),n.push({id:o.id,conversationId:e.id,title:i.detail?.trim()||i.label?.trim()||o.id,status:o.status,originMessageId:t.id,originCallRow:a}))});return n}function uk({tasks:e,runs:t,execOutputs:n,onStop:r}){return(0,F.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,i)=>{let a=e.id||`bg_${i}`,o=e.status?.trim()||``,s=o?YO[o]??(/[\u3400-\u9fff]/.test(o)?o:`未知状态`):`未知状态`;return(0,F.jsx)(dk,{task:e,status:s,run:t?.get(e.id),execOutputs:n,onStop:r},a)})})}function dk({task:e,status:t,run:n,execOutputs:r,onStop:i}){let[a,o]=(0,u.useState)(!1),s=vO(e.id,r),c=n?kD(n):s?.text||e.output,l=c&&OD(c),d=n?n.outputTruncated||n.toolCalls?.some(e=>e.outputTruncated):s?.truncated??e.outputTruncated;return(0,F.jsxs)(`li`,{className:`bg-item${a?` bg-item-expanded`:``}`,"data-bg-task":e.id,"data-bg-task-status":e.status??`unknown`,title:`状态:${t}`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`bg-item-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,"aria-label":`展开后台任务详情`,children:[(0,F.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务`}),(0,F.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,F.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,F.jsx)(`span`,{className:`bg-status`,children:t})]})]}),i&&(0,F.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:()=>i(e.id),children:`终止`}),a&&(0,F.jsx)(`pre`,{className:`bg-output`,"data-bg-output":e.id,children:[d?`日志仅保留最近一段。`:``,l].filter(Boolean).join(`
|
|
340
340
|
|
|
341
|
-
`)||`运行中,暂无输出`})]})}var
|
|
341
|
+
`)||`运行中,暂无输出`})]})}var fk=(0,u.lazy)(()=>vn(()=>import(`./GitDiffEditor-X8eCsha9.js`),__vite__mapDeps([22,1,2,3,4,0,21,23])));function pk({todos:e,tasks:t,backgroundRuns:n,execOutputs:r,scheduledTasks:i,scheduledCatalog:a,scheduledAgents:o,collapsed:s,onToggle:c,workspaceId:l,gitWorkspaceId:u=l,gitRepositoryOnly:d=!1,workspaceLabel:f,workspaceName:p,gitWorkspaceName:m=p,cwd:h=``,conversationId:g,followedWorktreeId:_,connected:v,files:y,onOpenFile:b,onOpenChanged:x,onOpenGitDiff:S,activeGitDiffUrl:C,onFileReference:w,onFilesMoved:T,onSearchFolder:E,activeTab:D,onSelectTab:O,sendCommand:k,registerTerminalSink:A,terminalShell:j,notify:ee,serverTimeZone:M,onOpenSession:te,side:N,onArrange:ne,pinned:re=!0,sharedGit:ie}){let ae=VO,oe=N===`left`;return(0,F.jsx)(`div`,{className:`right-rail${N?` workbench-panel workbench-panel-`+N:``}${s?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":oe?`左侧栏`:`右侧栏`,"data-right-rail":oe?void 0:`1`,"data-right-rail-collapsed":s,"data-workbench-panel":N,hidden:N&&s?!0:void 0,children:s?!N&&(0,F.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:c,children:`‹`}):(0,F.jsxs)(F.Fragment,{children:[N?(0,F.jsxs)(`div`,{className:`workbench-panel-heading`,children:[(0,F.jsx)(`h2`,{children:Ir[D]}),ne&&(0,F.jsx)(Jr,{view:D,side:N,pinned:re,onArrange:ne}),(0,F.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-right-rail-collapse":oe?void 0:`1`,title:oe?`收起左侧栏`:`收起右侧栏`,"aria-label":oe?`收起左侧栏`:`收起右侧栏`,onClick:c,children:(0,F.jsx)(Gr,{name:`close`})})]}):(0,F.jsxs)(`div`,{className:`right-rail-head`,children:[(0,F.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":ae.length,children:ae.map(e=>(0,F.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===D?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===D,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>O(e.id),children:e.label},e.id))}),(0,F.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":`收起右侧栏`,onClick:c,children:`›`})]}),VO.filter(e=>e.id===D).map(s=>(0,F.jsxs)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${s.id}`,"aria-label":N?Ir[s.id]:void 0,"aria-labelledby":N?void 0:`right-tab-${s.id}`,"data-right-panel":s.id,children:[s.id===`main`&&(0,F.jsxs)(F.Fragment,{children:[(e.length>0||t.length>0)&&(0,F.jsxs)(`p`,{className:`rail-legend`,"data-rail-legend":`1`,children:[(0,F.jsx)(`span`,{className:`rail-legend-label`,children:`左侧竖条=状态`}),(0,F.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,F.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-pending`,"aria-hidden":`true`}),`未开始`]}),(0,F.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,F.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-running`,"aria-hidden":`true`}),`运行中`]}),(0,F.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,F.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-done`,"aria-hidden":`true`}),`已完成`]})]}),(0,F.jsxs)(`div`,{className:`rail-task-sections`,children:[(0,F.jsx)(kw,{id:`todos`,title:`待办任务`,icon:`tasks`,count:(0,F.jsx)(`span`,{"data-todo-summary":`1`,children:sk(e)}),children:e.length>0?(0,F.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,F.jsx)(ck,{todo:e,index:t},e.id??`todo_${t}`))}):(0,F.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。开始多步骤任务后会自动显示。`})}),(0,F.jsx)(kw,{id:`background`,title:`后台任务`,icon:`activity`,count:(0,F.jsx)(`span`,{"data-bg-summary":`1`,children:t.length?`${t.filter(e=>e.status===`running`).length} 个运行中 / 共 ${t.length} 个`:`0 个`}),children:t.length>0?(0,F.jsx)(uk,{tasks:t,runs:n,execOutputs:r,onStop:e=>k({type:`backgroundTask.stop`,taskId:e})}):(0,F.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`})}),(0,F.jsx)(Uw,{tasks:i,workspaceId:l,catalog:a,agents:o,sendCommand:k,notify:ee,serverTimeZone:M})]})]}),s.id===`projects`&&(0,F.jsx)(OT,{workspaceId:l,notify:ee,onOpenSession:te,onOpenFile:b,cwd:h},l),s.id===`tools`&&(0,F.jsx)(mk,{workspaceId:l},l),s.id===`files`&&(0,F.jsx)(Pm,{workspaceId:l,workspaceName:p,cwd:h,files:y,onOpenFile:b,onOpenChanged:x,onReference:w,onMoved:T,onSearchFolder:E}),s.id===`git`&&(0,F.jsx)(Ni,{repositoryOnly:d,workspaceId:u??null,conversationId:g,cwd:u===l?h:``,followedWorktreeId:_,onOpenDiff:e=>S({...e,comparison:m?`${m} · ${e.comparison}`:e.comparison}),activeDiffUrl:C,onOpenConversation:te,sharedGit:ie},JSON.stringify([u,h,g,d])),s.id===`terminal`&&(0,F.jsx)(Ow,{workspaceId:l,workspaceLabel:f,cwd:h,conversationId:g,connected:v,sendCommand:k,registerSink:A,terminalShell:j},JSON.stringify([l,g]))]},s.id))]})})}function mk({workspaceId:e}){let{tools:t,mountedTools:n,openToolId:r,shortcuts:i}=iD(),[a,o]=(0,u.useState)(),s=async e=>{o(void 0);let t=await sD(e);t&&o(`移除工具失败:${Or(t)}`)},c=(e,t)=>t?`打开${e}(快捷键 ${jE(t)})`:`打开${e}`;return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`rail-section-head`,children:[(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,F.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[t.length+n.length,` 个`]})]}),t.length+n.length>0?(0,F.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":t.length+n.length,children:[t.map(e=>(0,F.jsxs)(`li`,{className:`tool-slot`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":r===e.id?`open`:`idle`,title:c(e.name,i[e.id]),"aria-label":c(e.name,i[e.id]),"aria-current":r===e.id?`true`:void 0,onClick:()=>aD.toggleTool(e.id),children:[(0,F.jsx)(lE,{className:`tool-icon-glyph`,glyph:e.glyph}),(0,F.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),i[e.id]&&(0,F.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${jE(i[e.id])}`,children:ME(i[e.id])}),e.kind===`link`&&(0,F.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>aD.removeTool(e.id),children:`✕`})]},e.id)),n.map(e=>(0,F.jsxs)(`li`,{className:`tool-slot`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,"data-tool-state":r===e.id?`open`:`idle`,title:c(e.name,i[e.id]),"aria-label":c(e.name,i[e.id]),onClick:()=>aD.toggleTool(e.id),children:[(0,F.jsx)(lE,{className:`tool-icon-glyph`,glyph:dE(e)}),(0,F.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),i[e.id]&&(0,F.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${jE(i[e.id])}`,children:ME(i[e.id])}),(0,F.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void s(e.id),children:`✕`})]},e.id))]}):(0,F.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,F.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具、快捷键与说明`,"aria-label":`打开工具设置`,onClick:()=>aD.openSettings(),children:`⚙ 工具设置`}),a&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-error":`1`,children:a})]})}function hk({onClose:e}){let{tools:t,mountedTools:n,shortcuts:r}=iD(),[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(``),[c,l]=(0,u.useState)(),[d,f]=(0,u.useState)(!1),[p,m]=(0,u.useState)(),[h,g]=(0,u.useState)(),[_,v]=(0,u.useState)(),[y,b]=(0,u.useState)(``),[x,S]=(0,u.useState)(),[C,w]=(0,u.useState)(),[T,E]=(0,u.useState)(!1),[D,O]=(0,u.useState)(),[k,A]=(0,u.useState)(),j=(0,u.useRef)(null),ee=(0,u.useRef)(null),[M,te]=(0,u.useState)(),[N,ne]=(0,u.useState)(),re=(0,u.useRef)(null),[ie,ae]=(0,u.useState)(()=>{let e=YE();return!e||typeof window>`u`?e:ZE(e,window.innerWidth,window.innerHeight)}),oe=async()=>{let e=await Bd(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
|
|
342
342
|
|
|
343
343
|
工具不属于当前 workspace;通过内置 tool_register 一次性提交完整文件(index.html、JS/CSS,必要时 .py),并用 glyph 提供一个易辨识的短图标(1 至 4 个字符,例如 {}、∑、◷),Super Pi 会保存为全局工具并自动出现在每个 workspace 的工具 Tab。
|
|
344
344
|
|
|
345
|
-
如需本地计算,声明 script: { path, timeoutMs, parameters }。脚本必须是 Python,参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象。在 index.html 中加载 <script src="./super-pi-tool.js"><\/script>,然后调用 SuperPiTool.run(params)、SuperPiTool.get(runId)、SuperPiTool.wait(runId) 或 SuperPiTool.cancel(runId)。这些都是已绑定本工具身份的相对接口;不要调用 /api/exec,不要猜测 toolId,也不要传 shell 命令、任意文件路径或未声明参数。页面必须实际执行一次示例任务并显示运行状态、日志和结构化结果。第三方包写进 environment.requires(必须钉死成 pkg==version),首次运行时会装进这个工具自己的虚拟环境。需要模型能力(摘要、改写、抽取、分类)时调用 SuperPiTool.llm({ prompt, system }),不要自己写模型客户端或保管密钥,并在注册时声明 permissions: { llm: true }——否则服务端会拒绝,导入页面也会提示用户。最后返回注册 id、访问地址、文件清单和验证结果。`);f(e),window.setTimeout(()=>f(!1),1800)};(0,u.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let se=(0,u.useMemo)(()=>[...t.map(e=>({id:e.id,name:e.name,glyph:e.glyph})),...n.map(e=>({id:e.id,name:e.name,glyph:uE(e)}))],[t,n]);(0,u.useEffect)(()=>{if(!M)return;let e=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),te(void 0);return}if(DE(e.key)||IE(e.target))return;e.preventDefault(),e.stopPropagation();let t=M;if(te(void 0),e.key===`Delete`||e.key===`Backspace`){iD.clearShortcut(t).then(e=>ne(e));return}let n=OE(e);if(!n){ne(`没有认出这个按键,换一个试试。`);return}let i=PE(n);if(!i.ok){ne(i.reason);return}let a=BE(r,n,t);if(a){let e=se.find(e=>e.id===a)?.name;ne(e?`这个组合键已经被「${e}」占用了,换一个键。`:`这个组合键已经被另一个工具占用了,换一个键。`)}else iD.setShortcut(t,n).then(e=>ne(e))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[M,r,se]);let ce=e=>{ae(XE(e,window.innerWidth,window.innerHeight))},le=e=>{YE(e)},ue=()=>{ae(void 0),YE(void 0)},de=(0,u.useRef)(!1),fe=n.map(e=>e.slug).filter(e=>typeof e==`string`),pe=e=>{m(void 0),g(void 0),A(void 0),O({tool:e,name:mD({slug:e.slug??`tool`})})},me=async(e,t)=>{m(void 0),g(void 0),A(void 0);let n=hD(t);if(!n.ok)A(n.reason);else try{let t=await Ne(`/api/tools/export?id=${encodeURIComponent(e.id)}`),r=await t.json();if(!t.ok||!r.bundle)throw Error(r.error??`HTTP ${t.status}`);let i=new Blob([JSON.stringify(r.bundle,null,2)],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.name,document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a),g(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){m(`导出失败:${Or(e)}`)}finally{O(void 0)}},he=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;m(void 0),g(void 0),S(void 0);let n=dD(await t.text(),t.name);n.ok?(v({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),b(fe.includes(n.bundle.slug)?pD(n.bundle.slug,fe):n.bundle.slug),w(n.bundle.files[0]?.path)):m(n.reason)},ge=()=>{v(void 0),b(``),S(void 0),w(void 0)},P=async()=>{if(!_)return;S(void 0);let e=fD(y);if(!e.ok)S(e.reason);else if(fe.includes(e.slug))S(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{E(!0);try{let t=await Ne(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(bD(_.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await aD(),g(`已导入「${_.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),ge()}catch(e){m(`导入失败:${Or(e)}`)}finally{E(!1)}}};(0,u.useEffect)(()=>{D&&ee.current?.scrollIntoView({block:`center`})},[D]);let _e=()=>{let e=Vt(i);e.ok?t.length>=32?l(`工具最多 32 个,先删掉一个再加。`):(iD.setTools([...t,{id:Gt(`link`,t.map(e=>e.id)),kind:`link`,name:o.trim()||yk(e.url),glyph:`↗`,url:e.url}]),a(``),s(``),l(void 0)):l(e.reason)},ve=ie?{width:`${ie.width}px`,height:`${ie.height}px`,maxWidth:`calc(100vw - 32px)`,maxHeight:`calc(100vh - 32px)`}:void 0;return(0,Re.createPortal)((0,F.jsxs)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onPointerDown:()=>{de.current=!1},onClick:t=>{de.current?de.current=!1:t.target===t.currentTarget&&e()},children:[(0,F.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,ref:re,style:ve,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:e,children:`✕`})]}),(0,F.jsx)(`div`,{className:`tool-dialog-body`,children:_?(0,F.jsx)(vk,{pending:_,slugDraft:y,slugError:x,preview:C,busy:T,onSlugChange:e=>{b(e),S(void 0)},onPreviewChange:w,onCancel:ge,onConfirm:()=>void P()}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,F.jsx)(`strong`,{children:`直接描述你要的工具`}),(0,F.jsx)(`p`,{className:`tool-hint`,children:`告诉 Super Pi Agent 你要创建什么,它会使用内置开发技能和 tool_register 完成注册。复制提示词仅作为备用入口。`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void oe(),children:d?`已复制`:`复制备用提示词`})]}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,F.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":Ft.length,children:Ft.map(e=>{let n=t.some(t=>t.kind===e.kind);return(0,F.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":e.kind,children:[(0,F.jsx)(cE,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,F.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{children:e.blurb})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":e.kind,disabled:n,title:n?`${e.name}已经在工具栏里了`:`添加${e.name}`,"aria-label":n?`${e.name}已添加`:`添加${e.name}`,onClick:()=>iD.setTools(Kt(t,e.kind)),children:n?`已添加`:`添加`})]},e.kind)})}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,F.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,F.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:i,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{a(e.target.value),l(void 0)}}),(0,F.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:o,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>s(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!i.trim(),onClick:_e,children:`添加网址工具`}),c&&(0,F.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:c}),(0,F.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,F.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`快捷键`})}),(0,F.jsxs)(`p`,{className:`tool-hint`,"data-tool-shortcut-hint":`1`,children:[`给每个工具绑一个组合键,按下就直接打开它,不用先找到右侧栏。`,(0,F.jsx)(`b`,{children:`弹窗打开时快捷键不生效`}),`——模态弹窗期间键盘归它自己,关掉之后再按。`]}),(0,F.jsx)(`div`,{className:`tool-shortcuts`,"data-tool-shortcut-count":se.length,children:se.map(e=>(0,F.jsxs)(`div`,{className:`tool-shortcut-row`,"data-tool-shortcut-row":e.id,children:[(0,F.jsx)(cE,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,F.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{children:r[e.id]?`按 ${AE(r[e.id])} 打开`:`还没有快捷键`})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-shortcut-set`,"data-tool-shortcut-set":e.id,"data-tool-shortcut-capturing":M===e.id?`1`:void 0,"aria-pressed":M===e.id,title:M===e.id?`按下想用的组合键(Esc 取消,Delete 清除)`:`点一下,然后按下想用的组合键`,onClick:()=>{ne(void 0),te(M===e.id?void 0:e.id)},children:M===e.id?`按下组合键…`:r[e.id]?AE(r[e.id]):`未设置`}),r[e.id]&&(0,F.jsx)(`button`,{type:`button`,className:`tool-shortcut-clear`,"data-tool-shortcut-clear":e.id,title:`清除${e.name}的快捷键`,"aria-label":`清除${e.name}的快捷键`,onClick:()=>{iD.clearShortcut(e.id),ne(void 0),te(void 0)},children:`清除`})]},e.id))}),N&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-shortcut-error":`1`,children:N}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有注册全局工具。直接告诉 Agent 你想做什么即可开始。`}):(0,F.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=vD(e.environmentState);return(0,F.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,F.jsx)(cE,{className:`tool-preset-glyph`,glyph:uE(e)}),(0,F.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{"data-tool-env":e.environmentState?.state??`unknown`,children:t?`${t.warn?`⚠ `:``}${t.text}${e.environmentState?.detail?` · ${e.environmentState.detail}`:``}`:`环境未知`}),e.permissions?.llm&&(0,F.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>pe(e),children:`导出`})]},e.id)})}),D&&(0,F.jsxs)(`div`,{className:`tool-share-review`,ref:ee,"data-tool-export-name":`1`,children:[(0,F.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,D.tool.name,`」`]}),(0,F.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,F.jsx)(`input`,{className:`tool-input`,value:D.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>O({...D,name:e.target.value})})]}),k&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:k}),(0,F.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{O(void 0),A(void 0)},children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void me(D.tool,D.name),children:`导出`})]})]}),h&&(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:h}),p&&(0,F.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:p}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,F.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,F.jsx)(`code`,{children:sD}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,F.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>j.current?.click(),children:`选择文件…`}),(0,F.jsx)(`input`,{ref:j,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void he(e)})]})})]}),(0,F.jsx)(gk,{targetRef:re,onResize:ce,onCommit:le,onDragEnd:()=>{de.current=!0},onReset:ue})]}),document.body)}var hk=18;function gk({targetRef:e,onResize:t,onCommit:n,onDragEnd:r,onReset:i}){let[a,o]=(0,u.useState)(),s=(0,u.useRef)(void 0);return(0,u.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=t.getBoundingClientRect();o({left:e.right-hk,top:e.bottom-hk})};n();let r=new ResizeObserver(n);return r.observe(t),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),()=>{r.disconnect(),window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[e]),(0,F.jsx)(`div`,{className:`tool-dialog-grip`,"data-tool-settings-grip":`1`,role:`separator`,"aria-orientation":`vertical`,tabIndex:0,"aria-label":`调整工具设置弹窗大小:拖动或用方向键,Enter 恢复默认尺寸`,style:a?{left:`${a.left}px`,top:`${a.top}px`}:void 0,onPointerDown:i=>{i.preventDefault(),i.stopPropagation();let a=e.current;if(!a)return;let o=a.getBoundingClientRect(),c=o.left+o.width/2,l=o.top+o.height/2;s.current=void 0;let u=e=>{let n=XE({width:2*(e.clientX-c),height:2*(e.clientY-l)},window.innerWidth,window.innerHeight);s.current=n,t(n)},d=()=>{window.removeEventListener(`pointermove`,u),window.removeEventListener(`pointerup`,d),window.removeEventListener(`pointercancel`,d),s.current&&(n(s.current),r())};window.addEventListener(`pointermove`,u),window.addEventListener(`pointerup`,d),window.addEventListener(`pointercancel`,d)},onDoubleClick:()=>i(),onKeyDown:r=>{if(r.key===`Enter`||r.key===` `){r.preventDefault(),i();return}let a=r.shiftKey?8:24,o=e.current?.getBoundingClientRect(),c=o?.width??HE.width,l=o?.height??HE.height;if(r.key===`ArrowRight`)c+=a;else if(r.key===`ArrowLeft`)c-=a;else if(r.key===`ArrowDown`)l+=a;else if(r.key===`ArrowUp`)l-=a;else return;r.preventDefault();let u=XE({width:c,height:l},window.innerWidth,window.innerHeight);s.current=u,t(u),n(u)},onClick:e=>e.stopPropagation()})}function _k(){let{tools:e,mountedTools:t,openToolId:n,settingsOpen:r,shortcuts:i}=rD(),a=e.find(e=>e.id===n),o=t.find(e=>e.id===n);return(0,u.useEffect)(()=>{let n=n=>{if(!r&&!document.querySelector(`[aria-modal="true"]`)&&!(n.isComposing||n.defaultPrevented)){for(let[r,a]of Object.entries(i))if(LE(a,n)&&(e.some(e=>e.id===r)||t.some(e=>e.id===r))){n.preventDefault(),iD.openTool(r);return}}};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[i,e,t,r]),(0,u.useEffect)(()=>{aD();let e=()=>{aD()};return window.addEventListener(`super-pi-tools-updated`,e),window.addEventListener(`super-pi-active-server`,e),()=>{window.removeEventListener(`super-pi-tools-updated`,e),window.removeEventListener(`super-pi-active-server`,e)}},[]),(0,u.useEffect)(()=>{iD.persistTools()},[]),(0,F.jsxs)(F.Fragment,{children:[r&&(0,F.jsx)(mk,{onClose:()=>iD.closeSettings()}),a&&(0,F.jsx)(bk,{tool:a,onClose:()=>iD.closeTool()}),o&&(0,F.jsx)(Ok,{tool:o,onClose:()=>iD.closeTool()})]})}function vk({pending:e,slugDraft:t,slugError:n,preview:r,busy:i,onSlugChange:a,onPreviewChange:o,onCancel:s,onConfirm:c}){let l=e.bundle,u=l.files.reduce((e,t)=>e+new TextEncoder().encode(t.content).length,0),d=_D(l),f=gD(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,F.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,F.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,F.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,F.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,yD(u)]}),(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,F.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,F.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,F.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,F.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,F.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` · `,l.environment.fingerprint.platform||`未知平台`,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,F.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,F.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,F.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,F.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,F.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,F.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,F.jsx)(`button`,{type:`button`,className:`tool-share-tab`,"aria-pressed":e.path===p?.path,"data-tool-import-file":e.path,onClick:()=>o(e.path),children:e.path},e.path))}),(0,F.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,F.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,F.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,F.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function yk(e){let t=e.replace(/^[./]+/,``).slice(0,30).trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return t||e.slice(0,30);try{return new URL(e,typeof window>`u`?`http://localhost`:window.location.href).hostname||t||e.slice(0,30)}catch{return e.slice(0,30)}}function bk({tool:e,onClose:t}){return(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,F.jsx)(cE,{className:`tool-dialog-glyph`,glyph:e.glyph}),e.name]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,F.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,F.jsx)(Sk,{}),e.kind===`timestamp`&&(0,F.jsx)(Ck,{}),e.kind===`link`&&(0,F.jsx)(wk,{tool:e})]})]})}),document.body)}function xk({image:e,onClose:t}){return(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Re.createPortal)((0,F.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,F.jsxs)(`div`,{className:`lightbox-head`,children:[(0,F.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,F.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,F.jsx)(`div`,{className:`lightbox-body`,children:(0,F.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function Sk(){let[e,t]=(0,u.useState)(`12 * (3 + 4)`),n=sn(e),r=e=>{t(t=>t+e)};return(0,F.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,F.jsx)(`input`,{className:`tool-input tool-calc-input`,"data-calc-input":`1`,value:e,maxLength:200,"aria-label":`算式`,spellCheck:!1,autoComplete:`off`,placeholder:`例如 (12 + 8) / 4`,onChange:e=>{t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&e.preventDefault()}}),(0,F.jsx)(`div`,{className:`tool-calc-keys`,"data-calc-keys":`1`,children:[[`7`,`7`],[`8`,`8`],[`9`,`9`],[`÷`,`/`],[`(`,`(`],[`)`,`)`],[`4`,`4`],[`5`,`5`],[`6`,`6`],[`×`,`*`],[`^`,`^`],[`%`,`%`],[`1`,`1`],[`2`,`2`],[`3`,`3`],[`-`,`-`],[`←`,`back`],[`C`,`clear`],[`0`,`0`],[`.`,`.`],[`+`,`+`]].map(([e,n])=>(0,F.jsx)(`button`,{type:`button`,className:`tool-calc-key`,"data-calc-key":n,"aria-label":e===`C`?`清空`:e===`←`?`退格`:`输入 ${e}`,onClick:()=>{n===`clear`?t(``):n===`back`?t(e=>e.slice(0,-1)):r(n)},children:e},e))}),n.ok?(0,F.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:cn(n.value)}):(0,F.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function Ck(){let[e,t]=(0,u.useState)(``),n=ln(e),r=n.ok?dn(n.ms):null;return(0,F.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,F.jsx)(`input`,{className:`tool-input`,"data-stamp-input":`1`,value:e,maxLength:64,spellCheck:!1,"aria-label":`时间戳或日期`,placeholder:`1757000000 或 2026-10-08T09:00:00`,onChange:e=>t(e.target.value)}),r?(0,F.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`本地时间`}),(0,F.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`ISO(UTC)`}),(0,F.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`秒`}),(0,F.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`毫秒`}),(0,F.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,F.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function wk({tool:e}){let[t,n]=(0,u.useState)(!1),r=async()=>{let e=await Bd(`请为 Super Pi 开发一个全局右侧栏工具并自动挂载。不要启动独立 HTTP 服务器。通过内置 tool_register 提交完整的 HTML/JS/CSS 文件;工具将被 Super Pi 保存并在所有 workspace 可用。如需计算,注册一个 Python 脚本(不接受 shell 命令),参数经 JSON stdin 传入,stdout 只输出 JSON 结果。在页面里加载 ./super-pi-tool.js,使用 SuperPiTool.run(params)、wait(runId)、get(runId) 和 cancel(runId) 执行、等待、查看和取消任务。它们会自动绑定当前工具;不要调用 /api/exec,也不要猜测 toolId。`);n(e),window.setTimeout(()=>n(!1),1800)};return(0,F.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,F.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,F.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,F.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,F.jsx)(`a`,{className:`tool-link-open`,"data-tool-link-open":e.id,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:e.url,children:`在新标签页打开 ↗`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-copy-prompt":e.id,onClick:()=>void r(),children:t?`已复制`:`复制开发 Prompt`})]}),/^https?:\/\//i.test(e.url??``)&&(0,F.jsx)(`iframe`,{className:`tool-link-frame`,"data-tool-frame":e.id,src:e.url,title:e.name,sandbox:`allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts`,referrerPolicy:`no-referrer`})]})}var Tk=`(max-width: 1100px)`,Ek=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Dk(e){let t=`super-pi.mounted-tool.owner.`+e;try{let e=window.localStorage.getItem(t);if(e&&/^[0-9a-f]{32}$/.test(e))return e}catch{}let n=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(t,n)}catch{}return n}function Ok({tool:e,onClose:t}){let n=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let r=(0,u.useMemo)(()=>Dk(e.id),[e.id]);(0,u.useLayoutEffect)(()=>Nn(()=>n.current,e.id,r),[e.id,r]);let i=e.dialogSize??{width:1100,height:780},a={width:`min(${i.width}px, calc(100vw - 32px))`,height:`min(${i.height}px, calc(100dvh - 32px))`};return(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`tool-dialog mounted-tool-dialog`,style:a,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsxs)(`h2`,{className:`tool-dialog-title`,children:[(0,F.jsx)(cE,{className:`tool-dialog-glyph`,glyph:uE(e)}),e.name]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,F.jsx)(`div`,{className:`tool-dialog-body`,children:(0,F.jsx)(`iframe`,{ref:n,className:`tool-link-frame`,src:Me(`/tools/${encodeURIComponent(e.id)}/#super-pi-owner=${r}`),title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function kk(e,t,n){let r=Math.max(0,Math.round(n)-480),i=Ek(520,180,Math.max(180,r-240)),a=Ek(Math.round(e),180,i),o=Ek(640,240,Math.max(240,r-a));return{sidebar:a,rail:Ek(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var Ak=`super-pi.rail-widths.v1`,jk=`super-pi.reader-state.v1`,Mk=`super-pi.folded-groups.v1`;function Nk(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.folded-groups.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t=e=>{let t={};if(e&&typeof e==`object`)for(let[n,r]of Object.entries(e))typeof r==`boolean`&&(t[n]=r);return t};return{workspaces:t(e.workspaces),archived:t(e.archived)}}catch{return{}}}function Pk(e){try{typeof window<`u`&&window.localStorage.setItem(Mk,JSON.stringify(e))}catch{}}var Fk=e=>{let t=document.querySelector(`[data-workspace-group="${CSS.escape(e)}"]`);return t?[...t.querySelectorAll(`.conversation-row[data-session-root]`)].map(e=>({id:e.dataset.sessionRoot??``,middle:(()=>{let t=e.getBoundingClientRect();return t.top+t.height/2})()})).filter(e=>e.id!==``):[]},Ik=6,Lk=400,Rk=32,zk=48,Bk=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function Vk(e,t,n=!1,r=!1){let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=n?!1:r?!0:t.followTail?i<=zk:i<=Rk,o,s;if(!a){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);o=n?.dataset.transcriptKey,s=n?n.getBoundingClientRect().top-t:void 0}return{followTail:a,scrollTop:e.scrollTop,...o?{anchorKey:o,anchorOffset:s}:{}}}function Hk(){try{if(typeof window>`u`)return{conversations:{}};let e=JSON.parse(window.localStorage.getItem(`super-pi.reader-state.v1`)??`null`);if(!e||typeof e!=`object`)return{conversations:{}};let t={};if(e.conversations&&typeof e.conversations==`object`)for(let[n,r]of Object.entries(e.conversations)){let e=r;typeof e.followTail==`boolean`&&(t[n]={followTail:e.followTail,scrollTop:Number.isFinite(e.scrollTop)?Math.max(0,Number(e.scrollTop)):0,...typeof e.anchorKey==`string`?{anchorKey:e.anchorKey}:{},...Number.isFinite(e.anchorOffset)?{anchorOffset:Number(e.anchorOffset)}:{}})}let n={};if(e.readAt&&typeof e.readAt==`object`)for(let[t,r]of Object.entries(e.readAt))typeof r==`string`&&(n[t]=r);return{activeId:typeof e.activeId==`string`?e.activeId:void 0,workspaceId:typeof e.workspaceId==`string`?e.workspaceId:void 0,conversations:t,readAt:n}}catch{return{conversations:{}}}}function Uk(e){try{typeof window<`u`&&window.localStorage.setItem(jk,JSON.stringify(e))}catch{}}var Wk=`super-pi.session-tabs.v1`;function Gk(e,t){if(!t||e.has(t))return e;let n=new Set(e);return n.add(t),n}function Kk(e,t,n){let r=e.touched.has(t),i=e.touched;if(r){let r=new Set(e.touched);r.delete(t),n&&r.add(n),i=r}return{ids:e.ids.flatMap(e=>e===t?n?[n]:[]:[e]),previewId:e.previewId===t?n&&!r?n:void 0:e.previewId,emptied:e.emptied,touched:i}}function qk(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(Pn(`super-pi.session-tabs.v1`)??`null`);if(!e||typeof e!=`object`)return{ids:[]};let t=e,n=Array.isArray(t.ids)?[...new Set(t.ids.filter(e=>typeof e==`string`))]:[],r=Array.isArray(t.touched)?[...new Set(t.touched.filter(e=>typeof e==`string`))]:[],i=typeof t.previewId==`string`&&n.includes(t.previewId)&&!r.includes(t.previewId)?t.previewId:void 0;i&&i!==t.activeId&&(n=n.filter(e=>e!==i));let a=typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0,o=typeof t.workspaceLandingId==`string`?t.workspaceLandingId:void 0;return{ids:n,activeId:a,contextId:typeof t.contextId==`string`?t.contextId:void 0,workspaceLandingId:o,previewId:i===a?i:void 0,touched:r,emptied:n.length===0&&(t.emptied===!0||!!i),selectionCleared:t.selectionCleared===!0}}catch{return{ids:[]}}}function Jk(e,t,n,r=!1){try{if(typeof window>`u`)return;let{ids:i,previewId:a,touched:o,emptied:s}=e;Fn(Wk,JSON.stringify({ids:i,...t&&i.includes(t)?{activeId:t}:{},...t?{contextId:t}:{},...n?{workspaceLandingId:n}:{},...a&&i.includes(a)?{previewId:a}:{},...o.size?{touched:[...o]}:{},...s?{emptied:s}:{},...r?{selectionCleared:!0}:{}}))}catch{}}function Yk(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(Ak);if(e===null)return{};let t=JSON.parse(e),n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0;return{sidebar:n(t.sidebar),rail:n(t.rail)}}catch{return{}}}function Xk(e){try{if(typeof window>`u`)return;window.localStorage.setItem(Ak,JSON.stringify(e))}catch{}}function Zk({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,u.useState)(!1),c=e=>e.shiftKey?64:16;return(0,F.jsx)(`div`,{className:`rail-resizer rail-resizer-${e}${o?` rail-resizer-dragging`:``}`,"data-rail-resizer":e,"data-rail-resizer-dragging":o?`true`:`false`,"data-rail-resizer-width":t,role:`separator`,"aria-orientation":`vertical`,"aria-label":i,"aria-valuenow":t,"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,onMouseDown:i=>{i.preventDefault(),i.currentTarget.focus();let o=i.clientX,c=t;s(!0);let l=document.body,u=l.style.cursor,d=l.style.userSelect;l.style.cursor=`col-resize`,l.style.userSelect=`none`;let f=t=>{let i=e===`left`?t.clientX-o:o-t.clientX;a(Ek(c+i,n,r))},p=()=>{l.style.cursor=u,l.style.userSelect=d,s(!1),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)};window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p)},onKeyDown:i=>{let o=c(i);i.key===`ArrowLeft`?(i.preventDefault(),a(Ek(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(Ek(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var Qk=`super-pi.composer-height.v1`,$k=148,eA=.55,tA=()=>Math.max($k,Math.round((typeof window>`u`?800:window.innerHeight)*eA)),nA=e=>{let t=Number.isFinite(e)?e:$k;return Math.round(Math.min(tA(),Math.max($k,t)))},rA=()=>{try{let e=window.localStorage.getItem(Qk);return e===null?$k:nA(Number(e))}catch{return $k}};function iA({height:e,onHeight:t}){let[n,r]=(0,u.useState)(!1),i=e=>e.shiftKey?64:16,a=tA();return(0,F.jsx)(`div`,{className:`composer-resize${n?` composer-resize-dragging`:``}`,"data-composer-resize":`1`,"data-composer-resize-dragging":n?`true`:`false`,"data-composer-height":e,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整消息编辑区高度`,"aria-valuenow":e,"aria-valuemin":$k,"aria-valuemax":a,tabIndex:0,onMouseDown:n=>{n.preventDefault(),n.currentTarget.focus();let i=n.clientY,a=e;r(!0);let o=document.documentElement,s=document.body.style.userSelect;document.body.style.cursor=`ns-resize`,document.body.style.userSelect=`none`;let c=e=>{let t=nA(a+(i-e.clientY));o.style.setProperty(`--composer-height`,`${t}px`)},l=()=>{document.body.style.cursor=``,document.body.style.userSelect=s;let n=Number.parseFloat(o.style.getPropertyValue(`--composer-height`));r(!1),window.removeEventListener(`mousemove`,c),window.removeEventListener(`mouseup`,l),t(Number.isFinite(n)?n:e)};window.addEventListener(`mousemove`,c),window.addEventListener(`mouseup`,l)},onKeyDown:n=>{let r=i(n);n.key===`ArrowUp`?(n.preventDefault(),t(nA(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(nA(e-r))):n.key===`Home`?(n.preventDefault(),t($k)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(nA(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(nA(e-96)))}})}function aA(e,t,n){if(!e.length)return;let r=n?e.find(e=>e.workspaceId===n):void 0;if(r)return r;if(!(n&&t.some(e=>e.id===n)))return n?e.find(e=>h(e.workspaceId).server===h(n).server):e[0]}function oA(e,t,n){let r=n&&e?JSON.stringify([e,t,n]):void 0,[i,a]=(0,u.useState)();(0,u.useEffect)(()=>{if(!r||!n||!e)return;let i=new AbortController;return Ne(`/api/files/diff?${new URLSearchParams({workspaceId:e,path:n,...t?{cwd:t}:{}})}`,{signal:i.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{i.signal.aborted||a({scope:r,diff:e,error:``})}).catch(e=>{i.signal.aborted||a({scope:r,diff:null,error:e instanceof Error?e.message:`读取差异失败`})}),()=>i.abort()},[r,e,t,n]);let o=i?.scope===r?i:void 0;return{diff:o?.diff??null,error:o?.error??``,loading:!!r&&!o}}function sA(e){try{let t=`super-pi.browser-notification-events`,n=Date.now(),r=JSON.parse(window.localStorage.getItem(t)??`[]`).filter(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`number`&&n-e[1]<864e5);return!r.some(([t])=>t===e)&&(window.localStorage.setItem(t,JSON.stringify([...r.slice(-63),[e,n]])),!0)}catch{return!0}}function cA(){let[e,t]=(0,u.useState)(MD),[n,r]=(0,u.useState)(()=>{try{return typeof window<`u`&&window.localStorage.getItem(`super-pi.browser-notifications`)===`enabled`}catch{return!1}}),[i,a]=(0,u.useState)(()=>ta()),o=(0,u.useCallback)(()=>a(ta()),[]),s=(0,u.useRef)(new Map),c=(0,u.useRef)(!1),l=(0,u.useRef)(new Map),d=(0,u.useCallback)(e=>{t(t=>{let n=typeof e==`function`?e(t):e;return wt(n,t)})},[]),[f,p]=(0,u.useState)(()=>cp().map(e=>{let t=new Date().toISOString();return{id:e.clientId,key:`send:${e.conversationId}:${e.clientId}`,serverId:de(e.conversationId),retry:!0,command:{...e},apply:n=>fp(n,e,t),accepted:t=>!!t.conversations.find(t=>t.id===e.conversationId)?.messages.some(t=>t.id===dp(e))}})),m=(0,u.useRef)(f),_=(0,u.useRef)(null);_.current||=Hk();let v=(0,u.useRef)(null);v.current||=qk();let y=v.current,b=(0,u.useRef)(null);b.current||=In();let x={current:b.current},S=(0,u.useRef)(null);S.current||=Ln();let w=S.current,T=f.reduce((e,t)=>t.apply(e),e),E=w.view===`file`||w.view===`diff`||w.view===`gitDiff`,[D,O]=(0,u.useState)(y.workspaceLandingId||y.selectionCleared?void 0:y.activeId??(E?y.contextId:void 0)??(y.emptied?void 0:_.current.activeId)),[k,A]=(0,u.useState)(y.workspaceLandingId??(y.selectionCleared?x.current.kind===`workspace`?x.current.workspaceId:void 0:_.current.workspaceId)),[j,ee]=(0,u.useState)(!1),M=ue(),te=j&&M.statuses.get(M.activeServer)?.state===`online`,[N,ne]=(0,u.useState)(),[ie,ae]=(0,u.useState)(()=>Nk().workspaces??{}),[oe,se]=(0,u.useState)(()=>({ids:y.ids,previewId:y.previewId,touched:new Set(y.touched??[]),emptied:y.emptied})),ce=oe.ids,le=oe.previewId,ye=(0,u.useRef)(0),[be,xe]=(0,u.useState)(),[Se,Ce]=(0,u.useState)({entries:[],index:-1}),[we,Te]=(0,u.useState)(),Ee=(0,u.useRef)(new Set),De=oe.emptied===!0,[Oe,ke]=(0,u.useState)(!1),[Ae,je]=(0,u.useState)(!1),[Pe,Fe]=(0,u.useState)(),Ie=(0,u.useRef)(null),Re=(0,u.useRef)(void 0),ze=(0,u.useRef)(_.current.conversations),Be=(0,u.useRef)(ce);Be.current=ce;let Ve=(0,u.useRef)(_.current.readAt??{}),[He,Ge]=(0,u.useState)(0),[Ke,qe]=(0,u.useState)(Xn),[Je,Ye]=(0,u.useState)(()=>w.groups.length?w.groups:Ke?[Ke]:[]),[Xe,Ze]=(0,u.useState)(w.view?w.view===`group`:!!Ke),[I,$e]=(0,u.useState)(()=>w.view??(Ke?`group`:`session`)),{index:et,reload:tt,remember:nt,forget:rt,activities:it,recordActivity:at}=or(T.workspaces,te),[ot,st]=(0,u.useState)(()=>new Set),ct=Ke?.workspaceId??``,lt=Ke?.roomId??``,ut=et[ct]?.rooms.find(e=>e.id===lt),dt=ut?.title;(0,u.useEffect)(()=>{Zn(I===`group`?Ke:void 0)},[Ke,I]),(0,u.useEffect)(()=>{I===`group`&&Oe&&!T.workspaces.some(e=>e.id===ct&&!e.closedAt)&&(Ze(!1),$e(`session`))},[I,Oe,T.workspaces,ct]);let ft=(0,u.useRef)(null),pt=(0,u.useRef)(null),mt=(0,u.useRef)(void 0),ht=(0,u.useRef)(!1),gt=(0,u.useRef)(!0),[_t,vt]=(0,u.useState)({followTail:!0,scrollTop:0}),yt=(0,u.useRef)(!1),bt=(0,u.useRef)(new Map),xt=(0,u.useRef)(void 0),St=(0,u.useRef)([]),Ct=(0,u.useRef)(void 0),wt=(0,u.useCallback)((e,t)=>{let n=new Map(t.conversations.map(e=>[e.id,e]));return{...e,conversations:e.conversations.map(e=>{let t=n.get(e.id);if(e.messagesLoaded===!1||!t||t.messagesLoaded===!1||t.status!==`running`)return e;let r=new Map(t.messages.map(e=>[e.id,e]));return{...e,messages:e.messages.map(e=>{let t=r.get(e.id);return!t||!(t.content.length>e.content.length||(t.thinking?.length??0)>(e.thinking?.length??0))?e:{...e,content:t.content,thinking:t.thinking,thinkingActive:t.thinkingActive,thinkingBlocks:RD(t.thinkingBlocks,e.thinkingBlocks)}})}})}},[]),Tt=(0,u.useCallback)(()=>{if(Ct.current!==void 0&&(cancelAnimationFrame(Ct.current),Ct.current=void 0),!St.current.length)return;let e=St.current;St.current=[];let t=new Map;for(let n of e){let e=`${n.conversationId}\u0000${n.messageId}`,r=t.get(e)??[];r.push(n),t.set(e,r)}d(e=>({...e,conversations:e.conversations.map(e=>{let n=e.messages.map(n=>{let r=t.get(`${e.id}\u0000${n.id}`);if(!r)return n;let i={...n};for(let e of r){if(e.type===`message.delta`){i.content+=e.delta;continue}if(i.thinkingActive=e.active,!e.delta)continue;let t=e.at??i.content.length,n=LD(i.thinkingBlocks??[],e,t);i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return n.every((t,n)=>t===e.messages[n])?e:{...e,messages:n}})}))},[]),Et=(0,u.useCallback)(e=>{let t=St.current,n=t.at(-1);n&&n.type===e.type&&n.conversationId===e.conversationId&&n.messageId===e.messageId&&(e.type!==`message.thinking`||n.type===`message.thinking`&&n.at===e.at&&n.active===e.active&&n.blockIndex===e.blockIndex)?t[t.length-1]={...e,delta:n.delta+e.delta}:t.push(e),Ct.current===void 0&&(Ct.current=requestAnimationFrame(Tt))},[Tt]),Dt=(0,u.useCallback)(e=>{xt.current=e},[]),[Ot,kt]=(0,u.useState)(()=>Nk().archived??{});(0,u.useEffect)(()=>{Pk({workspaces:ie,archived:Ot})},[ie,Ot]);let[At,jt]=(0,u.useState)(()=>_E());(0,u.useEffect)(()=>{vE(At)},[At]);let[Mt,Nt]=(0,u.useState)(),Pt=(0,u.useRef)(0),Ft=(0,u.useRef)(``),It=(e,t,n,r)=>{let i=(e.target instanceof Element?e.target:void 0)?.closest(`button`);if(i&&!i.classList.contains(`conversation`)||e.button!==0)return;let a=e.clientY,o=e.pointerType===`touch`,s=!1,c,l=[],u,d=!1,f=e=>{let t=l.filter(e=>e.id!==n);if(t.length===0){u=void 0,d=!1;return}let r=0;for(;r<t.length&&t[r].middle<e;)r+=1;r<t.length?(u=t[r].id,d=!1):(u=t[t.length-1].id,d=!0)},p=()=>Nt(e=>e&&e.dropRootId===u&&e.dropAfter===d?e:{workspaceId:t,conversationId:n,dropRootId:u,dropAfter:d}),m=()=>{s||(s=!0,l=Fk(t),f(a),document.body.style.userSelect=`none`,p())},h=e=>{if(!s){if(o){c!==void 0&&window.clearTimeout(c),c=void 0;return}if(Math.abs(e.clientY-a)<Ik)return;m()}f(e.clientY),p()},g=e=>{if(window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,_),window.removeEventListener(`pointercancel`,v),document.removeEventListener(`touchmove`,y),c!==void 0&&window.clearTimeout(c),document.body.style.userSelect=``,s&&e){let e=r.filter(e=>e!==n),i=u===void 0?e.length:d?e.indexOf(u)+1:e.indexOf(u);jt(e=>({...e,[t]:hE(r,n,i)})),Pt.current=Date.now(),Ft.current=n}Nt(void 0)},_=()=>g(!0),v=()=>g(!1),y=e=>{s&&e.preventDefault()};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,_),window.addEventListener(`pointercancel`,v),o&&(document.addEventListener(`touchmove`,y,{passive:!1}),c=window.setTimeout(m,Lk))},[Lt,Rt]=(0,u.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),zt=e=>{let t=e.slice(0,24);Rt(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},Bt=Lt.trim()||`你`,[Vt,Ht]=(0,u.useState)(),[Ut,Gt]=(0,u.useState)([]),[Kt,qt]=(0,u.useState)([]),[Jt,Yt]=(0,u.useState)(),[Xt,Zt]=(0,u.useState)(),[Qt,$t]=(0,u.useState)([]),[en,tn]=(0,u.useState)([]),[nn,rn]=(0,u.useState)(),[an,on]=(0,u.useState)(),[sn,cn]=(0,u.useState)(),[ln,un]=(0,u.useState)(),[dn,pn]=(0,u.useState)(),mn=Yi(sn),hn=(0,u.useMemo)(()=>Ut.filter(e=>e.request.blocking),[Ut]),[gn,_n]=(0,u.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[vn,yn]=(0,u.useState)(`chat`),[bn,xn]=(0,u.useState)(!1),Sn=(0,u.useCallback)(()=>{yn(`chat`),window.matchMedia(`(max-width: 700px)`).matches&&_n(!0)},[]),[wn,Tn]=(0,u.useState)(!1),[En,Dn]=(0,u.useState)(x.current.kind),[On,An]=(0,u.useState)(()=>x.current.serverId??localStorage.getItem(`super-pi.server-filter`)??`all`),[jn,Mn]=(0,u.useState)(x.current.workspaceId??_.current.workspaceId),[Nn,Pn]=(0,u.useState)(x.current.repoId??_.current.workspaceId),[Vn,Un]=(0,u.useState)(y.selectionCleared===!0);(0,u.useEffect)(()=>{try{Fn(`super-pi.sidebar-scope.v1`,JSON.stringify({kind:En,serverId:On,workspaceId:jn,repoId:Nn}))}catch{}},[En,On,jn,Nn]);let Wn=(0,u.useRef)(Vn);Wn.current=Vn;let[Gn,Kn]=(0,u.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,u.useEffect)(()=>{let e=()=>Kn(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[qn,Jn]=(0,u.useState)(Hr);(0,u.useEffect)(()=>Ur(qn),[qn]);let[Yn,tr]=(0,u.useState)(Yk),nr=kk(Yn.sidebar??270,Yn.rail??320,Gn>1100?Gn-88:Gn);(0,u.useEffect)(()=>{Xk({sidebar:Yn.sidebar??270,rail:Yn.rail??320})},[Yn.sidebar,Yn.rail]);let sr=e=>tr(t=>({...t,sidebar:e})),lr=e=>tr(t=>({...t,rail:e})),[ur,dr]=(0,u.useState)(null);(0,u.useEffect)(()=>{dr(rA())},[]),(0,u.useEffect)(()=>{ur!==null&&document.documentElement.style.setProperty(`--composer-height`,`${ur}px`)},[ur]);let fr=e=>{let t=nA(e);dr(t);try{window.localStorage.setItem(Qk,String(t))}catch{}};(0,u.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(Tk),t=e=>{e.matches&&_n(!0)};return e.addEventListener(`change`,t),e.matches&&_n(!0),()=>e.removeEventListener(`change`,t)},[]);let pr=Gn<=1100;(0,u.useEffect)(()=>{if(!pr||gn)return;let e=e=>{e.key===`Escape`&&(e.defaultPrevented||document.querySelector(`.tool-overlay, .lightbox-overlay, .quick-open-backdrop, .ctx-menu, .overlay, .picker-menu, .content-search-overlay`)||(e.preventDefault(),_n(!0)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[pr,gn]);let[mr,hr]=(0,u.useState)({}),[gr,_r]=(0,u.useState)({}),[vr,yr]=(0,u.useState)({}),[br,xr]=(0,u.useState)({}),[Sr,Cr]=(0,u.useState)(null),[wr,Tr]=(0,u.useState)(),[Er,Dr]=(0,u.useState)(()=>new Set);(0,u.useEffect)(()=>{Dr(e=>{if(e.size===0)return e;let t=new Set([...e].filter(e=>{let t=T.conversations.find(t=>t.id===e);return t?qO(t):!1}));return t.size===e.size?e:t})},[T.conversations]);let[Ar,jr]=(0,u.useState)(),[Mr,Nr]=(0,u.useState)(),Pr=(0,u.useRef)(new Map),[Fr,Ir]=(0,u.useState)(()=>{let e=pp(`super-pi.composer-drafts.v1`,{});return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,attachments:CO(t.text,t.attachments)}]))}),Lr=(0,u.useRef)(Fr),Rr=(0,u.useRef)(!1);Lr.current=Fr,(0,u.useEffect)(()=>{let e=()=>{let e=Object.entries(Lr.current).filter(([e,t])=>!e.startsWith(`pending:`)&&(t.text||t.images.length||t.attachments.length)).map(([e,{text:t,images:n,attachments:r}])=>[e,{text:t,images:n,attachments:r,uploading:0}]),t=mp(`super-pi.composer-drafts.v1`,Object.fromEntries(e));!t&&e.length&&!Rr.current&&Rs(`浏览器无法保存聊天草稿,刷新前请先保留这段内容。`,`warning`),Rr.current=!t&&e.length>0},t=window.setTimeout(e,250);return window.addEventListener(`pagehide`,e),()=>{window.clearTimeout(t),window.removeEventListener(`pagehide`,e)}},[Fr]);let zr=(0,u.useRef)(new Set),[Br,Vr]=(0,u.useState)([]),[Wr,qr]=(0,u.useState)([]),[Jr,Yr]=(0,u.useState)(),[Xr,Zr]=(0,u.useState)(!1),Qr=(0,u.useRef)(null),$r=(0,u.useRef)(!1),ei=(0,u.useRef)(0),ti=(0,u.useRef)([]),ni=(0,u.useRef)(void 0),ri=(0,u.useRef)(!1),ii=(0,u.useRef)(new Set),ai=(0,u.useRef)(new Set),oi=(0,u.useRef)(new Map),si=(0,u.useRef)(new Map),[ci,li]=(0,u.useState)(()=>Date.now());(0,u.useEffect)(()=>{let e=window.setInterval(()=>li(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let ui=(0,u.useMemo)(()=>T.conversations.filter(e=>!e.archivedAt),[T.conversations]),di=(0,u.useMemo)(()=>e.conversations.filter(e=>!e.archivedAt),[e.conversations]),fi=(0,u.useMemo)(()=>new Set(T.collapsedConversationIds??[]),[T.collapsedConversationIds]),L=(0,u.useMemo)(()=>{let e=ui.find(e=>e.id===D);if(e)return e;if(!(De||Vn||re(D??k)))return aA(ui,T.workspaces,k)},[De,Vn,D,ui,k,T.workspaces]),pi=(0,u.useMemo)(()=>L?{workspaceId:L.workspaceId,conversationId:L.id,onImageOpen:Yr}:void 0,[L?.workspaceId,L?.id]),[mi,hi]=(0,u.useState)(`queue`),_i=!!(L&&qO(L));(0,u.useEffect)(()=>{hi(`queue`)},[L?.id,_i]);let[vi,yi]=(0,u.useState)([]),bi=(0,u.useMemo)(()=>Bn(L?.parentConversationId,L?.parentConversationId?T.conversations.find(e=>e.id===L.parentConversationId):void 0),[L,T.conversations]),xi=!!(L&&T.unlockedChildConversationIds?.includes(L.id)),Si=bi&&!xi,Ci=(0,u.useMemo)(()=>(T.conversations||[]).filter(e=>e.parentConversationId===L?.id),[T.conversations,L?.id]),wi=(0,u.useMemo)(()=>(T.conversations||[]).find(e=>e.id===L?.parentConversationId),[T.conversations,L?.parentConversationId]),Ti=(0,u.useMemo)(()=>L?Hn({conversation:L,parent:wi,directChildren:Ci,isTopLevelUnread:!1}):null,[L,wi,Ci]),Ei=ft.current;if(Ei){let e=Ei.dataset.messageScrollContainer;e&&L?.id&&e!==L?.id&&Ei.querySelector(`[data-transcript-key]`)&&(ze.current[e]=Vk(Ei,ze.current[e]??{followTail:!0,scrollTop:0}))}gt.current=L?.messagesLoaded!==!1,(0,u.useEffect)(()=>{if(!Oe||re(D??k)||(De||Vn)&&!D||D&&di.some(e=>e.id===D)||D&&m.current.some(e=>e.temporaryId===D))return;let e=aA(ui,T.workspaces,k);De&&e||(D&&!e&&I!==`group`&&(ye.current++,$e(`session`)),O(e?.id),e&&se(t=>t.emptied||t.ids.length===0||t.ids.includes(e.id)?t:{...t,ids:[...t.ids,e.id]}))},[De,Vn,D,di,ui,Oe,k,T.workspaces,I]),(0,u.useEffect)(()=>{ne(void 0)},[D,k]);let Di=(0,u.useMemo)(()=>T.workspaces.find(e=>e.id===k)??(Vn||re(k)?void 0:T.workspaces[0]),[T.workspaces,k,Vn]),Oi=Di&&!ui.some(e=>e.workspaceId===Di.id)?Di:void 0,ki=Di?.id.startsWith(`pending:`)===!0,[Ai,ji]=(0,u.useState)(``);(0,u.useEffect)(()=>{ji(``)},[Di?.id]);let Mi=(0,u.useRef)(k);Mi.current=k,(0,u.useEffect)(()=>{L&&A(L.workspaceId)},[L?.id]),(0,u.useEffect)(()=>{ni.current=D},[D]),(0,u.useEffect)(()=>{mt.current=L?.id},[L?.id]);let Ni=(0,u.useCallback)(e=>{let t=e.activity.lastReplyAt,n=Qn({workspaceId:e.workspaceId,roomId:e.id});!t||t<=(Ve.current[n]??``)||(Ve.current[n]=t,Ge(e=>e+1),Uk({activeId:ni.current,workspaceId:Mi.current,conversations:ze.current,readAt:Ve.current}))},[]);cr(Ve,T.conversations,()=>{Ge(e=>e+1),Uk({activeId:ni.current,workspaceId:Mi.current,conversations:ze.current,readAt:Ve.current})}),(0,u.useEffect)(()=>{let e=L?.id;if(!e)return;let t=T.conversations.find(t=>t.id===e);if(!t||t.messagesLoaded===!1)return;let n=()=>{let n=ft.current;document.visibilityState!==`visible`||!n||n.getBoundingClientRect().height<=0||t.updatedAt<=(Ve.current[e]??``)||(Ve.current[e]=t.updatedAt,Ge(e=>e+1),Uk({activeId:ni.current,workspaceId:L?.workspaceId??k,conversations:ze.current,readAt:Ve.current}))},r=requestAnimationFrame(n);return document.addEventListener(`visibilitychange`,n),window.addEventListener(`focus`,n),()=>{cancelAnimationFrame(r),document.removeEventListener(`visibilitychange`,n),window.removeEventListener(`focus`,n)}},[L?.id,T.conversations,I]),(0,u.useEffect)(()=>{let e=L?.workspaceId??k;te&&Oe&&e&&!e.startsWith(`pending:`)&&!L?.id.startsWith(`pending:`)&&Uk({activeId:L?.id,workspaceId:e,conversations:ze.current,readAt:Ve.current})},[L?.id,L?.workspaceId,te,Oe,k]),(0,u.useEffect)(()=>{let e=ft.current;if(I!==`session`||!e||!L?.id||L.messagesLoaded===!1)return;let t=L.id;yt.current=!1;let n=ze.current[t]??{followTail:!0,scrollTop:0};ze.current[t]=n,vt(n);let r=requestAnimationFrame(()=>{if(ft.current!==e)ht.current=!1;else{if(n.followTail)Bk(e),e.scrollTop=e.scrollHeight;else{let t=n.anchorKey?e.querySelector(`[data-transcript-key="${CSS.escape(n.anchorKey)}"]`):null;e.scrollTop=t?Math.max(0,e.scrollTop+t.getBoundingClientRect().top-(n.anchorOffset??0)-e.getBoundingClientRect().top):n.scrollTop}ht.current=!1}});return()=>cancelAnimationFrame(r)},[L?.id,L?.messagesLoaded,I]),(0,u.useLayoutEffect)(()=>{ht.current=!0},[L?.id,L?.messagesLoaded,I]);let Pi=(0,u.useCallback)((e,t=!1,n=!1)=>{let r=mt.current;if(!r||ht.current||!gt.current)return;let i=Vk(e,ze.current[r]??{followTail:!0,scrollTop:0},t,n);yt.current=!i.followTail,ze.current[r]=i,vt(i),Uk({activeId:r,workspaceId:Mi.current,conversations:ze.current,readAt:Ve.current})},[]),Fi=L?.id??``,Ii=Fr[Fi]??{text:``,images:[],attachments:[],uploading:0},Li=Ii.text,Ri=Ii.images,zi=Ii.attachments,Bi=Object.keys(Ii.pendingSkills??{}).length>0,Vi=Ii.uploading,Hi=(e,t)=>Ir(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),Ui=(e,t)=>({...e,text:t,attachments:CO(t,e.attachments),pendingSkills:e.pendingSkills&&Object.fromEntries(Object.entries(e.pendingSkills).filter(([e])=>pf(t,e)))}),Wi=e=>Hi(Fi,t=>Ui(t,e)),Gi=(e,t,n,r)=>{let i=Wt();Hi(n,n=>{let r=Ui(n,t);return{...r,pendingSkills:{...r.pendingSkills,[e]:i}}});let a=t=>t[n]?.pendingSkills?.[e]===i?n:n.startsWith(`pending:`)?Object.keys(t).find(n=>t[n].pendingSkills?.[e]===i):void 0,o=t=>Ir(n=>{let r=a(n);if(!r)return n;let i=n[r],o={...i.pendingSkills};delete o[e];let s=t?[...i.attachments.filter(t=>t.id!==e),t]:i.attachments;return{...n,[r]:{...i,pendingSkills:o,attachments:s}}});Ne(`/api/skills/read?${new URLSearchParams({name:e,workspaceId:r})}`,{signal:AbortSignal.timeout(1e4)}).then(async t=>{if(!t.ok)throw Error(`读取技能失败`);let n=await t.json();if(typeof n.content!=`string`)throw Error(`读取技能失败`);o({kind:`skill`,id:e,name:n.name??e.slice(6),content:n.content})}).catch(()=>{a(Lr.current)&&Rs(`读取技能失败`,`error`),o()})},Ki=(e,t)=>Hi(L?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[qi,Ji]=(0,u.useState)({visible:!1,query:``,rect:null}),Zi=JSON.stringify([L?.id,L?.workspaceId,L?.cwd??``]),[Qi,$i]=(0,u.useState)(),ea=(0,u.useRef)(null),[R,oa]=(0,u.useState)(),sa=(0,u.useRef)(void 0),ca=(0,u.useRef)(``),la=!Si&&Qi?.scope===Zi?Qi:void 0,ua=e=>{let t=!$r.current&&!Si&&L?gf(e.value,e.selectionStart,e.selectionEnd):void 0,n=JSON.stringify([Zi,t]);return!t||ca.current===n?($i(void 0),!1):($i({scope:Zi,token:t,rect:e.getBoundingClientRect()}),Ji({visible:!1,query:``,rect:null}),!0)},da=()=>{ca.current=JSON.stringify([Zi,la?.token]),$i(void 0)};(0,u.useEffect)(()=>{$i(void 0),ca.current=``},[Zi]),(0,u.useLayoutEffect)(()=>{let e=sa.current;sa.current=void 0,e?.scope===Zi&&e.text===Li&&(pt.current?.focus(),pt.current?.setSelectionRange(e.caret,e.caret))},[Li,Zi]),(0,u.useEffect)(()=>{let e=()=>{let e=pt.current;e&&$i(t=>t?{...t,rect:e.getBoundingClientRect()}:void 0)};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let fa=e=>Hi(L?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),pa=ce.length>0?ce:De?[]:L?[L.id]:[],ma=(0,u.useMemo)(()=>pa.map(e=>ui.find(t=>t.id===e)).filter(e=>e!==void 0),[pa,ui]),ha=Oi?void 0:ma.filter(e=>e.id!==le).at(-1)?.id,ga=ma.some(e=>e.id===L?.id);(0,u.useEffect)(()=>{if(!Oe)return;let e=new Set(ui.map(e=>e.id));se(t=>{let n=t.ids.filter(t=>e.has(t)||re(t)),r=t.previewId&&(e.has(t.previewId)||re(t.previewId))?t.previewId:void 0;return n.length===t.ids.length&&r===t.previewId?t:{...t,ids:n,previewId:r}})},[Oe,ui]),(0,u.useEffect)(()=>{!Oe||ki||D?.startsWith(`pending:`)||re(D??k)||Jk(oe,D,D?void 0:Oi?.id,Vn||!D&&!Xe)},[D,Oe,oe,ki,Oi?.id,Vn,Xe]);let _a=(0,u.useCallback)(e=>{e&&se(t=>{if(t.touched.has(e))return t;let n=t.previewId===e?void 0:t.previewId;return{...t,previewId:n,touched:Gk(t.touched,e)}})},[]),va=(0,u.useCallback)(e=>{ve(de(e)),Un(!1),ye.current++,Ze(!1),O(e);let t=ui.find(t=>t.id===e)?.workspaceId;t&&A(t),$e(`session`),se(t=>{let n=t.emptied===!0,r=n?{...t,emptied:!1}:t;if(r.ids.includes(e))return r;let i=!n&&r.ids.length===0&&L?.id&&L.id!==e?[L.id]:[],a=[...r.ids,...i];if(r.touched.has(e))return{...r,ids:[...a,e]};let o=r.previewId?a.indexOf(r.previewId):-1,s=o>=0?a.map((t,n)=>n===o?e:t):[...a,e];return{...r,ids:s,previewId:e}})},[L,ui]);(0,u.useEffect)(()=>{if(!Oe)return;let t=new Map(e.conversations.filter(e=>!e.archivedAt).map(e=>[e.id,{status:e.status,hasPendingQuestion:!!e.hasPendingQuestion,title:e.title,workspaceId:e.workspaceId,parentConversationId:e.parentConversationId}]));if(!c.current){s.current=t,c.current=!0;return}let r=document.visibilityState===`visible`&&document.hasFocus(),a=n&&[`granted`,`native`].includes(i)&&!r;for(let[n,r]of t){let t=s.current.get(n);if(!t||r.parentConversationId||!a)continue;let i=!t.hasPendingQuestion&&r.hasPendingQuestion,o=r.status===`completed`&&t.status!==`completed`&&[`waiting`,`running`,`awaiting_background`].includes(t.status);if(!i&&!o)continue;let c=i?`question`:`completed`;if(sA(`${n}:${c}:${e.conversations.find(e=>e.id===n)?.updatedAt??``}`))try{let e=`${n}:${c}`,t=ra(i?`Super Pi · 等你回答`:`Super Pi · Agent 已完成`,{body:`${_e(r.workspaceId)} · ${i?`「${r.title}」需要你的回答。`:`「${r.title}」已完成。`}`,tag:`super-pi-${c}-${n}`});l.current.set(e,t),t.onclose=()=>{l.current.get(e)===t&&l.current.delete(e)},t.onclick=()=>{t.close(),l.current.delete(e),window.focus(),va(n)}}catch(e){console.warn(`[Super Pi] Browser notification could not be shown:`,e instanceof Error?e.message:`unknown error`)}}s.current=t},[e.conversations,Oe,n,i,va]);let ya=(0,u.useCallback)(e=>{e&&(_a(e),va(e))},[_a,va]),ba=e=>{e.startsWith(`pending:`)||ve(de(e)),Un(!0),ye.current++,Ze(!1),L&&ga&&se(e=>e.ids.length||e.emptied?e:{...e,ids:[L.id]}),A(e),O(void 0),$e(`session`),Tn(!1),Sn()},xa=(0,u.useCallback)((e,t=``)=>{ye.current++;let n={workspaceId:e,roomId:t};t&&Ye(r=>r.some(n=>n.workspaceId===e&&n.roomId===t)?r:[...r,n]),qe(n),Ze(!0),A(e),Tn(!1),$e(`group`),Sn()},[Sn]),Sa=(0,u.useCallback)((e,t)=>{nt(e,!0),t&&(ae(t=>t[e.workspaceId]?{...t,[e.workspaceId]:!1}:t),xa(e.workspaceId,e.id))},[xa,nt]);(0,u.useEffect)(()=>{let e=new Set;if(!n||i!==`granted`)aa(e);else{for(let t of Object.values(et))for(let n of t.rooms)if(!n.archivedAt)for(let t of n.cloneRequests??[]){if(t.status!==`pending`||t.automatic)continue;let r=`group-clone:${n.id}:${t.id}`;e.add(r),ia(r,`${_e(n.workspaceId)} · ${n.title} · 需要决定是否创建分身`,t.reason,I===`group`&<===n.id&&document.visibilityState===`visible`&&document.hasFocus(),()=>xa(n.workspaceId,n.id))}aa(e)}},[et,I,lt,xa,n,i]);let Ca=(0,u.useCallback)(e=>{tt(),rt(e)},[rt,tt]);async function wa(e,t){if(!ot.has(e.id)&&(t!==`delete`||window.confirm(`永久删除群聊「${e.title}」及其聊天记录?删除后无法恢复。`))){st(t=>new Set(t).add(e.id));try{let n=await rr(er(e.workspaceId,e.id),{action:t});if(t===`delete`)Ca({workspaceId:e.workspaceId,roomId:e.id});else{if(!n)throw Error(`服务没有确认群聊状态。`);tt(),nt(n),t===`archive`&&kt(t=>({...t,[e.workspaceId]:!1}))}}catch(e){Rs(e instanceof Error?e.message:`群聊操作失败。`,`error`)}finally{st(t=>new Set([...t].filter(t=>t!==e.id)))}}}let Ta=Xe&&I!==`session`,Ea=Ta?ct:L?.workspaceId??k,Da=Ea?.startsWith(`pending:`)?void 0:Ea,Oa=Da??(En===`repo`?T.workspaces.find(e=>e.id===Nn&&(!e.worktreeOf||!T.workspaces.some(t=>t.id===e.worktreeOf)))?.id??T.workspaces.find(e=>(On===`all`||h(e.id).server===On)&&(!e.worktreeOf||!T.workspaces.some(t=>t.id===e.worktreeOf)))?.id:void 0),ka=Oa?.startsWith(`pending:`)?void 0:Oa,Aa=Ta?``:L?.cwd??``;(0,u.useEffect)(()=>{Da&&ve(de(Da))},[Da]);let ja=En===`repo`&&(!L||Ta),Ma=JSON.stringify([Da,Aa]),[Na,Pa]=(0,u.useState)(),[Fa,Ia]=(0,u.useState)(50),La=Na?.scope===Ma?Na:void 0,Ra=!!La,za=La?.tabId;(0,u.useEffect)(()=>{Pa(e=>e?.scope===Ma?e:void 0)},[Ma]);let Ba=(0,u.useCallback)(e=>{Pa(t=>t?.scope===Ma?{...t,tabId:e}:t)},[Ma]),z=Em(Da,Aa,{navigation:ye,showingFile:I===`file`,splitFilePath:za?.startsWith(`file:`)?za.slice(5):void 0}),Va=gi(ka,ka===Da?Aa:``,te&&Oe),Ha=(0,u.useRef)(Va.refresh);Ha.current=Va.refresh;let Ua=(0,u.useRef)(z.setChangedFor),Wa=(0,u.useRef)(z.invalidateTree);Wa.current=z.invalidateTree;let Ga=(0,u.useRef)(Da);Ga.current=Da,(0,u.useEffect)(()=>{Ua.current=z.setChangedFor},[z.setChangedFor]);let[Ka]=(0,u.useState)(HO),[qa,Ja]=(0,u.useState)(Ka.tab),[Ya,Xa]=(0,u.useState)(Ka.byConversation),Za=(L?.id?Ya[L.id]:void 0)??qa;(0,u.useEffect)(()=>{try{Fn(VO,JSON.stringify({tab:qa,byConversation:Ya}))}catch{}},[qa,Ya]);let Qa=(0,u.useCallback)(e=>{Ja(e),L?.id&&Xa(t=>({...t,[L.id]:e}))},[L?.id]),$a=qn.order.filter(e=>qn.sides[e]===`left`),[eo,to]=(0,u.useState)(!1),[no,ro]=(0,u.useState)(!1),io=qn.order.filter(e=>e!==`sessions`&&qn.sides[e]===`right`),B=$a.includes(qn.leftView)?qn.leftView:`sessions`,ao=io.includes(Za)?Za:io[0],oo=qn.rightClosed||!ao,so=pr||!qn.leftClosed&&!eo&&B===`sessions`,co=(e,t=!1)=>{(e===`sessions`||qn.sides[e]===`left`)&&to(!1),pr?e===`sessions`?(Sn(),Tn(!0)):(Qa(e),_n(!1),Gn<=700&&yn(`rail`)):qn.sides[e]===`left`?Jn(n=>({...n,leftView:e,leftClosed:t&&!eo&&!n.leftClosed&&B===e})):e!==`sessions`&&(Qa(e),Jn(n=>({...n,rightClosed:t&&!n.rightClosed&&ao===e})))},lo=(e,t)=>{let n=qn.sides[e];if(t===`move`){let t=n===`left`?`right`:`left`;t===`left`&&to(!1),Jn(n=>({...n,sides:{...n.sides,[e]:t},...t===`left`?{leftView:e,leftClosed:!1}:{rightClosed:!1}})),t===`right`&&Qa(e),requestAnimationFrame(()=>{(document.querySelector(`[data-workbench-view="${e}"]`)??document.querySelector(`[data-workbench-panel-menu="${e}"]`))?.focus()})}else Jn(t===`pin`?t=>({...t,unpinned:t.unpinned.includes(e)?t.unpinned.filter(t=>t!==e):[...t.unpinned,e]}):r=>{let i=r.order.filter(e=>r.sides[e]===n&&!r.unpinned.includes(e)),a=i.indexOf(e),o=a>=0?i[a+(t===`up`?-1:1)]:void 0;if(!o||o===`sessions`)return r;let s=r.order.slice(),c=s.indexOf(e),l=s.indexOf(o);return[s[c],s[l]]=[s[l],s[c]],{...r,order:s}})},uo=(e,t)=>{e!==t&&Jn(n=>{if(n.sides[e]!==n.sides[t])return n;let r=n.order.slice(),i=r.indexOf(e),a=r.indexOf(t);return r.splice(i,1),r.splice(a,0,e),{...n,order:r}})},fo=JSON.stringify([Da,Aa]),[po,mo]=(0,u.useState)(),ho=po?.scope===fo?po:void 0,go=ho?.mode===`path`;(0,u.useEffect)(()=>{mo(e=>e?.scope===fo?e:void 0)},[fo]);let _o=(0,u.useCallback)((e,t,n)=>{ye.current++,mo(r=>r?.mode===e&&r.scope===fo&&r.directory===n?r:{mode:e,scope:fo,initialQuery:t,directory:n}),Tn(!1)},[fo]),vo=(0,u.useCallback)(()=>{ye.current++,mo(void 0)},[]),[yo,bo]=(0,u.useState)(),xo=(0,u.useRef)(0),So=e=>{va(e.conversationId),bo({hit:e,request:ye.current}),mo(void 0),Sn()};(0,u.useEffect)(()=>{if(!yo||yo.request===xo.current||L?.id!==yo.hit.conversationId||L?.messagesLoaded===!1||I!==`session`||!ga)return;let{hit:e,request:t}=yo,n=null,r,i=requestAnimationFrame(()=>{let i=ft.current;i&&ye.current===t&&(n=i.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`),n&&(xo.current=t,Bk(i),i.scrollTop+=n.getBoundingClientRect().top-i.getBoundingClientRect().top-24,Pi(i,!0),n.dataset.sessionSearchHit=`true`,n.tabIndex=-1,n.focus({preventScroll:!0}),r=setTimeout(()=>{n&&delete n.dataset.sessionSearchHit},2400)))});return()=>{cancelAnimationFrame(i),clearTimeout(r),n&&delete n.dataset.sessionSearchHit}},[L?.id,L?.messagesLoaded,I,Pi,ga,yo]);let[Co,wo]=(0,u.useState)(),[To,Eo]=(0,u.useState)(),[Do,Oo]=(0,u.useState)(w.diffs),ko=Do.paths,[Ao,V]=(0,u.useState)(w.gitDiffs),[H,U]=(0,u.useState)(w.gitDiffUrl);(0,u.useEffect)(()=>{if(!(!Oe||z.restoringWorkbench||re(D??k)))try{Rn({view:I,groups:Je,gitDiffs:Ao,gitDiffUrl:H,diffs:Do})}catch{}},[Oe,z.restoringWorkbench,D,k,I,Je,Ao,H,Do]);let W=I===`gitDiff`?Ao.find(e=>e.target.url===H):void 0,G=I===`gitDiff`?`diff`:I,jo=W?.target.path??To,Mo=(0,u.useCallback)(e=>{if(ja&&!e.commitHash)return;ye.current++;let t=document.activeElement instanceof HTMLElement?document.activeElement:void 0;V(n=>{let r=n.find(t=>t.target.url===e.url);if(!r){let r={target:e,workspaceId:Da,reading:{},revision:0,preview:!0,origin:t},i=Ra&&I===`gitDiff`?H:void 0,a=n.find(e=>e.preview&&e.target.url!==i);return a?n.map(e=>e===a?r:e):[...n,r]}if(e.commitHash)return n;let i=r.target.label===e.label?{...r.reading,snapshot:void 0}:{};return n.map(n=>n===r?{...n,target:e,reading:i,revision:n.revision+1,origin:t}:n)}),Ra?(Ba(`git-diff:${e.url}`),I===`gitDiff`&&H===e.url&&$e(`session`)):(U(e.url),$e(`gitDiff`)),Sn()},[Da,ja,H,I,Ba,Sn,Ra]),No=(0,u.useCallback)(()=>{!ga&&ha?va(ha):$e(`session`)},[ga,ha,va]);(0,u.useEffect)(()=>{let e=e=>{let t=et[e.workspaceId];return!t?.loaded||t.rooms.some(t=>t.id===e.roomId)},t=Je.filter(e);if(t.length!==Je.length&&Ye(t),I!==`group`||!Ke?.roomId||e(Ke))return;let n=t.filter(e=>e.workspaceId===Ke.workspaceId).at(-1);n?xa(n.workspaceId,n.roomId):No()},[et,Ke,Je,I,xa,No]),(0,u.useEffect)(()=>{I===`file`&&!z.active&&No()},[I,z.active,No]),(0,u.useEffect)(()=>{I===`diff`&&!To&&No()},[I,To,No]);let Po=(0,u.useRef)(`${Da??``}:${Aa}`);(0,u.useEffect)(()=>{let e=`${Da??``}:${Aa}`;Po.current!==e&&(Po.current=e,Oo({paths:[]}),Eo(void 0),$e(e=>e===`gitDiff`||e===`group`?e:`session`))},[Da,Aa]);let Fo=(0,u.useCallback)((e,t=!1)=>{ye.current++;let n=Ra&&!t;Oo(t=>{if(t.paths.includes(e))return t;let r=n&&I===`diff`&&To===t.previewPath;return{paths:t.previewPath&&!r?t.paths.map(n=>n===t.previewPath?e:n):[...t.paths,e],previewPath:e}}),n?(Ba(`diff:${e}`),I===`diff`&&To===e&&$e(`session`)):(Eo(e),$e(`diff`)),Sn(),Ja(`files`)},[To,I,Ba,Sn,Ra]),Io=I===`diff`?To:void 0,Lo=za?.startsWith(`diff:`)?za.slice(5):void 0,Ro=Lo&&Lo!==Io&&ko.includes(Lo)?Lo:void 0,K=oA(Da,Aa,Io),zo=oA(Da,Aa,Ro),[q,Bo]=(0,u.useState)(`server`),[Vo,Ho]=(0,u.useState)(`server`),Uo=e=>{let t=z.open.find(t=>t.path===e);return t?.dirty?t.content:void 0},Wo=(0,u.useCallback)(e=>{ye.current++,z.setActivePath(e),$e(`file`),Ja(`files`)},[z.setActivePath]),Go=(0,u.useCallback)(async(e,t,n=!1,r=!1,i=!1,a)=>{let o=++ye.current,s=()=>ye.current===o,c=Ra&&!i,l=await z.openFile(e,{preview:!n,activate:!c,isCurrent:s,throwOnError:r,requireText:a!==void 0});if(l&&s())return n&&z.pinFile(l),wo(t?{scope:fo,path:l,line:t,column:a,request:o}:void 0),c?(Ba(`file:${l}`),I===`file`&&z.activePath===l&&$e(`session`)):$e(`file`),Sn(),l},[z.openFile,z.pinFile,z.activePath,fo,I,Ba,Sn,Ra]),Ko=(0,u.useCallback)((e,t)=>{Go(e,void 0,t)},[Go]),qo=L&&!Si?(e,t)=>{let n=Li&&!/\s$/u.test(Li)?`${Li} `:Li,r=_f(n,{start:n.length,end:n.length,query:``},{path:e,kind:t?`directory`:`file`});sa.current={scope:Zi,...r},_a(L.id),va(L.id),Sn(),Wi(r.text)}:void 0,Jo=(e,t)=>{ye.current+=1,Oo(t=>({paths:t.paths.filter(t=>!Nf(t,e)),previewPath:t.previewPath&&!Nf(t.previewPath,e)?t.previewPath:void 0})),To&&Nf(To,e)&&Eo(void 0),Pa(n=>{let r=n?.tabId?.startsWith(`file:`)?n.tabId.slice(5):void 0;return n&&r&&Nf(r,e)?{...n,tabId:`file:${t}${r.slice(e.length)}`}:n}),wo(n=>n?.scope===fo&&Nf(n.path,e)?{...n,path:t+n.path.slice(e.length)}:n)};(0,u.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.altKey||e.isComposing)return;let t=e.key.toLowerCase();e.shiftKey&&t===`f`?(e.preventDefault(),_o(`content`)):!e.shiftKey&&t===`p`&&(e.preventDefault(),_o(`path`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[_o]);let Yo=(0,u.useMemo)(()=>ma.map(e=>({id:`session:${e.id}`,workspaceId:e.workspaceId,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:!0,preview:le===e.id,badge:(0,F.jsx)(ek,{state:QO(e,XO(e,hn),Ve.current[e.id],T.conversations)})})),[ma,hn,T.conversations,He,le]),Xo=(0,u.useMemo)(()=>z.open.map(e=>({id:`file:${e.path}`,workspaceId:z.ownerWorkspaceId,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,preview:e.preview,badge:e.dirty?(0,F.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[z.ownerWorkspaceId,z.open]),Zo=(0,u.useMemo)(()=>ko.map(e=>({id:`diff:${e}`,workspaceId:Da,rawId:e,kind:`diff`,label:e.split(/[\\/]/).pop()||e,title:`${e}(改动)`,closable:!0,preview:Do.previewPath===e,icon:(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`±`})})),[Da,ko,Do.previewPath]),Qo=(0,u.useMemo)(()=>[...Yo,...[...Je,...I===`group`&&Ke&&!lt?[Ke]:[]].flatMap(e=>{let t=T.workspaces.find(t=>t.id===e.workspaceId&&!t.closedAt);if(!t)return[];let n=et[e.workspaceId]?.rooms.find(t=>t.id===e.roomId),r=e.roomId?n?.title??`群聊`:`新建群聊`,i=n?ir(n,it[n.id]):`idle`,a=n?ar(n,it[n.id],Ve.current[Qn(e)]):`idle`,o=a===`completed`?`讨论已完成,有新回复未读`:a===`unread`?`有新回复未读`:WO[i],s=`${r} · ${t.name}${i===`idle`?``:` · ${o}`}`;return[{id:Qn(e),workspaceId:e.workspaceId,label:r,title:s,closable:!0,icon:(0,F.jsx)(Gr,{name:`group`}),badge:(0,F.jsx)(ek,{state:a,label:o})}]}),...Xo,...Zo,...Ao.map(({target:e,preview:t,workspaceId:n})=>({id:`git-diff:${e.url}`,workspaceId:n,kind:`diff`,closable:!0,preview:t,label:`${e.path.split(/[\\/]/).pop()||e.path} (${e.label})`,title:`${e.path} · ${e.comparison}`,icon:(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`±`})}))],[Yo,Xo,Zo,Ao,Je,et,it,Ke,lt,I,T.workspaces,He]),$o=I===`group`&&Ke?Qn(Ke):I===`file`&&z.activePath?`file:${z.activePath}`:I===`diff`&&To?`diff:${To}`:W?`git-diff:${W.target.url}`:ga&&L?.id?`session:${L.id}`:void 0,es=(0,u.useRef)(!1),ts=(0,u.useRef)(void 0);(0,u.useLayoutEffect)(()=>{let e=es.current;if(es.current=!1,ts.current!==z.restoredActive&&(ts.current=z.restoredActive,!we&&z.restoredActive&&z.restoredActive===z.activePath&&I!==`file`&&I!==`gitDiff`&&I!==`group`)){$e(`file`);return}if(!e&&Oe&&le&&$o!==`session:${le}`&&ui.some(e=>e.id===le)&&se(e=>{if(e.previewId!==le)return e;let t=e.ids.filter(e=>e!==le);return{...e,ids:t,previewId:void 0,emptied:t.length===0}}),!e)for(let e of z.open)e.preview&&$o!==`file:${e.path}`&&za!==`file:${e.path}`&&z.discardPreview(e.path);let t=Do.previewPath;!e&&t&&$o!==`diff:${t}`&&za!==`diff:${t}`&&Oo(e=>e.previewPath===t?{paths:e.paths.filter(e=>e!==t)}:e);let n=e=>{let t=`git-diff:${e.target.url}`;return!e.preview||t===$o||t===za};!e&&Ao.some(e=>!n(e))&&V(e=>e.filter(n)),Oe&&I===`session`&&L&&L.id===D&&!ga&&!z.restoringWorkbench&&ha&&va(ha)},[$o,Oe,le,z.open,z.activePath,z.restoredActive,z.discardPreview,Do.previewPath,I,L?.id,D,ga,z.restoringWorkbench,ha,va,ui,we,za,Ao]);let ns=(0,u.useCallback)(e=>{if(e.startsWith(`group:`)){let t=$n(e);t&&xa(t.workspaceId,t.roomId)}else if(e.startsWith(`file:`)){let t=e.slice(5);Wo(t)}else if(e.startsWith(`diff:`)){ye.current++;let t=e.slice(5);Eo(t),$e(`diff`)}else if(e.startsWith(`git-diff:`))ye.current++,U(e.slice(9)),$e(`gitDiff`);else if(e.startsWith(`session:`)){let t=e.slice(8);va(t)}},[Wo,va,xa]),rs=Qo.find(e=>e.id===$o),is=I===`file`?z.active:void 0,as=(0,u.useMemo)(()=>{if(!Oe||!rs||rs.id.startsWith(`session:pending:`))return;let{id:e,label:t}=rs;if(I!==`group`||lt&&dt){if(I===`session`)return e.startsWith(`session:`)?{key:e,tabId:e,title:t}:void 0;if(I===`file`||I===`diff`){if(!Da||z.restoringWorkbench||I===`file`&&!is||I===`diff`&&!To)return;let n={workspaceId:Da,cwd:Aa,conversationId:L?.id},r=is&&{path:is.path,name:is.name,text:null,...is.assetTicket||/^(?:[a-z]:[\\/]|[\\/])/i.test(is.path)?{openLink:!0}:{}};return{key:JSON.stringify([n.workspaceId,n.cwd,e]),tabId:e,title:t,scope:n,file:r}}return{key:e,tabId:e,title:t}}},[Oe,rs,I,Da,Aa,L?.id,z.restoringWorkbench,To,is?.path,is?.name,is?.assetTicket,lt,dt]);(0,u.useEffect)(()=>{!we&&as&&(Ee.current.delete(as.key),Ce(e=>Zm(e,as)))},[as,we]);let os=e=>{let t=ui.filter(t=>t.workspaceId===e.workspaceId&&(t.cwd??``)===e.cwd);return t.find(t=>t.id===e.conversationId)??t[0]},ss=e=>{if(e.key===as?.key||Ee.current.has(e.key))return!1;if(e.tabId.startsWith(`session:`))return ui.some(t=>`session:${t.id}`===e.tabId);let t=$n(e.tabId);if(t)return T.workspaces.some(e=>e.id===t.workspaceId&&!e.closedAt)&&!!et[t.workspaceId]?.rooms.some(e=>e.id===t.roomId);if(!e.scope)return Qo.some(t=>t.id===e.tabId);let{scope:n}=e;return T.workspaces.some(e=>e.id===n.workspaceId)?n.workspaceId===Da&&n.cwd===Aa||!!os(n)||!n.cwd&&!ui.some(e=>e.workspaceId===n.workspaceId):!1},cs=Qm(Se,Se.index+ +!as,-1,ss),ls=Qm(Se,Se.index,1,ss),us=e=>{let t=e<0?cs:ls;we||t<0||Te({index:t,direction:e,ticket:++ye.current,stage:`start`})},ds=(0,u.useRef)(us);ds.current=us,(0,u.useEffect)(()=>{let e=e=>{(e.button===3||e.button===4)&&(e.preventDefault(),e.type===`mouseup`&&ds.current(e.button===3?-1:1))};for(let t of[`mousedown`,`mouseup`,`auxclick`])window.addEventListener(t,e,!0);return()=>{for(let t of[`mousedown`,`mouseup`,`auxclick`])window.removeEventListener(t,e,!0)}},[]),(0,u.useEffect)(()=>{let e=we;if(!e)return;if(ye.current!==e.ticket){Te(void 0);return}let t=Se.entries[e.index];if(t.key===as?.key){Ce(t=>({...t,index:e.index})),Te(void 0);return}let n=(t=e.ticket)=>{let n=Qm(Se,e.index,e.direction,ss);Te(n<0?void 0:{...e,index:n,ticket:t,stage:`start`})};if(!ss(t)){n();return}let r=t.scope;if(r&&(r.workspaceId!==Da||r.cwd!==Aa)){if(e.stage!==`start`){n();return}let t=os(r);t?va(t.id):ba(r.workspaceId),Te({...e,stage:`scope`,ticket:ye.current});return}if(e.stage===`opening`||r&&z.restoringWorkbench)return;Tn(!1),Sn();let i=t.file;if(i&&!z.open.some(e=>e.path===i.path)){let r=Go(i,void 0,!1,!0,!0),a=ye.current;Te({...e,stage:`opening`,ticket:a}),r.then(e=>{!e&&ye.current===a&&Te(void 0)}).catch(e=>{ye.current===a&&(e instanceof $p&&e.status===404?(Ee.current.add(t.key),n(a)):(Rs(Or(e instanceof Error?e.message:void 0,`无法打开导航历史中的文件。`),`error`),Te(void 0)))})}else t.tabId.startsWith(`diff:`)&&!Qo.some(e=>e.id===t.tabId)?Fo(t.tabId.slice(5),!0):ns(t.tabId),Te({...e,stage:`opening`,ticket:ye.current})});let fs=(0,u.useCallback)(e=>{if(e.startsWith(`session:`))ya(e.slice(8));else if(e.startsWith(`file:`))z.pinFile(e.slice(5));else if(e.startsWith(`diff:`)){let t=e.slice(5);Oo(e=>e.previewPath===t?{paths:e.paths}:e)}else e.startsWith(`git-diff:`)&&V(t=>t.map(t=>t.preview&&`git-diff:${t.target.url}`===e?{...t,preview:!1}:t))},[ya,z.pinFile]),ps=Qo.filter(e=>e.kind===`file`||e.kind===`diff`),ms=Ra&&za!==$o?ps.find(e=>e.id===za):void 0,hs=e=>{ps.some(t=>t.id===e)&&(ye.current++,Ba(e),e===$o&&No())},gs=()=>{if(Ra){ye.current++,ms&&fs(ms.id),Pa(void 0);return}ye.current++;let e=ps.find(e=>e.id===$o)??ps.at(-1);Pa({scope:Ma,tabId:e?.id}),e&&e.id===$o&&(L&&!ga?va(L.id):No())},_s=(0,u.useCallback)(e=>{let t=pa.indexOf(e);if(t<0)return;let n=pa.filter(t=>t!==e);if(se(t=>({...t,ids:t.ids.filter(t=>t!==e),previewId:t.previewId===e?void 0:t.previewId,emptied:n.length===0||t.emptied})),L?.id!==e||I!==`session`)return;ye.current++;let r=n[Math.min(t,n.length-1)];if(r)O(r);else if(z.open.length>0){let e=z.activePath&&z.open.some(e=>e.path===z.activePath)?z.activePath:z.open[0].path;z.setActivePath(e),$e(`file`)}else ko.length>0?(Eo(ko[0]),$e(`diff`)):Ao.length>0?(U(Ao[0].target.url),$e(`gitDiff`)):O(void 0)},[pa,L,z,ko,Ao,I]),vs=(0,u.useCallback)(e=>{if(e.startsWith(`group:`)){let t=Je.filter(t=>Qn(t)!==e);if(Ye(t),I===`group`&&$o===e){let e=t.filter(e=>e.workspaceId===ct).at(-1);e?xa(e.workspaceId,e.roomId):No()}}else if(e.startsWith(`file:`)){let t=e.slice(5);z.closeFile(t),I===`file`&&z.activePath===t&&z.open.length<=1&&ye.current++}else if(e.startsWith(`diff:`)){let t=e.slice(5);Oo(e=>({paths:e.paths.filter(e=>e!==t),previewPath:e.previewPath===t?void 0:e.previewPath})),I===`diff`&&To===t&&(ye.current++,Eo(void 0),No())}else if(e.startsWith(`session:`)){let t=e.slice(8);_s(t)}else if(e.startsWith(`git-diff:`)){let t=e.slice(9),n=Ao.findIndex(e=>e.target.url===t);if(n<0)return;let r=Ao.filter(e=>e.target.url!==t);V(r);let i=document.activeElement?.getAttribute(`data-diff-tab-close`)===e;if(W?.target.url===t){ye.current++;let e=r[Math.max(0,n-1)];U(e?.target.url),e||No()}i&&requestAnimationFrame(()=>{let e=document.querySelector(`.chat-tab-strip [role="tab"][aria-selected="true"]`),t=Ao[n].origin;(e??(t?.getClientRects().length?t:void 0)??document.querySelector(`[data-workspace-welcome-create]:not(:disabled)`))?.focus()})}},[z,_s,To,I,Ao,W?.target.url,No,ct,Je,$o,xa]),ys=z.active,bs=JSON.stringify([Da,Aa,ys?.path]),[xs,Ss]=(0,u.useState)(),Cs=(0,u.useCallback)(e=>{Ss(t=>e?{scope:bs,position:e}:t?.scope===bs?void 0:t)},[bs]),ws=xs?.scope===bs?xs.position:void 0,[Ts,Es]=(0,u.useState)(),Ds=(0,u.useRef)(null),[J,Os]=(0,u.useState)(``),[ks,As]=(0,u.useState)({}),js=T.workspaces.find(e=>e.id===Da),Ms=T.workspaces.find(e=>e.id===ka),Ns=(e,t)=>{let n=e&&cm(e.path),r=e&&(e.assetTicket||n?(0,F.jsx)(`span`,{className:`file-editor-path`,title:n??e.path,children:n??e.path}):(0,F.jsx)(Sf,{root:Aa.split(`/`).at(-1)||js?.name||`工作目录`,path:e.path,reveal:(e,t)=>{co(`files`),z.locatePath(e,t)}})),i=Co?.scope===fo&&Co?.path===e?.path?Co:void 0,a=e&&(!e.view||e.view===`table`)&&(0,F.jsx)(xm,{file:e,state:z.saves[e.path]?.state??`idle`,message:z.saves[e.path]?.message??``,external:z.external[e.path]===!0,jumpToLine:i,languageOverride:ks[JSON.stringify([Da,Aa,e.path])],onChange:t=>z.updateBuffer(e.path,t),onSave:()=>void z.save(e.path,!1),onReload:()=>void z.reload(e.path),onOverwrite:()=>void z.save(e.path,!0),workspaceId:Da,cwd:Aa,navigation:e.view?void 0:r,embedded:!!e.view,onPosition:t?Cs:void 0});return(0,F.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":e?.path,"data-file-view-kind":`editor`,children:e?.view&&Da?(0,F.jsx)(Df,{workspaceId:Da,cwd:n?``:Aa,path:n??e.path,name:e.name,kind:e.view,content:e.content,version:e.etag,source:a||void 0,external:z.external[e.path],navigation:r,assetTicket:e.assetTicket,onReload:()=>void z.reload(e.path),sourceRequest:i?.request},JSON.stringify([Da,Aa,e.path])):a||(0,F.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})})},Ps=e=>ja&&!e.target.commitHash?(0,F.jsx)(`div`,{className:`chat-file-view`,role:`status`,children:(0,F.jsx)(`p`,{className:`rail-empty`,children:`请选择具体 session 以确定工作区,再查看或编辑工作区差异。`})}):(0,F.jsx)(`div`,{className:`chat-file-view chat-git-diff`,"data-main-diff-view":e.target.path,"data-file-view-kind":`diff`,children:(0,F.jsx)(u.Suspense,{fallback:(0,F.jsx)(`p`,{className:`rail-empty`,role:`status`,children:`正在读取差异…`}),children:(0,F.jsx)(dk,{tab:e,dark:ul!==`github-light`&&ul!==`solarized-light`},JSON.stringify([e.target.url,e.revision]))})}),Fs=(e,t)=>{let n=t?zo:K;return(0,F.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":e??``,"data-file-view-kind":`diff`,children:(0,F.jsx)(wm,{diff:n.diff,loading:n.loading,error:n.error,bufferContent:Uo(e),mode:t?Vo:q,onMode:t?Ho:Bo})})},Is=()=>{let e=ms?.id;if(!e)return null;if(e.startsWith(`file:`))return Ns(z.open.find(t=>`file:${t.path}`===e),!1);if(Ro)return Fs(Ro,!0);let t=Ao.find(t=>`git-diff:${t.target.url}`===e);return t?Ps(t):null},Ls=L?.id;(0,u.useEffect)(()=>{Ls&&!Ls.startsWith(`pending:`)&&Ks({type:`conversation.select`,conversationId:Ls})},[Ls]);let Rs=(e,t=`info`)=>{if(!e)return;let n=++ei.current;qt(r=>[...r,{key:n,text:e,kind:t}]),ti.current.push(window.setTimeout(()=>qt(e=>e.filter(e=>e.key!==n)),7e3))},zs=(e,t=``)=>{if(js&&js.id===e&&Aa===t)return e=>{let n=Qe(e,{root:js.path,cwd:t,origin:window.location.origin});if(n)return{title:n.artifact?n.path:`${n.path}:${n.line}${n.column?`:${n.column}`:``}`,open:()=>{let e=Rm(n.path,t);Go(e,n.artifact?void 0:n.line,!1,!0,!1,n.artifact?void 0:n.column??1).catch(t=>Rs(`打不开「${e.name}」:${t instanceof Error?t.message:`文件不可用`}`,`error`))}}}},Bs=zs(L?.workspaceId,L?.cwd),Vs=async e=>{if(!e){r(!1);try{window.localStorage.setItem(`super-pi.browser-notifications`,`disabled`)}catch{}}else if(typeof window>`u`||typeof Notification>`u`&&!window.superPiDesktop?.notifications)a(`unsupported`);else if(!window.isSecureContext&&!window.superPiDesktop?.notifications)a(`insecure`);else try{let e=await na();a(e);let t=e===`granted`||e===`native`;r(t);try{window.localStorage.setItem(`super-pi.browser-notifications`,t?`enabled`:`disabled`)}catch{}}catch{a(ta()),r(!1),Rs(`请求浏览器通知权限失败,请检查站点权限后重试。`,`error`)}};(0,u.useEffect)(()=>{let e=()=>{for(let e of l.current.values())e.close();l.current.clear()},t=()=>{if(a(ta()),document.visibilityState===`visible`&&document.hasFocus()){e();try{window.localStorage.setItem(`super-pi.browser-notification-focus`,String(Date.now()))}catch{}}},n=t=>{t.key===`super-pi.browser-notification-focus`&&e()};window.addEventListener(`focus`,t);let r=!1,i;return navigator.permissions?.query&&navigator.permissions.query({name:`notifications`}).then(e=>{r||(i=e,e.addEventListener(`change`,t),t())}).catch(()=>{}),window.addEventListener(`storage`,n),document.addEventListener(`visibilitychange`,t),()=>{r=!0,i?.removeEventListener(`change`,t),window.removeEventListener(`focus`,t),window.removeEventListener(`storage`,n),document.removeEventListener(`visibilitychange`,t),e()}},[]),(0,u.useEffect)(()=>{let e=L?.id,t=L?.agentNotice;e&&t&&!ii.current.has(e)&&(ii.current.add(e),Rs(t,`info`))},[L?.id,L?.agentNotice]);let Hs=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Us=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Ws=(e,t)=>{if(t.method===`notify`)Rs(t.message||t.title,t.notifyType??`info`);else if(t.blocking||t.method===`setStatus`||t.method===`setWidget`||t.method===`setTitle`){let n=e=>e.blocking?e.requestId:e.statusKey??e.widgetKey??``,r=t.method===`setStatus`&&t.statusText===void 0||t.method===`setWidget`&&t.widgetLines===void 0||t.method===`setTitle`&&!t.title;Gt(i=>{let a=i.filter(r=>r.conversationId!==e||r.request.method!==t.method||n(r.request)!==n(t));return r?a:[...a,{conversationId:e,request:t}]})}else t.method===`set_editor_text`&&e===ni.current&&Wi(t.text??``)},Gs=(e,t,n)=>{Gt(n=>n.filter(n=>!(n.conversationId===e&&n.request.blocking&&n.request.requestId===t)));let r=lO[n];r&&Rs(r,`warning`)};(0,u.useEffect)(()=>{let e=!1;return(()=>{if(e)return;let t=new Le(ni.current);Re.current=t,t.onopen=()=>{if(!e){ee(!0);for(let e of[{type:`stream.configure`,coalesce:!0},{type:`catalog.fetch`,conversationId:ni.current},...Mi.current?[{type:`prompt.catalog.fetch`,workspaceId:Mi.current}]:[],{type:`catalog.fetchAll`},{type:`agent.catalog.fetch`},{type:`subagent.catalog.fetch`}])t.canSend(e)&&t.send(JSON.stringify(e))}},t.onserveropen=e=>{for(let n of m.current)n.retry&&n.command&&n.serverId===e&&t.canSend(n.command)&&t.send(JSON.stringify({...n.command,operationRequestId:n.id}))},t.ondisconnect=(t,n)=>{if(e)return;let r=fE(m.current.filter(e=>e.serverId===t));for(let e of r.failed)e.onFailure?.(`${P(t)} 连接中断`);m.current=m.current.filter(e=>!r.failed.includes(e)),p(m.current),Rs(`${P(t)} 连接中断${n?`(code ${n.code}${n.reason?` · ${n.reason}`:``})`:``},正在自动重连。`,`warning`)},t.onmessage=({data:t})=>{if(e)return;let n=JSON.parse(t);if(n.type===`group.activity`)at(n);else if(n.type!==`message.delta`&&n.type!==`message.thinking`&&Tt(),n.type===`message.accepted`){up(n.conversationId,n.clientId);for(let e of m.current)e.command?.conversationId===n.conversationId&&e.command?.clientId===n.clientId&&(e.receipt=!0)}else if(n.type===`exec.output`){let e=bt.current.get(n.sessionId),t=e?.raw??e?.text??``,r=n.offset===void 0?void 0:n.offset-n.data.length;if(!n.replace&&e?.offset!==void 0&&n.offset!==void 0&&n.offset<=e.offset)return;let i=e&&(r===void 0||e.offset!==void 0&&e.offset>=r),a=r!==void 0&&e?.offset!==void 0?Math.max(0,e.offset-r):0,o=(n.replace||!i?n.data:t+n.data.slice(a)).slice(-ED),s=DD(o);bt.current.delete(n.sessionId),bt.current.set(n.sessionId,{text:s.slice(-ED),raw:o,offset:n.offset,truncated:n.offset===void 0?n.truncated||o.length>128e3:n.offset>o.length}),bt.current.size>64&&bt.current.delete(bt.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:n.sessionId}))}else if(n.type===`run.stopping`)Dr(e=>{let t=new Set(e);return t.add(n.conversationId),t});else if(n.type!==`exec.exit`){if(n.type.startsWith(`terminal.`))xt.current?.(n);else if(n.type===`conversation.autoRename.result`){let e=Pr.current.get(n.conversationId);e&&(Pr.current.delete(n.conversationId),n.ok?e.resolve(n.title):e.reject(Error(n.error)))}else if(n.type===`message.thinking`)Et(n);else if(n.type===`state`){Tt(),ri.current=!1;let e=ni.current,t=!!(e&&ai.current.has(e)),r=!(!e||n.state.conversations.some(t=>t.id===e)),i=t&&r&&e&&oi.current.has(e)?{...n.state,conversations:[oi.current.get(e),...n.state.conversations]}:n.state;e&&!r&&(ai.current.delete(e),oi.current.delete(e)),m.current=m.current.filter(e=>!e.accepted?.(i)||i.sendReceipts&&e.retry&&!e.receipt?!0:(e.retry&&typeof e.command?.conversationId==`string`&&typeof e.command.clientId==`string`&&up(e.command.conversationId,e.command.clientId),!1)),p(m.current),Dr(e=>{let t=new Set(e);for(let e of[...t]){let n=i.conversations.find(t=>t.id===e);(!n||n.status!==`running`&&n.status!==`waiting`)&&t.delete(e)}return t}),i.extensionUi&&Gt(i.extensionUi),i.stoppingConversationIds&&Dr(new Set(i.stoppingConversationIds)),d(i),ke(!0),ee(!0);let a=m.current.filter(e=>e.key===`create-workspace`).map(e=>e.temporaryId);A(e=>{if(!e&&Wn.current)return;if(e&&(re(e)||i.workspaces.some(t=>t.id===e)||a.includes(e)))return e;let t=_.current?.workspaceId;return t&&i.workspaces.some(e=>e.id===t)?t:i.workspaces[0]?.id})}else if(n.type===`message.delta`)Et(n);else if(n.type===`queue.withdrawn`){yi(e=>[...e.filter(e=>e.conversationId!==n.conversationId).slice(-9),{id:`withdrawn_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,conversationId:n.conversationId,actor:n.actor,withdrawn:n.withdrawn}]);let e=n.withdrawn.slice(0,2).map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,24)}」`).join(`、`),t=n.actor===`agent`?`上级 Agent 已撤回`:`已撤回`;Rs(`${t} ${n.withdrawn.length} 条排队消息:${e}${n.withdrawn.length>2?`…`:``}`,`info`)}else if(n.type===`message.revert.result`)Rl(void 0),Tr(void 0),n.ok||(console.error(`[Super Pi Error] revert failed:`,n.message),ne(n.message));else if(n.type===`operation.result`){let e=m.current.find(e=>e.id===n.requestId),t=e?.retry?e.command:void 0;if(t&&up(t.conversationId,t.clientId),m.current=m.current.filter(e=>e.id!==n.requestId),p(m.current),e?.temporaryId){let t=e.temporaryId;if(e.key===`create-workspace`&&n.ok&&n.entityId){let r=n.entityId;d(n=>{if(n.workspaces.some(e=>e.id===r))return n;let i=e.apply(n).workspaces.find(e=>e.id===t);return i?{...n,workspaces:[...n.workspaces,{...i,id:r}]}:n})}else if(n.ok&&n.entityId){let e=n.entityId,r=si.current.get(t);if(r&&oi.current.set(e,{...r,id:e}),ai.current.add(e),r){let t={...r,id:e};d(n=>n.conversations.some(t=>t.id===e)?n:{...n,conversations:[t,...n.conversations]})}Ir(n=>{let r=n[t];if(!r)return n;let i=n[e],a={...n};return a[e]=i?{...i,text:r.text||i.text,images:r.images.length?r.images:i.images,attachments:r.text?r.attachments:i.attachments,pendingSkills:r.text?r.pendingSkills:i.pendingSkills,uploading:r.uploading+i.uploading}:r,delete a[t],a}),si.current.delete(t)}O(r=>r===t?n.ok?n.entityId:e.previousActiveId:r),se(e=>Kk(e,t,n.ok&&n.entityId?n.entityId:void 0)),A(r=>r===t?n.ok?n.entityId:e.previousWorkspaceId:r),!n.ok&&e.key===`create-workspace`&&Mi.current===t&&O(t=>t??e.previousActiveId)}if(!n.ok){if(console.error(`[Super Pi Error] operation failed:`,n.message),!e?.receipt){if(e?.onFailure)e.onFailure(n.message);else if(t){let e=t.images??[],r=CO(t.content,t.attachments);Vr(i=>[...i,{id:t.clientId,conversationId:t.conversationId,content:t.content,images:e,attachments:r,reason:n.message}]),Hi(t.conversationId,n=>n.text||n.images.length||n.attachments.length?n:{...n,text:t.content,images:e,attachments:r})}}let r=n.message??`操作失败`;ne(r),e?.onFailure||Rs(Or(r),`error`)}}else n.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):n.type===`files.changed`?(Ua.current(n.workspaceId,n.changes,n.dropped),n.workspaceId===Ga.current&&Ha.current()):n.type===`files.invalidated`?(Wa.current(n.workspaceId,n.paths),n.workspaceId===Ga.current&&Ha.current()):n.type===`error`?(console.error(`[Super Pi Error]`,n.message),n.recordedTurnFailure||(ne(n.message),Rs(Or(n.message),`error`),ri.current&&=!1)):n.type===`extension.ui`?Ws(n.conversationId,n.request):n.type===`extension.ui.closed`?Gs(n.conversationId,n.requestId,n.reason):n.type===`model.catalog`?(!n.conversationId||n.conversationId===ni.current)&&Yt(n.catalog):n.type===`model.catalog.all`?Zt(n.catalog):n.type===`providers.list`?($t(n.providers),tn(n.apis)):n.type===`agent.catalog`?((n.sourceServerId??fe())===fe()&&rn(n.catalog),(n.sourceServerId??fe())===pe()&&un(n.catalog)):n.type===`prompt.catalog`?Ht(n.catalog):n.type===`subagent.catalog`?((n.sourceServerId??fe())===fe()&&on(n.catalog),(n.sourceServerId??fe())===pe()&&pn(n.catalog)):n.type===`server.version`?cn(n.version):n.type===`subagent.event`?d(e=>({...e,subagentRuns:Hs(e.subagentRuns??[],n.run)})):n.type===`workflow.event`?d(e=>({...e,workflows:Us(e.workflows??[],n.workflow)})):n.type===`message.tools`?d(e=>({...e,conversations:e.conversations.map(e=>e.id===n.conversationId?{...e,messages:e.messages.map(e=>e.id===n.messageId?{...e,toolCalls:n.toolCalls}:e)}:e)})):n.type===`conversation.fork.result`&&(Kl(e=>e===n.conversationId?void 0:e),Rs(n.ok?`已从「${n.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${n.messagesCopied?`复制了 ${n.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${Or(n.message)}`,n.ok?`info`:`error`))}}})(),()=>{e=!0,Tt();for(let e of ti.current)window.clearTimeout(e);Re.current?.close()}},[Et,Tt,at]);let Ks=(0,u.useCallback)(e=>{if(!Re.current?.canSend(e))return!1;try{return Re.current.send(JSON.stringify(e)),!0}catch(e){return Rs(e instanceof Error?e.message:`服务器未连接`,`error`),!1}},[]),qs=(0,u.useCallback)(e=>{xe({id:e,ticket:++ye.current});let t=ni.current;t?.startsWith(`pending:`)||Ks({type:`state.subscribe`,...t?{conversationId:t}:{}}),Sn()},[Ks,Sn]);(0,u.useEffect)(()=>{if(!be)return;if(be.ticket!==ye.current){xe(void 0);return}let e=di.find(e=>e.id===be.id);e&&T.workspaces.some(t=>t.id===e.workspaceId)&&(xe(void 0),va(e.id),A(e.workspaceId))},[be,di,T.workspaces,va]),(0,u.useEffect)(()=>{if(!te)return;let e=L?.id;e?.startsWith(`pending:`)||Ks({type:`state.subscribe`,...e?{conversationId:e}:{}})},[L?.id,te,Ks]);let Y=(e,t,n,r,i,a,o)=>{let s=Re.current?.canSend(e)===!0,c=dE(e);if(m.current.some(e=>e.key===t)||!s&&!c)return!1;if(c&&!lp(e))return Rs(`浏览器无法保存待发消息,正文仍在输入框。`,`error`),!1;let l=Wt(),u=C(e),d=[...u][0]??e._server??fe(),f={id:l,key:t,serverId:d,apply:e=>u.size||fe()===d?n(e):e,temporaryId:r,previousActiveId:ni.current,previousWorkspaceId:Mi.current,onFailure:i,accepted:a,...o?{expiresAt:Date.now()+o}:{},...c?{retry:!0,command:e}:{}};return m.current=[...m.current,f],p(m.current),s&&Re.current.send(JSON.stringify({...e,operationRequestId:l})),!0},Js=e=>Ks({...e,_server:pe()}),Ys=(e,...t)=>Y({...e,_server:pe()},...t),Xs=(e,t)=>{Ks({type:`conversation.childLock`,conversationId:e,unlocked:t})||Rs(t?`连接断开,这个子会话没有解锁,请重试`:`连接断开,这个子会话没有上锁,请重试`,`error`)},Zs=e=>{if(!e)return;let t=`message_${Wt()}`;Y({type:`message.send`,conversationId:e,content:QD,clientId:t},`continue-truncated:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===e?{...t,warning:void 0}:t)}),void 0,void 0,void 0)};(0,u.useEffect)(()=>{let e=f.flatMap(e=>e.expiresAt?[e.expiresAt]:[]);if(!e.length)return;let t=window.setTimeout(()=>{let e=m.current.filter(e=>e.expiresAt&&e.expiresAt<=Date.now());if(e.length){m.current=m.current.filter(t=>!e.includes(t)),p(m.current);for(let t of e)t.onFailure?.(`打断请求超时,尚未确认是否开始回答;请检查会话状态后重试`)}},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[f]);let Qs=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),$s=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),ec=L?.id.startsWith(`pending:`)===!0,tc=!!(L&&qO(L)&&(Er.has(L.id)||f.some(e=>e.key===`stop:${L.id}`))),nc=L?.messagesLoaded===!1||f.some(e=>e.key.startsWith(`send:${L?.id}:`)||e.key===`configuration:${L?.id}`||e.temporaryId===L?.id||e.key===`archive:${L?.id}`),rc=(e,t,n,r,i)=>{e&&Ks({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i})},ic=(e,t)=>xr(n=>({...n,[e]:t})),ac=(e,t,n)=>(_a(e),Y({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e)),oc=L?.model??Jt?.defaultModel,sc=L?.thinkingLevel??Jt?.defaultThinkingLevel,cc=sc&&Jt?.levels.includes(sc)?sc:void 0,lc=Jt?.source===`pi`,uc=Jt?.models.find(e=>e.provider===oc?.provider&&e.modelId===oc?.modelId),X=!!uc?.imageInput,dc=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(T.modelFilterRules??[]).every(n=>{try{let r=new RegExp(n.workspacePattern,`i`),i=[t.name,t.path,t.worktreeProjectPath].filter(e=>!!e).some(e=>r.test(e.replaceAll(`\\`,`/`))),a=new RegExp(n.modelPattern,`i`);return!i||a.test(e.label)||a.test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},fc=!!L?.messages?.some(e=>e.images&&e.images.length>0),pc=dc(Jt,T.workspaces.find(e=>e.id===L?.workspaceId))?.models??[],mc=fc?pc.filter(e=>e.imageInput):pc,hc=mc.map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,CD(e.contextWindow)?`${CD(e.contextWindow)} 上下文`:``,wD(e.maxTokens)?`${wD(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:rO(e),selected:oc?.provider===e.provider&&oc.modelId===e.modelId})),gc=(Jt?.levels??[]).map(e=>({key:e,label:e,selected:e===sc})),_c=e=>{if(!L)return;let[t,n]=e.split(`/`);t&&n&&(_a(L.id),Y({type:`conversation.model`,conversationId:L.id,provider:t,modelId:n},`configuration:${L.id}`,Qs(L.id,{model:Jt?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}})))},vc=e=>{L&&(_a(L.id),Y({type:`conversation.thinking`,conversationId:L.id,level:e},`configuration:${L.id}`,Qs(L.id,{thinkingLevel:e})))},yc=nn?.agents.find(e=>e.id===L?.agentId),bc=[{key:RO,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!L?.agentId},...(nn?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:L?.agentId===e.id}))],xc=yc?.model,Sc=!!(xc&&L?.model&&L.model.provider===xc.provider&&L.model.modelId===xc.modelId);yc?.thinkingLevel&&(L?.thinkingLevel,yc.thinkingLevel);let Cc=e=>{if(L){let t=nn?.agents.find(t=>t.id===e);Y({type:`conversation.agent`,conversationId:L.id,agentId:e===RO?null:e},`configuration:${L.id}`,Qs(L.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},wc=hn.filter(e=>e.conversationId===L?.id),Tc=(0,u.useMemo)(()=>{let e=L?.id;return e?(L.messages??[]).flatMap(t=>(t.toolCalls??[]).flatMap((n,r)=>n.question?.status===`pending`?[{key:AO(e,t.id,r),messageId:t.id,index:r,value:n.question}]:[])):[]},[L?.id,L?.messages]),Ec=Tc[0],Dc=()=>{let e=Ec;e&&(Cr(e.key),$e(`session`),window.setTimeout(()=>{(ft.current?.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`))?.scrollIntoView({block:`center`,behavior:`smooth`})},0))},Oc=Ut.filter(e=>e.conversationId===L?.id).map(e=>e.request),kc=new Map(Oc.filter(e=>e.method===`setStatus`).map(e=>[e.statusKey??``,e.statusText??``])),Ac=new Map(Oc.filter(e=>e.method===`setWidget`).map(e=>[e.widgetKey??``,{lines:e.widgetLines??[],placement:e.widgetPlacement??`aboveEditor`}])),jc=Oc.find(e=>e.method===`setTitle`)?.title,Mc=(0,u.useMemo)(()=>(T.subagentRuns??[]).filter(e=>e.conversationId===L?.id),[T.subagentRuns,L?.id]),Nc=(0,u.useMemo)(()=>(T.workflows??[]).filter(e=>e.conversationId===L?.id),[T.workflows,L?.id]),Pc=(0,u.useMemo)(()=>new Map(Nc.map(e=>[e.id,e])),[Nc]),Fc=(0,u.useMemo)(()=>new Map((an?.agents??[]).map(e=>[e.id,e.name])),[an]),Ic=(0,u.useMemo)(()=>new Map((L?.messages??[]).map(e=>[e.id,e])),[L?.messages]),Lc=(0,u.useMemo)(()=>new Map(Mc.map(e=>[e.id,e])),[Mc]),Rc=(0,u.useMemo)(()=>{let e=new Map;for(let t of Mc)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[Mc]),zc=(0,u.useMemo)(()=>{if(!L||!ga)return[];let e=wr?.conversationId===L.id?(()=>{let e=L.messages.find(e=>e.id===wr.messageId);if(e)return{index:L.messages.indexOf(e),at:Date.parse(e.createdAt)||0,inclusive:!0}})():void 0,t=[];return L.messages.forEach((n,r)=>{e&&(r>e.index||e.inclusive&&r===e.index)||n.delivery||t.push({at:Date.parse(n.createdAt)||0,seq:r,key:`m:${n.id}`})}),Mc.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&L?.messages.some(e=>e.id===n.originMessageId&&e.toolCalls?.[n.originCallRow])||e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`r:${n.id}`})}),Nc.forEach((n,r)=>{e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`w:${n.id}`})}),Xi(t)},[L,Mc,Nc,wr]),Bc=(0,u.useMemo)(()=>{for(let e=zc.length-1;e>=0;--e){let t=zc[e];if(t.startsWith(`m:`)&&Ic.get(t.slice(2))?.role===`user`)return t.slice(2)}},[zc,Ic]);(0,u.useEffect)(()=>{let e=ft.current;if(!e||!L?.id)return;let t=()=>{!yt.current&&ze.current[L.id]?.followTail&&(Bk(e),e.scrollTop=e.scrollHeight)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);n.observe(e);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[L?.id,L?.messages,Mc,Nc,ga,zc,I]);let Vc=e=>hr(t=>({...t,[e]:!t[e]})),Hc=(e,t)=>_r(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),Uc=(e,t)=>yr(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[Wc,Gc]=(0,u.useState)({}),Kc=e=>Gc(t=>({...t,[e]:t[e]!==!0})),qc=e=>{Y({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||Rs(`连接断开,无法停止子智能体,请重试`,`error`)},Jc=e=>{Y({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||Rs(`连接断开,无法停止编排,请重试`,`error`)},Yc=e=>[...Ac].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,F.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,uO).map((e,t)=>(0,F.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>uO&&(0,F.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),Xc=(e,t)=>{let n=`pending:${Wt()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};Y({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(ba(n),je(!1))},[Zc,Qc]=(0,u.useState)(),$c=(e,t)=>Qc(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),el=()=>Qc(void 0),tl=(e,t)=>Zc?.kind===e&&Zc.id===t,nl=(e,t,n)=>!t.startsWith(`pending:`)&&(e===`conversation`&&_a(t),Y(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?$s(t,{name:n}):Qs(t,{title:n}))?(ri.current=!0,el(),!0):(Rs(`连接断开,改名未保存,请重试`,`error`),!1)),rl=async e=>{if(e.startsWith(`pending:`)){Rs(`这个会话还在创建中,稍后再试`,`warning`);return}if(Pr.current.has(e))return;Rs(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{Pr.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{Pr.current.delete(e)&&n(Error(`模型在 ${Math.round(kD/1e3)} 秒内没有返回标题`))},kD)});if(!Ks({type:`conversation.autoRename`,conversationId:e}))Pr.current.delete(e),Rs(`连接断开,无法生成标题`,`error`);else try{let n=await t;nl(`conversation`,e,n),Rs(`已重命名为「${n}」`,`info`)}catch(e){Rs(`重命名失败:${Or(e)}`,`error`)}},il=e=>{if(e.id.startsWith(`pending:`))return;let t=T.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`从列表移除工作区「${e.name}」?${t?`其中的 ${t} 条会话会保留,`:``}重新添加同一个目录即可恢复,不会删除任何会话。`)&&(ol(void 0),Y({type:`workspace.delete`,workspaceId:e.id},`delete:${e.id}`,t=>({...t,workspaces:t.workspaces.filter(t=>t.id!==e.id),conversations:t.conversations.filter(t=>t.workspaceId!==e.id)})))},[al,ol]=(0,u.useState)(),[sl,cl]=(0,u.useState)(!1),ll=al?T.workspaces.find(e=>e.id===al):void 0,{theme:ul,setTheme:dl}=Qh(),[fl,pl]=(0,u.useState)(!1),[ml,hl]=(0,u.useState)();(0,u.useEffect)(()=>{let e=()=>{he(),me(`entry`),hl(`servers`),pl(!0)};return window.addEventListener(`super-pi-open-server-management`,e),()=>window.removeEventListener(`super-pi-open-server-management`,e)},[]),(0,u.useEffect)(()=>{let e=e=>{let t=e.detail;typeof t==`string`&&T.conversations.some(e=>e.id===t)&&va(t)};return window.addEventListener(`super-pi-open-rsi-work`,e),()=>window.removeEventListener(`super-pi-open-rsi-work`,e)},[T.conversations,va]);let[gl,_l]=(0,u.useState)(!1),vl=(e,t,n,r)=>{e.startsWith(`pending:`)||(Y({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,$s(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?ol(void 0):Rs(`连接断开,设置未保存,请重试`,`error`))},yl=(e,t)=>{let n=M.activeServer;Y({type:`workspaces.settings.bulk`,model:e?{provider:e.provider,modelId:e.modelId}:null,thinkingLevel:t??null},`workspace-defaults-bulk`,r=>({...r,workspaces:r.workspaces.map(r=>{if(h(r.id).server!==n||r.closedAt||r.id.startsWith(`pending:`))return r;let i={...r};return e?i.defaultModel=e:delete i.defaultModel,t?i.defaultThinkingLevel=t:delete i.defaultThinkingLevel,i})}))?cl(!1):Rs(`连接断开,批量设置未保存,请重试`,`error`)},bl=(e,t=``)=>{if(e.startsWith(`pending:`))return;if(m.current.some(t=>t.key===`defaults:${e}`)){Rs(`工作区设置正在保存,请稍后再新建会话`,`warning`);return}let n=`pending:${Wt()}`,r={id:n,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[],...t?{cwd:t}:{}};si.current.set(n,r),Y({type:`conversation.create`,workspaceId:e,...t?{cwd:t}:{}},`create-session:${e}:${n}`,e=>({...e,conversations:[r,...e.conversations]}),n)?(ye.current++,A(e),O(n),$e(`session`),se(e=>({...e,ids:[...e.ids.filter(e=>e!==n),n],touched:Gk(e.touched,n)}))):(si.current.delete(n),Rs(`连接断开,会话未创建,请重试`,`error`))},xl=e=>{if(e.startsWith(`pending:`))return;let t=T.conversations.find(t=>t.id===e);if(!t||t.archivedAt||t.parentConversationId&&T.conversations.some(e=>e.id===t.parentConversationId))return;let n=qD(T.conversations,e),r=n.filter(e=>!e.archivedAt),i=r.length-1,a=n.length-r.length,o=TD(T.pendingUserDecisionsByConversation,n.map(e=>e.id)),s=AD({title:t.title,activeCount:r.length,activeDescendants:i,alreadyArchived:a,pendingDecisions:o});if(jD({activeDescendants:i,pendingDecisions:o})&&!window.confirm(s))return;let c=new Date().toISOString(),l=new Set(r.map(e=>e.id));Y({type:`conversation.archive`,conversationId:e},`archive:${e}`,e=>({...e,conversations:e.conversations.map(e=>l.has(e.id)&&!e.archivedAt?{...e,archivedAt:c}:e)}))},Sl=(e,t)=>Y({type:`conversation.collapse`,conversationId:e,collapsed:t},`collapse:${e}`,n=>{let r=new Set(n.collapsedConversationIds??[]);t?r.add(e):r.delete(e);let i={...n};return r.size===0?delete i.collapsedConversationIds:i.collapsedConversationIds=[...r],i}),Cl=e=>{let t=T.conversations.find(t=>t.id===e);if(!t?.archivedAt||(t.parentConversationId?T.conversations.find(e=>e.id===t.parentConversationId):void 0)?.archivedAt)return;let n=new Set(qD(T.conversations,e).filter(e=>e.archivedAt).map(e=>e.id));Y({type:`conversation.unarchive`,conversationId:e},`unarchive:${e}`,e=>({...e,conversations:e.conversations.map(e=>{if(!n.has(e.id)||!e.archivedAt)return e;let t={...e};return delete t.archivedAt,t})}))},wl=async e=>{if(!L){Rs(`请先选择或创建会话`,`error`);return}if(!X){Rs(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(Rs(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(Rs(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=L.id;Hi(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:Wt(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));qr(e=>[...e,...i]);for(let[e,t]of n.entries()){let n=i[e];try{let e=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let t=r.result,n=t.indexOf(`,`);e(n>=0?t.slice(n+1):t)},r.onerror=n,r.readAsDataURL(t)}),i=await Ne(`/api/upload`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({conversationId:r,name:t.name,mimeType:t.type,data:e})});if(!(i.headers.get(`content-type`)??``).includes(`application/json`)){Rs(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(zr.current.has(n.id))continue;qr(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),Hi(r,t=>({...t,images:[...t.images,{id:g(de(r),e.id),name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));Rs(Or(e.error,`上传失败(HTTP ${i.status})`),`error`)}}catch(e){Rs(`上传失败:${Or(e,`网络或服务暂时不可用`)}`,`error`)}finally{qr(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),Hi(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Tl=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.type.startsWith(`image/`)){let e=r.getAsFile();e&&n.push(e)}}if(n.length>0){if(!X){Rs(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),wl(n)}},El=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),Zr(!0))},Dl=e=>{e.currentTarget.contains(e.relatedTarget)||Zr(!1)},Ol=e=>{Zr(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!X){Rs(`当前模型不支持图片输入`,`error`);return}wl(t)}},kl=t=>{if(t.preventDefault(),!L)return;if(Si){Rs(zn,`warning`);return}if(nc){Rs(ec?`会话正在创建,请稍候再发送`:L.messagesLoaded===!1?`正在加载会话,请稍候再发送`:`正在保存配置,请稍候再发送`,`info`);return}if(!Li.trim()&&Ri.length===0)return;if(Ri.length>0&&!X){Rs(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(Vi>0){Rs(`图片正在上传中,请稍候…`,`info`);return}if(Bi){Rs(`技能正在读取中,请稍候…`,`info`);return}let n=`message_${Wt()}`,r=L.id,i=Li,a=Ri,o=zi;_a(r),e.stoppingConversationIds||Dr(e=>{if(!e.has(r))return e;let t=new Set(e);return t.delete(r),t});let s=wO({conversationId:r,content:i,clientId:n,images:a,attachments:o,inFlight:qO(L),deliveryMode:mi}),c=new Date().toISOString();Y(s,`send:${r}:${n}`,e=>fp(e,s,c),n,e=>{Vr(t=>[...t,{id:n,conversationId:r,content:i,images:a,attachments:o,reason:e}]),Hi(r,e=>e.text||e.images.length||e.attachments.length?e:{...e,text:i,images:a,attachments:o})},e=>!!e.conversations.find(e=>e.id===r)?.messages.some(e=>e.id===dp(s)))&&Hi(r,e=>({...e,text:``,images:[],attachments:[],pendingSkills:void 0}))},Al=(0,u.useMemo)(()=>(L?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[L?.messages]),jl=e=>{Y({type:`message.cancel`,conversationId:L?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===L?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||Rs(`连接断开,撤回没有生效,请重试`,`error`)},Ml=e=>{if(!L?.id||!e.length)return;let t=new Set(e),n=`queue-many:${L.id}:${e.join(`,`)}`;Y({type:`message.cancelMany`,conversationId:L.id,messageIds:e},n,e=>({...e,conversations:e.conversations.map(e=>e.id===L.id?{...e,messages:e.messages.filter(e=>!t.has(e.id))}:e)}),void 0,e=>Rs(e??`撤回所选消息失败,请重试`,`error`),t=>{let n=t.conversations.find(e=>e.id===L.id);return!!(n&&e.every(e=>!n.messages.some(t=>t.id===e&&t.delivery)))})||Rs(`连接断开,批量撤回没有生效,请重试`,`error`)},Nl=e=>{Y({type:`message.steer`,conversationId:L?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===L?.id?{...t,messages:PD(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===L?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||Rs(`连接断开,插到最前没有生效,请重试`,`error`)},Pl=e=>{let t=L?.id;t&&(Re.current?.readyState===WebSocket.OPEN?Y({type:`message.interrupt`,conversationId:t,messageId:e},`interrupt:${t}:${e}`,e=>e,void 0,e=>Rs(e??`打断失败,请重试`,`error`),n=>{let r=n.conversations.find(e=>e.id===t)?.messages.find(t=>t.id===e);return!(!r||r.delivery)},3e4)||Rs(`正在打断,请稍候`,`info`):Rs(`连接断开,打断没有生效,请重试`,`error`))},Fl=e=>{Y({type:`message.sendQueued`,conversationId:L?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===L?.id)?.messages.find(t=>t.id===e)?.delivery)||Rs(`连接断开,发送没有生效,请重试`,`error`)},Il=(e,t)=>{Y({type:`message.edit`,conversationId:L?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===L?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||Rs(`连接断开,修改没有生效,请重试`,`error`)},[Ll,Rl]=(0,u.useState)(),zl=(e,t=!0)=>{if(!L||L.messagesLoaded===!1||Ll)return;let n=L.messages.find(t=>t.id===e);n&&(Ir(e=>{let t=e[L.id]??{text:``,images:[],attachments:[],uploading:0};return t.text.trim()||t.images.length||t.attachments.length?e:{...e,[L.id]:{...t,text:n.content,images:n.images??[],attachments:CO(n.content,n.attachments)}}}),Tr({conversationId:L.id,messageId:e,kind:t?`withdraw`:`revert`})),Ks({type:`message.revert`,conversationId:L.id,messageId:e,withdraw:t})?Rl(e):(Tr(void 0),Rs(`连接断开,回退未执行,请重试`,`error`))},[Bl,Vl]=(0,u.useState)(),Hl=(0,u.useRef)(void 0),Ul=(0,u.useRef)(0),Wl=async(e,t)=>{let n=++Ul.current,r=await Bd(t);n===Ul.current&&(clearTimeout(Hl.current),Vl({id:e,kind:r?`copied`:`error`}),r||Rs(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),Hl.current=setTimeout(()=>Vl(void 0),2e3))};(0,u.useEffect)(()=>()=>{Ul.current+=1,clearTimeout(Hl.current)},[]);let[Gl,Kl]=(0,u.useState)(),ql=e=>{Gl||e.startsWith(`pending:`)||(_a(e),Ks({type:`conversation.fork`,conversationId:e})?Kl(e):Rs(`连接断开,分叉没有执行,请重试`,`error`))},Z=new Map;for(let e of T.scheduledTasks??[])e.conversationId&&!Z.has(e.conversationId)&&Z.set(e.conversationId,e);let Jl=(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,title:`设置`,"aria-haspopup":`dialog`,"aria-expanded":fl,onClick:()=>{hl(void 0),he(),pl(!0),Js({type:`catalog.fetchAll`}),Js({type:`providers.fetch`})},children:[(0,F.jsx)(Gr,{name:`settings`}),(0,F.jsx)(`span`,{className:`workbench-action-label`,children:`设置`})]}),(0,F.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,title:`使用指南`,"aria-haspopup":`dialog`,"aria-expanded":gl,onClick:()=>_l(!0),children:[(0,F.jsx)(Gr,{name:`help`}),(0,F.jsx)(`span`,{className:`workbench-action-label`,children:`使用指南`})]})]}),Yl=Ta?void 0:L,Xl=ye.current,Zl={onOpenSession:e=>{Xl===ye.current&&qs(e)},todos:T.todosByConversation?.[Yl?.id??``]??[],tasks:ck(Yl,T.backgroundTasks??[]),backgroundRuns:Yl?Lc:void 0,execOutputs:bt.current,scheduledTasks:(T.scheduledTasks??[]).filter(e=>e.workspaceId===Da),scheduledCatalog:dc(Jt,js),scheduledAgents:nn,notify:Rs,serverTimeZone:T.serverTimeZone,workspaceId:Da,gitWorkspaceId:ka,gitRepositoryOnly:ja,gitWorkspaceName:Ms?.name,workspaceLabel:js?.path,workspaceName:js?.name,conversationId:Yl?.id,followedWorktreeId:Yl?.followedWorktreeId,cwd:Aa,connected:te&&M.statuses.get(M.activeServer)?.state===`online`&&Oe&&!Yl?.id.startsWith(`pending:`),files:z,onOpenFile:Ko,onOpenChanged:Fo,onOpenGitDiff:Mo,activeGitDiffUrl:W?.target.url,onFileReference:qo,onFilesMoved:Jo,onSearchFolder:e=>_o(`content`,void 0,[Aa,e].filter(Boolean).join(`/`)),onSelectTab:Qa,sendCommand:Ks,registerTerminalSink:Dt,terminalShell:T.terminalShell,sharedGit:Va},Ql=e=>M.connections.some(t=>t.id===h(e).server)&&(On===`all`||h(e).server===On),$l=new Set(T.workspaces.map(e=>e.id)),eu=T.workspaces.filter(e=>Ql(e.id)&&(!e.worktreeOf||!$l.has(e.worktreeOf))),tu=eu.flatMap(e=>[e,...T.workspaces.filter(t=>t.worktreeOf===e.id)]),nu=(0,u.useMemo)(()=>{let e=new Map;for(let t of T.workspaces){if(t.closedAt)continue;let n=t.name.trim().toLowerCase();n&&e.set(n,(e.get(n)??0)+1)}return new Set([...e].filter(([,e])=>e>1).map(([e])=>e))},[T.workspaces]),ru=jn&&tu.some(e=>e.id===jn)?jn:k&&tu.some(e=>e.id===k)?k:tu[0]?.id,iu=T.workspaces.find(e=>e.id===k),au=iu?.worktreeOf&&$l.has(iu.worktreeOf)?iu.worktreeOf:iu?.id,ou=Nn&&eu.some(e=>e.id===Nn)?Nn:au&&eu.some(e=>e.id===au)?au:eu[0]?.id,su=Date.now()-18e6,cu=tu.filter(e=>e.id===ou||e.worktreeOf===ou),lu=e=>{let t=T.conversations.some(t=>t.workspaceId===e&&!t.archivedAt&&(En===`recent`?Date.parse(t.updatedAt)>=su:t.status===`running`||t.status===`waiting`)),n=(et[e]?.rooms??[]).some(e=>!e.archivedAt&&(En===`recent`?Date.parse(e.updatedAt)>=su:[`running`,`queued`].includes(ir(e,it[e.id]))));return t||n},uu=eu.flatMap(e=>{let t=tu.filter(t=>t.worktreeOf===e.id&&lu(t.id));return lu(e.id)||t.length>0?[e,...t]:[]}),du=En===`all`?tu:En===`workspace`?tu.filter(e=>e.id===ru):En===`repo`?cu:uu,fu=En===`all`||En===`workspace`||En===`repo`,pu=(e,t=En,n=ru,r=ou)=>{if(!e||!Ql(e))return!1;if(t===`all`)return!0;if(t===`workspace`)return e===n;if(t===`repo`)return e===r||tu.some(t=>t.id===e&&t.worktreeOf===r);let i=T.conversations.filter(t=>t.workspaceId===e&&!t.archivedAt).some(e=>t===`recent`?Date.parse(e.updatedAt)>=su:e.status===`running`||e.status===`waiting`),a=(et[e]?.rooms??[]).some(e=>!e.archivedAt&&(t===`recent`?Date.parse(e.updatedAt)>=su:[`running`,`queued`].includes(ir(e,it[e.id]))));return i||a},mu=(e,t=ru,n=ou)=>{Dn(e),t&&Mn(t),n&&Pn(n);let r=I===`group`&&ct&<?et[ct]?.rooms.find(e=>e.id===lt):void 0,i=I===`group`?!!(ct&&r&&!r.archivedAt&&pu(ct,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(r.updatedAt)>=su:[`running`,`queued`].includes(ir(r,it[r.id]))))):!!(L&&!L.archivedAt&&pu(L.workspaceId,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(L.updatedAt)>=su:L.status===`running`||L.status===`waiting`)));if(es.current=!0,i){e===`workspace`&&A(t);let r=Qo.find(e=>e.id===$o)?.workspaceId;(e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!pu(r,e,t,n))&&$e(`session`)}else Un(!0),O(void 0),Ze(!1),(I===`session`||I===`group`||e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!pu(Qo.find(e=>e.id===$o)?.workspaceId,e,t,n))&&$e(`session`),A(e===`workspace`?t:void 0)},hu=e=>{An(e),localStorage.setItem(`super-pi.server-filter`,e),e!==`all`&&ve(e);let t=I===`group`?ct:L?.workspaceId??k;if(t&&e!==`all`&&h(t).server!==e){es.current=!0,Un(!0),O(void 0),Ze(!1);let t=T.workspaces.filter(t=>h(t.id).server===e);if(En===`workspace`){let e=t.find(e=>e.id===jn)?.id??t[0]?.id;Mn(e),A(e)}else A(void 0),En===`repo`&&Pn(t.find(e=>!e.worktreeOf)?.id);$e(`session`)}};(0,u.useEffect)(()=>{On!==`all`&&!M.connections.some(e=>e.id===On)&&hu(`all`)},[On,M.connections]);let gu=Qo.filter(e=>{if(!e.workspaceId||!Ql(e.workspaceId))return!1;if(En===`all`)return!0;if(En===`workspace`||En===`repo`)return pu(e.workspaceId);if(e.id.startsWith(`session:`)){let t=T.conversations.find(t=>t.id===e.rawId);return!!(t&&!t.archivedAt&&pu(t.workspaceId)&&(En===`recent`?Date.parse(t.updatedAt)>=su:t.status===`running`||t.status===`waiting`))}if(e.id.startsWith(`group:`)){let t=$n(e.id),n=t?.roomId?et[t.workspaceId]?.rooms.find(e=>e.id===t.roomId):void 0;return!!(t&&n&&!n.archivedAt&&pu(t.workspaceId)&&(En===`recent`?Date.parse(n.updatedAt)>=su:[`running`,`queued`].includes(ir(n,it[n.id]))))}return!1}),_u=ja?`未选工作区`:Va.status?.detached?`游离 HEAD`:Va.status?.branch,vu=!ja&&Va.status&&new Set([...Va.status.staged,...Va.status.unstaged,...Va.status.untracked].map(e=>e.path)).size,yu=!ja&&Va.status&&(Va.status.ahead||Va.status.behind)?[Va.status.ahead?`↑`+Va.status.ahead:``,Va.status.behind?`↓`+Va.status.behind:``].filter(Boolean).join(` `):``,bu=()=>Jn(e=>({...e,rightClosed:!0})),xu=()=>Jn(e=>({...e,leftClosed:!0})),Su=pr?gn:oo;return(0,F.jsxs)(`main`,{className:`shell workbench-shell${Su?` shell-rail-collapsed`:``} mobile-panel-${vn}${wn?` mobile-drawer-open`:``}`,"data-rail-collapsed":Su,"data-workbench-left-closed":!pr&&qn.leftClosed,"data-selected-workspace":k??``,style:{"--sidebar-width":`${nr.sidebar}px`,"--rail-col":Su?void 0:`${nr.rail}px`},children:[!pr&&(0,F.jsx)(Kr,{side:`left`,views:$a,unpinned:qn.unpinned,active:qn.leftClosed||eo?void 0:B,onSelect:e=>co(e,!0),searchActive:!qn.leftClosed&&eo,onSearch:()=>{ro(!0),to(!0),Jn(e=>({...e,leftClosed:eo&&!e.leftClosed}))},onArrange:lo,onReorder:uo,children:Jl}),(0,F.jsxs)(`aside`,{className:`workbench-sessions`,id:`workbench-sessions`,"data-workbench-session-view":so?`shown`:`hidden`,children:[(0,F.jsxs)(`div`,{className:`sidebar-actions`,children:[(0,F.jsx)(`button`,{className:`workspace-new`,onClick:()=>je(!0),children:`+ 添加工作区`}),L&&ga&&gu.length===1&&(0,F.jsx)(`button`,{type:`button`,className:`mobile-close-session`,onClick:()=>{_s(L.id),Tn(!1)},children:`关闭当前标签`})]}),(0,F.jsxs)(`div`,{className:`label label-desktop workspace-title-row`,children:[(0,F.jsx)(`span`,{children:`工作区`}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-bulk-settings`,title:`批量设置所有工作区`,"aria-label":`批量设置所有工作区`,onClick:()=>cl(!0),children:`⚙`})]}),(0,F.jsx)(`div`,{className:`label label-phone`,children:`会话`}),sl&&(0,F.jsx)(sE,{workspaces:T.workspaces.filter(e=>h(e.id).server===M.activeServer&&!e.closedAt&&!e.id.startsWith(`pending:`)),catalog:Xt??{source:`unavailable`,models:[],levels:[],fetchedAt:``},onClose:()=>cl(!1),onSave:yl}),(0,F.jsxs)(`div`,{className:`sidebar-session-filters`,"aria-label":`会话与群聊筛选`,children:[(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`span`,{children:`服务器`}),(0,F.jsxs)(`select`,{"aria-label":`服务器范围`,value:On,onChange:e=>hu(e.target.value),children:[(0,F.jsx)(`option`,{value:`all`,children:`全部服务器`}),M.connections.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[e.name,M.statuses.get(e.id)?.state===`offline`?` · 离线`:``]},e.id))]})]}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`span`,{children:`显示`}),(0,F.jsxs)(`select`,{"aria-label":`会话列表筛选方式`,value:En,onChange:e=>mu(e.currentTarget.value),children:[(0,F.jsx)(`option`,{value:`all`,children:`全部`}),(0,F.jsx)(`option`,{value:`workspace`,children:`按工作区`}),(0,F.jsx)(`option`,{value:`repo`,children:`按仓库`}),(0,F.jsx)(`option`,{value:`recent`,children:`近期活跃 · 5 小时`}),(0,F.jsx)(`option`,{value:`running`,children:`正在运行`})]})]}),En===`workspace`&&(0,F.jsx)(`select`,{"aria-label":`选择工作区`,value:ru??``,onChange:e=>mu(`workspace`,e.currentTarget.value,ou),children:(0,F.jsx)(kn,{workspaces:tu})}),En===`repo`&&(0,F.jsx)(`select`,{"aria-label":`选择仓库`,value:ou??``,onChange:e=>mu(`repo`,ru,e.currentTarget.value),children:(0,F.jsx)(kn,{workspaces:eu})})]}),(0,F.jsx)(`nav`,{"aria-label":`工作区、会话与群聊`,children:du.length===0?(0,F.jsx)(`div`,{className:`sidebar-filter-empty`,children:En===`recent`?`近 5 小时没有活跃的会话或群聊`:`当前没有正在运行的会话或群聊`}):du.map((e,t)=>{let n=et[e.id],r=(n?.rooms.filter(e=>!e.archivedAt)??[]).filter(e=>fu||(En===`recent`?Date.parse(e.updatedAt)>=su:[`running`,`queued`].includes(ir(e,it[e.id])))),i=fu?n?.rooms.filter(e=>e.archivedAt)??[]:[],a=T.conversations.filter(t=>t.workspaceId===e.id),o=a.filter(e=>!e.archivedAt&&(fu||(En===`recent`?Date.parse(e.updatedAt)>=su:e.status===`running`||e.status===`waiting`))),s=yE(o,fi,{manualRoots:At[e.id]}),c=s.filter(e=>e.depth===0).map(e=>e.conversation.id),l=fu?a.filter(e=>e.archivedAt):[],u=yE(l,new Set),d=fu?l.length+i.length:0,f=ie[e.id]??!1,p=Ot[e.id]??!0,m=nu.has(e.name.trim().toLowerCase()),g=!e.worktreeOf||!$l.has(e.worktreeOf),_=(En===`recent`||En===`running`)&&g,v=t=>I===`group`&&ct===e.id&<===t;return(0,F.jsxs)(`section`,{className:`workspace-group${e.worktreeOf&&$l.has(e.worktreeOf)?` workspace-linked-checkout`:``}${_?` workspace-active-repo-root`:``}`,"data-workspace-parent":e.worktreeOf,"data-workspace-group":e.id,"data-sidebar-repo-root":_?e.id:void 0,"data-current-workspace":k===e.id,children:[M.connections.length>1&&(t===0||h(du[t-1].id).server!==h(e.id).server)&&(0,F.jsxs)(`div`,{className:`workspace-server-label`,children:[_e(e.id),M.statuses.get(h(e.id).server)?.state===`offline`?` · 离线`:``]}),(0,F.jsx)(`div`,{className:`workspace-header`,children:tl(`workspace`,e.id)?(0,F.jsx)(IO,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>nl(`workspace`,e.id,t),onClose:el}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{type:`button`,className:`workspace-disclosure`,"data-workspace-fold":e.id,"aria-expanded":!f,"aria-label":`${f?`展开`:`折叠`}工作区 ${e.name}`,onClick:()=>ae(t=>({...t,[e.id]:!t[e.id]})),children:(0,F.jsx)(`span`,{className:`chevron-folder`,"aria-hidden":`true`,children:f?`▸`:`▾`})}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-toggle`,"aria-label":e.name,"aria-describedby":m?`workspace-name-warning-${e.id}`:void 0,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();jr({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{Mn(e.id);let t=ui.find(t=>t.workspaceId===e.id)?.id;t?(t!==L?.id||I!==`session`||!ga)&&va(t):ba(e.id)},children:(0,F.jsxs)(`span`,{children:[(0,F.jsxs)(`span`,{className:`workspace-name-line`,children:[(0,F.jsx)(`strong`,{onDoubleClick:()=>$c(`workspace`,e.id),children:e.name}),m&&(0,F.jsx)(`small`,{id:`workspace-name-warning-${e.id}`,className:`workspace-name-warning`,"data-workspace-name-warning":e.id,title:`请重命名其中一个工作区;名称唯一后提示会自动消失。`,children:`存在同名,易混淆`})]}),(0,F.jsx)(`small`,{children:e.path})]})}),(0,F.jsx)(`button`,{className:`workspace-add`,disabled:e.id.startsWith(`pending:`),title:`在此工作区新建会话`,onClick:t=>{Mn(e.id),Ie.current=t.currentTarget,Fe({workspaceId:e.id})},children:`+`}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-group-chat`,"data-open-group-chat":e.id,disabled:e.id.startsWith(`pending:`),title:`新建群聊`,"aria-label":`在 ${e.name} 新建群聊`,onClick:()=>{Mn(e.id),xa(e.id)},children:(0,F.jsx)(Gr,{name:`group-add`})}),(0,F.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>ol(e.id),children:`⚙`})]})}),!f&&r.map(t=>{let n=v(t.id),r=ir(t,it[t.id]),i=ar(t,it[t.id],Ve.current[Qn({workspaceId:e.id,roomId:t.id})]),a=i===`completed`?`讨论已完成,有新回复未读`:i===`unread`?`有新回复未读`:WO[r];return(0,F.jsxs)(`div`,{className:`conversation-row group-room-row`,children:[(0,F.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),(0,F.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-sidebar-group-chat":t.id,"aria-current":n?`true`:void 0,"aria-label":`打开群聊 ${t.title},${a}`,title:t.title,onClick:()=>{Mn(e.id),xa(e.id,t.id)},children:[(0,F.jsx)(`i`,{className:`conversation-mark`,children:(0,F.jsx)(ek,{state:i,label:a})}),(0,F.jsx)(Gr,{name:`group`}),(0,F.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-archive`,"data-archive-group":t.id,title:`归档群聊`,"aria-label":`归档群聊 ${t.title}`,disabled:ot.has(t.id),onClick:()=>void wa(t,`archive`),children:(0,F.jsx)(Gr,{name:`archive`})})]},t.id)}),!f&&n?.failed&&(0,F.jsx)(`button`,{type:`button`,className:`group-rooms-retry`,onClick:tt,children:`重试载入群聊`}),!f&&(s.length?s.map(({conversation:t,depth:n,childCount:r,isLastSibling:i})=>(0,F.jsxs)(`div`,{className:`conversation-row`,style:{"--tree-depth":n},"data-session-root":n===0?t.id:void 0,"data-session-dragging":Mt?.conversationId===t.id?`true`:void 0,"data-session-drop":Mt?.dropRootId===t.id?Mt.dropAfter?`after`:`before`:void 0,onPointerDown:n===0?n=>It(n,e.id,t.id,c):void 0,children:[r>0?(0,F.jsxs)(`button`,{type:`button`,className:`conversation-tree-toggle`,"data-tree-toggle":t.id,"aria-expanded":!fi.has(t.id),title:fi.has(t.id)?`展开 ${r} 个子会话`:`折叠 ${r} 个子会话`,"aria-label":fi.has(t.id)?`展开会话 ${t.title} 的 ${r} 个子会话`:`折叠会话 ${t.title} 的 ${r} 个子会话`,onClick:()=>Sl(t.id,!fi.has(t.id)),children:[(0,F.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:fi.has(t.id)?`▸`:`▾`}),(0,F.jsx)(`small`,{children:r})]}):(0,F.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),tl(`conversation`,t.id)?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(IO,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>nl(`conversation`,t.id,e),onClose:el}),(0,F.jsx)(`small`,{className:`conversation-time`,children:KD(t.updatedAt,ci)})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`button`,{className:`conversation ${!Ta&&L?.id===t.id?`selected`:``}`,"data-conversation":t.id,"aria-current":!Ta&&L?.id===t.id?`true`:void 0,"data-tree-child":n>0?`true`:void 0,"data-tree-last":n>0&&i?`true`:void 0,title:n>0?`${t.title}(由「${o.find(e=>e.id===t.parentConversationId)?.title??`已不存在的会话`}」创建)`:t.title,"aria-label":`打开会话 ${t.title}${nk(t,Z.get(t.id))}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();Nr({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{t.id===Ft.current&&Date.now()-Pt.current<300||(Mn(e.id),va(t.id),A(e.id),Tn(!1))},onDoubleClick:()=>{ya(t.id)},children:[(0,F.jsx)(`i`,{className:`conversation-mark`,children:(0,F.jsx)(ek,{state:QO(t,XO(t,hn),Ve.current[t.id],T.conversations)})}),(0,F.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:e=>{e.stopPropagation(),$c(`conversation`,t.id)},style:{flex:`0 1 auto`,minWidth:`3.5em`},children:t.title}),(0,F.jsx)(`span`,{className:`conversation-title-gap`,"aria-hidden":`true`,style:{marginLeft:`-8px`}}),$O(QO(t,XO(t,hn),Ve.current[t.id],T.conversations),ZO(t,T.conversations,Ve.current[t.id])),tk(t,Z.get(t.id)),(0,F.jsx)(`small`,{children:KD(t.updatedAt,ci)})]}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":Gl===t.id?`pending`:`idle`,disabled:!!Gl,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>ql(t.id),children:`⑂`}),!(t.parentConversationId&&T.conversations.some(e=>e.id===t.parentConversationId))&&(0,F.jsx)(`button`,{className:`conversation-archive`,"data-archive-conversation":t.id,title:`归档整棵会话树`,"aria-label":`归档会话 ${t.title}`,onClick:()=>xl(t.id),children:`×`})]})]},t.id)):!r.length&&(0,F.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!f&&d>0&&(0,F.jsxs)(`div`,{className:`archived-group`,"data-archived-count":d,children:[(0,F.jsxs)(`button`,{className:`archived-toggle`,title:p?`展开已归档`:`收起已归档`,"aria-expanded":!p,onClick:()=>kt(t=>({...t,[e.id]:!p})),children:[(0,F.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:p?`▸`:`▾`}),(0,F.jsxs)(`span`,{className:`archived-label`,children:[`已归档 (`,d,`)`]})]}),!p&&u.map(({conversation:e,depth:t,isLastSibling:n})=>{let r=qD(l,e.id).length-1,i=!!(e.parentConversationId&&T.conversations.some(t=>t.id===e.parentConversationId&&t.archivedAt));return(0,F.jsxs)(`div`,{className:`conversation-archived`,"data-archived-conversation":e.id,"data-archived-at":e.archivedAt,"data-tree-child":t>0?`true`:void 0,"data-tree-last":t>0&&n?`true`:void 0,style:{"--tree-depth":t},children:[(0,F.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,F.jsx)(`span`,{"data-archived-title":e.id,children:e.title}),tk(e,Z.get(e.id)),(0,F.jsx)(`small`,{children:JD(e.archivedAt)}),!i&&(0,F.jsx)(`button`,{className:`conversation-restore`,"data-restore-conversation":e.id,title:r?`恢复这个会话和它的 ${r} 个子孙会话`:`恢复为正常会话`,"aria-label":r?`恢复会话 ${e.title} 及其 ${r} 个子孙会话`:`恢复会话 ${e.title}`,onClick:()=>Cl(e.id),children:`↑`})]},e.id)}),!p&&i.map(t=>{let n=v(t.id),r=ot.has(t.id);return(0,F.jsxs)(`div`,{className:`conversation-row group-room-row group-room-history`,"data-archived-group":t.id,children:[(0,F.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-open-archived-group":t.id,"aria-current":n?`true`:void 0,"aria-label":`查看已归档群聊 ${t.title}`,title:t.title,onClick:()=>xa(e.id,t.id),children:[(0,F.jsx)(Gr,{name:`group`}),(0,F.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-restore-group":t.id,title:`恢复群聊`,"aria-label":`恢复群聊 ${t.title}`,disabled:r,onClick:()=>void wa(t,`restore`),children:`↑`}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-delete-group":t.id,title:`永久删除群聊`,"aria-label":`永久删除群聊 ${t.title}`,disabled:r,onClick:()=>void wa(t,`delete`),children:(0,F.jsx)(Gr,{name:`delete`})})]},t.id)})]}),!f&&(()=>{let t=T.warmSessions?.filter(t=>t.workspaceId===e.id)??[];return t.length?(0,F.jsxs)(`details`,{className:`archived-group`,"data-warm-sessions":e.id,children:[(0,F.jsx)(`summary`,{className:`archived-toggle`,children:(0,F.jsxs)(`span`,{className:`archived-label`,children:[`预热会话 (`,t.length,`)`]})}),t.map(e=>(0,F.jsxs)(`div`,{className:`conversation-archived`,"data-warm-session":e.id,children:[(0,F.jsx)(`span`,{title:e.title,children:e.title}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-restore`,"aria-label":`移除预热会话 ${e.title}`,onClick:()=>{window.confirm(`移除预热会话「${e.title}」?`)&&!Ks({type:`conversation.warm.delete`,conversationId:e.id})&&Rs(`连接断开,未移除预热会话`,`error`)},children:`×`})]},e.id))]}):null})()]},e.id)})}),pr&&(0,F.jsxs)(`footer`,{className:`workbench-mobile-utilities`,children:[(0,F.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-mobile-workbench-search":!0,"aria-label":`搜索`,title:`搜索`,onClick:()=>_o(`content`),children:(0,F.jsx)(Gr,{name:`search`})}),Jl]})]}),no&&(0,F.jsx)(`section`,{className:`workbench-panel workbench-panel-left workbench-search-panel`,"data-workbench-search-panel":!0,"aria-label":`侧栏搜索`,hidden:pr||!eo||qn.leftClosed,children:(0,F.jsx)(Hm,{workspaceId:Da,workspaceName:js?.name,cwd:Aa,connected:te,active:!pr&&eo&&!qn.leftClosed,onOpen:(e,t,n)=>Go(e,t,!1,!0,!1,n),onSession:So},fo)}),!pr&&!qn.leftClosed&&!eo&&B!==`sessions`&&(0,F.jsx)(fk,{...Zl,side:`left`,activeTab:B,collapsed:!1,onToggle:xu,pinned:!qn.unpinned.includes(B),onArrange:lo}),(pr||!qn.leftClosed)&&(0,F.jsx)(Zk,{side:`left`,width:nr.sidebar,min:nr.sidebarMin,max:nr.sidebarMax,label:`调整左侧栏宽度`,onWidth:sr}),(0,F.jsx)(`div`,{className:`workbench-main`,children:(0,F.jsxs)(`div`,{className:`workbench-main-panes`,"data-workbench-split":Ra,style:{"--split-share":`${Fa}%`},children:[(0,F.jsxs)(`section`,{className:`chat`,"data-main-view":G,"data-main-view-kind":G,children:[gu.length>0&&(0,F.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":ma.length,"data-file-count":z.open.length,children:(0,F.jsx)(Km,{tabs:(ms?gu.filter(e=>e.id!==ms.id):gu).map(e=>M.connections.length>1&&e.workspaceId?{...e,label:`${e.label} · ${_e(e.workspaceId)}`,title:`${_e(e.workspaceId)} · ${e.title??e.label}`}:e),prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:$o,onSelect:ns,onClose:vs,onActivate:fs,minWidth:120,maxWidth:320})}),(0,F.jsxs)(`header`,{children:[(0,F.jsx)(`button`,{type:`button`,className:`mobile-drawer-toggle`,"data-mobile-drawer-toggle":`1`,"aria-label":`打开会话列表`,title:`会话列表`,"aria-expanded":wn,onClick:()=>Tn(!0),children:`☰`}),(0,F.jsxs)(`div`,{className:`chat-head`,children:[(0,F.jsx)(`h1`,{children:I===`group`?lt?dt??`群聊`:`新建群聊`:L?.title??`准备开始`}),I!==`group`&&kc.size>0?[...kc].map(([e,t])=>(0,F.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):null]}),(0,F.jsxs)(`div`,{className:`workbench-history-controls`,role:`group`,"aria-label":`主区导航`,"data-workbench-history":cs>=0||ls>=0?`available`:`empty`,children:[L&&I!==`group`&&(0,F.jsx)(VT,{id:L.id,workspaceId:L.workspaceId,models:Jt?.models??[]}),(0,F.jsx)(`button`,{type:`button`,"data-workbench-history-back":!0,"aria-label":`后退`,className:`workbench-icon-button`,title:cs<0?`后退`:`后退到 ${Se.entries[cs].title}`,disabled:cs<0||!!we,onClick:()=>us(-1),children:(0,F.jsx)(Gr,{name:`back`})}),(0,F.jsx)(`button`,{type:`button`,"data-workbench-history-forward":!0,"aria-label":`前进`,className:`workbench-icon-button`,title:ls<0?`前进`:`前进到 ${Se.entries[ls].title}`,disabled:ls<0||!!we,onClick:()=>us(1),children:(0,F.jsx)(Gr,{name:`forward`})}),Da&&(0,F.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-toggle-workbench-split":!0,"aria-pressed":Ra,"aria-label":Ra?`合并主区`:`拆分主区`,title:Ra?`合并主区`:`拆分主区`,onClick:gs,children:(0,F.jsx)(Gr,{name:`split`})})]}),mn.entry(`workbench-status-button software-update-mobile`),(0,F.jsxs)(`span`,{className:`chat-view chat-view-${G}`,"data-main-view-indicator":G,"data-main-view-kind":G,title:I===`file`?`中间主画面正在显示文件 ${z.active?.path??``}`:G===`diff`?`中间主画面正在显示 ${jo??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,F.jsx)(`span`,{className:`chat-view-kind`,children:I===`group`?`群聊`:I===`file`?`文件`:G===`diff`?`改动`:`会话`}),I===`file`&&z.active&&(0,F.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":z.active.name,children:z.active.name}),G===`diff`&&jo&&(0,F.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":jo,children:jo})]}),!Ta&&(0,F.jsx)(`div`,{className:`badge`,"data-workbench-header-status":Ti||L?.status===`failed`?`attention`:`routine`,"data-conversation-status":L?.status??`idle`,...Ti?{"data-reporting-status":Ti}:{},children:Ti===`awaiting_decision`?`等上面拍板`:qO(L)?KO[L?.status??`idle`]:Ti===`awaiting_subordinates`?`等待下级`:Ti===`pending_report`?`待汇报`:KO[L?.status??`idle`]}),(0,F.jsx)(`button`,{type:`button`,className:`mobile-tools-toggle`,"data-mobile-nav":`rail`,onClick:()=>{yn(`rail`),_n(!1)},children:`工具`})]}),N&&(0,F.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,F.jsx)(`span`,{title:kr(N),children:Or(N)}),(0,F.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>ne(void 0),children:`×`})]}),!Ta&&L?.error&&(0,F.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,title:kr(L.error),children:Or(L.error)}),L?.warning&&(0,F.jsxs)(`div`,{className:`warning`,role:`status`,"data-role":`conversation-warning`,title:kr(L.warning),children:[(0,F.jsx)(`span`,{children:L.warning}),(0,F.jsx)(`button`,{type:`button`,"data-role":`conversation-warning-continue`,title:`让模型继续完成当前任务`,onClick:()=>Zs(L?.id??``),children:`继续任务`})]}),!Ta&&L?.modelNotice&&(0,F.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-model-notice`,children:L.modelNotice}),L?.agentNotice&&(0,F.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-agent-notice`,children:L.agentNotice}),jc&&(0,F.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,jc]}),Kt.length>0&&(0,F.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Kt.length,children:Kt.map(e=>(0,F.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),I===`group`?js?(0,F.jsx)(iE,{workspaceId:ct,roomId:lt,sourceLink:zs(ct),composerResize:ur===null?void 0:(0,F.jsx)(iA,{height:ur,onHeight:fr}),onEnableNotifications:()=>Vs(!0),agents:nn?.agents??[],catalog:dc(Jt,js),userLabel:Bt,archivedAt:ut?.archivedAt,restoring:ot.has(lt),onRestore:e=>void wa(e,`restore`),onRoomSeen:nt,onRoomRead:Ni,onRoomMissing:Ca,onCreated:Sa,onCancelCreate:()=>Ke&&vs(Qn(Ke))},Ke&&Qn(Ke)):(0,F.jsx)(`div`,{className:`group-empty`,children:Oe?`这个群聊的工作区已不可用。`:`正在加载工作区…`}):I===`file`?Ns(ys,!0):W?Ps(W):I===`diff`?Fs(To,!1):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`messages`,ref:ft,"data-message-scroll-container":L?.id??``,onWheel:e=>{e.deltaY<0&&ze.current[L?.id??``]?.followTail&&(yt.current=!0,Pi(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:Pi(t)},children:[(!L||!ga)&&(0,F.jsxs)(`div`,{className:`empty`,"data-workspace-welcome":Oi?.id,children:[(0,F.jsx)(`div`,{className:`orb`,children:`π`}),(0,F.jsx)(`h2`,{children:Oi?.name??`开始一个新会话`}),T.workspaces.length===0?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,F.jsx)(`button`,{onClick:()=>je(!0),children:`+ 新建工作区`})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{children:Oi?`暂无活跃会话。你可以创建会话,也可以直接使用资源管理器、Git 和终端。`:T.workspaces.length===1&&Di?`在「${Di.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),Oi&&(0,F.jsx)(`p`,{className:`workspace-welcome-path`,title:Oi.path,children:Oi.path}),T.workspaces.length>1&&(0,F.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,F.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,F.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Di?.id,onChange:e=>{e.target.value===`__new__`?je(!0):ba(e.target.value)},children:[(0,F.jsx)(kn,{workspaces:T.workspaces}),(0,F.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Di&&(0,F.jsxs)(F.Fragment,{children:[!ki&&(0,F.jsx)(oO,{workspaceId:Di.id,value:Ai,onChange:ji}),(0,F.jsx)(`button`,{"data-workspace-welcome-create":Oi?`1`:void 0,disabled:ki||!te,onClick:()=>bl(Di.id,Ai),children:ki?`正在创建工作区…`:`新建会话`})]}),(0,F.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>je(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),je(!0))},children:`+ 新建工作区`})]})]}),L?.messagesLoaded===!1&&(0,F.jsx)(`p`,{role:`status`,"data-conversation-loading":`1`,children:`正在加载会话…`}),zc.map(e=>{if(e.startsWith(`m:`)){let t=Ic.get(e.slice(2));if(!t)return null;let n=t.id===Bc,r=t.role===`user`&&L?.status!==`running`&&L?.status!==`waiting`&&Ll!==t.id,i=r&&n&&!t.id.startsWith(`pending:`),a=r&&!n&&!!t.piEntryId,o=t.content?(0,F.jsx)(ef,{source:t.content,media:pi,sourceLink:Bs}):(0,F.jsx)(`span`,{className:`typing`,children:`正在思考`});if(t.source===`session-reminder`)return(0,F.jsx)(`article`,{className:`message message-reminder`,"data-transcript-key":e,"data-message-reminder":t.id,children:(0,F.jsxs)(`details`,{children:[(0,F.jsxs)(`summary`,{className:`reminder-header`,children:[(0,F.jsxs)(`span`,{className:`reminder-label`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`◷`}),` 定时提醒`]}),(0,F.jsx)(`time`,{dateTime:t.createdAt,children:zD(t.createdAt)})]}),(0,F.jsx)(`div`,{className:`content`,children:o})]})},e);let s=t.toolCalls??[],c=Bl?.id===t.id?Bl.kind:void 0;if(t.role===`user`){let n=t.content||(t.images?.length?`[图片]`:``),r=CO(t.content,t.attachments);return(0,F.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,F.jsxs)(`div`,{className:`message-body`,children:[(0,F.jsxs)(`div`,{className:`bubble`,children:[(0,F.jsxs)(`div`,{className:`meta`,children:[Bt,(0,F.jsx)(`time`,{children:zD(t.createdAt)})]}),t.images&&t.images.length>0&&(0,F.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,F.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>Yr({url:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,F.jsx)(`img`,{src:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,F.jsx)(`div`,{className:`content`,children:o})]}),r.length>0&&(0,F.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:r.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=gr[n]??!1;return(0,F.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,F.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>_r(e=>({...e,[n]:!r})),children:[(0,F.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,F.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,F.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,F.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,F.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,F.jsxs)(`div`,{className:`message-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":c,"aria-label":`复制这条消息:${n}`,onClick:()=>Wl(t.id,n),children:c===`copied`?`已复制`:c===`error`?`复制失败`:`复制`}),i&&(0,F.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>zl(t.id,!0),children:`撤回`}),a&&(0,F.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退并编辑:删除这条消息及后续全部对话,将原消息恢复到输入框`,onClick:()=>zl(t.id),children:`回退`})]})]}),(0,F.jsx)(`div`,{className:`avatar`,title:Bt,children:Bt})]},e)}if(t.role===`tool`){let n=SD(t.content),r=n!==void 0,i=/<task id="[^"]+" state="[^"]+"/.test(t.content),a=(()=>{if(r)return`输出额度触顶后的自动恢复`;let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():i?`后台回传`:(t.content.split(`
|
|
345
|
+
如需本地计算,声明 script: { path, timeoutMs, parameters }。脚本必须是 Python,参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象。在 index.html 中加载 <script src="./super-pi-tool.js"><\/script>,然后调用 SuperPiTool.run(params)、SuperPiTool.get(runId)、SuperPiTool.wait(runId) 或 SuperPiTool.cancel(runId)。这些都是已绑定本工具身份的相对接口;不要调用 /api/exec,不要猜测 toolId,也不要传 shell 命令、任意文件路径或未声明参数。页面必须实际执行一次示例任务并显示运行状态、日志和结构化结果。第三方包写进 environment.requires(必须钉死成 pkg==version),首次运行时会装进这个工具自己的虚拟环境。需要模型能力(摘要、改写、抽取、分类)时调用 SuperPiTool.llm({ prompt, system }),不要自己写模型客户端或保管密钥,并在注册时声明 permissions: { llm: true }——否则服务端会拒绝,导入页面也会提示用户。最后返回注册 id、访问地址、文件清单和验证结果。`);f(e),window.setTimeout(()=>f(!1),1800)};(0,u.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let se=(0,u.useMemo)(()=>[...t.map(e=>({id:e.id,name:e.name,glyph:e.glyph})),...n.map(e=>({id:e.id,name:e.name,glyph:dE(e)}))],[t,n]);(0,u.useEffect)(()=>{if(!M)return;let e=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),te(void 0);return}if(OE(e.key)||LE(e.target))return;e.preventDefault(),e.stopPropagation();let t=M;if(te(void 0),e.key===`Delete`||e.key===`Backspace`){aD.clearShortcut(t).then(e=>ne(e));return}let n=kE(e);if(!n){ne(`没有认出这个按键,换一个试试。`);return}let i=FE(n);if(!i.ok){ne(i.reason);return}let a=VE(r,n,t);if(a){let e=se.find(e=>e.id===a)?.name;ne(e?`这个组合键已经被「${e}」占用了,换一个键。`:`这个组合键已经被另一个工具占用了,换一个键。`)}else aD.setShortcut(t,n).then(e=>ne(e))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[M,r,se]);let ce=e=>{ae(ZE(e,window.innerWidth,window.innerHeight))},le=e=>{XE(e)},ue=()=>{ae(void 0),XE(void 0)},de=(0,u.useRef)(!1),fe=n.map(e=>e.slug).filter(e=>typeof e==`string`),pe=e=>{m(void 0),g(void 0),A(void 0),O({tool:e,name:hD({slug:e.slug??`tool`})})},me=async(e,t)=>{m(void 0),g(void 0),A(void 0);let n=gD(t);if(!n.ok)A(n.reason);else try{let t=await Ne(`/api/tools/export?id=${encodeURIComponent(e.id)}`),r=await t.json();if(!t.ok||!r.bundle)throw Error(r.error??`HTTP ${t.status}`);let i=new Blob([JSON.stringify(r.bundle,null,2)],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.name,document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a),g(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){m(`导出失败:${Or(e)}`)}finally{O(void 0)}},he=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;m(void 0),g(void 0),S(void 0);let n=fD(await t.text(),t.name);n.ok?(v({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),b(fe.includes(n.bundle.slug)?mD(n.bundle.slug,fe):n.bundle.slug),w(n.bundle.files[0]?.path)):m(n.reason)},ge=()=>{v(void 0),b(``),S(void 0),w(void 0)},P=async()=>{if(!_)return;S(void 0);let e=pD(y);if(!e.ok)S(e.reason);else if(fe.includes(e.slug))S(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{E(!0);try{let t=await Ne(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(xD(_.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await oD(),g(`已导入「${_.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),ge()}catch(e){m(`导入失败:${Or(e)}`)}finally{E(!1)}}};(0,u.useEffect)(()=>{D&&ee.current?.scrollIntoView({block:`center`})},[D]);let _e=()=>{let e=Vt(i);e.ok?t.length>=32?l(`工具最多 32 个,先删掉一个再加。`):(aD.setTools([...t,{id:Gt(`link`,t.map(e=>e.id)),kind:`link`,name:o.trim()||bk(e.url),glyph:`↗`,url:e.url}]),a(``),s(``),l(void 0)):l(e.reason)},ve=ie?{width:`${ie.width}px`,height:`${ie.height}px`,maxWidth:`calc(100vw - 32px)`,maxHeight:`calc(100vh - 32px)`}:void 0;return(0,Re.createPortal)((0,F.jsxs)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onPointerDown:()=>{de.current=!1},onClick:t=>{de.current?de.current=!1:t.target===t.currentTarget&&e()},children:[(0,F.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,ref:re,style:ve,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:e,children:`✕`})]}),(0,F.jsx)(`div`,{className:`tool-dialog-body`,children:_?(0,F.jsx)(yk,{pending:_,slugDraft:y,slugError:x,preview:C,busy:T,onSlugChange:e=>{b(e),S(void 0)},onPreviewChange:w,onCancel:ge,onConfirm:()=>void P()}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,F.jsx)(`strong`,{children:`直接描述你要的工具`}),(0,F.jsx)(`p`,{className:`tool-hint`,children:`告诉 Super Pi Agent 你要创建什么,它会使用内置开发技能和 tool_register 完成注册。复制提示词仅作为备用入口。`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void oe(),children:d?`已复制`:`复制备用提示词`})]}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,F.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":Ft.length,children:Ft.map(e=>{let n=t.some(t=>t.kind===e.kind);return(0,F.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":e.kind,children:[(0,F.jsx)(lE,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,F.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{children:e.blurb})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":e.kind,disabled:n,title:n?`${e.name}已经在工具栏里了`:`添加${e.name}`,"aria-label":n?`${e.name}已添加`:`添加${e.name}`,onClick:()=>aD.setTools(Kt(t,e.kind)),children:n?`已添加`:`添加`})]},e.kind)})}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,F.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,F.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:i,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{a(e.target.value),l(void 0)}}),(0,F.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:o,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>s(e.target.value)}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!i.trim(),onClick:_e,children:`添加网址工具`}),c&&(0,F.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:c}),(0,F.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,F.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`快捷键`})}),(0,F.jsxs)(`p`,{className:`tool-hint`,"data-tool-shortcut-hint":`1`,children:[`给每个工具绑一个组合键,按下就直接打开它,不用先找到右侧栏。`,(0,F.jsx)(`b`,{children:`弹窗打开时快捷键不生效`}),`——模态弹窗期间键盘归它自己,关掉之后再按。`]}),(0,F.jsx)(`div`,{className:`tool-shortcuts`,"data-tool-shortcut-count":se.length,children:se.map(e=>(0,F.jsxs)(`div`,{className:`tool-shortcut-row`,"data-tool-shortcut-row":e.id,children:[(0,F.jsx)(lE,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,F.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{children:r[e.id]?`按 ${jE(r[e.id])} 打开`:`还没有快捷键`})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-shortcut-set`,"data-tool-shortcut-set":e.id,"data-tool-shortcut-capturing":M===e.id?`1`:void 0,"aria-pressed":M===e.id,title:M===e.id?`按下想用的组合键(Esc 取消,Delete 清除)`:`点一下,然后按下想用的组合键`,onClick:()=>{ne(void 0),te(M===e.id?void 0:e.id)},children:M===e.id?`按下组合键…`:r[e.id]?jE(r[e.id]):`未设置`}),r[e.id]&&(0,F.jsx)(`button`,{type:`button`,className:`tool-shortcut-clear`,"data-tool-shortcut-clear":e.id,title:`清除${e.name}的快捷键`,"aria-label":`清除${e.name}的快捷键`,onClick:()=>{aD.clearShortcut(e.id),ne(void 0),te(void 0)},children:`清除`})]},e.id))}),N&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-shortcut-error":`1`,children:N}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有注册全局工具。直接告诉 Agent 你想做什么即可开始。`}):(0,F.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=yD(e.environmentState);return(0,F.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,F.jsx)(lE,{className:`tool-preset-glyph`,glyph:dE(e)}),(0,F.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,F.jsx)(`strong`,{children:e.name}),(0,F.jsx)(`small`,{"data-tool-env":e.environmentState?.state??`unknown`,children:t?`${t.warn?`⚠ `:``}${t.text}${e.environmentState?.detail?` · ${e.environmentState.detail}`:``}`:`环境未知`}),e.permissions?.llm&&(0,F.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>pe(e),children:`导出`})]},e.id)})}),D&&(0,F.jsxs)(`div`,{className:`tool-share-review`,ref:ee,"data-tool-export-name":`1`,children:[(0,F.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,D.tool.name,`」`]}),(0,F.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,F.jsx)(`input`,{className:`tool-input`,value:D.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>O({...D,name:e.target.value})})]}),k&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:k}),(0,F.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{O(void 0),A(void 0)},children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void me(D.tool,D.name),children:`导出`})]})]}),h&&(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:h}),p&&(0,F.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:p}),(0,F.jsx)(`div`,{className:`rail-section-head`,children:(0,F.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,F.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,F.jsx)(`code`,{children:cD}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,F.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>j.current?.click(),children:`选择文件…`}),(0,F.jsx)(`input`,{ref:j,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void he(e)})]})})]}),(0,F.jsx)(_k,{targetRef:re,onResize:ce,onCommit:le,onDragEnd:()=>{de.current=!0},onReset:ue})]}),document.body)}var gk=18;function _k({targetRef:e,onResize:t,onCommit:n,onDragEnd:r,onReset:i}){let[a,o]=(0,u.useState)(),s=(0,u.useRef)(void 0);return(0,u.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=t.getBoundingClientRect();o({left:e.right-gk,top:e.bottom-gk})};n();let r=new ResizeObserver(n);return r.observe(t),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),()=>{r.disconnect(),window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[e]),(0,F.jsx)(`div`,{className:`tool-dialog-grip`,"data-tool-settings-grip":`1`,role:`separator`,"aria-orientation":`vertical`,tabIndex:0,"aria-label":`调整工具设置弹窗大小:拖动或用方向键,Enter 恢复默认尺寸`,style:a?{left:`${a.left}px`,top:`${a.top}px`}:void 0,onPointerDown:i=>{i.preventDefault(),i.stopPropagation();let a=e.current;if(!a)return;let o=a.getBoundingClientRect(),c=o.left+o.width/2,l=o.top+o.height/2;s.current=void 0;let u=e=>{let n=ZE({width:2*(e.clientX-c),height:2*(e.clientY-l)},window.innerWidth,window.innerHeight);s.current=n,t(n)},d=()=>{window.removeEventListener(`pointermove`,u),window.removeEventListener(`pointerup`,d),window.removeEventListener(`pointercancel`,d),s.current&&(n(s.current),r())};window.addEventListener(`pointermove`,u),window.addEventListener(`pointerup`,d),window.addEventListener(`pointercancel`,d)},onDoubleClick:()=>i(),onKeyDown:r=>{if(r.key===`Enter`||r.key===` `){r.preventDefault(),i();return}let a=r.shiftKey?8:24,o=e.current?.getBoundingClientRect(),c=o?.width??UE.width,l=o?.height??UE.height;if(r.key===`ArrowRight`)c+=a;else if(r.key===`ArrowLeft`)c-=a;else if(r.key===`ArrowDown`)l+=a;else if(r.key===`ArrowUp`)l-=a;else return;r.preventDefault();let u=ZE({width:c,height:l},window.innerWidth,window.innerHeight);s.current=u,t(u),n(u)},onClick:e=>e.stopPropagation()})}function vk(){let{tools:e,mountedTools:t,openToolId:n,settingsOpen:r,shortcuts:i}=iD(),a=e.find(e=>e.id===n),o=t.find(e=>e.id===n);return(0,u.useEffect)(()=>{let n=n=>{if(!r&&!document.querySelector(`[aria-modal="true"]`)&&!(n.isComposing||n.defaultPrevented)){for(let[r,a]of Object.entries(i))if(RE(a,n)&&(e.some(e=>e.id===r)||t.some(e=>e.id===r))){n.preventDefault(),aD.openTool(r);return}}};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[i,e,t,r]),(0,u.useEffect)(()=>{oD();let e=()=>{oD()};return window.addEventListener(`super-pi-tools-updated`,e),window.addEventListener(`super-pi-active-server`,e),()=>{window.removeEventListener(`super-pi-tools-updated`,e),window.removeEventListener(`super-pi-active-server`,e)}},[]),(0,u.useEffect)(()=>{aD.persistTools()},[]),(0,F.jsxs)(F.Fragment,{children:[r&&(0,F.jsx)(hk,{onClose:()=>aD.closeSettings()}),a&&(0,F.jsx)(xk,{tool:a,onClose:()=>aD.closeTool()}),o&&(0,F.jsx)(kk,{tool:o,onClose:()=>aD.closeTool()})]})}function yk({pending:e,slugDraft:t,slugError:n,preview:r,busy:i,onSlugChange:a,onPreviewChange:o,onCancel:s,onConfirm:c}){let l=e.bundle,u=l.files.reduce((e,t)=>e+new TextEncoder().encode(t.content).length,0),d=vD(l),f=_D(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,F.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,F.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,F.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,F.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,bD(u)]}),(0,F.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,F.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,F.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,F.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,F.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,F.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` · `,l.environment.fingerprint.platform||`未知平台`,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,F.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,F.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,F.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,F.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,F.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,F.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,F.jsx)(`button`,{type:`button`,className:`tool-share-tab`,"aria-pressed":e.path===p?.path,"data-tool-import-file":e.path,onClick:()=>o(e.path),children:e.path},e.path))}),(0,F.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,F.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,F.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,F.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,F.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function bk(e){let t=e.replace(/^[./]+/,``).slice(0,30).trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return t||e.slice(0,30);try{return new URL(e,typeof window>`u`?`http://localhost`:window.location.href).hostname||t||e.slice(0,30)}catch{return e.slice(0,30)}}function xk({tool:e,onClose:t}){return(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,F.jsx)(lE,{className:`tool-dialog-glyph`,glyph:e.glyph}),e.name]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,F.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,F.jsx)(Ck,{}),e.kind===`timestamp`&&(0,F.jsx)(wk,{}),e.kind===`link`&&(0,F.jsx)(Tk,{tool:e})]})]})}),document.body)}function Sk({image:e,onClose:t}){return(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Re.createPortal)((0,F.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,F.jsxs)(`div`,{className:`lightbox-head`,children:[(0,F.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,F.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,F.jsx)(`div`,{className:`lightbox-body`,children:(0,F.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function Ck(){let[e,t]=(0,u.useState)(`12 * (3 + 4)`),n=sn(e),r=e=>{t(t=>t+e)};return(0,F.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,F.jsx)(`input`,{className:`tool-input tool-calc-input`,"data-calc-input":`1`,value:e,maxLength:200,"aria-label":`算式`,spellCheck:!1,autoComplete:`off`,placeholder:`例如 (12 + 8) / 4`,onChange:e=>{t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&e.preventDefault()}}),(0,F.jsx)(`div`,{className:`tool-calc-keys`,"data-calc-keys":`1`,children:[[`7`,`7`],[`8`,`8`],[`9`,`9`],[`÷`,`/`],[`(`,`(`],[`)`,`)`],[`4`,`4`],[`5`,`5`],[`6`,`6`],[`×`,`*`],[`^`,`^`],[`%`,`%`],[`1`,`1`],[`2`,`2`],[`3`,`3`],[`-`,`-`],[`←`,`back`],[`C`,`clear`],[`0`,`0`],[`.`,`.`],[`+`,`+`]].map(([e,n])=>(0,F.jsx)(`button`,{type:`button`,className:`tool-calc-key`,"data-calc-key":n,"aria-label":e===`C`?`清空`:e===`←`?`退格`:`输入 ${e}`,onClick:()=>{n===`clear`?t(``):n===`back`?t(e=>e.slice(0,-1)):r(n)},children:e},e))}),n.ok?(0,F.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:cn(n.value)}):(0,F.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function wk(){let[e,t]=(0,u.useState)(``),n=ln(e),r=n.ok?dn(n.ms):null;return(0,F.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,F.jsx)(`input`,{className:`tool-input`,"data-stamp-input":`1`,value:e,maxLength:64,spellCheck:!1,"aria-label":`时间戳或日期`,placeholder:`1757000000 或 2026-10-08T09:00:00`,onChange:e=>t(e.target.value)}),r?(0,F.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`本地时间`}),(0,F.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`ISO(UTC)`}),(0,F.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`秒`}),(0,F.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,F.jsxs)(`div`,{children:[(0,F.jsx)(`dt`,{children:`毫秒`}),(0,F.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,F.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function Tk({tool:e}){let[t,n]=(0,u.useState)(!1),r=async()=>{let e=await Bd(`请为 Super Pi 开发一个全局右侧栏工具并自动挂载。不要启动独立 HTTP 服务器。通过内置 tool_register 提交完整的 HTML/JS/CSS 文件;工具将被 Super Pi 保存并在所有 workspace 可用。如需计算,注册一个 Python 脚本(不接受 shell 命令),参数经 JSON stdin 传入,stdout 只输出 JSON 结果。在页面里加载 ./super-pi-tool.js,使用 SuperPiTool.run(params)、wait(runId)、get(runId) 和 cancel(runId) 执行、等待、查看和取消任务。它们会自动绑定当前工具;不要调用 /api/exec,也不要猜测 toolId。`);n(e),window.setTimeout(()=>n(!1),1800)};return(0,F.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,F.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,F.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,F.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,F.jsx)(`a`,{className:`tool-link-open`,"data-tool-link-open":e.id,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:e.url,children:`在新标签页打开 ↗`}),(0,F.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-copy-prompt":e.id,onClick:()=>void r(),children:t?`已复制`:`复制开发 Prompt`})]}),/^https?:\/\//i.test(e.url??``)&&(0,F.jsx)(`iframe`,{className:`tool-link-frame`,"data-tool-frame":e.id,src:e.url,title:e.name,sandbox:`allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts`,referrerPolicy:`no-referrer`})]})}var Ek=`(max-width: 1100px)`,Dk=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ok(e){let t=`super-pi.mounted-tool.owner.`+e;try{let e=window.localStorage.getItem(t);if(e&&/^[0-9a-f]{32}$/.test(e))return e}catch{}let n=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(t,n)}catch{}return n}function kk({tool:e,onClose:t}){let n=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let r=(0,u.useMemo)(()=>Ok(e.id),[e.id]);(0,u.useLayoutEffect)(()=>Nn(()=>n.current,e.id,r),[e.id,r]);let i=e.dialogSize??{width:1100,height:780},a={width:`min(${i.width}px, calc(100vw - 32px))`,height:`min(${i.height}px, calc(100dvh - 32px))`};return(0,Re.createPortal)((0,F.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,F.jsxs)(`div`,{className:`tool-dialog mounted-tool-dialog`,style:a,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,F.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,F.jsxs)(`h2`,{className:`tool-dialog-title`,children:[(0,F.jsx)(lE,{className:`tool-dialog-glyph`,glyph:dE(e)}),e.name]}),(0,F.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,F.jsx)(`div`,{className:`tool-dialog-body`,children:(0,F.jsx)(`iframe`,{ref:n,className:`tool-link-frame`,src:Me(`/tools/${encodeURIComponent(e.id)}/#super-pi-owner=${r}`),title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function Ak(e,t,n){let r=Math.max(0,Math.round(n)-480),i=Dk(520,180,Math.max(180,r-240)),a=Dk(Math.round(e),180,i),o=Dk(640,240,Math.max(240,r-a));return{sidebar:a,rail:Dk(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var jk=`super-pi.rail-widths.v1`,Mk=`super-pi.reader-state.v1`,Nk=`super-pi.folded-groups.v1`;function Pk(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.folded-groups.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t=e=>{let t={};if(e&&typeof e==`object`)for(let[n,r]of Object.entries(e))typeof r==`boolean`&&(t[n]=r);return t};return{workspaces:t(e.workspaces),archived:t(e.archived)}}catch{return{}}}function Fk(e){try{typeof window<`u`&&window.localStorage.setItem(Nk,JSON.stringify(e))}catch{}}var Ik=e=>{let t=document.querySelector(`[data-workspace-group="${CSS.escape(e)}"]`);return t?[...t.querySelectorAll(`.conversation-row[data-session-root]`)].map(e=>({id:e.dataset.sessionRoot??``,middle:(()=>{let t=e.getBoundingClientRect();return t.top+t.height/2})()})).filter(e=>e.id!==``):[]},Lk=6,Rk=400,zk=32,Bk=48,Vk=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function Hk(e,t,n=!1,r=!1){let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=n?!1:r?!0:t.followTail?i<=Bk:i<=zk,o,s;if(!a){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);o=n?.dataset.transcriptKey,s=n?n.getBoundingClientRect().top-t:void 0}return{followTail:a,scrollTop:e.scrollTop,...o?{anchorKey:o,anchorOffset:s}:{}}}function Uk(){try{if(typeof window>`u`)return{conversations:{}};let e=JSON.parse(window.localStorage.getItem(`super-pi.reader-state.v1`)??`null`);if(!e||typeof e!=`object`)return{conversations:{}};let t={};if(e.conversations&&typeof e.conversations==`object`)for(let[n,r]of Object.entries(e.conversations)){let e=r;typeof e.followTail==`boolean`&&(t[n]={followTail:e.followTail,scrollTop:Number.isFinite(e.scrollTop)?Math.max(0,Number(e.scrollTop)):0,...typeof e.anchorKey==`string`?{anchorKey:e.anchorKey}:{},...Number.isFinite(e.anchorOffset)?{anchorOffset:Number(e.anchorOffset)}:{}})}let n={};if(e.readAt&&typeof e.readAt==`object`)for(let[t,r]of Object.entries(e.readAt))typeof r==`string`&&(n[t]=r);return{activeId:typeof e.activeId==`string`?e.activeId:void 0,workspaceId:typeof e.workspaceId==`string`?e.workspaceId:void 0,conversations:t,readAt:n}}catch{return{conversations:{}}}}function Wk(e){try{typeof window<`u`&&window.localStorage.setItem(Mk,JSON.stringify(e))}catch{}}var Gk=`super-pi.session-tabs.v1`;function Kk(e,t){if(!t||e.has(t))return e;let n=new Set(e);return n.add(t),n}function qk(e,t,n){let r=e.touched.has(t),i=e.touched;if(r){let r=new Set(e.touched);r.delete(t),n&&r.add(n),i=r}return{ids:e.ids.flatMap(e=>e===t?n?[n]:[]:[e]),previewId:e.previewId===t?n&&!r?n:void 0:e.previewId,emptied:e.emptied,touched:i}}function Jk(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(Pn(`super-pi.session-tabs.v1`)??`null`);if(!e||typeof e!=`object`)return{ids:[]};let t=e,n=Array.isArray(t.ids)?[...new Set(t.ids.filter(e=>typeof e==`string`))]:[],r=Array.isArray(t.touched)?[...new Set(t.touched.filter(e=>typeof e==`string`))]:[],i=typeof t.previewId==`string`&&n.includes(t.previewId)&&!r.includes(t.previewId)?t.previewId:void 0;i&&i!==t.activeId&&(n=n.filter(e=>e!==i));let a=typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0,o=typeof t.workspaceLandingId==`string`?t.workspaceLandingId:void 0;return{ids:n,activeId:a,contextId:typeof t.contextId==`string`?t.contextId:void 0,workspaceLandingId:o,previewId:i===a?i:void 0,touched:r,emptied:n.length===0&&(t.emptied===!0||!!i),selectionCleared:t.selectionCleared===!0}}catch{return{ids:[]}}}function Yk(e,t,n,r=!1){try{if(typeof window>`u`)return;let{ids:i,previewId:a,touched:o,emptied:s}=e;Fn(Gk,JSON.stringify({ids:i,...t&&i.includes(t)?{activeId:t}:{},...t?{contextId:t}:{},...n?{workspaceLandingId:n}:{},...a&&i.includes(a)?{previewId:a}:{},...o.size?{touched:[...o]}:{},...s?{emptied:s}:{},...r?{selectionCleared:!0}:{}}))}catch{}}function Xk(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(jk);if(e===null)return{};let t=JSON.parse(e),n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0;return{sidebar:n(t.sidebar),rail:n(t.rail)}}catch{return{}}}function Zk(e){try{if(typeof window>`u`)return;window.localStorage.setItem(jk,JSON.stringify(e))}catch{}}function Qk({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,u.useState)(!1),c=e=>e.shiftKey?64:16;return(0,F.jsx)(`div`,{className:`rail-resizer rail-resizer-${e}${o?` rail-resizer-dragging`:``}`,"data-rail-resizer":e,"data-rail-resizer-dragging":o?`true`:`false`,"data-rail-resizer-width":t,role:`separator`,"aria-orientation":`vertical`,"aria-label":i,"aria-valuenow":t,"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,onMouseDown:i=>{i.preventDefault(),i.currentTarget.focus();let o=i.clientX,c=t;s(!0);let l=document.body,u=l.style.cursor,d=l.style.userSelect;l.style.cursor=`col-resize`,l.style.userSelect=`none`;let f=t=>{let i=e===`left`?t.clientX-o:o-t.clientX;a(Dk(c+i,n,r))},p=()=>{l.style.cursor=u,l.style.userSelect=d,s(!1),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)};window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p)},onKeyDown:i=>{let o=c(i);i.key===`ArrowLeft`?(i.preventDefault(),a(Dk(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(Dk(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var $k=`super-pi.composer-height.v1`,eA=148,tA=.55,nA=()=>Math.max(eA,Math.round((typeof window>`u`?800:window.innerHeight)*tA)),rA=e=>{let t=Number.isFinite(e)?e:eA;return Math.round(Math.min(nA(),Math.max(eA,t)))},iA=()=>{try{let e=window.localStorage.getItem($k);return e===null?eA:rA(Number(e))}catch{return eA}};function aA({height:e,onHeight:t}){let[n,r]=(0,u.useState)(!1),i=e=>e.shiftKey?64:16,a=nA();return(0,F.jsx)(`div`,{className:`composer-resize${n?` composer-resize-dragging`:``}`,"data-composer-resize":`1`,"data-composer-resize-dragging":n?`true`:`false`,"data-composer-height":e,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整消息编辑区高度`,"aria-valuenow":e,"aria-valuemin":eA,"aria-valuemax":a,tabIndex:0,onMouseDown:n=>{n.preventDefault(),n.currentTarget.focus();let i=n.clientY,a=e;r(!0);let o=document.documentElement,s=document.body.style.userSelect;document.body.style.cursor=`ns-resize`,document.body.style.userSelect=`none`;let c=e=>{let t=rA(a+(i-e.clientY));o.style.setProperty(`--composer-height`,`${t}px`)},l=()=>{document.body.style.cursor=``,document.body.style.userSelect=s;let n=Number.parseFloat(o.style.getPropertyValue(`--composer-height`));r(!1),window.removeEventListener(`mousemove`,c),window.removeEventListener(`mouseup`,l),t(Number.isFinite(n)?n:e)};window.addEventListener(`mousemove`,c),window.addEventListener(`mouseup`,l)},onKeyDown:n=>{let r=i(n);n.key===`ArrowUp`?(n.preventDefault(),t(rA(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(rA(e-r))):n.key===`Home`?(n.preventDefault(),t(eA)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(rA(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(rA(e-96)))}})}function oA(e,t,n){if(!e.length)return;let r=n?e.find(e=>e.workspaceId===n):void 0;if(r)return r;if(!(n&&t.some(e=>e.id===n)))return n?e.find(e=>h(e.workspaceId).server===h(n).server):e[0]}function sA(e,t,n){let r=n&&e?JSON.stringify([e,t,n]):void 0,[i,a]=(0,u.useState)();(0,u.useEffect)(()=>{if(!r||!n||!e)return;let i=new AbortController;return Ne(`/api/files/diff?${new URLSearchParams({workspaceId:e,path:n,...t?{cwd:t}:{}})}`,{signal:i.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{i.signal.aborted||a({scope:r,diff:e,error:``})}).catch(e=>{i.signal.aborted||a({scope:r,diff:null,error:e instanceof Error?e.message:`读取差异失败`})}),()=>i.abort()},[r,e,t,n]);let o=i?.scope===r?i:void 0;return{diff:o?.diff??null,error:o?.error??``,loading:!!r&&!o}}function cA(e){try{let t=`super-pi.browser-notification-events`,n=Date.now(),r=JSON.parse(window.localStorage.getItem(t)??`[]`).filter(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`number`&&n-e[1]<864e5);return!r.some(([t])=>t===e)&&(window.localStorage.setItem(t,JSON.stringify([...r.slice(-63),[e,n]])),!0)}catch{return!0}}function lA(){let[e,t]=(0,u.useState)(ND),[n,r]=(0,u.useState)(()=>{try{return typeof window<`u`&&window.localStorage.getItem(`super-pi.browser-notifications`)===`enabled`}catch{return!1}}),[i,a]=(0,u.useState)(()=>ta()),o=(0,u.useCallback)(()=>a(ta()),[]),s=(0,u.useRef)(new Map),c=(0,u.useRef)(!1),l=(0,u.useRef)(new Map),d=(0,u.useCallback)(e=>{t(t=>{let n=typeof e==`function`?e(t):e;return wt(n,t)})},[]),[f,p]=(0,u.useState)(()=>cp().map(e=>{let t=new Date().toISOString();return{id:e.clientId,key:`send:${e.conversationId}:${e.clientId}`,serverId:de(e.conversationId),retry:!0,command:{...e},apply:n=>fp(n,e,t),accepted:t=>!!t.conversations.find(t=>t.id===e.conversationId)?.messages.some(t=>t.id===dp(e))}})),m=(0,u.useRef)(f),_=(0,u.useRef)(null);_.current||=Uk();let v=(0,u.useRef)(null);v.current||=Jk();let y=v.current,b=(0,u.useRef)(null);b.current||=In();let x={current:b.current},S=(0,u.useRef)(null);S.current||=Ln();let w=S.current,T=f.reduce((e,t)=>t.apply(e),e),E=w.view===`file`||w.view===`diff`||w.view===`gitDiff`,[D,O]=(0,u.useState)(y.workspaceLandingId||y.selectionCleared?void 0:y.activeId??(E?y.contextId:void 0)??(y.emptied?void 0:_.current.activeId)),[k,A]=(0,u.useState)(y.workspaceLandingId??(y.selectionCleared?x.current.kind===`workspace`?x.current.workspaceId:void 0:_.current.workspaceId)),[j,ee]=(0,u.useState)(!1),M=ue(),te=j&&M.statuses.get(M.activeServer)?.state===`online`,[N,ne]=(0,u.useState)(),[ie,ae]=(0,u.useState)(()=>Pk().workspaces??{}),[oe,se]=(0,u.useState)(()=>({ids:y.ids,previewId:y.previewId,touched:new Set(y.touched??[]),emptied:y.emptied})),ce=oe.ids,le=oe.previewId,ye=(0,u.useRef)(0),[be,xe]=(0,u.useState)(),[Se,Ce]=(0,u.useState)({entries:[],index:-1}),[we,Te]=(0,u.useState)(),Ee=(0,u.useRef)(new Set),De=oe.emptied===!0,[Oe,ke]=(0,u.useState)(!1),[Ae,je]=(0,u.useState)(!1),[Pe,Fe]=(0,u.useState)(),Ie=(0,u.useRef)(null),Re=(0,u.useRef)(void 0),ze=(0,u.useRef)(_.current.conversations),Be=(0,u.useRef)(ce);Be.current=ce;let Ve=(0,u.useRef)(_.current.readAt??{}),[He,Ge]=(0,u.useState)(0),[Ke,qe]=(0,u.useState)(Xn),[Je,Ye]=(0,u.useState)(()=>w.groups.length?w.groups:Ke?[Ke]:[]),[Xe,Ze]=(0,u.useState)(w.view?w.view===`group`:!!Ke),[I,$e]=(0,u.useState)(()=>w.view??(Ke?`group`:`session`)),{index:et,reload:tt,remember:nt,forget:rt,activities:it,recordActivity:at}=or(T.workspaces,te),[ot,st]=(0,u.useState)(()=>new Set),ct=Ke?.workspaceId??``,lt=Ke?.roomId??``,ut=et[ct]?.rooms.find(e=>e.id===lt),dt=ut?.title;(0,u.useEffect)(()=>{Zn(I===`group`?Ke:void 0)},[Ke,I]),(0,u.useEffect)(()=>{I===`group`&&Oe&&!T.workspaces.some(e=>e.id===ct&&!e.closedAt)&&(Ze(!1),$e(`session`))},[I,Oe,T.workspaces,ct]);let ft=(0,u.useRef)(null),pt=(0,u.useRef)(null),mt=(0,u.useRef)(void 0),ht=(0,u.useRef)(!1),gt=(0,u.useRef)(!0),[_t,vt]=(0,u.useState)({followTail:!0,scrollTop:0}),yt=(0,u.useRef)(!1),bt=(0,u.useRef)(new Map),xt=(0,u.useRef)(void 0),St=(0,u.useRef)([]),Ct=(0,u.useRef)(void 0),wt=(0,u.useCallback)((e,t)=>{let n=new Map(t.conversations.map(e=>[e.id,e]));return{...e,conversations:e.conversations.map(e=>{let t=n.get(e.id);if(e.messagesLoaded===!1||!t||t.messagesLoaded===!1||t.status!==`running`)return e;let r=new Map(t.messages.map(e=>[e.id,e]));return{...e,messages:e.messages.map(e=>{let t=r.get(e.id);return!t||!(t.content.length>e.content.length||(t.thinking?.length??0)>(e.thinking?.length??0))?e:{...e,content:t.content,thinking:t.thinking,thinkingActive:t.thinkingActive,thinkingBlocks:zD(t.thinkingBlocks,e.thinkingBlocks)}})}})}},[]),Tt=(0,u.useCallback)(()=>{if(Ct.current!==void 0&&(cancelAnimationFrame(Ct.current),Ct.current=void 0),!St.current.length)return;let e=St.current;St.current=[];let t=new Map;for(let n of e){let e=`${n.conversationId}\u0000${n.messageId}`,r=t.get(e)??[];r.push(n),t.set(e,r)}d(e=>({...e,conversations:e.conversations.map(e=>{let n=e.messages.map(n=>{let r=t.get(`${e.id}\u0000${n.id}`);if(!r)return n;let i={...n};for(let e of r){if(e.type===`message.delta`){i.content+=e.delta;continue}if(i.thinkingActive=e.active,!e.delta)continue;let t=e.at??i.content.length,n=RD(i.thinkingBlocks??[],e,t);i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return n.every((t,n)=>t===e.messages[n])?e:{...e,messages:n}})}))},[]),Et=(0,u.useCallback)(e=>{let t=St.current,n=t.at(-1);n&&n.type===e.type&&n.conversationId===e.conversationId&&n.messageId===e.messageId&&(e.type!==`message.thinking`||n.type===`message.thinking`&&n.at===e.at&&n.active===e.active&&n.blockIndex===e.blockIndex)?t[t.length-1]={...e,delta:n.delta+e.delta}:t.push(e),Ct.current===void 0&&(Ct.current=requestAnimationFrame(Tt))},[Tt]),Dt=(0,u.useCallback)(e=>{xt.current=e},[]),[Ot,kt]=(0,u.useState)(()=>Pk().archived??{});(0,u.useEffect)(()=>{Fk({workspaces:ie,archived:Ot})},[ie,Ot]);let[At,jt]=(0,u.useState)(()=>vE());(0,u.useEffect)(()=>{yE(At)},[At]);let[Mt,Nt]=(0,u.useState)(),Pt=(0,u.useRef)(0),Ft=(0,u.useRef)(``),It=(e,t,n,r)=>{let i=(e.target instanceof Element?e.target:void 0)?.closest(`button`);if(i&&!i.classList.contains(`conversation`)||e.button!==0)return;let a=e.clientY,o=e.pointerType===`touch`,s=!1,c,l=[],u,d=!1,f=e=>{let t=l.filter(e=>e.id!==n);if(t.length===0){u=void 0,d=!1;return}let r=0;for(;r<t.length&&t[r].middle<e;)r+=1;r<t.length?(u=t[r].id,d=!1):(u=t[t.length-1].id,d=!0)},p=()=>Nt(e=>e&&e.dropRootId===u&&e.dropAfter===d?e:{workspaceId:t,conversationId:n,dropRootId:u,dropAfter:d}),m=()=>{s||(s=!0,l=Ik(t),f(a),document.body.style.userSelect=`none`,p())},h=e=>{if(!s){if(o){c!==void 0&&window.clearTimeout(c),c=void 0;return}if(Math.abs(e.clientY-a)<Lk)return;m()}f(e.clientY),p()},g=e=>{if(window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,_),window.removeEventListener(`pointercancel`,v),document.removeEventListener(`touchmove`,y),c!==void 0&&window.clearTimeout(c),document.body.style.userSelect=``,s&&e){let e=r.filter(e=>e!==n),i=u===void 0?e.length:d?e.indexOf(u)+1:e.indexOf(u);jt(e=>({...e,[t]:gE(r,n,i)})),Pt.current=Date.now(),Ft.current=n}Nt(void 0)},_=()=>g(!0),v=()=>g(!1),y=e=>{s&&e.preventDefault()};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,_),window.addEventListener(`pointercancel`,v),o&&(document.addEventListener(`touchmove`,y,{passive:!1}),c=window.setTimeout(m,Rk))},[Lt,Rt]=(0,u.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),zt=e=>{let t=e.slice(0,24);Rt(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},Bt=Lt.trim()||`你`,[Vt,Ht]=(0,u.useState)(),[Ut,Gt]=(0,u.useState)([]),[Kt,qt]=(0,u.useState)([]),[Jt,Yt]=(0,u.useState)(),[Xt,Zt]=(0,u.useState)(),[Qt,$t]=(0,u.useState)([]),[en,tn]=(0,u.useState)([]),[nn,rn]=(0,u.useState)(),[an,on]=(0,u.useState)(),[sn,cn]=(0,u.useState)(),[ln,un]=(0,u.useState)(),[dn,pn]=(0,u.useState)(),mn=Yi(sn),hn=(0,u.useMemo)(()=>Ut.filter(e=>e.request.blocking),[Ut]),[gn,_n]=(0,u.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[vn,yn]=(0,u.useState)(`chat`),[bn,xn]=(0,u.useState)(!1),Sn=(0,u.useCallback)(()=>{yn(`chat`),window.matchMedia(`(max-width: 700px)`).matches&&_n(!0)},[]),[wn,Tn]=(0,u.useState)(!1),[En,Dn]=(0,u.useState)(x.current.kind),[On,An]=(0,u.useState)(()=>x.current.serverId??localStorage.getItem(`super-pi.server-filter`)??`all`),[jn,Mn]=(0,u.useState)(x.current.workspaceId??_.current.workspaceId),[Nn,Pn]=(0,u.useState)(x.current.repoId??_.current.workspaceId),[Vn,Un]=(0,u.useState)(y.selectionCleared===!0);(0,u.useEffect)(()=>{try{Fn(`super-pi.sidebar-scope.v1`,JSON.stringify({kind:En,serverId:On,workspaceId:jn,repoId:Nn}))}catch{}},[En,On,jn,Nn]);let Wn=(0,u.useRef)(Vn);Wn.current=Vn;let[Gn,Kn]=(0,u.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,u.useEffect)(()=>{let e=()=>Kn(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[qn,Jn]=(0,u.useState)(Hr);(0,u.useEffect)(()=>Ur(qn),[qn]);let[Yn,tr]=(0,u.useState)(Xk),nr=Ak(Yn.sidebar??270,Yn.rail??320,Gn>1100?Gn-88:Gn);(0,u.useEffect)(()=>{Zk({sidebar:Yn.sidebar??270,rail:Yn.rail??320})},[Yn.sidebar,Yn.rail]);let sr=e=>tr(t=>({...t,sidebar:e})),lr=e=>tr(t=>({...t,rail:e})),[ur,dr]=(0,u.useState)(null);(0,u.useEffect)(()=>{dr(iA())},[]),(0,u.useEffect)(()=>{ur!==null&&document.documentElement.style.setProperty(`--composer-height`,`${ur}px`)},[ur]);let fr=e=>{let t=rA(e);dr(t);try{window.localStorage.setItem($k,String(t))}catch{}};(0,u.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(Ek),t=e=>{e.matches&&_n(!0)};return e.addEventListener(`change`,t),e.matches&&_n(!0),()=>e.removeEventListener(`change`,t)},[]);let pr=Gn<=1100;(0,u.useEffect)(()=>{if(!pr||gn)return;let e=e=>{e.key===`Escape`&&(e.defaultPrevented||document.querySelector(`.tool-overlay, .lightbox-overlay, .quick-open-backdrop, .ctx-menu, .overlay, .picker-menu, .content-search-overlay`)||(e.preventDefault(),_n(!0)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[pr,gn]);let[mr,hr]=(0,u.useState)({}),[gr,_r]=(0,u.useState)({}),[vr,yr]=(0,u.useState)({}),[br,xr]=(0,u.useState)({}),[Sr,Cr]=(0,u.useState)(null),[wr,Tr]=(0,u.useState)(),[Er,Dr]=(0,u.useState)(()=>new Set);(0,u.useEffect)(()=>{Dr(e=>{if(e.size===0)return e;let t=new Set([...e].filter(e=>{let t=T.conversations.find(t=>t.id===e);return t?JO(t):!1}));return t.size===e.size?e:t})},[T.conversations]);let[Ar,jr]=(0,u.useState)(),[Mr,Nr]=(0,u.useState)(),Pr=(0,u.useRef)(new Map),[Fr,Ir]=(0,u.useState)(()=>{let e=pp(`super-pi.composer-drafts.v1`,{});return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,attachments:wO(t.text,t.attachments)}]))}),Lr=(0,u.useRef)(Fr),Rr=(0,u.useRef)(!1);Lr.current=Fr,(0,u.useEffect)(()=>{let e=()=>{let e=Object.entries(Lr.current).filter(([e,t])=>!e.startsWith(`pending:`)&&(t.text||t.images.length||t.attachments.length)).map(([e,{text:t,images:n,attachments:r}])=>[e,{text:t,images:n,attachments:r,uploading:0}]),t=mp(`super-pi.composer-drafts.v1`,Object.fromEntries(e));!t&&e.length&&!Rr.current&&Rs(`浏览器无法保存聊天草稿,刷新前请先保留这段内容。`,`warning`),Rr.current=!t&&e.length>0},t=window.setTimeout(e,250);return window.addEventListener(`pagehide`,e),()=>{window.clearTimeout(t),window.removeEventListener(`pagehide`,e)}},[Fr]);let zr=(0,u.useRef)(new Set),[Br,Vr]=(0,u.useState)([]),[Wr,qr]=(0,u.useState)([]),[Jr,Yr]=(0,u.useState)(),[Xr,Zr]=(0,u.useState)(!1),Qr=(0,u.useRef)(null),$r=(0,u.useRef)(!1),ei=(0,u.useRef)(0),ti=(0,u.useRef)([]),ni=(0,u.useRef)(void 0),ri=(0,u.useRef)(!1),ii=(0,u.useRef)(new Set),ai=(0,u.useRef)(new Set),oi=(0,u.useRef)(new Map),si=(0,u.useRef)(new Map),[ci,li]=(0,u.useState)(()=>Date.now());(0,u.useEffect)(()=>{let e=window.setInterval(()=>li(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let ui=(0,u.useMemo)(()=>T.conversations.filter(e=>!e.archivedAt),[T.conversations]),di=(0,u.useMemo)(()=>e.conversations.filter(e=>!e.archivedAt),[e.conversations]),fi=(0,u.useMemo)(()=>new Set(T.collapsedConversationIds??[]),[T.collapsedConversationIds]),L=(0,u.useMemo)(()=>{let e=ui.find(e=>e.id===D);if(e)return e;if(!(De||Vn||re(D??k)))return oA(ui,T.workspaces,k)},[De,Vn,D,ui,k,T.workspaces]),pi=(0,u.useMemo)(()=>L?{workspaceId:L.workspaceId,conversationId:L.id,onImageOpen:Yr}:void 0,[L?.workspaceId,L?.id]),[mi,hi]=(0,u.useState)(`queue`),_i=!!(L&&JO(L));(0,u.useEffect)(()=>{hi(`queue`)},[L?.id,_i]);let[vi,yi]=(0,u.useState)([]),bi=(0,u.useMemo)(()=>Bn(L?.parentConversationId,L?.parentConversationId?T.conversations.find(e=>e.id===L.parentConversationId):void 0),[L,T.conversations]),xi=!!(L&&T.unlockedChildConversationIds?.includes(L.id)),Si=bi&&!xi,Ci=(0,u.useMemo)(()=>(T.conversations||[]).filter(e=>e.parentConversationId===L?.id),[T.conversations,L?.id]),wi=(0,u.useMemo)(()=>(T.conversations||[]).find(e=>e.id===L?.parentConversationId),[T.conversations,L?.parentConversationId]),Ti=(0,u.useMemo)(()=>L?Hn({conversation:L,parent:wi,directChildren:Ci,isTopLevelUnread:!1}):null,[L,wi,Ci]),Ei=ft.current;if(Ei){let e=Ei.dataset.messageScrollContainer;e&&L?.id&&e!==L?.id&&Ei.querySelector(`[data-transcript-key]`)&&(ze.current[e]=Hk(Ei,ze.current[e]??{followTail:!0,scrollTop:0}))}gt.current=L?.messagesLoaded!==!1,(0,u.useEffect)(()=>{if(!Oe||re(D??k)||(De||Vn)&&!D||D&&di.some(e=>e.id===D)||D&&m.current.some(e=>e.temporaryId===D))return;let e=oA(ui,T.workspaces,k);De&&e||(D&&!e&&I!==`group`&&(ye.current++,$e(`session`)),O(e?.id),e&&se(t=>t.emptied||t.ids.length===0||t.ids.includes(e.id)?t:{...t,ids:[...t.ids,e.id]}))},[De,Vn,D,di,ui,Oe,k,T.workspaces,I]),(0,u.useEffect)(()=>{ne(void 0)},[D,k]);let Di=(0,u.useMemo)(()=>T.workspaces.find(e=>e.id===k)??(Vn||re(k)?void 0:T.workspaces[0]),[T.workspaces,k,Vn]),Oi=Di&&!ui.some(e=>e.workspaceId===Di.id)?Di:void 0,ki=Di?.id.startsWith(`pending:`)===!0,[Ai,ji]=(0,u.useState)(``);(0,u.useEffect)(()=>{ji(``)},[Di?.id]);let Mi=(0,u.useRef)(k);Mi.current=k,(0,u.useEffect)(()=>{L&&A(L.workspaceId)},[L?.id]),(0,u.useEffect)(()=>{ni.current=D},[D]),(0,u.useEffect)(()=>{mt.current=L?.id},[L?.id]);let Ni=(0,u.useCallback)(e=>{let t=e.activity.lastReplyAt,n=Qn({workspaceId:e.workspaceId,roomId:e.id});!t||t<=(Ve.current[n]??``)||(Ve.current[n]=t,Ge(e=>e+1),Wk({activeId:ni.current,workspaceId:Mi.current,conversations:ze.current,readAt:Ve.current}))},[]);cr(Ve,T.conversations,()=>{Ge(e=>e+1),Wk({activeId:ni.current,workspaceId:Mi.current,conversations:ze.current,readAt:Ve.current})}),(0,u.useEffect)(()=>{let e=L?.id;if(!e)return;let t=T.conversations.find(t=>t.id===e);if(!t||t.messagesLoaded===!1)return;let n=()=>{let n=ft.current;document.visibilityState!==`visible`||!n||n.getBoundingClientRect().height<=0||t.updatedAt<=(Ve.current[e]??``)||(Ve.current[e]=t.updatedAt,Ge(e=>e+1),Wk({activeId:ni.current,workspaceId:L?.workspaceId??k,conversations:ze.current,readAt:Ve.current}))},r=requestAnimationFrame(n);return document.addEventListener(`visibilitychange`,n),window.addEventListener(`focus`,n),()=>{cancelAnimationFrame(r),document.removeEventListener(`visibilitychange`,n),window.removeEventListener(`focus`,n)}},[L?.id,T.conversations,I]),(0,u.useEffect)(()=>{let e=L?.workspaceId??k;te&&Oe&&e&&!e.startsWith(`pending:`)&&!L?.id.startsWith(`pending:`)&&Wk({activeId:L?.id,workspaceId:e,conversations:ze.current,readAt:Ve.current})},[L?.id,L?.workspaceId,te,Oe,k]),(0,u.useEffect)(()=>{let e=ft.current;if(I!==`session`||!e||!L?.id||L.messagesLoaded===!1)return;let t=L.id;yt.current=!1;let n=ze.current[t]??{followTail:!0,scrollTop:0};ze.current[t]=n,vt(n);let r=requestAnimationFrame(()=>{if(ft.current!==e)ht.current=!1;else{if(n.followTail)Vk(e),e.scrollTop=e.scrollHeight;else{let t=n.anchorKey?e.querySelector(`[data-transcript-key="${CSS.escape(n.anchorKey)}"]`):null;e.scrollTop=t?Math.max(0,e.scrollTop+t.getBoundingClientRect().top-(n.anchorOffset??0)-e.getBoundingClientRect().top):n.scrollTop}ht.current=!1}});return()=>cancelAnimationFrame(r)},[L?.id,L?.messagesLoaded,I]),(0,u.useLayoutEffect)(()=>{ht.current=!0},[L?.id,L?.messagesLoaded,I]);let Pi=(0,u.useCallback)((e,t=!1,n=!1)=>{let r=mt.current;if(!r||ht.current||!gt.current)return;let i=Hk(e,ze.current[r]??{followTail:!0,scrollTop:0},t,n);yt.current=!i.followTail,ze.current[r]=i,vt(i),Wk({activeId:r,workspaceId:Mi.current,conversations:ze.current,readAt:Ve.current})},[]),Fi=L?.id??``,Ii=Fr[Fi]??{text:``,images:[],attachments:[],uploading:0},Li=Ii.text,Ri=Ii.images,zi=Ii.attachments,Bi=Object.keys(Ii.pendingSkills??{}).length>0,Vi=Ii.uploading,Hi=(e,t)=>Ir(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),Ui=(e,t)=>({...e,text:t,attachments:wO(t,e.attachments),pendingSkills:e.pendingSkills&&Object.fromEntries(Object.entries(e.pendingSkills).filter(([e])=>pf(t,e)))}),Wi=e=>Hi(Fi,t=>Ui(t,e)),Gi=(e,t,n,r)=>{let i=Wt();Hi(n,n=>{let r=Ui(n,t);return{...r,pendingSkills:{...r.pendingSkills,[e]:i}}});let a=t=>t[n]?.pendingSkills?.[e]===i?n:n.startsWith(`pending:`)?Object.keys(t).find(n=>t[n].pendingSkills?.[e]===i):void 0,o=t=>Ir(n=>{let r=a(n);if(!r)return n;let i=n[r],o={...i.pendingSkills};delete o[e];let s=t?[...i.attachments.filter(t=>t.id!==e),t]:i.attachments;return{...n,[r]:{...i,pendingSkills:o,attachments:s}}});Ne(`/api/skills/read?${new URLSearchParams({name:e,workspaceId:r})}`,{signal:AbortSignal.timeout(1e4)}).then(async t=>{if(!t.ok)throw Error(`读取技能失败`);let n=await t.json();if(typeof n.content!=`string`)throw Error(`读取技能失败`);o({kind:`skill`,id:e,name:n.name??e.slice(6),content:n.content})}).catch(()=>{a(Lr.current)&&Rs(`读取技能失败`,`error`),o()})},Ki=(e,t)=>Hi(L?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[qi,Ji]=(0,u.useState)({visible:!1,query:``,rect:null}),Zi=JSON.stringify([L?.id,L?.workspaceId,L?.cwd??``]),[Qi,$i]=(0,u.useState)(),ea=(0,u.useRef)(null),[R,oa]=(0,u.useState)(),sa=(0,u.useRef)(void 0),ca=(0,u.useRef)(``),la=!Si&&Qi?.scope===Zi?Qi:void 0,ua=e=>{let t=!$r.current&&!Si&&L?gf(e.value,e.selectionStart,e.selectionEnd):void 0,n=JSON.stringify([Zi,t]);return!t||ca.current===n?($i(void 0),!1):($i({scope:Zi,token:t,rect:e.getBoundingClientRect()}),Ji({visible:!1,query:``,rect:null}),!0)},da=()=>{ca.current=JSON.stringify([Zi,la?.token]),$i(void 0)};(0,u.useEffect)(()=>{$i(void 0),ca.current=``},[Zi]),(0,u.useLayoutEffect)(()=>{let e=sa.current;sa.current=void 0,e?.scope===Zi&&e.text===Li&&(pt.current?.focus(),pt.current?.setSelectionRange(e.caret,e.caret))},[Li,Zi]),(0,u.useEffect)(()=>{let e=()=>{let e=pt.current;e&&$i(t=>t?{...t,rect:e.getBoundingClientRect()}:void 0)};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let fa=e=>Hi(L?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),pa=ce.length>0?ce:De?[]:L?[L.id]:[],ma=(0,u.useMemo)(()=>pa.map(e=>ui.find(t=>t.id===e)).filter(e=>e!==void 0),[pa,ui]),ha=Oi?void 0:ma.filter(e=>e.id!==le).at(-1)?.id,ga=ma.some(e=>e.id===L?.id);(0,u.useEffect)(()=>{if(!Oe)return;let e=new Set(ui.map(e=>e.id));se(t=>{let n=t.ids.filter(t=>e.has(t)||re(t)),r=t.previewId&&(e.has(t.previewId)||re(t.previewId))?t.previewId:void 0;return n.length===t.ids.length&&r===t.previewId?t:{...t,ids:n,previewId:r}})},[Oe,ui]),(0,u.useEffect)(()=>{!Oe||ki||D?.startsWith(`pending:`)||re(D??k)||Yk(oe,D,D?void 0:Oi?.id,Vn||!D&&!Xe)},[D,Oe,oe,ki,Oi?.id,Vn,Xe]);let _a=(0,u.useCallback)(e=>{e&&se(t=>{if(t.touched.has(e))return t;let n=t.previewId===e?void 0:t.previewId;return{...t,previewId:n,touched:Kk(t.touched,e)}})},[]),va=(0,u.useCallback)(e=>{ve(de(e)),Un(!1),ye.current++,Ze(!1),O(e);let t=ui.find(t=>t.id===e)?.workspaceId;t&&A(t),$e(`session`),se(t=>{let n=t.emptied===!0,r=n?{...t,emptied:!1}:t;if(r.ids.includes(e))return r;let i=!n&&r.ids.length===0&&L?.id&&L.id!==e?[L.id]:[],a=[...r.ids,...i];if(r.touched.has(e))return{...r,ids:[...a,e]};let o=r.previewId?a.indexOf(r.previewId):-1,s=o>=0?a.map((t,n)=>n===o?e:t):[...a,e];return{...r,ids:s,previewId:e}})},[L,ui]);(0,u.useEffect)(()=>{if(!Oe)return;let t=new Map(e.conversations.filter(e=>!e.archivedAt).map(e=>[e.id,{status:e.status,hasPendingQuestion:!!e.hasPendingQuestion,title:e.title,workspaceId:e.workspaceId,parentConversationId:e.parentConversationId}]));if(!c.current){s.current=t,c.current=!0;return}let r=document.visibilityState===`visible`&&document.hasFocus(),a=n&&[`granted`,`native`].includes(i)&&!r;for(let[n,r]of t){let t=s.current.get(n);if(!t||r.parentConversationId||!a)continue;let i=!t.hasPendingQuestion&&r.hasPendingQuestion,o=r.status===`completed`&&t.status!==`completed`&&[`waiting`,`running`,`awaiting_background`].includes(t.status);if(!i&&!o)continue;let c=i?`question`:`completed`;if(cA(`${n}:${c}:${e.conversations.find(e=>e.id===n)?.updatedAt??``}`))try{let e=`${n}:${c}`,t=ra(i?`Super Pi · 等你回答`:`Super Pi · Agent 已完成`,{body:`${_e(r.workspaceId)} · ${i?`「${r.title}」需要你的回答。`:`「${r.title}」已完成。`}`,tag:`super-pi-${c}-${n}`});l.current.set(e,t),t.onclose=()=>{l.current.get(e)===t&&l.current.delete(e)},t.onclick=()=>{t.close(),l.current.delete(e),window.focus(),va(n)}}catch(e){console.warn(`[Super Pi] Browser notification could not be shown:`,e instanceof Error?e.message:`unknown error`)}}s.current=t},[e.conversations,Oe,n,i,va]);let ya=(0,u.useCallback)(e=>{e&&(_a(e),va(e))},[_a,va]),ba=e=>{e.startsWith(`pending:`)||ve(de(e)),Un(!0),ye.current++,Ze(!1),L&&ga&&se(e=>e.ids.length||e.emptied?e:{...e,ids:[L.id]}),A(e),O(void 0),$e(`session`),Tn(!1),Sn()},xa=(0,u.useCallback)((e,t=``)=>{ye.current++;let n={workspaceId:e,roomId:t};t&&Ye(r=>r.some(n=>n.workspaceId===e&&n.roomId===t)?r:[...r,n]),qe(n),Ze(!0),A(e),Tn(!1),$e(`group`),Sn()},[Sn]),Sa=(0,u.useCallback)((e,t)=>{nt(e,!0),t&&(ae(t=>t[e.workspaceId]?{...t,[e.workspaceId]:!1}:t),xa(e.workspaceId,e.id))},[xa,nt]);(0,u.useEffect)(()=>{let e=new Set;if(!n||i!==`granted`)aa(e);else{for(let t of Object.values(et))for(let n of t.rooms)if(!n.archivedAt)for(let t of n.cloneRequests??[]){if(t.status!==`pending`||t.automatic)continue;let r=`group-clone:${n.id}:${t.id}`;e.add(r),ia(r,`${_e(n.workspaceId)} · ${n.title} · 需要决定是否创建分身`,t.reason,I===`group`&<===n.id&&document.visibilityState===`visible`&&document.hasFocus(),()=>xa(n.workspaceId,n.id))}aa(e)}},[et,I,lt,xa,n,i]);let Ca=(0,u.useCallback)(e=>{tt(),rt(e)},[rt,tt]);async function wa(e,t){if(!ot.has(e.id)&&(t!==`delete`||window.confirm(`永久删除群聊「${e.title}」及其聊天记录?删除后无法恢复。`))){st(t=>new Set(t).add(e.id));try{let n=await rr(er(e.workspaceId,e.id),{action:t});if(t===`delete`)Ca({workspaceId:e.workspaceId,roomId:e.id});else{if(!n)throw Error(`服务没有确认群聊状态。`);tt(),nt(n),t===`archive`&&kt(t=>({...t,[e.workspaceId]:!1}))}}catch(e){Rs(e instanceof Error?e.message:`群聊操作失败。`,`error`)}finally{st(t=>new Set([...t].filter(t=>t!==e.id)))}}}let Ta=Xe&&I!==`session`,Ea=Ta?ct:L?.workspaceId??k,Da=Ea?.startsWith(`pending:`)?void 0:Ea,Oa=Da??(En===`repo`?T.workspaces.find(e=>e.id===Nn&&(!e.worktreeOf||!T.workspaces.some(t=>t.id===e.worktreeOf)))?.id??T.workspaces.find(e=>(On===`all`||h(e.id).server===On)&&(!e.worktreeOf||!T.workspaces.some(t=>t.id===e.worktreeOf)))?.id:void 0),ka=Oa?.startsWith(`pending:`)?void 0:Oa,Aa=Ta?``:L?.cwd??``;(0,u.useEffect)(()=>{Da&&ve(de(Da))},[Da]);let ja=En===`repo`&&(!L||Ta),Ma=JSON.stringify([Da,Aa]),[Na,Pa]=(0,u.useState)(),[Fa,Ia]=(0,u.useState)(50),La=Na?.scope===Ma?Na:void 0,Ra=!!La,za=La?.tabId;(0,u.useEffect)(()=>{Pa(e=>e?.scope===Ma?e:void 0)},[Ma]);let Ba=(0,u.useCallback)(e=>{Pa(t=>t?.scope===Ma?{...t,tabId:e}:t)},[Ma]),z=Em(Da,Aa,{navigation:ye,showingFile:I===`file`,splitFilePath:za?.startsWith(`file:`)?za.slice(5):void 0}),Va=gi(ka,ka===Da?Aa:``,te&&Oe),Ha=(0,u.useRef)(Va.refresh);Ha.current=Va.refresh;let Ua=(0,u.useRef)(z.setChangedFor),Wa=(0,u.useRef)(z.invalidateTree);Wa.current=z.invalidateTree;let Ga=(0,u.useRef)(Da);Ga.current=Da,(0,u.useEffect)(()=>{Ua.current=z.setChangedFor},[z.setChangedFor]);let[Ka]=(0,u.useState)(UO),[qa,Ja]=(0,u.useState)(Ka.tab),[Ya,Xa]=(0,u.useState)(Ka.byConversation),Za=(L?.id?Ya[L.id]:void 0)??qa;(0,u.useEffect)(()=>{try{Fn(HO,JSON.stringify({tab:qa,byConversation:Ya}))}catch{}},[qa,Ya]);let Qa=(0,u.useCallback)(e=>{Ja(e),L?.id&&Xa(t=>({...t,[L.id]:e}))},[L?.id]),$a=qn.order.filter(e=>qn.sides[e]===`left`),[eo,to]=(0,u.useState)(!1),[no,ro]=(0,u.useState)(!1),io=qn.order.filter(e=>e!==`sessions`&&qn.sides[e]===`right`),B=$a.includes(qn.leftView)?qn.leftView:`sessions`,ao=io.includes(Za)?Za:io[0],oo=qn.rightClosed||!ao,so=pr||!qn.leftClosed&&!eo&&B===`sessions`,co=(e,t=!1)=>{(e===`sessions`||qn.sides[e]===`left`)&&to(!1),pr?e===`sessions`?(Sn(),Tn(!0)):(Qa(e),_n(!1),Gn<=700&&yn(`rail`)):qn.sides[e]===`left`?Jn(n=>({...n,leftView:e,leftClosed:t&&!eo&&!n.leftClosed&&B===e})):e!==`sessions`&&(Qa(e),Jn(n=>({...n,rightClosed:t&&!n.rightClosed&&ao===e})))},lo=(e,t)=>{let n=qn.sides[e];if(t===`move`){let t=n===`left`?`right`:`left`;t===`left`&&to(!1),Jn(n=>({...n,sides:{...n.sides,[e]:t},...t===`left`?{leftView:e,leftClosed:!1}:{rightClosed:!1}})),t===`right`&&Qa(e),requestAnimationFrame(()=>{(document.querySelector(`[data-workbench-view="${e}"]`)??document.querySelector(`[data-workbench-panel-menu="${e}"]`))?.focus()})}else Jn(t===`pin`?t=>({...t,unpinned:t.unpinned.includes(e)?t.unpinned.filter(t=>t!==e):[...t.unpinned,e]}):r=>{let i=r.order.filter(e=>r.sides[e]===n&&!r.unpinned.includes(e)),a=i.indexOf(e),o=a>=0?i[a+(t===`up`?-1:1)]:void 0;if(!o||o===`sessions`)return r;let s=r.order.slice(),c=s.indexOf(e),l=s.indexOf(o);return[s[c],s[l]]=[s[l],s[c]],{...r,order:s}})},uo=(e,t)=>{e!==t&&Jn(n=>{if(n.sides[e]!==n.sides[t])return n;let r=n.order.slice(),i=r.indexOf(e),a=r.indexOf(t);return r.splice(i,1),r.splice(a,0,e),{...n,order:r}})},fo=JSON.stringify([Da,Aa]),[po,mo]=(0,u.useState)(),ho=po?.scope===fo?po:void 0,go=ho?.mode===`path`;(0,u.useEffect)(()=>{mo(e=>e?.scope===fo?e:void 0)},[fo]);let _o=(0,u.useCallback)((e,t,n)=>{ye.current++,mo(r=>r?.mode===e&&r.scope===fo&&r.directory===n?r:{mode:e,scope:fo,initialQuery:t,directory:n}),Tn(!1)},[fo]),vo=(0,u.useCallback)(()=>{ye.current++,mo(void 0)},[]),[yo,bo]=(0,u.useState)(),xo=(0,u.useRef)(0),So=e=>{va(e.conversationId),bo({hit:e,request:ye.current}),mo(void 0),Sn()};(0,u.useEffect)(()=>{if(!yo||yo.request===xo.current||L?.id!==yo.hit.conversationId||L?.messagesLoaded===!1||I!==`session`||!ga)return;let{hit:e,request:t}=yo,n=null,r,i=requestAnimationFrame(()=>{let i=ft.current;i&&ye.current===t&&(n=i.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`),n&&(xo.current=t,Vk(i),i.scrollTop+=n.getBoundingClientRect().top-i.getBoundingClientRect().top-24,Pi(i,!0),n.dataset.sessionSearchHit=`true`,n.tabIndex=-1,n.focus({preventScroll:!0}),r=setTimeout(()=>{n&&delete n.dataset.sessionSearchHit},2400)))});return()=>{cancelAnimationFrame(i),clearTimeout(r),n&&delete n.dataset.sessionSearchHit}},[L?.id,L?.messagesLoaded,I,Pi,ga,yo]);let[Co,wo]=(0,u.useState)(),[To,Eo]=(0,u.useState)(),[Do,Oo]=(0,u.useState)(w.diffs),ko=Do.paths,[Ao,V]=(0,u.useState)(w.gitDiffs),[H,U]=(0,u.useState)(w.gitDiffUrl);(0,u.useEffect)(()=>{if(!(!Oe||z.restoringWorkbench||re(D??k)))try{Rn({view:I,groups:Je,gitDiffs:Ao,gitDiffUrl:H,diffs:Do})}catch{}},[Oe,z.restoringWorkbench,D,k,I,Je,Ao,H,Do]);let W=I===`gitDiff`?Ao.find(e=>e.target.url===H):void 0,G=I===`gitDiff`?`diff`:I,jo=W?.target.path??To,Mo=(0,u.useCallback)(e=>{if(ja&&!e.commitHash)return;ye.current++;let t=document.activeElement instanceof HTMLElement?document.activeElement:void 0;V(n=>{let r=n.find(t=>t.target.url===e.url);if(!r){let r={target:e,workspaceId:Da,reading:{},revision:0,preview:!0,origin:t},i=Ra&&I===`gitDiff`?H:void 0,a=n.find(e=>e.preview&&e.target.url!==i);return a?n.map(e=>e===a?r:e):[...n,r]}if(e.commitHash)return n;let i=r.target.label===e.label?{...r.reading,snapshot:void 0}:{};return n.map(n=>n===r?{...n,target:e,reading:i,revision:n.revision+1,origin:t}:n)}),Ra?(Ba(`git-diff:${e.url}`),I===`gitDiff`&&H===e.url&&$e(`session`)):(U(e.url),$e(`gitDiff`)),Sn()},[Da,ja,H,I,Ba,Sn,Ra]),No=(0,u.useCallback)(()=>{!ga&&ha?va(ha):$e(`session`)},[ga,ha,va]);(0,u.useEffect)(()=>{let e=e=>{let t=et[e.workspaceId];return!t?.loaded||t.rooms.some(t=>t.id===e.roomId)},t=Je.filter(e);if(t.length!==Je.length&&Ye(t),I!==`group`||!Ke?.roomId||e(Ke))return;let n=t.filter(e=>e.workspaceId===Ke.workspaceId).at(-1);n?xa(n.workspaceId,n.roomId):No()},[et,Ke,Je,I,xa,No]),(0,u.useEffect)(()=>{I===`file`&&!z.active&&No()},[I,z.active,No]),(0,u.useEffect)(()=>{I===`diff`&&!To&&No()},[I,To,No]);let Po=(0,u.useRef)(`${Da??``}:${Aa}`);(0,u.useEffect)(()=>{let e=`${Da??``}:${Aa}`;Po.current!==e&&(Po.current=e,Oo({paths:[]}),Eo(void 0),$e(e=>e===`gitDiff`||e===`group`?e:`session`))},[Da,Aa]);let Fo=(0,u.useCallback)((e,t=!1)=>{ye.current++;let n=Ra&&!t;Oo(t=>{if(t.paths.includes(e))return t;let r=n&&I===`diff`&&To===t.previewPath;return{paths:t.previewPath&&!r?t.paths.map(n=>n===t.previewPath?e:n):[...t.paths,e],previewPath:e}}),n?(Ba(`diff:${e}`),I===`diff`&&To===e&&$e(`session`)):(Eo(e),$e(`diff`)),Sn(),Ja(`files`)},[To,I,Ba,Sn,Ra]),Io=I===`diff`?To:void 0,Lo=za?.startsWith(`diff:`)?za.slice(5):void 0,Ro=Lo&&Lo!==Io&&ko.includes(Lo)?Lo:void 0,K=sA(Da,Aa,Io),zo=sA(Da,Aa,Ro),[q,Bo]=(0,u.useState)(`server`),[Vo,Ho]=(0,u.useState)(`server`),Uo=e=>{let t=z.open.find(t=>t.path===e);return t?.dirty?t.content:void 0},Wo=(0,u.useCallback)(e=>{ye.current++,z.setActivePath(e),$e(`file`),Ja(`files`)},[z.setActivePath]),Go=(0,u.useCallback)(async(e,t,n=!1,r=!1,i=!1,a)=>{let o=++ye.current,s=()=>ye.current===o,c=Ra&&!i,l=await z.openFile(e,{preview:!n,activate:!c,isCurrent:s,throwOnError:r,requireText:a!==void 0});if(l&&s())return n&&z.pinFile(l),wo(t?{scope:fo,path:l,line:t,column:a,request:o}:void 0),c?(Ba(`file:${l}`),I===`file`&&z.activePath===l&&$e(`session`)):$e(`file`),Sn(),l},[z.openFile,z.pinFile,z.activePath,fo,I,Ba,Sn,Ra]),Ko=(0,u.useCallback)((e,t)=>{Go(e,void 0,t)},[Go]),qo=L&&!Si?(e,t)=>{let n=Li&&!/\s$/u.test(Li)?`${Li} `:Li,r=_f(n,{start:n.length,end:n.length,query:``},{path:e,kind:t?`directory`:`file`});sa.current={scope:Zi,...r},_a(L.id),va(L.id),Sn(),Wi(r.text)}:void 0,Jo=(e,t)=>{ye.current+=1,Oo(t=>({paths:t.paths.filter(t=>!Nf(t,e)),previewPath:t.previewPath&&!Nf(t.previewPath,e)?t.previewPath:void 0})),To&&Nf(To,e)&&Eo(void 0),Pa(n=>{let r=n?.tabId?.startsWith(`file:`)?n.tabId.slice(5):void 0;return n&&r&&Nf(r,e)?{...n,tabId:`file:${t}${r.slice(e.length)}`}:n}),wo(n=>n?.scope===fo&&Nf(n.path,e)?{...n,path:t+n.path.slice(e.length)}:n)};(0,u.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.altKey||e.isComposing)return;let t=e.key.toLowerCase();e.shiftKey&&t===`f`?(e.preventDefault(),_o(`content`)):!e.shiftKey&&t===`p`&&(e.preventDefault(),_o(`path`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[_o]);let Yo=(0,u.useMemo)(()=>ma.map(e=>({id:`session:${e.id}`,workspaceId:e.workspaceId,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:!0,preview:le===e.id,badge:(0,F.jsx)(tk,{state:$O(e,ZO(e,hn),Ve.current[e.id],T.conversations)})})),[ma,hn,T.conversations,He,le]),Xo=(0,u.useMemo)(()=>z.open.map(e=>({id:`file:${e.path}`,workspaceId:z.ownerWorkspaceId,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,preview:e.preview,badge:e.dirty?(0,F.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[z.ownerWorkspaceId,z.open]),Zo=(0,u.useMemo)(()=>ko.map(e=>({id:`diff:${e}`,workspaceId:Da,rawId:e,kind:`diff`,label:e.split(/[\\/]/).pop()||e,title:`${e}(改动)`,closable:!0,preview:Do.previewPath===e,icon:(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`±`})})),[Da,ko,Do.previewPath]),Qo=(0,u.useMemo)(()=>[...Yo,...[...Je,...I===`group`&&Ke&&!lt?[Ke]:[]].flatMap(e=>{let t=T.workspaces.find(t=>t.id===e.workspaceId&&!t.closedAt);if(!t)return[];let n=et[e.workspaceId]?.rooms.find(t=>t.id===e.roomId),r=e.roomId?n?.title??`群聊`:`新建群聊`,i=n?ir(n,it[n.id]):`idle`,a=n?ar(n,it[n.id],Ve.current[Qn(e)]):`idle`,o=a===`completed`?`讨论已完成,有新回复未读`:a===`unread`?`有新回复未读`:GO[i],s=`${r} · ${t.name}${i===`idle`?``:` · ${o}`}`;return[{id:Qn(e),workspaceId:e.workspaceId,label:r,title:s,closable:!0,icon:(0,F.jsx)(Gr,{name:`group`}),badge:(0,F.jsx)(tk,{state:a,label:o})}]}),...Xo,...Zo,...Ao.map(({target:e,preview:t,workspaceId:n})=>({id:`git-diff:${e.url}`,workspaceId:n,kind:`diff`,closable:!0,preview:t,label:`${e.path.split(/[\\/]/).pop()||e.path} (${e.label})`,title:`${e.path} · ${e.comparison}`,icon:(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`±`})}))],[Yo,Xo,Zo,Ao,Je,et,it,Ke,lt,I,T.workspaces,He]),$o=I===`group`&&Ke?Qn(Ke):I===`file`&&z.activePath?`file:${z.activePath}`:I===`diff`&&To?`diff:${To}`:W?`git-diff:${W.target.url}`:ga&&L?.id?`session:${L.id}`:void 0,es=(0,u.useRef)(!1),ts=(0,u.useRef)(void 0);(0,u.useLayoutEffect)(()=>{let e=es.current;if(es.current=!1,ts.current!==z.restoredActive&&(ts.current=z.restoredActive,!we&&z.restoredActive&&z.restoredActive===z.activePath&&I!==`file`&&I!==`gitDiff`&&I!==`group`)){$e(`file`);return}if(!e&&Oe&&le&&$o!==`session:${le}`&&ui.some(e=>e.id===le)&&se(e=>{if(e.previewId!==le)return e;let t=e.ids.filter(e=>e!==le);return{...e,ids:t,previewId:void 0,emptied:t.length===0}}),!e)for(let e of z.open)e.preview&&$o!==`file:${e.path}`&&za!==`file:${e.path}`&&z.discardPreview(e.path);let t=Do.previewPath;!e&&t&&$o!==`diff:${t}`&&za!==`diff:${t}`&&Oo(e=>e.previewPath===t?{paths:e.paths.filter(e=>e!==t)}:e);let n=e=>{let t=`git-diff:${e.target.url}`;return!e.preview||t===$o||t===za};!e&&Ao.some(e=>!n(e))&&V(e=>e.filter(n)),Oe&&I===`session`&&L&&L.id===D&&!ga&&!z.restoringWorkbench&&ha&&va(ha)},[$o,Oe,le,z.open,z.activePath,z.restoredActive,z.discardPreview,Do.previewPath,I,L?.id,D,ga,z.restoringWorkbench,ha,va,ui,we,za,Ao]);let ns=(0,u.useCallback)(e=>{if(e.startsWith(`group:`)){let t=$n(e);t&&xa(t.workspaceId,t.roomId)}else if(e.startsWith(`file:`)){let t=e.slice(5);Wo(t)}else if(e.startsWith(`diff:`)){ye.current++;let t=e.slice(5);Eo(t),$e(`diff`)}else if(e.startsWith(`git-diff:`))ye.current++,U(e.slice(9)),$e(`gitDiff`);else if(e.startsWith(`session:`)){let t=e.slice(8);va(t)}},[Wo,va,xa]),rs=Qo.find(e=>e.id===$o),is=I===`file`?z.active:void 0,as=(0,u.useMemo)(()=>{if(!Oe||!rs||rs.id.startsWith(`session:pending:`))return;let{id:e,label:t}=rs;if(I!==`group`||lt&&dt){if(I===`session`)return e.startsWith(`session:`)?{key:e,tabId:e,title:t}:void 0;if(I===`file`||I===`diff`){if(!Da||z.restoringWorkbench||I===`file`&&!is||I===`diff`&&!To)return;let n={workspaceId:Da,cwd:Aa,conversationId:L?.id},r=is&&{path:is.path,name:is.name,text:null,...is.assetTicket||/^(?:[a-z]:[\\/]|[\\/])/i.test(is.path)?{openLink:!0}:{}};return{key:JSON.stringify([n.workspaceId,n.cwd,e]),tabId:e,title:t,scope:n,file:r}}return{key:e,tabId:e,title:t}}},[Oe,rs,I,Da,Aa,L?.id,z.restoringWorkbench,To,is?.path,is?.name,is?.assetTicket,lt,dt]);(0,u.useEffect)(()=>{!we&&as&&(Ee.current.delete(as.key),Ce(e=>Zm(e,as)))},[as,we]);let os=e=>{let t=ui.filter(t=>t.workspaceId===e.workspaceId&&(t.cwd??``)===e.cwd);return t.find(t=>t.id===e.conversationId)??t[0]},ss=e=>{if(e.key===as?.key||Ee.current.has(e.key))return!1;if(e.tabId.startsWith(`session:`))return ui.some(t=>`session:${t.id}`===e.tabId);let t=$n(e.tabId);if(t)return T.workspaces.some(e=>e.id===t.workspaceId&&!e.closedAt)&&!!et[t.workspaceId]?.rooms.some(e=>e.id===t.roomId);if(!e.scope)return Qo.some(t=>t.id===e.tabId);let{scope:n}=e;return T.workspaces.some(e=>e.id===n.workspaceId)?n.workspaceId===Da&&n.cwd===Aa||!!os(n)||!n.cwd&&!ui.some(e=>e.workspaceId===n.workspaceId):!1},cs=Qm(Se,Se.index+ +!as,-1,ss),ls=Qm(Se,Se.index,1,ss),us=e=>{let t=e<0?cs:ls;we||t<0||Te({index:t,direction:e,ticket:++ye.current,stage:`start`})},ds=(0,u.useRef)(us);ds.current=us,(0,u.useEffect)(()=>{let e=e=>{(e.button===3||e.button===4)&&(e.preventDefault(),e.type===`mouseup`&&ds.current(e.button===3?-1:1))};for(let t of[`mousedown`,`mouseup`,`auxclick`])window.addEventListener(t,e,!0);return()=>{for(let t of[`mousedown`,`mouseup`,`auxclick`])window.removeEventListener(t,e,!0)}},[]),(0,u.useEffect)(()=>{let e=we;if(!e)return;if(ye.current!==e.ticket){Te(void 0);return}let t=Se.entries[e.index];if(t.key===as?.key){Ce(t=>({...t,index:e.index})),Te(void 0);return}let n=(t=e.ticket)=>{let n=Qm(Se,e.index,e.direction,ss);Te(n<0?void 0:{...e,index:n,ticket:t,stage:`start`})};if(!ss(t)){n();return}let r=t.scope;if(r&&(r.workspaceId!==Da||r.cwd!==Aa)){if(e.stage!==`start`){n();return}let t=os(r);t?va(t.id):ba(r.workspaceId),Te({...e,stage:`scope`,ticket:ye.current});return}if(e.stage===`opening`||r&&z.restoringWorkbench)return;Tn(!1),Sn();let i=t.file;if(i&&!z.open.some(e=>e.path===i.path)){let r=Go(i,void 0,!1,!0,!0),a=ye.current;Te({...e,stage:`opening`,ticket:a}),r.then(e=>{!e&&ye.current===a&&Te(void 0)}).catch(e=>{ye.current===a&&(e instanceof $p&&e.status===404?(Ee.current.add(t.key),n(a)):(Rs(Or(e instanceof Error?e.message:void 0,`无法打开导航历史中的文件。`),`error`),Te(void 0)))})}else t.tabId.startsWith(`diff:`)&&!Qo.some(e=>e.id===t.tabId)?Fo(t.tabId.slice(5),!0):ns(t.tabId),Te({...e,stage:`opening`,ticket:ye.current})});let fs=(0,u.useCallback)(e=>{if(e.startsWith(`session:`))ya(e.slice(8));else if(e.startsWith(`file:`))z.pinFile(e.slice(5));else if(e.startsWith(`diff:`)){let t=e.slice(5);Oo(e=>e.previewPath===t?{paths:e.paths}:e)}else e.startsWith(`git-diff:`)&&V(t=>t.map(t=>t.preview&&`git-diff:${t.target.url}`===e?{...t,preview:!1}:t))},[ya,z.pinFile]),ps=Qo.filter(e=>e.kind===`file`||e.kind===`diff`),ms=Ra&&za!==$o?ps.find(e=>e.id===za):void 0,hs=e=>{ps.some(t=>t.id===e)&&(ye.current++,Ba(e),e===$o&&No())},gs=()=>{if(Ra){ye.current++,ms&&fs(ms.id),Pa(void 0);return}ye.current++;let e=ps.find(e=>e.id===$o)??ps.at(-1);Pa({scope:Ma,tabId:e?.id}),e&&e.id===$o&&(L&&!ga?va(L.id):No())},_s=(0,u.useCallback)(e=>{let t=pa.indexOf(e);if(t<0)return;let n=pa.filter(t=>t!==e);if(se(t=>({...t,ids:t.ids.filter(t=>t!==e),previewId:t.previewId===e?void 0:t.previewId,emptied:n.length===0||t.emptied})),L?.id!==e||I!==`session`)return;ye.current++;let r=n[Math.min(t,n.length-1)];if(r)O(r);else if(z.open.length>0){let e=z.activePath&&z.open.some(e=>e.path===z.activePath)?z.activePath:z.open[0].path;z.setActivePath(e),$e(`file`)}else ko.length>0?(Eo(ko[0]),$e(`diff`)):Ao.length>0?(U(Ao[0].target.url),$e(`gitDiff`)):O(void 0)},[pa,L,z,ko,Ao,I]),vs=(0,u.useCallback)(e=>{if(e.startsWith(`group:`)){let t=Je.filter(t=>Qn(t)!==e);if(Ye(t),I===`group`&&$o===e){let e=t.filter(e=>e.workspaceId===ct).at(-1);e?xa(e.workspaceId,e.roomId):No()}}else if(e.startsWith(`file:`)){let t=e.slice(5);z.closeFile(t),I===`file`&&z.activePath===t&&z.open.length<=1&&ye.current++}else if(e.startsWith(`diff:`)){let t=e.slice(5);Oo(e=>({paths:e.paths.filter(e=>e!==t),previewPath:e.previewPath===t?void 0:e.previewPath})),I===`diff`&&To===t&&(ye.current++,Eo(void 0),No())}else if(e.startsWith(`session:`)){let t=e.slice(8);_s(t)}else if(e.startsWith(`git-diff:`)){let t=e.slice(9),n=Ao.findIndex(e=>e.target.url===t);if(n<0)return;let r=Ao.filter(e=>e.target.url!==t);V(r);let i=document.activeElement?.getAttribute(`data-diff-tab-close`)===e;if(W?.target.url===t){ye.current++;let e=r[Math.max(0,n-1)];U(e?.target.url),e||No()}i&&requestAnimationFrame(()=>{let e=document.querySelector(`.chat-tab-strip [role="tab"][aria-selected="true"]`),t=Ao[n].origin;(e??(t?.getClientRects().length?t:void 0)??document.querySelector(`[data-workspace-welcome-create]:not(:disabled)`))?.focus()})}},[z,_s,To,I,Ao,W?.target.url,No,ct,Je,$o,xa]),ys=z.active,bs=JSON.stringify([Da,Aa,ys?.path]),[xs,Ss]=(0,u.useState)(),Cs=(0,u.useCallback)(e=>{Ss(t=>e?{scope:bs,position:e}:t?.scope===bs?void 0:t)},[bs]),ws=xs?.scope===bs?xs.position:void 0,[Ts,Es]=(0,u.useState)(),Ds=(0,u.useRef)(null),[J,Os]=(0,u.useState)(``),[ks,As]=(0,u.useState)({}),js=T.workspaces.find(e=>e.id===Da),Ms=T.workspaces.find(e=>e.id===ka),Ns=(e,t)=>{let n=e&&cm(e.path),r=e&&(e.assetTicket||n?(0,F.jsx)(`span`,{className:`file-editor-path`,title:n??e.path,children:n??e.path}):(0,F.jsx)(Sf,{root:Aa.split(`/`).at(-1)||js?.name||`工作目录`,path:e.path,reveal:(e,t)=>{co(`files`),z.locatePath(e,t)}})),i=Co?.scope===fo&&Co?.path===e?.path?Co:void 0,a=e&&(!e.view||e.view===`table`)&&(0,F.jsx)(xm,{file:e,state:z.saves[e.path]?.state??`idle`,message:z.saves[e.path]?.message??``,external:z.external[e.path]===!0,jumpToLine:i,languageOverride:ks[JSON.stringify([Da,Aa,e.path])],onChange:t=>z.updateBuffer(e.path,t),onSave:()=>void z.save(e.path,!1),onReload:()=>void z.reload(e.path),onOverwrite:()=>void z.save(e.path,!0),workspaceId:Da,cwd:Aa,navigation:e.view?void 0:r,embedded:!!e.view,onPosition:t?Cs:void 0});return(0,F.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":e?.path,"data-file-view-kind":`editor`,children:e?.view&&Da?(0,F.jsx)(Df,{workspaceId:Da,cwd:n?``:Aa,path:n??e.path,name:e.name,kind:e.view,content:e.content,version:e.etag,source:a||void 0,external:z.external[e.path],navigation:r,assetTicket:e.assetTicket,onReload:()=>void z.reload(e.path),sourceRequest:i?.request},JSON.stringify([Da,Aa,e.path])):a||(0,F.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})})},Ps=e=>ja&&!e.target.commitHash?(0,F.jsx)(`div`,{className:`chat-file-view`,role:`status`,children:(0,F.jsx)(`p`,{className:`rail-empty`,children:`请选择具体 session 以确定工作区,再查看或编辑工作区差异。`})}):(0,F.jsx)(`div`,{className:`chat-file-view chat-git-diff`,"data-main-diff-view":e.target.path,"data-file-view-kind":`diff`,children:(0,F.jsx)(u.Suspense,{fallback:(0,F.jsx)(`p`,{className:`rail-empty`,role:`status`,children:`正在读取差异…`}),children:(0,F.jsx)(fk,{tab:e,dark:ul!==`github-light`&&ul!==`solarized-light`},JSON.stringify([e.target.url,e.revision]))})}),Fs=(e,t)=>{let n=t?zo:K;return(0,F.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":e??``,"data-file-view-kind":`diff`,children:(0,F.jsx)(wm,{diff:n.diff,loading:n.loading,error:n.error,bufferContent:Uo(e),mode:t?Vo:q,onMode:t?Ho:Bo})})},Is=()=>{let e=ms?.id;if(!e)return null;if(e.startsWith(`file:`))return Ns(z.open.find(t=>`file:${t.path}`===e),!1);if(Ro)return Fs(Ro,!0);let t=Ao.find(t=>`git-diff:${t.target.url}`===e);return t?Ps(t):null},Ls=L?.id;(0,u.useEffect)(()=>{Ls&&!Ls.startsWith(`pending:`)&&Ks({type:`conversation.select`,conversationId:Ls})},[Ls]);let Rs=(e,t=`info`)=>{if(!e)return;let n=++ei.current;qt(r=>[...r,{key:n,text:e,kind:t}]),ti.current.push(window.setTimeout(()=>qt(e=>e.filter(e=>e.key!==n)),7e3))},zs=(e,t=``)=>{if(js&&js.id===e&&Aa===t)return e=>{let n=Qe(e,{root:js.path,cwd:t,origin:window.location.origin});if(n)return{title:n.artifact?n.path:`${n.path}:${n.line}${n.column?`:${n.column}`:``}`,open:()=>{let e=Rm(n.path,t);Go(e,n.artifact?void 0:n.line,!1,!0,!1,n.artifact?void 0:n.column??1).catch(t=>Rs(`打不开「${e.name}」:${t instanceof Error?t.message:`文件不可用`}`,`error`))}}}},Bs=zs(L?.workspaceId,L?.cwd),Vs=async e=>{if(!e){r(!1);try{window.localStorage.setItem(`super-pi.browser-notifications`,`disabled`)}catch{}}else if(typeof window>`u`||typeof Notification>`u`&&!window.superPiDesktop?.notifications)a(`unsupported`);else if(!window.isSecureContext&&!window.superPiDesktop?.notifications)a(`insecure`);else try{let e=await na();a(e);let t=e===`granted`||e===`native`;r(t);try{window.localStorage.setItem(`super-pi.browser-notifications`,t?`enabled`:`disabled`)}catch{}}catch{a(ta()),r(!1),Rs(`请求浏览器通知权限失败,请检查站点权限后重试。`,`error`)}};(0,u.useEffect)(()=>{let e=()=>{for(let e of l.current.values())e.close();l.current.clear()},t=()=>{if(a(ta()),document.visibilityState===`visible`&&document.hasFocus()){e();try{window.localStorage.setItem(`super-pi.browser-notification-focus`,String(Date.now()))}catch{}}},n=t=>{t.key===`super-pi.browser-notification-focus`&&e()};window.addEventListener(`focus`,t);let r=!1,i;return navigator.permissions?.query&&navigator.permissions.query({name:`notifications`}).then(e=>{r||(i=e,e.addEventListener(`change`,t),t())}).catch(()=>{}),window.addEventListener(`storage`,n),document.addEventListener(`visibilitychange`,t),()=>{r=!0,i?.removeEventListener(`change`,t),window.removeEventListener(`focus`,t),window.removeEventListener(`storage`,n),document.removeEventListener(`visibilitychange`,t),e()}},[]),(0,u.useEffect)(()=>{let e=L?.id,t=L?.agentNotice;e&&t&&!ii.current.has(e)&&(ii.current.add(e),Rs(t,`info`))},[L?.id,L?.agentNotice]);let Hs=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Us=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Ws=(e,t)=>{if(t.method===`notify`)Rs(t.message||t.title,t.notifyType??`info`);else if(t.blocking||t.method===`setStatus`||t.method===`setWidget`||t.method===`setTitle`){let n=e=>e.blocking?e.requestId:e.statusKey??e.widgetKey??``,r=t.method===`setStatus`&&t.statusText===void 0||t.method===`setWidget`&&t.widgetLines===void 0||t.method===`setTitle`&&!t.title;Gt(i=>{let a=i.filter(r=>r.conversationId!==e||r.request.method!==t.method||n(r.request)!==n(t));return r?a:[...a,{conversationId:e,request:t}]})}else t.method===`set_editor_text`&&e===ni.current&&Wi(t.text??``)},Gs=(e,t,n)=>{Gt(n=>n.filter(n=>!(n.conversationId===e&&n.request.blocking&&n.request.requestId===t)));let r=uO[n];r&&Rs(r,`warning`)};(0,u.useEffect)(()=>{let e=!1;return(()=>{if(e)return;let t=new Le(ni.current);Re.current=t,t.onopen=()=>{if(!e){ee(!0);for(let e of[{type:`stream.configure`,coalesce:!0},{type:`catalog.fetch`,conversationId:ni.current},...Mi.current?[{type:`prompt.catalog.fetch`,workspaceId:Mi.current}]:[],{type:`catalog.fetchAll`},{type:`agent.catalog.fetch`},{type:`subagent.catalog.fetch`}])t.canSend(e)&&t.send(JSON.stringify(e))}},t.onserveropen=e=>{for(let n of m.current)n.retry&&n.command&&n.serverId===e&&t.canSend(n.command)&&t.send(JSON.stringify({...n.command,operationRequestId:n.id}))},t.ondisconnect=(t,n)=>{if(e)return;let r=pE(m.current.filter(e=>e.serverId===t));for(let e of r.failed)e.onFailure?.(`${P(t)} 连接中断`);m.current=m.current.filter(e=>!r.failed.includes(e)),p(m.current),Rs(`${P(t)} 连接中断${n?`(code ${n.code}${n.reason?` · ${n.reason}`:``})`:``},正在自动重连。`,`warning`)},t.onmessage=({data:t})=>{if(e)return;let n=JSON.parse(t);if(n.type===`group.activity`)at(n);else if(n.type!==`message.delta`&&n.type!==`message.thinking`&&Tt(),n.type===`message.accepted`){up(n.conversationId,n.clientId);for(let e of m.current)e.command?.conversationId===n.conversationId&&e.command?.clientId===n.clientId&&(e.receipt=!0)}else if(n.type===`exec.output`){let e=bt.current.get(n.sessionId),t=e?.raw??e?.text??``,r=n.offset===void 0?void 0:n.offset-n.data.length;if(!n.replace&&e?.offset!==void 0&&n.offset!==void 0&&n.offset<=e.offset)return;let i=e&&(r===void 0||e.offset!==void 0&&e.offset>=r),a=r!==void 0&&e?.offset!==void 0?Math.max(0,e.offset-r):0,o=(n.replace||!i?n.data:t+n.data.slice(a)).slice(-DD),s=OD(o);bt.current.delete(n.sessionId),bt.current.set(n.sessionId,{text:s.slice(-DD),raw:o,offset:n.offset,truncated:n.offset===void 0?n.truncated||o.length>128e3:n.offset>o.length}),bt.current.size>64&&bt.current.delete(bt.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:n.sessionId}))}else if(n.type===`run.stopping`)Dr(e=>{let t=new Set(e);return t.add(n.conversationId),t});else if(n.type!==`exec.exit`){if(n.type.startsWith(`terminal.`))xt.current?.(n);else if(n.type===`conversation.autoRename.result`){let e=Pr.current.get(n.conversationId);e&&(Pr.current.delete(n.conversationId),n.ok?e.resolve(n.title):e.reject(Error(n.error)))}else if(n.type===`message.thinking`)Et(n);else if(n.type===`state`){Tt(),ri.current=!1;let e=ni.current,t=!!(e&&ai.current.has(e)),r=!(!e||n.state.conversations.some(t=>t.id===e)),i=t&&r&&e&&oi.current.has(e)?{...n.state,conversations:[oi.current.get(e),...n.state.conversations]}:n.state;e&&!r&&(ai.current.delete(e),oi.current.delete(e)),m.current=m.current.filter(e=>!e.accepted?.(i)||i.sendReceipts&&e.retry&&!e.receipt?!0:(e.retry&&typeof e.command?.conversationId==`string`&&typeof e.command.clientId==`string`&&up(e.command.conversationId,e.command.clientId),!1)),p(m.current),Dr(e=>{let t=new Set(e);for(let e of[...t]){let n=i.conversations.find(t=>t.id===e);(!n||n.status!==`running`&&n.status!==`waiting`)&&t.delete(e)}return t}),i.extensionUi&&Gt(i.extensionUi),i.stoppingConversationIds&&Dr(new Set(i.stoppingConversationIds)),d(i),ke(!0),ee(!0);let a=m.current.filter(e=>e.key===`create-workspace`).map(e=>e.temporaryId);A(e=>{if(!e&&Wn.current)return;if(e&&(re(e)||i.workspaces.some(t=>t.id===e)||a.includes(e)))return e;let t=_.current?.workspaceId;return t&&i.workspaces.some(e=>e.id===t)?t:i.workspaces[0]?.id})}else if(n.type===`message.delta`)Et(n);else if(n.type===`queue.withdrawn`){yi(e=>[...e.filter(e=>e.conversationId!==n.conversationId).slice(-9),{id:`withdrawn_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,conversationId:n.conversationId,actor:n.actor,withdrawn:n.withdrawn}]);let e=n.withdrawn.slice(0,2).map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,24)}」`).join(`、`),t=n.actor===`agent`?`上级 Agent 已撤回`:`已撤回`;Rs(`${t} ${n.withdrawn.length} 条排队消息:${e}${n.withdrawn.length>2?`…`:``}`,`info`)}else if(n.type===`message.revert.result`)Rl(void 0),Tr(void 0),n.ok||(console.error(`[Super Pi Error] revert failed:`,n.message),ne(n.message));else if(n.type===`operation.result`){let e=m.current.find(e=>e.id===n.requestId),t=e?.retry?e.command:void 0;if(t&&up(t.conversationId,t.clientId),m.current=m.current.filter(e=>e.id!==n.requestId),p(m.current),e?.temporaryId){let t=e.temporaryId;if(e.key===`create-workspace`&&n.ok&&n.entityId){let r=n.entityId;d(n=>{if(n.workspaces.some(e=>e.id===r))return n;let i=e.apply(n).workspaces.find(e=>e.id===t);return i?{...n,workspaces:[...n.workspaces,{...i,id:r}]}:n})}else if(n.ok&&n.entityId){let e=n.entityId,r=si.current.get(t);if(r&&oi.current.set(e,{...r,id:e}),ai.current.add(e),r){let t={...r,id:e};d(n=>n.conversations.some(t=>t.id===e)?n:{...n,conversations:[t,...n.conversations]})}Ir(n=>{let r=n[t];if(!r)return n;let i=n[e],a={...n};return a[e]=i?{...i,text:r.text||i.text,images:r.images.length?r.images:i.images,attachments:r.text?r.attachments:i.attachments,pendingSkills:r.text?r.pendingSkills:i.pendingSkills,uploading:r.uploading+i.uploading}:r,delete a[t],a}),si.current.delete(t)}O(r=>r===t?n.ok?n.entityId:e.previousActiveId:r),se(e=>qk(e,t,n.ok&&n.entityId?n.entityId:void 0)),A(r=>r===t?n.ok?n.entityId:e.previousWorkspaceId:r),!n.ok&&e.key===`create-workspace`&&Mi.current===t&&O(t=>t??e.previousActiveId)}if(!n.ok){if(console.error(`[Super Pi Error] operation failed:`,n.message),!e?.receipt){if(e?.onFailure)e.onFailure(n.message);else if(t){let e=t.images??[],r=wO(t.content,t.attachments);Vr(i=>[...i,{id:t.clientId,conversationId:t.conversationId,content:t.content,images:e,attachments:r,reason:n.message}]),Hi(t.conversationId,n=>n.text||n.images.length||n.attachments.length?n:{...n,text:t.content,images:e,attachments:r})}}let r=n.message??`操作失败`;ne(r),e?.onFailure||Rs(Or(r),`error`)}}else n.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):n.type===`files.changed`?(Ua.current(n.workspaceId,n.changes,n.dropped),n.workspaceId===Ga.current&&Ha.current()):n.type===`files.invalidated`?(Wa.current(n.workspaceId,n.paths),n.workspaceId===Ga.current&&Ha.current()):n.type===`error`?(console.error(`[Super Pi Error]`,n.message),n.recordedTurnFailure||(ne(n.message),Rs(Or(n.message),`error`),ri.current&&=!1)):n.type===`extension.ui`?Ws(n.conversationId,n.request):n.type===`extension.ui.closed`?Gs(n.conversationId,n.requestId,n.reason):n.type===`model.catalog`?(!n.conversationId||n.conversationId===ni.current)&&Yt(n.catalog):n.type===`model.catalog.all`?Zt(n.catalog):n.type===`providers.list`?($t(n.providers),tn(n.apis)):n.type===`agent.catalog`?((n.sourceServerId??fe())===fe()&&rn(n.catalog),(n.sourceServerId??fe())===pe()&&un(n.catalog)):n.type===`prompt.catalog`?Ht(n.catalog):n.type===`subagent.catalog`?((n.sourceServerId??fe())===fe()&&on(n.catalog),(n.sourceServerId??fe())===pe()&&pn(n.catalog)):n.type===`server.version`?cn(n.version):n.type===`subagent.event`?d(e=>({...e,subagentRuns:Hs(e.subagentRuns??[],n.run)})):n.type===`workflow.event`?d(e=>({...e,workflows:Us(e.workflows??[],n.workflow)})):n.type===`message.tools`?d(e=>({...e,conversations:e.conversations.map(e=>e.id===n.conversationId?{...e,messages:e.messages.map(e=>e.id===n.messageId?{...e,toolCalls:n.toolCalls}:e)}:e)})):n.type===`conversation.fork.result`&&(Kl(e=>e===n.conversationId?void 0:e),Rs(n.ok?`已从「${n.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${n.messagesCopied?`复制了 ${n.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${Or(n.message)}`,n.ok?`info`:`error`))}}})(),()=>{e=!0,Tt();for(let e of ti.current)window.clearTimeout(e);Re.current?.close()}},[Et,Tt,at]);let Ks=(0,u.useCallback)(e=>{if(!Re.current?.canSend(e))return!1;try{return Re.current.send(JSON.stringify(e)),!0}catch(e){return Rs(e instanceof Error?e.message:`服务器未连接`,`error`),!1}},[]),qs=(0,u.useCallback)(e=>{xe({id:e,ticket:++ye.current});let t=ni.current;t?.startsWith(`pending:`)||Ks({type:`state.subscribe`,...t?{conversationId:t}:{}}),Sn()},[Ks,Sn]);(0,u.useEffect)(()=>{if(!be)return;if(be.ticket!==ye.current){xe(void 0);return}let e=di.find(e=>e.id===be.id);e&&T.workspaces.some(t=>t.id===e.workspaceId)&&(xe(void 0),va(e.id),A(e.workspaceId))},[be,di,T.workspaces,va]),(0,u.useEffect)(()=>{if(!te)return;let e=L?.id;e?.startsWith(`pending:`)||Ks({type:`state.subscribe`,...e?{conversationId:e}:{}})},[L?.id,te,Ks]);let Y=(e,t,n,r,i,a,o)=>{let s=Re.current?.canSend(e)===!0,c=fE(e);if(m.current.some(e=>e.key===t)||!s&&!c)return!1;if(c&&!lp(e))return Rs(`浏览器无法保存待发消息,正文仍在输入框。`,`error`),!1;let l=Wt(),u=C(e),d=[...u][0]??e._server??fe(),f={id:l,key:t,serverId:d,apply:e=>u.size||fe()===d?n(e):e,temporaryId:r,previousActiveId:ni.current,previousWorkspaceId:Mi.current,onFailure:i,accepted:a,...o?{expiresAt:Date.now()+o}:{},...c?{retry:!0,command:e}:{}};return m.current=[...m.current,f],p(m.current),s&&Re.current.send(JSON.stringify({...e,operationRequestId:l})),!0},Js=e=>Ks({...e,_server:pe()}),Ys=(e,...t)=>Y({...e,_server:pe()},...t),Xs=(e,t)=>{Ks({type:`conversation.childLock`,conversationId:e,unlocked:t})||Rs(t?`连接断开,这个子会话没有解锁,请重试`:`连接断开,这个子会话没有上锁,请重试`,`error`)},Zs=e=>{if(!e)return;let t=`message_${Wt()}`;Y({type:`message.send`,conversationId:e,content:$D,clientId:t},`continue-truncated:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===e?{...t,warning:void 0}:t)}),void 0,void 0,void 0)};(0,u.useEffect)(()=>{let e=f.flatMap(e=>e.expiresAt?[e.expiresAt]:[]);if(!e.length)return;let t=window.setTimeout(()=>{let e=m.current.filter(e=>e.expiresAt&&e.expiresAt<=Date.now());if(e.length){m.current=m.current.filter(t=>!e.includes(t)),p(m.current);for(let t of e)t.onFailure?.(`打断请求超时,尚未确认是否开始回答;请检查会话状态后重试`)}},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[f]);let Qs=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),$s=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),ec=L?.id.startsWith(`pending:`)===!0,tc=!!(L&&JO(L)&&(Er.has(L.id)||f.some(e=>e.key===`stop:${L.id}`))),nc=L?.messagesLoaded===!1||f.some(e=>e.key.startsWith(`send:${L?.id}:`)||e.key===`configuration:${L?.id}`||e.temporaryId===L?.id||e.key===`archive:${L?.id}`),rc=(e,t,n,r,i)=>{e&&Ks({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i})},ic=(e,t)=>xr(n=>({...n,[e]:t})),ac=(e,t,n)=>(_a(e),Y({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e)),oc=L?.model??Jt?.defaultModel,sc=L?.thinkingLevel??Jt?.defaultThinkingLevel,cc=sc&&Jt?.levels.includes(sc)?sc:void 0,lc=Jt?.source===`pi`,uc=Jt?.models.find(e=>e.provider===oc?.provider&&e.modelId===oc?.modelId),X=!!uc?.imageInput,dc=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(T.modelFilterRules??[]).every(n=>{try{let r=new RegExp(n.workspacePattern,`i`),i=[t.name,t.path,t.worktreeProjectPath].filter(e=>!!e).some(e=>r.test(e.replaceAll(`\\`,`/`))),a=new RegExp(n.modelPattern,`i`);return!i||a.test(e.label)||a.test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},fc=!!L?.messages?.some(e=>e.images&&e.images.length>0),pc=dc(Jt,T.workspaces.find(e=>e.id===L?.workspaceId))?.models??[],mc=fc?pc.filter(e=>e.imageInput):pc,hc=mc.map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,wD(e.contextWindow)?`${wD(e.contextWindow)} 上下文`:``,TD(e.maxTokens)?`${TD(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:iO(e),selected:oc?.provider===e.provider&&oc.modelId===e.modelId})),gc=(Jt?.levels??[]).map(e=>({key:e,label:e,selected:e===sc})),_c=e=>{if(!L)return;let[t,n]=e.split(`/`);t&&n&&(_a(L.id),Y({type:`conversation.model`,conversationId:L.id,provider:t,modelId:n},`configuration:${L.id}`,Qs(L.id,{model:Jt?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}})))},vc=e=>{L&&(_a(L.id),Y({type:`conversation.thinking`,conversationId:L.id,level:e},`configuration:${L.id}`,Qs(L.id,{thinkingLevel:e})))},yc=nn?.agents.find(e=>e.id===L?.agentId),bc=[{key:zO,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!L?.agentId},...(nn?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:L?.agentId===e.id}))],xc=yc?.model,Sc=!!(xc&&L?.model&&L.model.provider===xc.provider&&L.model.modelId===xc.modelId);yc?.thinkingLevel&&(L?.thinkingLevel,yc.thinkingLevel);let Cc=e=>{if(L){let t=nn?.agents.find(t=>t.id===e);Y({type:`conversation.agent`,conversationId:L.id,agentId:e===zO?null:e},`configuration:${L.id}`,Qs(L.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},wc=hn.filter(e=>e.conversationId===L?.id),Tc=(0,u.useMemo)(()=>{let e=L?.id;return e?(L.messages??[]).flatMap(t=>(t.toolCalls??[]).flatMap((n,r)=>n.question?.status===`pending`?[{key:jO(e,t.id,r),messageId:t.id,index:r,value:n.question}]:[])):[]},[L?.id,L?.messages]),Ec=Tc[0],Dc=()=>{let e=Ec;e&&(Cr(e.key),$e(`session`),window.setTimeout(()=>{(ft.current?.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`))?.scrollIntoView({block:`center`,behavior:`smooth`})},0))},Oc=Ut.filter(e=>e.conversationId===L?.id).map(e=>e.request),kc=new Map(Oc.filter(e=>e.method===`setStatus`).map(e=>[e.statusKey??``,e.statusText??``])),Ac=new Map(Oc.filter(e=>e.method===`setWidget`).map(e=>[e.widgetKey??``,{lines:e.widgetLines??[],placement:e.widgetPlacement??`aboveEditor`}])),jc=Oc.find(e=>e.method===`setTitle`)?.title,Mc=(0,u.useMemo)(()=>(T.subagentRuns??[]).filter(e=>e.conversationId===L?.id),[T.subagentRuns,L?.id]),Nc=(0,u.useMemo)(()=>(T.workflows??[]).filter(e=>e.conversationId===L?.id),[T.workflows,L?.id]),Pc=(0,u.useMemo)(()=>new Map(Nc.map(e=>[e.id,e])),[Nc]),Fc=(0,u.useMemo)(()=>new Map((an?.agents??[]).map(e=>[e.id,e.name])),[an]),Ic=(0,u.useMemo)(()=>new Map((L?.messages??[]).map(e=>[e.id,e])),[L?.messages]),Lc=(0,u.useMemo)(()=>new Map(Mc.map(e=>[e.id,e])),[Mc]),Rc=(0,u.useMemo)(()=>{let e=new Map;for(let t of Mc)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[Mc]),zc=(0,u.useMemo)(()=>{if(!L||!ga)return[];let e=wr?.conversationId===L.id?(()=>{let e=L.messages.find(e=>e.id===wr.messageId);if(e)return{index:L.messages.indexOf(e),at:Date.parse(e.createdAt)||0,inclusive:!0}})():void 0,t=[];return L.messages.forEach((n,r)=>{e&&(r>e.index||e.inclusive&&r===e.index)||n.delivery||t.push({at:Date.parse(n.createdAt)||0,seq:r,key:`m:${n.id}`})}),Mc.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&L?.messages.some(e=>e.id===n.originMessageId&&e.toolCalls?.[n.originCallRow])||e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`r:${n.id}`})}),Nc.forEach((n,r)=>{e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`w:${n.id}`})}),Xi(t)},[L,Mc,Nc,wr]),Bc=(0,u.useMemo)(()=>{for(let e=zc.length-1;e>=0;--e){let t=zc[e];if(t.startsWith(`m:`)&&Ic.get(t.slice(2))?.role===`user`)return t.slice(2)}},[zc,Ic]);(0,u.useEffect)(()=>{let e=ft.current;if(!e||!L?.id)return;let t=()=>{!yt.current&&ze.current[L.id]?.followTail&&(Vk(e),e.scrollTop=e.scrollHeight)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);n.observe(e);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[L?.id,L?.messages,Mc,Nc,ga,zc,I]);let Vc=e=>hr(t=>({...t,[e]:!t[e]})),Hc=(e,t)=>_r(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),Uc=(e,t)=>yr(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[Wc,Gc]=(0,u.useState)({}),Kc=e=>Gc(t=>({...t,[e]:t[e]!==!0})),qc=e=>{Y({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||Rs(`连接断开,无法停止子智能体,请重试`,`error`)},Jc=e=>{Y({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||Rs(`连接断开,无法停止编排,请重试`,`error`)},Yc=e=>[...Ac].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,F.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,dO).map((e,t)=>(0,F.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>dO&&(0,F.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),Xc=(e,t)=>{let n=`pending:${Wt()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};Y({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(ba(n),je(!1))},[Zc,Qc]=(0,u.useState)(),$c=(e,t)=>Qc(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),el=()=>Qc(void 0),tl=(e,t)=>Zc?.kind===e&&Zc.id===t,nl=(e,t,n)=>!t.startsWith(`pending:`)&&(e===`conversation`&&_a(t),Y(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?$s(t,{name:n}):Qs(t,{title:n}))?(ri.current=!0,el(),!0):(Rs(`连接断开,改名未保存,请重试`,`error`),!1)),rl=async e=>{if(e.startsWith(`pending:`)){Rs(`这个会话还在创建中,稍后再试`,`warning`);return}if(Pr.current.has(e))return;Rs(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{Pr.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{Pr.current.delete(e)&&n(Error(`模型在 ${Math.round(AD/1e3)} 秒内没有返回标题`))},AD)});if(!Ks({type:`conversation.autoRename`,conversationId:e}))Pr.current.delete(e),Rs(`连接断开,无法生成标题`,`error`);else try{let n=await t;nl(`conversation`,e,n),Rs(`已重命名为「${n}」`,`info`)}catch(e){Rs(`重命名失败:${Or(e)}`,`error`)}},il=e=>{if(e.id.startsWith(`pending:`))return;let t=T.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`从列表移除工作区「${e.name}」?${t?`其中的 ${t} 条会话会保留,`:``}重新添加同一个目录即可恢复,不会删除任何会话。`)&&(ol(void 0),Y({type:`workspace.delete`,workspaceId:e.id},`delete:${e.id}`,t=>({...t,workspaces:t.workspaces.filter(t=>t.id!==e.id),conversations:t.conversations.filter(t=>t.workspaceId!==e.id)})))},[al,ol]=(0,u.useState)(),[sl,cl]=(0,u.useState)(!1),ll=al?T.workspaces.find(e=>e.id===al):void 0,{theme:ul,setTheme:dl}=$h(),[fl,pl]=(0,u.useState)(!1),[ml,hl]=(0,u.useState)();(0,u.useEffect)(()=>{let e=()=>{he(),me(`entry`),hl(`servers`),pl(!0)};return window.addEventListener(`super-pi-open-server-management`,e),()=>window.removeEventListener(`super-pi-open-server-management`,e)},[]),(0,u.useEffect)(()=>{let e=e=>{let t=e.detail;typeof t==`string`&&T.conversations.some(e=>e.id===t)&&va(t)};return window.addEventListener(`super-pi-open-rsi-work`,e),()=>window.removeEventListener(`super-pi-open-rsi-work`,e)},[T.conversations,va]);let[gl,_l]=(0,u.useState)(!1),vl=(e,t,n,r)=>{e.startsWith(`pending:`)||(Y({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,$s(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?ol(void 0):Rs(`连接断开,设置未保存,请重试`,`error`))},yl=(e,t)=>{let n=M.activeServer;Y({type:`workspaces.settings.bulk`,model:e?{provider:e.provider,modelId:e.modelId}:null,thinkingLevel:t??null},`workspace-defaults-bulk`,r=>({...r,workspaces:r.workspaces.map(r=>{if(h(r.id).server!==n||r.closedAt||r.id.startsWith(`pending:`))return r;let i={...r};return e?i.defaultModel=e:delete i.defaultModel,t?i.defaultThinkingLevel=t:delete i.defaultThinkingLevel,i})}))?cl(!1):Rs(`连接断开,批量设置未保存,请重试`,`error`)},bl=(e,t=``)=>{if(e.startsWith(`pending:`))return;if(m.current.some(t=>t.key===`defaults:${e}`)){Rs(`工作区设置正在保存,请稍后再新建会话`,`warning`);return}let n=`pending:${Wt()}`,r={id:n,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[],...t?{cwd:t}:{}};si.current.set(n,r),Y({type:`conversation.create`,workspaceId:e,...t?{cwd:t}:{}},`create-session:${e}:${n}`,e=>({...e,conversations:[r,...e.conversations]}),n)?(ye.current++,A(e),O(n),$e(`session`),se(e=>({...e,ids:[...e.ids.filter(e=>e!==n),n],touched:Kk(e.touched,n)}))):(si.current.delete(n),Rs(`连接断开,会话未创建,请重试`,`error`))},xl=e=>{if(e.startsWith(`pending:`))return;let t=T.conversations.find(t=>t.id===e);if(!t||t.archivedAt||t.parentConversationId&&T.conversations.some(e=>e.id===t.parentConversationId))return;let n=JD(T.conversations,e),r=n.filter(e=>!e.archivedAt),i=r.length-1,a=n.length-r.length,o=ED(T.pendingUserDecisionsByConversation,n.map(e=>e.id)),s=jD({title:t.title,activeCount:r.length,activeDescendants:i,alreadyArchived:a,pendingDecisions:o});if(MD({activeDescendants:i,pendingDecisions:o})&&!window.confirm(s))return;let c=new Date().toISOString(),l=new Set(r.map(e=>e.id));Y({type:`conversation.archive`,conversationId:e},`archive:${e}`,e=>({...e,conversations:e.conversations.map(e=>l.has(e.id)&&!e.archivedAt?{...e,archivedAt:c}:e)}))},Sl=(e,t)=>Y({type:`conversation.collapse`,conversationId:e,collapsed:t},`collapse:${e}`,n=>{let r=new Set(n.collapsedConversationIds??[]);t?r.add(e):r.delete(e);let i={...n};return r.size===0?delete i.collapsedConversationIds:i.collapsedConversationIds=[...r],i}),Cl=e=>{let t=T.conversations.find(t=>t.id===e);if(!t?.archivedAt||(t.parentConversationId?T.conversations.find(e=>e.id===t.parentConversationId):void 0)?.archivedAt)return;let n=new Set(JD(T.conversations,e).filter(e=>e.archivedAt).map(e=>e.id));Y({type:`conversation.unarchive`,conversationId:e},`unarchive:${e}`,e=>({...e,conversations:e.conversations.map(e=>{if(!n.has(e.id)||!e.archivedAt)return e;let t={...e};return delete t.archivedAt,t})}))},wl=async e=>{if(!L){Rs(`请先选择或创建会话`,`error`);return}if(!X){Rs(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(Rs(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(Rs(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=L.id;Hi(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:Wt(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));qr(e=>[...e,...i]);for(let[e,t]of n.entries()){let n=i[e];try{let e=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let t=r.result,n=t.indexOf(`,`);e(n>=0?t.slice(n+1):t)},r.onerror=n,r.readAsDataURL(t)}),i=await Ne(`/api/upload`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({conversationId:r,name:t.name,mimeType:t.type,data:e})});if(!(i.headers.get(`content-type`)??``).includes(`application/json`)){Rs(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(zr.current.has(n.id))continue;qr(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),Hi(r,t=>({...t,images:[...t.images,{id:g(de(r),e.id),name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));Rs(Or(e.error,`上传失败(HTTP ${i.status})`),`error`)}}catch(e){Rs(`上传失败:${Or(e,`网络或服务暂时不可用`)}`,`error`)}finally{qr(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),Hi(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Tl=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.type.startsWith(`image/`)){let e=r.getAsFile();e&&n.push(e)}}if(n.length>0){if(!X){Rs(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),wl(n)}},El=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),Zr(!0))},Dl=e=>{e.currentTarget.contains(e.relatedTarget)||Zr(!1)},Ol=e=>{Zr(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!X){Rs(`当前模型不支持图片输入`,`error`);return}wl(t)}},kl=t=>{if(t.preventDefault(),!L)return;if(Si){Rs(zn,`warning`);return}if(nc){Rs(ec?`会话正在创建,请稍候再发送`:L.messagesLoaded===!1?`正在加载会话,请稍候再发送`:`正在保存配置,请稍候再发送`,`info`);return}if(!Li.trim()&&Ri.length===0)return;if(Ri.length>0&&!X){Rs(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(Vi>0){Rs(`图片正在上传中,请稍候…`,`info`);return}if(Bi){Rs(`技能正在读取中,请稍候…`,`info`);return}let n=`message_${Wt()}`,r=L.id,i=Li,a=Ri,o=zi;_a(r),e.stoppingConversationIds||Dr(e=>{if(!e.has(r))return e;let t=new Set(e);return t.delete(r),t});let s=TO({conversationId:r,content:i,clientId:n,images:a,attachments:o,inFlight:JO(L),deliveryMode:mi}),c=new Date().toISOString();Y(s,`send:${r}:${n}`,e=>fp(e,s,c),n,e=>{Vr(t=>[...t,{id:n,conversationId:r,content:i,images:a,attachments:o,reason:e}]),Hi(r,e=>e.text||e.images.length||e.attachments.length?e:{...e,text:i,images:a,attachments:o})},e=>!!e.conversations.find(e=>e.id===r)?.messages.some(e=>e.id===dp(s)))&&Hi(r,e=>({...e,text:``,images:[],attachments:[],pendingSkills:void 0}))},Al=(0,u.useMemo)(()=>(L?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[L?.messages]),jl=e=>{Y({type:`message.cancel`,conversationId:L?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===L?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||Rs(`连接断开,撤回没有生效,请重试`,`error`)},Ml=e=>{if(!L?.id||!e.length)return;let t=new Set(e),n=`queue-many:${L.id}:${e.join(`,`)}`;Y({type:`message.cancelMany`,conversationId:L.id,messageIds:e},n,e=>({...e,conversations:e.conversations.map(e=>e.id===L.id?{...e,messages:e.messages.filter(e=>!t.has(e.id))}:e)}),void 0,e=>Rs(e??`撤回所选消息失败,请重试`,`error`),t=>{let n=t.conversations.find(e=>e.id===L.id);return!!(n&&e.every(e=>!n.messages.some(t=>t.id===e&&t.delivery)))})||Rs(`连接断开,批量撤回没有生效,请重试`,`error`)},Nl=e=>{Y({type:`message.steer`,conversationId:L?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===L?.id?{...t,messages:FD(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===L?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||Rs(`连接断开,插到最前没有生效,请重试`,`error`)},Pl=e=>{let t=L?.id;t&&(Re.current?.readyState===WebSocket.OPEN?Y({type:`message.interrupt`,conversationId:t,messageId:e},`interrupt:${t}:${e}`,e=>e,void 0,e=>Rs(e??`打断失败,请重试`,`error`),n=>{let r=n.conversations.find(e=>e.id===t)?.messages.find(t=>t.id===e);return!(!r||r.delivery)},3e4)||Rs(`正在打断,请稍候`,`info`):Rs(`连接断开,打断没有生效,请重试`,`error`))},Fl=e=>{Y({type:`message.sendQueued`,conversationId:L?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===L?.id)?.messages.find(t=>t.id===e)?.delivery)||Rs(`连接断开,发送没有生效,请重试`,`error`)},Il=(e,t)=>{Y({type:`message.edit`,conversationId:L?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===L?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||Rs(`连接断开,修改没有生效,请重试`,`error`)},[Ll,Rl]=(0,u.useState)(),zl=(e,t=!0)=>{if(!L||L.messagesLoaded===!1||Ll)return;let n=L.messages.find(t=>t.id===e);n&&(Ir(e=>{let t=e[L.id]??{text:``,images:[],attachments:[],uploading:0};return t.text.trim()||t.images.length||t.attachments.length?e:{...e,[L.id]:{...t,text:n.content,images:n.images??[],attachments:wO(n.content,n.attachments)}}}),Tr({conversationId:L.id,messageId:e,kind:t?`withdraw`:`revert`})),Ks({type:`message.revert`,conversationId:L.id,messageId:e,withdraw:t})?Rl(e):(Tr(void 0),Rs(`连接断开,回退未执行,请重试`,`error`))},[Bl,Vl]=(0,u.useState)(),Hl=(0,u.useRef)(void 0),Ul=(0,u.useRef)(0),Wl=async(e,t)=>{let n=++Ul.current,r=await Bd(t);n===Ul.current&&(clearTimeout(Hl.current),Vl({id:e,kind:r?`copied`:`error`}),r||Rs(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),Hl.current=setTimeout(()=>Vl(void 0),2e3))};(0,u.useEffect)(()=>()=>{Ul.current+=1,clearTimeout(Hl.current)},[]);let[Gl,Kl]=(0,u.useState)(),ql=e=>{Gl||e.startsWith(`pending:`)||(_a(e),Ks({type:`conversation.fork`,conversationId:e})?Kl(e):Rs(`连接断开,分叉没有执行,请重试`,`error`))},Z=new Map;for(let e of T.scheduledTasks??[])e.conversationId&&!Z.has(e.conversationId)&&Z.set(e.conversationId,e);let Jl=(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,title:`设置`,"aria-haspopup":`dialog`,"aria-expanded":fl,onClick:()=>{hl(void 0),he(),pl(!0),Js({type:`catalog.fetchAll`}),Js({type:`providers.fetch`})},children:[(0,F.jsx)(Gr,{name:`settings`}),(0,F.jsx)(`span`,{className:`workbench-action-label`,children:`设置`})]}),(0,F.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,title:`使用指南`,"aria-haspopup":`dialog`,"aria-expanded":gl,onClick:()=>_l(!0),children:[(0,F.jsx)(Gr,{name:`help`}),(0,F.jsx)(`span`,{className:`workbench-action-label`,children:`使用指南`})]})]}),Yl=Ta?void 0:L,Xl=ye.current,Zl={onOpenSession:e=>{Xl===ye.current&&qs(e)},todos:T.todosByConversation?.[Yl?.id??``]??[],tasks:lk(Yl,T.backgroundTasks??[]),backgroundRuns:Yl?Lc:void 0,execOutputs:bt.current,scheduledTasks:(T.scheduledTasks??[]).filter(e=>e.workspaceId===Da),scheduledCatalog:dc(Jt,js),scheduledAgents:nn,notify:Rs,serverTimeZone:T.serverTimeZone,workspaceId:Da,gitWorkspaceId:ka,gitRepositoryOnly:ja,gitWorkspaceName:Ms?.name,workspaceLabel:js?.path,workspaceName:js?.name,conversationId:Yl?.id,followedWorktreeId:Yl?.followedWorktreeId,cwd:Aa,connected:te&&M.statuses.get(M.activeServer)?.state===`online`&&Oe&&!Yl?.id.startsWith(`pending:`),files:z,onOpenFile:Ko,onOpenChanged:Fo,onOpenGitDiff:Mo,activeGitDiffUrl:W?.target.url,onFileReference:qo,onFilesMoved:Jo,onSearchFolder:e=>_o(`content`,void 0,[Aa,e].filter(Boolean).join(`/`)),onSelectTab:Qa,sendCommand:Ks,registerTerminalSink:Dt,terminalShell:T.terminalShell,sharedGit:Va},Ql=e=>M.connections.some(t=>t.id===h(e).server)&&(On===`all`||h(e).server===On),$l=new Set(T.workspaces.map(e=>e.id)),eu=T.workspaces.filter(e=>Ql(e.id)&&(!e.worktreeOf||!$l.has(e.worktreeOf))),tu=eu.flatMap(e=>[e,...T.workspaces.filter(t=>t.worktreeOf===e.id)]),nu=(0,u.useMemo)(()=>{let e=new Map;for(let t of T.workspaces){if(t.closedAt)continue;let n=t.name.trim().toLowerCase();n&&e.set(n,(e.get(n)??0)+1)}return new Set([...e].filter(([,e])=>e>1).map(([e])=>e))},[T.workspaces]),ru=jn&&tu.some(e=>e.id===jn)?jn:k&&tu.some(e=>e.id===k)?k:tu[0]?.id,iu=T.workspaces.find(e=>e.id===k),au=iu?.worktreeOf&&$l.has(iu.worktreeOf)?iu.worktreeOf:iu?.id,ou=Nn&&eu.some(e=>e.id===Nn)?Nn:au&&eu.some(e=>e.id===au)?au:eu[0]?.id,su=Date.now()-18e6,cu=tu.filter(e=>e.id===ou||e.worktreeOf===ou),lu=e=>{let t=T.conversations.some(t=>t.workspaceId===e&&!t.archivedAt&&(En===`recent`?Date.parse(t.updatedAt)>=su:t.status===`running`||t.status===`waiting`)),n=(et[e]?.rooms??[]).some(e=>!e.archivedAt&&(En===`recent`?Date.parse(e.updatedAt)>=su:[`running`,`queued`].includes(ir(e,it[e.id]))));return t||n},uu=eu.flatMap(e=>{let t=tu.filter(t=>t.worktreeOf===e.id&&lu(t.id));return lu(e.id)||t.length>0?[e,...t]:[]}),du=En===`all`?tu:En===`workspace`?tu.filter(e=>e.id===ru):En===`repo`?cu:uu,fu=En===`all`||En===`workspace`||En===`repo`,pu=(e,t=En,n=ru,r=ou)=>{if(!e||!Ql(e))return!1;if(t===`all`)return!0;if(t===`workspace`)return e===n;if(t===`repo`)return e===r||tu.some(t=>t.id===e&&t.worktreeOf===r);let i=T.conversations.filter(t=>t.workspaceId===e&&!t.archivedAt).some(e=>t===`recent`?Date.parse(e.updatedAt)>=su:e.status===`running`||e.status===`waiting`),a=(et[e]?.rooms??[]).some(e=>!e.archivedAt&&(t===`recent`?Date.parse(e.updatedAt)>=su:[`running`,`queued`].includes(ir(e,it[e.id]))));return i||a},mu=(e,t=ru,n=ou)=>{Dn(e),t&&Mn(t),n&&Pn(n);let r=I===`group`&&ct&<?et[ct]?.rooms.find(e=>e.id===lt):void 0,i=I===`group`?!!(ct&&r&&!r.archivedAt&&pu(ct,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(r.updatedAt)>=su:[`running`,`queued`].includes(ir(r,it[r.id]))))):!!(L&&!L.archivedAt&&pu(L.workspaceId,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(L.updatedAt)>=su:L.status===`running`||L.status===`waiting`)));if(es.current=!0,i){e===`workspace`&&A(t);let r=Qo.find(e=>e.id===$o)?.workspaceId;(e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!pu(r,e,t,n))&&$e(`session`)}else Un(!0),O(void 0),Ze(!1),(I===`session`||I===`group`||e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!pu(Qo.find(e=>e.id===$o)?.workspaceId,e,t,n))&&$e(`session`),A(e===`workspace`?t:void 0)},hu=e=>{An(e),localStorage.setItem(`super-pi.server-filter`,e),e!==`all`&&ve(e);let t=I===`group`?ct:L?.workspaceId??k;if(t&&e!==`all`&&h(t).server!==e){es.current=!0,Un(!0),O(void 0),Ze(!1);let t=T.workspaces.filter(t=>h(t.id).server===e);if(En===`workspace`){let e=t.find(e=>e.id===jn)?.id??t[0]?.id;Mn(e),A(e)}else A(void 0),En===`repo`&&Pn(t.find(e=>!e.worktreeOf)?.id);$e(`session`)}};(0,u.useEffect)(()=>{On!==`all`&&!M.connections.some(e=>e.id===On)&&hu(`all`)},[On,M.connections]);let gu=Qo.filter(e=>{if(!e.workspaceId||!Ql(e.workspaceId))return!1;if(En===`all`)return!0;if(En===`workspace`||En===`repo`)return pu(e.workspaceId);if(e.id.startsWith(`session:`)){let t=T.conversations.find(t=>t.id===e.rawId);return!!(t&&!t.archivedAt&&pu(t.workspaceId)&&(En===`recent`?Date.parse(t.updatedAt)>=su:t.status===`running`||t.status===`waiting`))}if(e.id.startsWith(`group:`)){let t=$n(e.id),n=t?.roomId?et[t.workspaceId]?.rooms.find(e=>e.id===t.roomId):void 0;return!!(t&&n&&!n.archivedAt&&pu(t.workspaceId)&&(En===`recent`?Date.parse(n.updatedAt)>=su:[`running`,`queued`].includes(ir(n,it[n.id]))))}return!1}),_u=ja?`未选工作区`:Va.status?.detached?`游离 HEAD`:Va.status?.branch,vu=!ja&&Va.status&&new Set([...Va.status.staged,...Va.status.unstaged,...Va.status.untracked].map(e=>e.path)).size,yu=!ja&&Va.status&&(Va.status.ahead||Va.status.behind)?[Va.status.ahead?`↑`+Va.status.ahead:``,Va.status.behind?`↓`+Va.status.behind:``].filter(Boolean).join(` `):``,bu=()=>Jn(e=>({...e,rightClosed:!0})),xu=()=>Jn(e=>({...e,leftClosed:!0})),Su=pr?gn:oo;return(0,F.jsxs)(`main`,{className:`shell workbench-shell${Su?` shell-rail-collapsed`:``} mobile-panel-${vn}${wn?` mobile-drawer-open`:``}`,"data-rail-collapsed":Su,"data-workbench-left-closed":!pr&&qn.leftClosed,"data-selected-workspace":k??``,style:{"--sidebar-width":`${nr.sidebar}px`,"--rail-col":Su?void 0:`${nr.rail}px`},children:[!pr&&(0,F.jsx)(Kr,{side:`left`,views:$a,unpinned:qn.unpinned,active:qn.leftClosed||eo?void 0:B,onSelect:e=>co(e,!0),searchActive:!qn.leftClosed&&eo,onSearch:()=>{ro(!0),to(!0),Jn(e=>({...e,leftClosed:eo&&!e.leftClosed}))},onArrange:lo,onReorder:uo,children:Jl}),(0,F.jsxs)(`aside`,{className:`workbench-sessions`,id:`workbench-sessions`,"data-workbench-session-view":so?`shown`:`hidden`,children:[(0,F.jsxs)(`div`,{className:`sidebar-actions`,children:[(0,F.jsx)(`button`,{className:`workspace-new`,onClick:()=>je(!0),children:`+ 添加工作区`}),L&&ga&&gu.length===1&&(0,F.jsx)(`button`,{type:`button`,className:`mobile-close-session`,onClick:()=>{_s(L.id),Tn(!1)},children:`关闭当前标签`})]}),(0,F.jsxs)(`div`,{className:`label label-desktop workspace-title-row`,children:[(0,F.jsx)(`span`,{children:`工作区`}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-bulk-settings`,title:`批量设置所有工作区`,"aria-label":`批量设置所有工作区`,onClick:()=>cl(!0),children:`⚙`})]}),(0,F.jsx)(`div`,{className:`label label-phone`,children:`会话`}),sl&&(0,F.jsx)(cE,{workspaces:T.workspaces.filter(e=>h(e.id).server===M.activeServer&&!e.closedAt&&!e.id.startsWith(`pending:`)),catalog:Xt??{source:`unavailable`,models:[],levels:[],fetchedAt:``},onClose:()=>cl(!1),onSave:yl}),(0,F.jsxs)(`div`,{className:`sidebar-session-filters`,"aria-label":`会话与群聊筛选`,children:[(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`span`,{children:`服务器`}),(0,F.jsxs)(`select`,{"aria-label":`服务器范围`,value:On,onChange:e=>hu(e.target.value),children:[(0,F.jsx)(`option`,{value:`all`,children:`全部服务器`}),M.connections.map(e=>(0,F.jsxs)(`option`,{value:e.id,children:[e.name,M.statuses.get(e.id)?.state===`offline`?` · 离线`:``]},e.id))]})]}),(0,F.jsxs)(`label`,{children:[(0,F.jsx)(`span`,{children:`显示`}),(0,F.jsxs)(`select`,{"aria-label":`会话列表筛选方式`,value:En,onChange:e=>mu(e.currentTarget.value),children:[(0,F.jsx)(`option`,{value:`all`,children:`全部`}),(0,F.jsx)(`option`,{value:`workspace`,children:`按工作区`}),(0,F.jsx)(`option`,{value:`repo`,children:`按仓库`}),(0,F.jsx)(`option`,{value:`recent`,children:`近期活跃 · 5 小时`}),(0,F.jsx)(`option`,{value:`running`,children:`正在运行`})]})]}),En===`workspace`&&(0,F.jsx)(`select`,{"aria-label":`选择工作区`,value:ru??``,onChange:e=>mu(`workspace`,e.currentTarget.value,ou),children:(0,F.jsx)(kn,{workspaces:tu})}),En===`repo`&&(0,F.jsx)(`select`,{"aria-label":`选择仓库`,value:ou??``,onChange:e=>mu(`repo`,ru,e.currentTarget.value),children:(0,F.jsx)(kn,{workspaces:eu})})]}),(0,F.jsx)(`nav`,{"aria-label":`工作区、会话与群聊`,children:du.length===0?(0,F.jsx)(`div`,{className:`sidebar-filter-empty`,children:En===`recent`?`近 5 小时没有活跃的会话或群聊`:`当前没有正在运行的会话或群聊`}):du.map((e,t)=>{let n=et[e.id],r=(n?.rooms.filter(e=>!e.archivedAt)??[]).filter(e=>fu||(En===`recent`?Date.parse(e.updatedAt)>=su:[`running`,`queued`].includes(ir(e,it[e.id])))),i=fu?n?.rooms.filter(e=>e.archivedAt)??[]:[],a=T.conversations.filter(t=>t.workspaceId===e.id),o=a.filter(e=>!e.archivedAt&&(fu||(En===`recent`?Date.parse(e.updatedAt)>=su:e.status===`running`||e.status===`waiting`))),s=bE(o,fi,{manualRoots:At[e.id]}),c=s.filter(e=>e.depth===0).map(e=>e.conversation.id),l=fu?a.filter(e=>e.archivedAt):[],u=bE(l,new Set),d=fu?l.length+i.length:0,f=ie[e.id]??!1,p=Ot[e.id]??!0,m=nu.has(e.name.trim().toLowerCase()),g=!e.worktreeOf||!$l.has(e.worktreeOf),_=(En===`recent`||En===`running`)&&g,v=t=>I===`group`&&ct===e.id&<===t;return(0,F.jsxs)(`section`,{className:`workspace-group${e.worktreeOf&&$l.has(e.worktreeOf)?` workspace-linked-checkout`:``}${_?` workspace-active-repo-root`:``}`,"data-workspace-parent":e.worktreeOf,"data-workspace-group":e.id,"data-sidebar-repo-root":_?e.id:void 0,"data-current-workspace":k===e.id,children:[M.connections.length>1&&(t===0||h(du[t-1].id).server!==h(e.id).server)&&(0,F.jsxs)(`div`,{className:`workspace-server-label`,children:[_e(e.id),M.statuses.get(h(e.id).server)?.state===`offline`?` · 离线`:``]}),(0,F.jsx)(`div`,{className:`workspace-header`,children:tl(`workspace`,e.id)?(0,F.jsx)(LO,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>nl(`workspace`,e.id,t),onClose:el}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{type:`button`,className:`workspace-disclosure`,"data-workspace-fold":e.id,"aria-expanded":!f,"aria-label":`${f?`展开`:`折叠`}工作区 ${e.name}`,onClick:()=>ae(t=>({...t,[e.id]:!t[e.id]})),children:(0,F.jsx)(`span`,{className:`chevron-folder`,"aria-hidden":`true`,children:f?`▸`:`▾`})}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-toggle`,"aria-label":e.name,"aria-describedby":m?`workspace-name-warning-${e.id}`:void 0,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();jr({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{Mn(e.id);let t=ui.find(t=>t.workspaceId===e.id)?.id;t?(t!==L?.id||I!==`session`||!ga)&&va(t):ba(e.id)},children:(0,F.jsxs)(`span`,{children:[(0,F.jsxs)(`span`,{className:`workspace-name-line`,children:[(0,F.jsx)(`strong`,{onDoubleClick:()=>$c(`workspace`,e.id),children:e.name}),m&&(0,F.jsx)(`small`,{id:`workspace-name-warning-${e.id}`,className:`workspace-name-warning`,"data-workspace-name-warning":e.id,title:`请重命名其中一个工作区;名称唯一后提示会自动消失。`,children:`存在同名,易混淆`})]}),(0,F.jsx)(`small`,{children:e.path})]})}),(0,F.jsx)(`button`,{className:`workspace-add`,disabled:e.id.startsWith(`pending:`),title:`在此工作区新建会话`,onClick:t=>{Mn(e.id),Ie.current=t.currentTarget,Fe({workspaceId:e.id})},children:`+`}),(0,F.jsx)(`button`,{type:`button`,className:`workspace-group-chat`,"data-open-group-chat":e.id,disabled:e.id.startsWith(`pending:`),title:`新建群聊`,"aria-label":`在 ${e.name} 新建群聊`,onClick:()=>{Mn(e.id),xa(e.id)},children:(0,F.jsx)(Gr,{name:`group-add`})}),(0,F.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>ol(e.id),children:`⚙`})]})}),!f&&r.map(t=>{let n=v(t.id),r=ir(t,it[t.id]),i=ar(t,it[t.id],Ve.current[Qn({workspaceId:e.id,roomId:t.id})]),a=i===`completed`?`讨论已完成,有新回复未读`:i===`unread`?`有新回复未读`:GO[r];return(0,F.jsxs)(`div`,{className:`conversation-row group-room-row`,children:[(0,F.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),(0,F.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-sidebar-group-chat":t.id,"aria-current":n?`true`:void 0,"aria-label":`打开群聊 ${t.title},${a}`,title:t.title,onClick:()=>{Mn(e.id),xa(e.id,t.id)},children:[(0,F.jsx)(`i`,{className:`conversation-mark`,children:(0,F.jsx)(tk,{state:i,label:a})}),(0,F.jsx)(Gr,{name:`group`}),(0,F.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-archive`,"data-archive-group":t.id,title:`归档群聊`,"aria-label":`归档群聊 ${t.title}`,disabled:ot.has(t.id),onClick:()=>void wa(t,`archive`),children:(0,F.jsx)(Gr,{name:`archive`})})]},t.id)}),!f&&n?.failed&&(0,F.jsx)(`button`,{type:`button`,className:`group-rooms-retry`,onClick:tt,children:`重试载入群聊`}),!f&&(s.length?s.map(({conversation:t,depth:n,childCount:r,isLastSibling:i})=>(0,F.jsxs)(`div`,{className:`conversation-row`,style:{"--tree-depth":n},"data-session-root":n===0?t.id:void 0,"data-session-dragging":Mt?.conversationId===t.id?`true`:void 0,"data-session-drop":Mt?.dropRootId===t.id?Mt.dropAfter?`after`:`before`:void 0,onPointerDown:n===0?n=>It(n,e.id,t.id,c):void 0,children:[r>0?(0,F.jsxs)(`button`,{type:`button`,className:`conversation-tree-toggle`,"data-tree-toggle":t.id,"aria-expanded":!fi.has(t.id),title:fi.has(t.id)?`展开 ${r} 个子会话`:`折叠 ${r} 个子会话`,"aria-label":fi.has(t.id)?`展开会话 ${t.title} 的 ${r} 个子会话`:`折叠会话 ${t.title} 的 ${r} 个子会话`,onClick:()=>Sl(t.id,!fi.has(t.id)),children:[(0,F.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:fi.has(t.id)?`▸`:`▾`}),(0,F.jsx)(`small`,{children:r})]}):(0,F.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),tl(`conversation`,t.id)?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(LO,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>nl(`conversation`,t.id,e),onClose:el}),(0,F.jsx)(`small`,{className:`conversation-time`,children:qD(t.updatedAt,ci)})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`button`,{className:`conversation ${!Ta&&L?.id===t.id?`selected`:``}`,"data-conversation":t.id,"aria-current":!Ta&&L?.id===t.id?`true`:void 0,"data-tree-child":n>0?`true`:void 0,"data-tree-last":n>0&&i?`true`:void 0,title:n>0?`${t.title}(由「${o.find(e=>e.id===t.parentConversationId)?.title??`已不存在的会话`}」创建)`:t.title,"aria-label":`打开会话 ${t.title}${rk(t,Z.get(t.id))}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();Nr({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{t.id===Ft.current&&Date.now()-Pt.current<300||(Mn(e.id),va(t.id),A(e.id),Tn(!1))},onDoubleClick:()=>{ya(t.id)},children:[(0,F.jsx)(`i`,{className:`conversation-mark`,children:(0,F.jsx)(tk,{state:$O(t,ZO(t,hn),Ve.current[t.id],T.conversations)})}),(0,F.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:e=>{e.stopPropagation(),$c(`conversation`,t.id)},style:{flex:`0 1 auto`,minWidth:`3.5em`},children:t.title}),(0,F.jsx)(`span`,{className:`conversation-title-gap`,"aria-hidden":`true`,style:{marginLeft:`-8px`}}),ek($O(t,ZO(t,hn),Ve.current[t.id],T.conversations),QO(t,T.conversations,Ve.current[t.id])),nk(t,Z.get(t.id)),(0,F.jsx)(`small`,{children:qD(t.updatedAt,ci)})]}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":Gl===t.id?`pending`:`idle`,disabled:!!Gl,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>ql(t.id),children:`⑂`}),!(t.parentConversationId&&T.conversations.some(e=>e.id===t.parentConversationId))&&(0,F.jsx)(`button`,{className:`conversation-archive`,"data-archive-conversation":t.id,title:`归档整棵会话树`,"aria-label":`归档会话 ${t.title}`,onClick:()=>xl(t.id),children:`×`})]})]},t.id)):!r.length&&(0,F.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!f&&d>0&&(0,F.jsxs)(`div`,{className:`archived-group`,"data-archived-count":d,children:[(0,F.jsxs)(`button`,{className:`archived-toggle`,title:p?`展开已归档`:`收起已归档`,"aria-expanded":!p,onClick:()=>kt(t=>({...t,[e.id]:!p})),children:[(0,F.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:p?`▸`:`▾`}),(0,F.jsxs)(`span`,{className:`archived-label`,children:[`已归档 (`,d,`)`]})]}),!p&&u.map(({conversation:e,depth:t,isLastSibling:n})=>{let r=JD(l,e.id).length-1,i=!!(e.parentConversationId&&T.conversations.some(t=>t.id===e.parentConversationId&&t.archivedAt));return(0,F.jsxs)(`div`,{className:`conversation-archived`,"data-archived-conversation":e.id,"data-archived-at":e.archivedAt,"data-tree-child":t>0?`true`:void 0,"data-tree-last":t>0&&n?`true`:void 0,style:{"--tree-depth":t},children:[(0,F.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,F.jsx)(`span`,{"data-archived-title":e.id,children:e.title}),nk(e,Z.get(e.id)),(0,F.jsx)(`small`,{children:YD(e.archivedAt)}),!i&&(0,F.jsx)(`button`,{className:`conversation-restore`,"data-restore-conversation":e.id,title:r?`恢复这个会话和它的 ${r} 个子孙会话`:`恢复为正常会话`,"aria-label":r?`恢复会话 ${e.title} 及其 ${r} 个子孙会话`:`恢复会话 ${e.title}`,onClick:()=>Cl(e.id),children:`↑`})]},e.id)}),!p&&i.map(t=>{let n=v(t.id),r=ot.has(t.id);return(0,F.jsxs)(`div`,{className:`conversation-row group-room-row group-room-history`,"data-archived-group":t.id,children:[(0,F.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-open-archived-group":t.id,"aria-current":n?`true`:void 0,"aria-label":`查看已归档群聊 ${t.title}`,title:t.title,onClick:()=>xa(e.id,t.id),children:[(0,F.jsx)(Gr,{name:`group`}),(0,F.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-restore-group":t.id,title:`恢复群聊`,"aria-label":`恢复群聊 ${t.title}`,disabled:r,onClick:()=>void wa(t,`restore`),children:`↑`}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-delete-group":t.id,title:`永久删除群聊`,"aria-label":`永久删除群聊 ${t.title}`,disabled:r,onClick:()=>void wa(t,`delete`),children:(0,F.jsx)(Gr,{name:`delete`})})]},t.id)})]}),!f&&(()=>{let t=T.warmSessions?.filter(t=>t.workspaceId===e.id)??[];return t.length?(0,F.jsxs)(`details`,{className:`archived-group`,"data-warm-sessions":e.id,children:[(0,F.jsx)(`summary`,{className:`archived-toggle`,children:(0,F.jsxs)(`span`,{className:`archived-label`,children:[`预热会话 (`,t.length,`)`]})}),t.map(e=>(0,F.jsxs)(`div`,{className:`conversation-archived`,"data-warm-session":e.id,children:[(0,F.jsx)(`span`,{title:e.title,children:e.title}),(0,F.jsx)(`button`,{type:`button`,className:`conversation-restore`,"aria-label":`移除预热会话 ${e.title}`,onClick:()=>{window.confirm(`移除预热会话「${e.title}」?`)&&!Ks({type:`conversation.warm.delete`,conversationId:e.id})&&Rs(`连接断开,未移除预热会话`,`error`)},children:`×`})]},e.id))]}):null})()]},e.id)})}),pr&&(0,F.jsxs)(`footer`,{className:`workbench-mobile-utilities`,children:[(0,F.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-mobile-workbench-search":!0,"aria-label":`搜索`,title:`搜索`,onClick:()=>_o(`content`),children:(0,F.jsx)(Gr,{name:`search`})}),Jl]})]}),no&&(0,F.jsx)(`section`,{className:`workbench-panel workbench-panel-left workbench-search-panel`,"data-workbench-search-panel":!0,"aria-label":`侧栏搜索`,hidden:pr||!eo||qn.leftClosed,children:(0,F.jsx)(Hm,{workspaceId:Da,workspaceName:js?.name,cwd:Aa,connected:te,active:!pr&&eo&&!qn.leftClosed,onOpen:(e,t,n)=>Go(e,t,!1,!0,!1,n),onSession:So},fo)}),!pr&&!qn.leftClosed&&!eo&&B!==`sessions`&&(0,F.jsx)(pk,{...Zl,side:`left`,activeTab:B,collapsed:!1,onToggle:xu,pinned:!qn.unpinned.includes(B),onArrange:lo}),(pr||!qn.leftClosed)&&(0,F.jsx)(Qk,{side:`left`,width:nr.sidebar,min:nr.sidebarMin,max:nr.sidebarMax,label:`调整左侧栏宽度`,onWidth:sr}),(0,F.jsx)(`div`,{className:`workbench-main`,children:(0,F.jsxs)(`div`,{className:`workbench-main-panes`,"data-workbench-split":Ra,style:{"--split-share":`${Fa}%`},children:[(0,F.jsxs)(`section`,{className:`chat`,"data-main-view":G,"data-main-view-kind":G,children:[gu.length>0&&(0,F.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":ma.length,"data-file-count":z.open.length,children:(0,F.jsx)(Km,{tabs:(ms?gu.filter(e=>e.id!==ms.id):gu).map(e=>M.connections.length>1&&e.workspaceId?{...e,label:`${e.label} · ${_e(e.workspaceId)}`,title:`${_e(e.workspaceId)} · ${e.title??e.label}`}:e),prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:$o,onSelect:ns,onClose:vs,onActivate:fs,minWidth:120,maxWidth:320})}),(0,F.jsxs)(`header`,{children:[(0,F.jsx)(`button`,{type:`button`,className:`mobile-drawer-toggle`,"data-mobile-drawer-toggle":`1`,"aria-label":`打开会话列表`,title:`会话列表`,"aria-expanded":wn,onClick:()=>Tn(!0),children:`☰`}),(0,F.jsxs)(`div`,{className:`chat-head`,children:[(0,F.jsx)(`h1`,{children:I===`group`?lt?dt??`群聊`:`新建群聊`:L?.title??`准备开始`}),I!==`group`&&kc.size>0?[...kc].map(([e,t])=>(0,F.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):null]}),(0,F.jsxs)(`div`,{className:`workbench-history-controls`,role:`group`,"aria-label":`主区导航`,"data-workbench-history":cs>=0||ls>=0?`available`:`empty`,children:[L&&I!==`group`&&(0,F.jsx)(HT,{id:L.id,workspaceId:L.workspaceId,models:Jt?.models??[]}),(0,F.jsx)(`button`,{type:`button`,"data-workbench-history-back":!0,"aria-label":`后退`,className:`workbench-icon-button`,title:cs<0?`后退`:`后退到 ${Se.entries[cs].title}`,disabled:cs<0||!!we,onClick:()=>us(-1),children:(0,F.jsx)(Gr,{name:`back`})}),(0,F.jsx)(`button`,{type:`button`,"data-workbench-history-forward":!0,"aria-label":`前进`,className:`workbench-icon-button`,title:ls<0?`前进`:`前进到 ${Se.entries[ls].title}`,disabled:ls<0||!!we,onClick:()=>us(1),children:(0,F.jsx)(Gr,{name:`forward`})}),Da&&(0,F.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-toggle-workbench-split":!0,"aria-pressed":Ra,"aria-label":Ra?`合并主区`:`拆分主区`,title:Ra?`合并主区`:`拆分主区`,onClick:gs,children:(0,F.jsx)(Gr,{name:`split`})})]}),mn.entry(`workbench-status-button software-update-mobile`),(0,F.jsxs)(`span`,{className:`chat-view chat-view-${G}`,"data-main-view-indicator":G,"data-main-view-kind":G,title:I===`file`?`中间主画面正在显示文件 ${z.active?.path??``}`:G===`diff`?`中间主画面正在显示 ${jo??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,F.jsx)(`span`,{className:`chat-view-kind`,children:I===`group`?`群聊`:I===`file`?`文件`:G===`diff`?`改动`:`会话`}),I===`file`&&z.active&&(0,F.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":z.active.name,children:z.active.name}),G===`diff`&&jo&&(0,F.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":jo,children:jo})]}),!Ta&&(0,F.jsx)(`div`,{className:`badge`,"data-workbench-header-status":Ti||L?.status===`failed`?`attention`:`routine`,"data-conversation-status":L?.status??`idle`,...Ti?{"data-reporting-status":Ti}:{},children:Ti===`awaiting_decision`?`等上面拍板`:JO(L)?qO[L?.status??`idle`]:Ti===`awaiting_subordinates`?`等待下级`:Ti===`pending_report`?`待汇报`:qO[L?.status??`idle`]}),(0,F.jsx)(`button`,{type:`button`,className:`mobile-tools-toggle`,"data-mobile-nav":`rail`,onClick:()=>{yn(`rail`),_n(!1)},children:`工具`})]}),N&&(0,F.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,F.jsx)(`span`,{title:kr(N),children:Or(N)}),(0,F.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>ne(void 0),children:`×`})]}),!Ta&&L?.error&&(0,F.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,title:kr(L.error),children:Or(L.error)}),L?.warning&&(0,F.jsxs)(`div`,{className:`warning`,role:`status`,"data-role":`conversation-warning`,title:kr(L.warning),children:[(0,F.jsx)(`span`,{children:L.warning}),(0,F.jsx)(`button`,{type:`button`,"data-role":`conversation-warning-continue`,title:`让模型继续完成当前任务`,onClick:()=>Zs(L?.id??``),children:`继续任务`})]}),!Ta&&L?.modelNotice&&(0,F.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-model-notice`,children:L.modelNotice}),L?.agentNotice&&(0,F.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-agent-notice`,children:L.agentNotice}),jc&&(0,F.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,jc]}),Kt.length>0&&(0,F.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Kt.length,children:Kt.map(e=>(0,F.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),I===`group`?js?(0,F.jsx)(aE,{workspaceId:ct,roomId:lt,sourceLink:zs(ct),composerResize:ur===null?void 0:(0,F.jsx)(aA,{height:ur,onHeight:fr}),onEnableNotifications:()=>Vs(!0),agents:nn?.agents??[],catalog:dc(Jt,js),userLabel:Bt,archivedAt:ut?.archivedAt,restoring:ot.has(lt),onRestore:e=>void wa(e,`restore`),onRoomSeen:nt,onRoomRead:Ni,onRoomMissing:Ca,onCreated:Sa,onCancelCreate:()=>Ke&&vs(Qn(Ke))},Ke&&Qn(Ke)):(0,F.jsx)(`div`,{className:`group-empty`,children:Oe?`这个群聊的工作区已不可用。`:`正在加载工作区…`}):I===`file`?Ns(ys,!0):W?Ps(W):I===`diff`?Fs(To,!1):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`div`,{className:`messages`,ref:ft,"data-message-scroll-container":L?.id??``,onWheel:e=>{e.deltaY<0&&ze.current[L?.id??``]?.followTail&&(yt.current=!0,Pi(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:Pi(t)},children:[(!L||!ga)&&(0,F.jsxs)(`div`,{className:`empty`,"data-workspace-welcome":Oi?.id,children:[(0,F.jsx)(`div`,{className:`orb`,children:`π`}),(0,F.jsx)(`h2`,{children:Oi?.name??`开始一个新会话`}),T.workspaces.length===0?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,F.jsx)(`button`,{onClick:()=>je(!0),children:`+ 新建工作区`})]}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`p`,{children:Oi?`暂无活跃会话。你可以创建会话,也可以直接使用资源管理器、Git 和终端。`:T.workspaces.length===1&&Di?`在「${Di.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),Oi&&(0,F.jsx)(`p`,{className:`workspace-welcome-path`,title:Oi.path,children:Oi.path}),T.workspaces.length>1&&(0,F.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,F.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,F.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Di?.id,onChange:e=>{e.target.value===`__new__`?je(!0):ba(e.target.value)},children:[(0,F.jsx)(kn,{workspaces:T.workspaces}),(0,F.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Di&&(0,F.jsxs)(F.Fragment,{children:[!ki&&(0,F.jsx)(sO,{workspaceId:Di.id,value:Ai,onChange:ji}),(0,F.jsx)(`button`,{"data-workspace-welcome-create":Oi?`1`:void 0,disabled:ki||!te,onClick:()=>bl(Di.id,Ai),children:ki?`正在创建工作区…`:`新建会话`})]}),(0,F.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>je(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),je(!0))},children:`+ 新建工作区`})]})]}),L?.messagesLoaded===!1&&(0,F.jsx)(`p`,{role:`status`,"data-conversation-loading":`1`,children:`正在加载会话…`}),zc.map(e=>{if(e.startsWith(`m:`)){let t=Ic.get(e.slice(2));if(!t)return null;let n=t.id===Bc,r=t.role===`user`&&L?.status!==`running`&&L?.status!==`waiting`&&Ll!==t.id,i=r&&n&&!t.id.startsWith(`pending:`),a=r&&!n&&!!t.piEntryId,o=t.content?(0,F.jsx)(ef,{source:t.content,media:pi,sourceLink:Bs}):(0,F.jsx)(`span`,{className:`typing`,children:`正在思考`});if(t.source===`session-reminder`)return(0,F.jsx)(`article`,{className:`message message-reminder`,"data-transcript-key":e,"data-message-reminder":t.id,children:(0,F.jsxs)(`details`,{children:[(0,F.jsxs)(`summary`,{className:`reminder-header`,children:[(0,F.jsxs)(`span`,{className:`reminder-label`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`◷`}),` 定时提醒`]}),(0,F.jsx)(`time`,{dateTime:t.createdAt,children:BD(t.createdAt)})]}),(0,F.jsx)(`div`,{className:`content`,children:o})]})},e);let s=t.toolCalls??[],c=Bl?.id===t.id?Bl.kind:void 0;if(t.role===`user`){let n=t.content||(t.images?.length?`[图片]`:``),r=wO(t.content,t.attachments);return(0,F.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,F.jsxs)(`div`,{className:`message-body`,children:[(0,F.jsxs)(`div`,{className:`bubble`,children:[(0,F.jsxs)(`div`,{className:`meta`,children:[Bt,(0,F.jsx)(`time`,{children:BD(t.createdAt)})]}),t.images&&t.images.length>0&&(0,F.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,F.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>Yr({url:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,F.jsx)(`img`,{src:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,F.jsx)(`div`,{className:`content`,children:o})]}),r.length>0&&(0,F.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:r.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=gr[n]??!1;return(0,F.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,F.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>_r(e=>({...e,[n]:!r})),children:[(0,F.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,F.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,F.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,F.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,F.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,F.jsxs)(`div`,{className:`message-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":c,"aria-label":`复制这条消息:${n}`,onClick:()=>Wl(t.id,n),children:c===`copied`?`已复制`:c===`error`?`复制失败`:`复制`}),i&&(0,F.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>zl(t.id,!0),children:`撤回`}),a&&(0,F.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退并编辑:删除这条消息及后续全部对话,将原消息恢复到输入框`,onClick:()=>zl(t.id),children:`回退`})]})]}),(0,F.jsx)(`div`,{className:`avatar`,title:Bt,children:Bt})]},e)}if(t.role===`tool`){let n=CD(t.content),r=n!==void 0,i=/<task id="[^"]+" state="[^"]+"/.test(t.content),a=(()=>{if(r)return`输出额度触顶后的自动恢复`;let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():i?`后台回传`:(t.content.split(`
|
|
346
346
|
`).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`})(),o=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),s=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:n??t.content})(),c=t.backgroundTask,l=c?.output===void 0?s:[c.reason,c.outputTruncated?`日志仅保留最近一段。`:``,c.output||`任务未产生输出。`].filter(Boolean).join(`
|
|
347
347
|
|
|
348
|
-
`),u=(()=>{let e=/<result_file>([\s\S]*?)<\/result_file>/.exec(t.content);return e&&e[1].trim()?e[1].trim():void 0})(),d=(()=>{let e=/<task id="([^"]+)"/.exec(t.content);return e?e[1]:void 0})(),f=!!(d&&ui.some(e=>e.id===d)),p=`tool:${t.id}`,m=gr[p]??!1,h=r?`自动恢复`:i?`后台回传`:`智能体下发`;return(0,F.jsx)(`article`,{className:`message tool${i?``:` tool-order`}`,"data-transcript-key":e,"data-tool-state":o,"data-tool-kind":r?`recovery`:i?`delivery`:`order`,children:(0,F.jsxs)(`div`,{className:`message-body`,children:[(0,F.jsxs)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:[(0,F.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":m,title:m?`折叠${h}`:`展开${h}`,onClick:()=>_r(e=>({...e,[p]:!m})),children:[(0,F.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:o===`error`?`✕`:i?`↩`:`↓`}),(0,F.jsx)(`span`,{className:`bg-result-label`,children:c&&(c.status===`cancelled`||c.status===`interrupted`)?
|
|
349
|
-
`).map(e=>e.trim()).find(Boolean)??``,expanded:Wc[`${t.id}:${e}`]===!0,onToggle:()=>Kc(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,F.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,F.jsx)(`div`,{className:`avatar`,children:`π`}),(0,F.jsxs)(`div`,{className:`message-body`,children:[(0,F.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,F.jsx)(`time`,{children:
|
|
350
|
-
`),children:e.withdrawn.map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,48)}」`).join(` · `)})]}),(0,F.jsx)(`div`,{className:`composer-notice-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-queue-withdrawn-dismiss":`1`,onClick:()=>yi(t=>t.filter(t=>t.id!==e.id)),children:`知道了`})})]},e.id)),Br.filter(e=>e.conversationId===L?.id).map(e=>(0,F.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,F.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,F.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,F.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,title:kr(e.reason),children:e.reason?.trim()?Or(e.reason):`服务端没有接受这条消息。`}),(0,F.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,F.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(Li||Ri.length||zi.length),title:Li||Ri.length||zi.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{Hi(e.conversationId,t=>({...t,text:e.content,images:e.images,attachments:e.attachments})),Vr(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,F.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>Vr(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),Wr.filter(e=>e.conversationId===L?.id).map(e=>(0,F.jsxs)(`div`,{className:`composer-upload-preview${e.failed?` composer-upload-preview-failed`:``}`,"data-upload-preview":e.id,children:[(0,F.jsx)(`img`,{src:e.url,alt:e.name,width:44,height:44,className:`composer-upload-thumb`}),(0,F.jsx)(`span`,{className:`composer-upload-state`,"data-upload-preview-state":e.failed?`failed`:`uploading`,children:e.failed?`上传失败`:`上传中…`}),(0,F.jsx)(`button`,{type:`button`,className:`composer-upload-remove`,"aria-label":`移除 ${e.name}`,title:`移除这张图片`,onClick:()=>{zr.current.add(e.id),URL.revokeObjectURL(e.url),qr(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(Ri.length>0||Vi>0||zi.length>0||Bi)&&(0,F.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[Ri.map((e,t)=>(0,F.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,F.jsx)(`img`,{src:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>Yr({url:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,F.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,F.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>fa(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),Vi>0&&(0,F.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,F.jsxs)(`span`,{children:[`图片上传中 (`,Vi,`)…`]})}),Bi&&(0,F.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,"data-composer-skill-loading":!0,role:`status`,children:`读取技能中…`}),zi.map(e=>(0,F.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,F.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,F.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,F.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>Ki(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),L&&qO(L)&&(0,F.jsx)(TO,{mode:mi,onChange:hi}),(0,F.jsxs)(`div`,{className:`composer`,children:[(0,F.jsxs)(`div`,{className:`session-picker`,id:`composer-session-options`,"data-session-picker":`1`,"data-mobile-expanded":bn,children:[(0,F.jsx)(LO,{kind:`agent`,label:yc?.name??`跟随 Pi 默认`,value:L?.agentId??RO,options:bc,disabled:!nn||nn.source===`unavailable`||nc,note:fO(nn),onChoose:Cc}),(0,F.jsx)(LO,{kind:`model`,label:oc?.label??(Jt?`Pi 默认`:`读取中…`),value:oc?`${oc.provider}/${oc.modelId}`:void 0,detail:Sc?`来自 ${yc?.name}`:oc&&Jt?.source===`pi`&&!L?.model?`Pi 默认模型`:oc?`${oc.provider}/${oc.modelId}`:void 0,options:hc,providerOptions:[...new Set(mc.map(e=>e.provider))],disabled:!lc||nc,note:dO(`模型`,Jt,fc),onChoose:_c}),(0,F.jsx)(LO,{kind:`thinking`,label:cc??(Jt?Jt.levels.length?`Pi 默认`:`无可用等级`:`读取中…`),value:sc,options:gc,disabled:!lc||nc,note:dO(`思考等级`,Jt),onChoose:vc})]}),(0,F.jsx)(`button`,{type:`button`,className:`mobile-composer-options`,"aria-controls":`composer-session-options`,"aria-expanded":bn,onClick:()=>xn(e=>!e),children:`会话选项`}),(0,F.jsxs)(`div`,{className:`composer-hints`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>Qr.current?.click(),disabled:!L||!X||Vi>0,title:L?X?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),(0,F.jsx)(`span`,{className:`composer-attach-label`,children:` 图片`})]}),(0,F.jsx)(`input`,{ref:Qr,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(wl(Array.from(e.target.files)),e.target.value=``)}}),fc&&(0,F.jsx)(`span`,{"data-image-session-hint":`1`,title:`此会话历史已包含图片,仅显示支持图文的模型`,children:`图文会话`}),(0,F.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,F.jsxs)(`div`,{className:`composer-actions`,children:[bi&&!Si&&(0,F.jsx)(`button`,{type:`button`,className:`composer-relock`,"data-child-session-relock":`1`,title:`重新给这个子会话上锁`,onClick:()=>Xs(L?.id??``,!1),children:`重新上锁`}),L&&(qO(L)||L.status===`awaiting_background`)&&(0,F.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":L.id,disabled:f.some(e=>e.key===`stop:${L.id}`)||Er.has(L.id),onClick:()=>Y({type:`run.stop`,conversationId:L.id},`stop:${L.id}`,e=>e),children:f.some(e=>e.key===`stop:${L.id}`)||Er.has(L.id)?`停止中…`:`停止`}),(0,F.jsx)(`button`,{className:`send ${qO(L)?mi===`steer`?`send-steer`:`send-queued`:``}`,"data-send-mode":qO(L)?mi===`steer`?`steer`:`queued`:`direct`,disabled:!Li.trim()&&Ri.length===0||!L||Vi>0||Bi||!!Ll||nc||Si,title:L?Si?`汇报线只允许逐级上升,子会话默认不能直接对话;确有特殊情况可解锁。`:ec?`正在创建会话,请稍候再发送`:L.messagesLoaded===!1?`正在加载会话,请稍候再发送`:Ll?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!Li.trim()&&Ri.length===0?`请输入消息或添加图片后发送`:Vi>0?`图片上传中…`:Bi?`技能正在读取中,请稍候…`:qO(L)?mi===`steer`?`当前工具完成后在下一回合边界插队回答(不会强行中止正在执行的工具)`:`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:Ll?`撤回中…`:qO(L)?mi===`steer`?`打断发送 ↑`:`排队发送 ↑`:`发送 ↑`})]})]})]}),Yc(`belowEditor`)]})]})]}),Ra&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Ym,{share:Fa,onShare:Ia}),(0,F.jsx)(Xm,{tabs:ps,selected:ms?.id,onSelect:hs,onPin:fs,onCloseTab:vs,onClose:gs,children:Is()})]})]})}),(pr||!Su)&&(0,F.jsx)(Zk,{side:`right`,width:gn&&pr?30:nr.rail,min:nr.railMin,max:nr.railMax,label:`调整右侧栏宽度`,onWidth:lr}),go&&(0,F.jsx)(Vm,{workspaceId:Da,cwd:Aa,connected:te,initialQuery:ho.initialQuery,onOpen:e=>Go(e,void 0,!1,!0),onClose:vo,onMode:_o},fo),ho?.mode===`content`&&(0,F.jsx)(Bm,{workspaceId:Da,cwd:Aa,directory:ho.directory,initialQuery:ho.initialQuery,onOpen:(e,t,n)=>Go(e,t,!1,!0,!1,n),onClose:vo,onMode:_o},JSON.stringify([fo,ho.directory])),ho?.mode===`session`&&(0,F.jsx)(Hf,{workspaceId:Da,initialQuery:ho.initialQuery,onOpen:So,onClose:vo,onMode:_o},fo),(0,F.jsx)(_k,{}),wn&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{type:`button`,className:`mobile-drawer-backdrop`,"data-mobile-drawer-backdrop":`1`,"aria-label":`关闭会话列表`,onClick:()=>Tn(!1)}),(0,F.jsx)(`button`,{type:`button`,className:`mobile-drawer-close`,"data-mobile-drawer-close":`1`,"aria-label":`关闭会话列表`,title:`关闭`,onClick:()=>Tn(!1),children:`×`})]}),vn===`rail`&&(0,F.jsx)(`button`,{type:`button`,className:`mobile-rail-back`,"data-mobile-nav":`chat`,onClick:Sn,children:`‹ 返回对话`}),Ar&&(0,F.jsx)(YD,{workspace:Ar.workspace,x:Ar.x,y:Ar.y,notify:Rs,onClose:()=>jr(void 0)}),Mr&&(0,F.jsx)(XD,{conversation:Mr.conversation,x:Mr.x,y:Mr.y,notify:Rs,onRename:()=>void rl(Mr.conversation.id),onClose:()=>Nr(void 0),sendCommand:Ks,orchestrated:Mr.conversation.origin===`orchestrator`,childCount:ui.filter(e=>e.parentConversationId===Mr.conversation.id).length}),Ae&&(0,F.jsx)(cO,{onClose:()=>je(!1),onCreate:Xc}),Pe&&(()=>{let e=T.workspaces.find(e=>e.id===Pe.workspaceId);return e?(0,F.jsx)(sO,{workspace:e,onClose:()=>{Fe(void 0),Ie.current?.focus()},onCreate:e=>{bl(Pe.workspaceId,e),Fe(void 0),Ie.current?.focus()}}):null})(),fl&&(0,F.jsx)(hg,{initialCategory:ml,workspaceId:k,theme:ul,onChooseTheme:e=>dl(e),onClose:()=>{pl(!1),ge()},agentCatalog:ln,subagentCatalog:dn,modelFilterRules:M.settingsSnapshot?.modelFilterRules??[],pendingSettings:f.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Ys({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:M.settingsSnapshot?.defaultModel,modelCatalog:Xt,onSetDefaultModel:e=>Ys({type:`settings.defaultModel`,model:e?{provider:e.provider,modelId:e.modelId}:null},`default-model`,t=>{let n={...t};return e?n.defaultModel=e:delete n.defaultModel,n}),providers:Qt,providerApis:en,onSetProvider:e=>{Js({type:`providers.set`,provider:e})},onRemoveProvider:e=>{Js({type:`providers.remove`,providerId:e})},onRepairProviders:()=>{Js({type:`providers.repair`}),Rs(`正在清理 Pi 不接受的空字段并重新读取模型清单`,`info`)},onToggleProvider:(e,t)=>{Js(t?{type:`providers.enable`,providerId:e}:{type:`providers.disable`,providerId:e}),Rs(t?`已启用供应商「${e}」,它的模型重新出现在选择器里`:`已停用供应商「${e}」:配置已从 Pi 的文件里拿掉并保存在这里,模型不再出现在选择器里`,`info`)},onRemoveProviderModel:(e,t)=>{Js({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:M.settingsSnapshot?.customAgentDirs??[],onSetCustomAgentDirs:e=>Ys({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>Js({type:`agents.rescan`}),userNickname:Lt,onSetUserNickname:zt,terminalShell:M.settingsSnapshot?.terminalShell,onSetTerminalShell:e=>{Js({type:`terminal.shell.set`,command:e})},onCheckBrowserNotifications:o,browserNotificationsEnabled:n,browserNotificationPermission:i,onSetBrowserNotifications:Vs}),gl&&(0,F.jsx)(lh,{onClose:()=>_l(!1)}),ll&&(0,F.jsx)(zO,{workspace:ll,onRemove:()=>il(ll),catalog:dc(Jt,ll),agents:nn,onClose:()=>ol(void 0),onRename:()=>{let e=ll.id;ol(void 0),$c(`workspace`,e)},onSave:(e,t,n)=>vl(ll.id,e,t,n)}),Jr&&(0,F.jsx)(xk,{image:Jr,onClose:()=>Yr(void 0)}),pr&&!gn&&(0,F.jsx)(`div`,{className:`rail-backdrop`,role:`presentation`,"aria-hidden":`true`,onClick:()=>_n(!0)}),pr?(0,F.jsx)(fk,{...Zl,activeTab:Za,collapsed:gn,onToggle:()=>_n(e=>!e)}):(0,F.jsxs)(F.Fragment,{children:[ao&&(0,F.jsx)(fk,{...Zl,side:`right`,activeTab:ao,collapsed:oo,onToggle:bu,pinned:!qn.unpinned.includes(ao),onArrange:lo}),(0,F.jsx)(Kr,{side:`right`,views:io,unpinned:qn.unpinned,previous:ao,active:oo?void 0:ao,onSelect:e=>co(e,!0),onArrange:lo,onReorder:uo})]}),mn.panel,I!==`group`&&Ec&&L&&(()=>{let e=Ec.key,t=Ec.value,n=br[e]??jO(t);return(0,F.jsx)(PO,{question:{key:e,messageId:Ec.messageId,index:Ec.index,value:t},pendingCount:Tc.length,minimized:Sr===e,floatingRight:pr?`12px`:gn?`24px`:`calc(var(--rail-width, 320px) + 24px)`,onMinimize:()=>Cr(e),onExpand:()=>Cr(null),onLocate:Dc,draft:n,onDraftChange:t=>ic(e,t),onAnswer:(e,t)=>rc(L.id,Ec.messageId,Ec.index,e,t)})})(),Ts===`workspaces`&&(0,F.jsx)(We,{anchor:Ds.current,title:`进入工作区`,onClose:()=>Es(void 0),choices:T.workspaces.filter(e=>!e.closedAt&&!e.id.startsWith(`pending:`)).sort((e,t)=>_e(e.id).localeCompare(_e(t.id))||(e.worktreeOf??e.id).localeCompare(t.worktreeOf??t.id)||Number(!!e.worktreeOf)-Number(!!t.worktreeOf)).map(e=>({id:e.id,label:e.name+(e.id===Da?` · 当前`:``),detail:e.path,group:_e(e.id)+` · `+(T.workspaces.find(t=>t.id===e.worktreeOf)?.name??e.name)})),onChoose:e=>{hu(de(e)),mu(`workspace`,e),ba(e),Es(void 0)},children:(0,F.jsx)(`button`,{type:`button`,onClick:()=>{Es(void 0),je(!0)},children:`添加工作区`})}),Ts===`worktrees`&&ka&&(0,F.jsx)(fn,{anchor:Ds.current,workspaceId:ka,summaries:T.workspaces.filter(e=>de(e.id)===de(ka)).map(e=>({path:e.path,running:T.conversations.filter(t=>t.workspaceId===e.id&&[`running`,`waiting`,`awaiting_background`].includes(t.status)).length})),onClose:()=>Es(void 0),onEnter:e=>{hu(de(e)),mu(`workspace`,e),ba(e),Es(void 0)},onBranches:()=>{Es(void 0),co(`git`),window.setTimeout(()=>window.dispatchEvent(new CustomEvent(`super-pi-status-git-view`,{detail:{workspaceId:ka,view:`branches`}})),0)}}),Ts===`line`&&ys&&(0,F.jsx)(We,{anchor:Ds.current,title:`跳转到行与列`,onClose:()=>Es(void 0),children:(0,F.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=/^(\d+)(?::(\d+))?$/.exec(J.trim());!t||Number(t[1])<1||t[2]&&Number(t[2])<1||(wo({scope:fo,path:ys.path,line:Number(t[1]),column:Number(t[2]??1),request:++ye.current}),Es(void 0))},children:[(0,F.jsxs)(`label`,{children:[`行号或 行号:列号`,(0,F.jsx)(`input`,{autoFocus:!0,"aria-label":`跳转位置`,value:J,onChange:e=>Os(e.target.value),pattern:`[1-9][0-9]*(:[1-9][0-9]*)?`,required:!0})]}),(0,F.jsx)(`button`,{type:`submit`,children:`跳转`})]})}),Ts===`language`&&(0,F.jsx)(We,{anchor:Ds.current,title:`文件语言与语法高亮`,onClose:()=>Es(void 0),choices:[{id:`auto`,label:`自动识别`},{id:`plain`,label:`纯文本`},...[`cpp`,`c`,`js`,`ts`,`tsx`,`py`,`go`,`rs`,`java`,`json`,`md`,`sh`,`css`,`html`,`yaml`,`sql`].map(e=>({id:e,label:Cn(e)||e}))],onChoose:e=>{As(t=>({...t,[bs]:e===`auto`?void 0:e})),Es(void 0)}}),Ts===`diff`&&(0,F.jsxs)(We,{anchor:Ds.current,title:`当前文件差异`,onClose:()=>Es(void 0),children:[(0,F.jsxs)(`p`,{children:[W?.target.comparison,` · `,jo]}),[-1,1].map(e=>(0,F.jsx)(`button`,{type:`button`,onClick:()=>{Es(void 0),window.dispatchEvent(new CustomEvent(`super-pi-status-diff-jump`,{detail:{url:W?.target.url,direction:e}}))},children:e<0?`上一处改动`:`下一处改动`},e))]}),(0,F.jsxs)(`footer`,{className:`workbench-status`,"data-workbench-status":`1`,"aria-label":`工作台状态`,children:[(0,F.jsxs)(`div`,{className:`workbench-status-group`,children:[(0,F.jsx)(Ue,{connected:te,onSelectServer:e=>hu(e),onSettings:()=>{he(),hl(`servers`),pl(!0)}}),_u&&te&&(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-branch`,"data-workbench-branch":_u,title:`进入其他工作树或管理分支`,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`worktrees`?void 0:`worktrees`)},children:[(0,F.jsx)(Gr,{name:`git`}),(0,F.jsx)(`code`,{children:_u}),yu&&(0,F.jsx)(`code`,{children:yu})]}),!!vu&&(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-changes`,"data-workbench-changes":vu,onClick:()=>{co(`git`),window.setTimeout(()=>window.dispatchEvent(new CustomEvent(`super-pi-status-git-view`,{detail:{workspaceId:ka,view:`changes`}})),0)},children:[vu,` 个改动`]}),(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-scope workbench-status-button`,title:js?.path??`选择工作区`,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`workspaces`?void 0:`workspaces`)},children:[(0,F.jsx)(Gr,{name:`files`}),(0,F.jsxs)(`span`,{children:[js?.name??`选择工作区`,Aa?` / `+Aa:``]})]})]}),(0,F.jsxs)(`div`,{className:`workbench-status-group workbench-status-context`,children:[I===`session`&&L&&(0,F.jsx)(LO,{kind:`model`,label:uc?.label??oc?.modelId??`选择模型`,value:oc?`${oc.provider}/${oc.modelId}`:void 0,options:hc,providerOptions:[...new Set(mc.map(e=>e.provider))],disabled:!lc||nc,onChoose:_c}),I===`session`&&L&&(0,F.jsx)(LO,{kind:`thinking`,label:cc??`思考等级`,value:sc,options:gc,disabled:!lc||nc,onChoose:vc}),I===`group`&<&&(0,F.jsx)(`button`,{type:`button`,className:`workbench-status-button`,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-status-group-models`,{detail:{roomId:lt}})),children:`群成员模型`}),I===`file`&&ys&&(ws?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-editor-cursor`,"data-workbench-editor-position":`1`,onClick:e=>{Ds.current=e.currentTarget,Os(`${ws.line}:${ws.column}`),Es(`line`)},children:[`第 `,ws.line,` 行,第 `,ws.column,` 列`]}),(0,F.jsx)(`button`,{type:`button`,className:`workbench-status-button`,"data-file-highlight-status":ws.highlight,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`language`?void 0:`language`)},children:ws.language})]}):(0,F.jsx)(`span`,{title:ys.path,children:ys.name})),G===`diff`&&jo&&(0,F.jsx)(`button`,{type:`button`,className:`workbench-status-button`,title:jo,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`diff`?void 0:`diff`)},children:jo}),mn.entry(`workbench-status-button software-update-desktop`),(0,F.jsxs)(`button`,{type:`button`,className:`workbench-version workbench-status-button`,"data-super-pi-version":(mn.status??sn)?.runningVersion??``,title:`查看版本与软件更新`,onClick:mn.open,children:[`v`,(mn.status??sn)?.runningVersion??`…`]})]})]})]})}Zh(Xh()),(0,d.createRoot)(document.getElementById(`root`)).render((0,F.jsx)(u.StrictMode,{children:(0,F.jsx)(cA,{})}));export{ii as a,Cn as c,Be as d,r as f,ti as i,Sn as l,Rp as n,kr as o,Vp as r,Or as s,Xp as t,vn as u};
|
|
348
|
+
`),u=(()=>{let e=/<result_file>([\s\S]*?)<\/result_file>/.exec(t.content);return e&&e[1].trim()?e[1].trim():void 0})(),d=(()=>{let e=/<task id="([^"]+)"/.exec(t.content);return e?e[1]:void 0})(),f=!!(d&&ui.some(e=>e.id===d)),p=`tool:${t.id}`,m=gr[p]??!1,h=r?`自动恢复`:i?`后台回传`:`智能体下发`;return(0,F.jsx)(`article`,{className:`message tool${i?``:` tool-order`}`,"data-transcript-key":e,"data-tool-state":o,"data-tool-kind":r?`recovery`:i?`delivery`:`order`,children:(0,F.jsxs)(`div`,{className:`message-body`,children:[(0,F.jsxs)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:[(0,F.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":m,title:m?`折叠${h}`:`展开${h}`,onClick:()=>_r(e=>({...e,[p]:!m})),children:[(0,F.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:o===`error`?`✕`:i?`↩`:`↓`}),(0,F.jsx)(`span`,{className:`bg-result-label`,children:c&&(c.status===`cancelled`||c.status===`interrupted`)?YO[c.status]:h}),(0,F.jsx)(`span`,{className:`bg-result-summary`,title:a,children:a}),!m&&(0,F.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看任务输出`,children:c?.reason||_O(l)}),(0,F.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:m?`▾`:`▸`})]}),(u||f&&d)&&(0,F.jsxs)(`div`,{className:`bg-result-actions`,"data-bg-result-actions":t.id,children:[u&&(0,F.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-file-link":u,title:`在主区域打开产物文件:${u}`,onClick:e=>{e.stopPropagation();let t=u.split(/[/\\]/).pop()||u;Go({path:u,name:t,text:!0}).catch(e=>{console.warn(`打开产物文件失败:`,e)})},children:[(0,F.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`📄`}),(0,F.jsx)(`span`,{children:`查看产物文件`})]}),f&&d&&(0,F.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-session-link":d,title:`跳转到子会话:${d}`,onClick:e=>{e.stopPropagation(),va(d)},children:[(0,F.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`↗`}),(0,F.jsx)(`span`,{children:`跳转到子会话`})]})]})]}),m&&(0,F.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,F.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:l})})]})},e)}let l=t.thinking?.trim()?t.thinking:``,u=t.thinkingBlocks?.length?t.thinkingBlocks:l?[{at:0,text:l}]:[],d=(e,n)=>{let r=typeof e.at==`number`&&Number.isFinite(e.at)?e.at:n;return Math.max(0,Math.min(r,t.content.length))},p=e=>e.thinkingBlock===void 0?typeof e.thinkingAt!=`number`||!(e.thinkingAt<l.length||t.thinkingActive)?-1:u.findIndex((t,n)=>(e.at??0)>=t.at&&(u[n+1]===void 0||(e.at??0)<u[n+1].at)):e.thinkingBlock??-1,m=e=>s.map((e,t)=>({call:e,index:t})).filter(({call:t})=>p(t)===e),h=[],g=[...u.map((e,t)=>({at:e.at,order:u.slice(0,t).reduce((e,t)=>e+t.text.length,0)*2+1,segment:{blockIndex:t}})),...s.map((e,t)=>({at:d(e,t),order:(e.thinkingAt??0)*2,segment:{call:e,index:t}})).filter(({segment:e})=>`call`in e&&p(e.call)<0)].sort((e,t)=>e.at-t.at||e.order-t.order),_=0;for(let e of g){let n=Math.max(_,Math.min(e.at,t.content.length));n>_&&h.push({text:t.content.slice(_,n)}),h.push(e.segment),_=n}_<t.content.length&&h.push({text:t.content.slice(_)});let v=e=>{let t=Rc.get(e);if(t)return(0,F.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,F.jsx)(CO,{run:t,name:Fc.get(t.agentId)??``,expanded:!!mr[t.id],onToggle:()=>Vc(t.id),onStop:()=>qc(t.id),stopping:f.some(e=>e.key===`stop:${t.id}`)})})},y=e=>e.call.question?(()=>{let n=jO(L?.id??``,t.id,e.index),r=br[n]??MO(e.call.question);return(0,F.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,F.jsx)(NO,{question:e.call.question,index:e.index,draft:r,onDraftChange:e=>ic(n,e),expanded:`${t.id}:${e.index}`in vr?!!vr[`${t.id}:${e.index}`]:!0,onToggle:()=>Uc(t.id,e.index),onAnswer:(n,r)=>rc(L?.id??``,t.id,e.index,n,r)})},`c${e.index}`)})():(0,F.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,F.jsx)(bO,{call:e.call,index:e.index,expanded:`${t.id}:${e.index}`in gr&&!!gr[`${t.id}:${e.index}`],onToggle:()=>Hc(t.id,e.index),backgroundOutput:e.call.backgroundTask&&(0,F.jsx)(yO,{task:e.call.backgroundTask,execOutputs:bt.current,expanded:`${t.id}:${e.index}`in gr&&!!gr[`${t.id}:${e.index}`]}),runCard:v(`${t.id}:${e.index}`)})},`c${e.index}`),b=e=>{let n=u[e],r=u.slice(0,e).reduce((e,t)=>e+t.text.length,0),i=0,a=[];for(let{call:t,index:o}of m(e).sort((e,t)=>(e.call.thinkingAt??r)-(t.call.thinkingAt??r)||e.index-t.index)){let e=Math.max(i,Math.min(n.text.length,(t.thinkingAt??r)-r));e>i&&a.push((0,F.jsx)(`div`,{className:`content thinking-text`,children:(0,F.jsx)(ef,{source:n.text.slice(i,e),media:pi})},`t${o}`)),a.push(y({call:t,index:o})),i=e}i<n.text.length&&a.push((0,F.jsx)(`div`,{className:`content thinking-text`,children:(0,F.jsx)(ef,{source:n.text.slice(i),media:pi})},`tail`));let o=m(e).filter(e=>e.call.status===void 0),s=o.find(e=>e.call.question?.status===`pending`);return(0,F.jsx)(SO,{liveCall:s?`question`:o.at(-1)?.call.label,liveAwaitingReader:!!s,liveExtra:o.length>1?o.length-1:void 0,messageId:`${t.id}:${e}`,nestedCount:m(e).length,preview:n.text.split(`
|
|
349
|
+
`).map(e=>e.trim()).find(Boolean)??``,expanded:Wc[`${t.id}:${e}`]===!0,onToggle:()=>Kc(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,F.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,F.jsx)(`div`,{className:`avatar`,children:`π`}),(0,F.jsxs)(`div`,{className:`message-body`,children:[(0,F.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,F.jsx)(`time`,{children:BD(t.createdAt)})]}),h.length===0&&(L?.status===`running`||L?.status===`waiting`)?(0,F.jsx)(`div`,{className:`content`,children:(0,F.jsx)(`span`,{className:`typing`,children:`正在思考`})}):h.map((e,t)=>`blockIndex`in e?b(e.blockIndex):`text`in e?e.text?(0,F.jsx)(`div`,{className:`content`,children:(0,F.jsx)(ef,{source:e.text,media:pi,sourceLink:Bs})},`t${t}`):null:y(e)),t.content.trim()&&(0,F.jsx)(`div`,{className:`message-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":c,"aria-label":`复制智能体回复`,onClick:()=>void Wl(t.id,t.content),children:(0,F.jsx)(`span`,{"aria-live":`polite`,children:c===`copied`?`已复制`:c===`error`?`复制失败`:`复制`})})})]})]},e)}if(e.startsWith(`w:`)){let t=Pc.get(e.slice(2));return t?(0,F.jsxs)(`div`,{"data-transcript-key":e,children:[f.some(e=>e.key===`stop:${t.id}`)&&(0,F.jsx)(`span`,{children:`停止中…`}),(0,F.jsx)(sh,{workflow:t,names:Fc,stopping:f.some(e=>e.key===`stop:${t.id}`),onStop:()=>Jc(t.id)},e)]},e):null}let t=Lc.get(e.slice(2));return t?(0,F.jsxs)(`div`,{"data-transcript-key":e,children:[f.some(e=>e.key===`stop:${t.id}`)&&(0,F.jsx)(`span`,{children:`停止中…`}),(0,F.jsx)(CO,{run:t,stopping:f.some(e=>e.key===`stop:${t.id}`),name:Fc.get(t.agentId)??``,expanded:!!mr[t.id],onToggle:()=>Vc(t.id),onStop:()=>qc(t.id)},e)]},e):null})]}),!Oi&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(DO,{messages:Al,pendingInterrupts:f.filter(e=>e.key.startsWith(`interrupt:${L?.id}:`)).map(e=>e.key.slice(`interrupt:${L?.id}:`.length)),running:L?.status===`running`,onSteer:Nl,onInterrupt:Pl,onSend:Fl,onCancel:jl,onCancelMany:Ml,onEdit:Il}),(0,F.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":_t.followTail?`true`:`false`,children:[ur!==null&&(0,F.jsx)(aA,{height:ur,onHeight:fr}),(0,F.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":L?.status??`idle`,"data-stream-state":te?tc?`stopping`:L&&ZO(L,hn)?`question`:L?.status===`waiting`?`waiting`:L?.status===`running`?`streaming`:L?.status===`awaiting_background`||Al.length?`waiting`:L?.status===`failed`?`failed`:Ti===`awaiting_decision`?`awaiting_decision`:Ti===`awaiting_subordinates`?`awaiting_subordinates`:Ti===`pending_report`?`pending_report`:`ready`:`waiting`,children:te?ec?`正在创建会话…`:tc?`正在停止…`:L&&ZO(L,hn)?`等你回答 · Agent 在等你的回复`:L?.messagesLoaded===!1?`正在加载会话…`:L?.status===`waiting`?`等待 LLM 返回`:L?.status===`running`?`Streaming · 正在生成`:L?.status===`awaiting_background`?`等待后台任务 · 任务在后台运行中`:Al.length?`Waiting · 消息排队中`:L?.status===`failed`?`运行失败`:L?.status===`stopped`?`已停止`:Ti===`awaiting_decision`?`等待上级处理例外…`:Ti===`awaiting_subordinates`?`等待下级汇报…`:Ti===`pending_report`?`已完成,待向父会话汇报`:`就绪`:`连接中 / 等待连接`}),!_t.followTail&&(0,F.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=ft.current;e&&(Vk(e),e.scrollTop=e.scrollHeight,Pi(e,!1,!0))},children:`↓ 跳到底部`}),(0,F.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":_t.followTail?`true`:`false`,children:_t.followTail?`贴底`:`自由浏览`})]}),(wc.length>0||[...Ac.values()].some(e=>e.placement===`aboveEditor`))&&(0,F.jsxs)(`div`,{className:`extui`,"data-extui-count":wc.length,children:[wc.map(e=>(0,F.jsx)(IO,{request:e.request,pending:f.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>ac(e.conversationId,e.request.requestId,t)},e.request.requestId)),Yc(`aboveEditor`)]}),(0,F.jsxs)(`form`,{onSubmit:kl,onPaste:Tl,onDragOver:El,onDragLeave:Dl,onDrop:Ol,className:Xr?`composer-dropzone-active`:void 0,children:[(0,F.jsxs)(`div`,{className:`composer-input`,"data-composer-input":`1`,children:[(0,F.jsx)(`textarea`,{ref:pt,value:Li,onCompositionStart:()=>{$r.current=!0,$i(void 0)},onCompositionEnd:e=>{$r.current=!1,ca.current=``,ua(e.currentTarget)},onSelect:e=>{e.currentTarget===document.activeElement&&ua(e.currentTarget)},"aria-autocomplete":la?`list`:void 0,"aria-controls":la?`file-mention-menu`:void 0,"aria-activedescendant":la?R:void 0,onChange:e=>{Wi(e.target.value),e.target.value!==Li&&_a(L?.id??``);let t=e.target.value;if(ca.current=``,ua(e.currentTarget))return;let n=e.target.selectionStart??t.length,r=t.slice(0,n),i=r.lastIndexOf(`/`),a=r.slice(i+1),o=i>0?r[i-1]:``;i>=0&&(i===0||/\s/.test(o))&&/^[\w:-]*$/u.test(a)?Ji({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):Ji({visible:!1,query:``,rect:null})},placeholder:L?X?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!L,readOnly:Si,"aria-describedby":Si?`child-session-lock-reason`:void 0,onKeyDown:e=>{if(!($r.current||PD(e))&&!(la&&ea.current?.handleKey(e))){if(qi.visible){if(e.key===`Escape`){e.preventDefault(),Ji({visible:!1,query:``,rect:null});return}if([`ArrowDown`,`ArrowUp`,`Enter`].includes(e.key)){e.preventDefault();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}}),Si&&(0,F.jsxs)(`div`,{className:`composer-lock`,"data-child-session-lock":`1`,role:`note`,"aria-labelledby":`child-session-lock-title`,children:[(0,F.jsx)(`span`,{className:`composer-lock-glyph`,"data-child-session-lock-glyph":`1`,"aria-hidden":`true`,children:(0,F.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`30`,height:`30`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,focusable:`false`,children:[(0,F.jsx)(`rect`,{x:`4`,y:`10`,width:`16`,height:`11`,rx:`2.5`}),(0,F.jsx)(`path`,{d:`M8 10V7a4 4 0 0 1 8 0v3`}),(0,F.jsx)(`path`,{d:`M12 14.5v2.5`})]})}),(0,F.jsxs)(`span`,{className:`composer-lock-text`,children:[(0,F.jsx)(`span`,{className:`composer-lock-title`,"data-child-session-lock-title":`1`,id:`child-session-lock-title`,children:`子会话输入框已上锁`}),(0,F.jsx)(`span`,{className:`composer-lock-reason`,"data-child-session-lock-reason":`1`,id:`child-session-lock-reason`,children:`汇报线只允许逐级上升,子会话默认不能直接对话;确有特殊情况可解锁。`})]}),(0,F.jsx)(`button`,{type:`button`,className:`composer-lock-action`,"data-child-session-unlock":`1`,onClick:()=>Xs(L?.id??``,!0),children:`临时解锁`})]})]}),la&&L?.workspaceId&&(0,F.jsx)(hf,{ref:ea,workspaceId:L.workspaceId,cwd:L.cwd??``,query:la.token.query,anchor:la.rect,onClose:da,onActive:oa,onChoose:e=>{let t=pt.current,n=t?.value??Li,r=t?gf(n,t.selectionStart,t.selectionEnd):void 0;if(!r||r.start!==la.token.start||r.query!==la.token.query){da();return}let i=_f(n,r,e);sa.current={scope:Zi,...i},Wi(i.text),$i(void 0)}},Zi),!la&&qi.visible&&qi.rect&&(0,F.jsx)(mf,{query:qi.query,anchorRect:qi.rect,workspaceId:L?.workspaceId,promptCatalog:Vt,command:Ks,onSelect:e=>{let t=pt.current?.selectionStart??Li.length,n=Li.slice(0,t),r=n.lastIndexOf(`/`),i=df(e,qi.query),a=`${n.slice(0,r)}/${i} ${Li.slice(t)}`;e.id.startsWith(`skill:`)&&L?Gi(e.id,a,L.id,L.workspaceId):Wi(a),Ji({visible:!1,query:``,rect:null})},onClose:()=>Ji({visible:!1,query:``,rect:null})}),vi.filter(e=>e.conversationId===L?.id).map(e=>(0,F.jsxs)(`div`,{className:`composer-notice queue-withdrawn-notice`,"data-queue-withdrawn-notice":`1`,role:`status`,children:[(0,F.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`↺`}),(0,F.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,F.jsx)(`p`,{className:`composer-notice-title`,children:e.actor===`agent`?`上级 Agent 已撤回 ${e.withdrawn.length} 条排队消息(不会再被回答)`:`已撤回 ${e.withdrawn.length} 条排队消息(不会再被回答)`}),(0,F.jsx)(`p`,{className:`composer-notice-text`,title:e.withdrawn.map(e=>e.content).join(`
|
|
350
|
+
`),children:e.withdrawn.map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,48)}」`).join(` · `)})]}),(0,F.jsx)(`div`,{className:`composer-notice-actions`,children:(0,F.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-queue-withdrawn-dismiss":`1`,onClick:()=>yi(t=>t.filter(t=>t.id!==e.id)),children:`知道了`})})]},e.id)),Br.filter(e=>e.conversationId===L?.id).map(e=>(0,F.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,F.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,F.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,F.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,title:kr(e.reason),children:e.reason?.trim()?Or(e.reason):`服务端没有接受这条消息。`}),(0,F.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,F.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,F.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(Li||Ri.length||zi.length),title:Li||Ri.length||zi.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{Hi(e.conversationId,t=>({...t,text:e.content,images:e.images,attachments:e.attachments})),Vr(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,F.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>Vr(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),Wr.filter(e=>e.conversationId===L?.id).map(e=>(0,F.jsxs)(`div`,{className:`composer-upload-preview${e.failed?` composer-upload-preview-failed`:``}`,"data-upload-preview":e.id,children:[(0,F.jsx)(`img`,{src:e.url,alt:e.name,width:44,height:44,className:`composer-upload-thumb`}),(0,F.jsx)(`span`,{className:`composer-upload-state`,"data-upload-preview-state":e.failed?`failed`:`uploading`,children:e.failed?`上传失败`:`上传中…`}),(0,F.jsx)(`button`,{type:`button`,className:`composer-upload-remove`,"aria-label":`移除 ${e.name}`,title:`移除这张图片`,onClick:()=>{zr.current.add(e.id),URL.revokeObjectURL(e.url),qr(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(Ri.length>0||Vi>0||zi.length>0||Bi)&&(0,F.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[Ri.map((e,t)=>(0,F.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,F.jsx)(`img`,{src:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>Yr({url:Me(`/api/upload/${encodeURIComponent(L?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,F.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,F.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>fa(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),Vi>0&&(0,F.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,F.jsxs)(`span`,{children:[`图片上传中 (`,Vi,`)…`]})}),Bi&&(0,F.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,"data-composer-skill-loading":!0,role:`status`,children:`读取技能中…`}),zi.map(e=>(0,F.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,F.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,F.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,F.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>Ki(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),L&&JO(L)&&(0,F.jsx)(EO,{mode:mi,onChange:hi}),(0,F.jsxs)(`div`,{className:`composer`,children:[(0,F.jsxs)(`div`,{className:`session-picker`,id:`composer-session-options`,"data-session-picker":`1`,"data-mobile-expanded":bn,children:[(0,F.jsx)(RO,{kind:`agent`,label:yc?.name??`跟随 Pi 默认`,value:L?.agentId??zO,options:bc,disabled:!nn||nn.source===`unavailable`||nc,note:pO(nn),onChoose:Cc}),(0,F.jsx)(RO,{kind:`model`,label:oc?.label??(Jt?`Pi 默认`:`读取中…`),value:oc?`${oc.provider}/${oc.modelId}`:void 0,detail:Sc?`来自 ${yc?.name}`:oc&&Jt?.source===`pi`&&!L?.model?`Pi 默认模型`:oc?`${oc.provider}/${oc.modelId}`:void 0,options:hc,providerOptions:[...new Set(mc.map(e=>e.provider))],disabled:!lc||nc,note:fO(`模型`,Jt,fc),onChoose:_c}),(0,F.jsx)(RO,{kind:`thinking`,label:cc??(Jt?Jt.levels.length?`Pi 默认`:`无可用等级`:`读取中…`),value:sc,options:gc,disabled:!lc||nc,note:fO(`思考等级`,Jt),onChoose:vc})]}),(0,F.jsx)(`button`,{type:`button`,className:`mobile-composer-options`,"aria-controls":`composer-session-options`,"aria-expanded":bn,onClick:()=>xn(e=>!e),children:`会话选项`}),(0,F.jsxs)(`div`,{className:`composer-hints`,children:[(0,F.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>Qr.current?.click(),disabled:!L||!X||Vi>0,title:L?X?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,F.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),(0,F.jsx)(`span`,{className:`composer-attach-label`,children:` 图片`})]}),(0,F.jsx)(`input`,{ref:Qr,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(wl(Array.from(e.target.files)),e.target.value=``)}}),fc&&(0,F.jsx)(`span`,{"data-image-session-hint":`1`,title:`此会话历史已包含图片,仅显示支持图文的模型`,children:`图文会话`}),(0,F.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,F.jsxs)(`div`,{className:`composer-actions`,children:[bi&&!Si&&(0,F.jsx)(`button`,{type:`button`,className:`composer-relock`,"data-child-session-relock":`1`,title:`重新给这个子会话上锁`,onClick:()=>Xs(L?.id??``,!1),children:`重新上锁`}),L&&(JO(L)||L.status===`awaiting_background`)&&(0,F.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":L.id,disabled:f.some(e=>e.key===`stop:${L.id}`)||Er.has(L.id),onClick:()=>Y({type:`run.stop`,conversationId:L.id},`stop:${L.id}`,e=>e),children:f.some(e=>e.key===`stop:${L.id}`)||Er.has(L.id)?`停止中…`:`停止`}),(0,F.jsx)(`button`,{className:`send ${JO(L)?mi===`steer`?`send-steer`:`send-queued`:``}`,"data-send-mode":JO(L)?mi===`steer`?`steer`:`queued`:`direct`,disabled:!Li.trim()&&Ri.length===0||!L||Vi>0||Bi||!!Ll||nc||Si,title:L?Si?`汇报线只允许逐级上升,子会话默认不能直接对话;确有特殊情况可解锁。`:ec?`正在创建会话,请稍候再发送`:L.messagesLoaded===!1?`正在加载会话,请稍候再发送`:Ll?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!Li.trim()&&Ri.length===0?`请输入消息或添加图片后发送`:Vi>0?`图片上传中…`:Bi?`技能正在读取中,请稍候…`:JO(L)?mi===`steer`?`当前工具完成后在下一回合边界插队回答(不会强行中止正在执行的工具)`:`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:Ll?`撤回中…`:JO(L)?mi===`steer`?`打断发送 ↑`:`排队发送 ↑`:`发送 ↑`})]})]})]}),Yc(`belowEditor`)]})]})]}),Ra&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Ym,{share:Fa,onShare:Ia}),(0,F.jsx)(Xm,{tabs:ps,selected:ms?.id,onSelect:hs,onPin:fs,onCloseTab:vs,onClose:gs,children:Is()})]})]})}),(pr||!Su)&&(0,F.jsx)(Qk,{side:`right`,width:gn&&pr?30:nr.rail,min:nr.railMin,max:nr.railMax,label:`调整右侧栏宽度`,onWidth:lr}),go&&(0,F.jsx)(Vm,{workspaceId:Da,cwd:Aa,connected:te,initialQuery:ho.initialQuery,onOpen:e=>Go(e,void 0,!1,!0),onClose:vo,onMode:_o},fo),ho?.mode===`content`&&(0,F.jsx)(Bm,{workspaceId:Da,cwd:Aa,directory:ho.directory,initialQuery:ho.initialQuery,onOpen:(e,t,n)=>Go(e,t,!1,!0,!1,n),onClose:vo,onMode:_o},JSON.stringify([fo,ho.directory])),ho?.mode===`session`&&(0,F.jsx)(Hf,{workspaceId:Da,initialQuery:ho.initialQuery,onOpen:So,onClose:vo,onMode:_o},fo),(0,F.jsx)(vk,{}),wn&&(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`button`,{type:`button`,className:`mobile-drawer-backdrop`,"data-mobile-drawer-backdrop":`1`,"aria-label":`关闭会话列表`,onClick:()=>Tn(!1)}),(0,F.jsx)(`button`,{type:`button`,className:`mobile-drawer-close`,"data-mobile-drawer-close":`1`,"aria-label":`关闭会话列表`,title:`关闭`,onClick:()=>Tn(!1),children:`×`})]}),vn===`rail`&&(0,F.jsx)(`button`,{type:`button`,className:`mobile-rail-back`,"data-mobile-nav":`chat`,onClick:Sn,children:`‹ 返回对话`}),Ar&&(0,F.jsx)(XD,{workspace:Ar.workspace,x:Ar.x,y:Ar.y,notify:Rs,onClose:()=>jr(void 0)}),Mr&&(0,F.jsx)(ZD,{conversation:Mr.conversation,x:Mr.x,y:Mr.y,notify:Rs,onRename:()=>void rl(Mr.conversation.id),onClose:()=>Nr(void 0),sendCommand:Ks,orchestrated:Mr.conversation.origin===`orchestrator`,childCount:ui.filter(e=>e.parentConversationId===Mr.conversation.id).length}),Ae&&(0,F.jsx)(lO,{onClose:()=>je(!1),onCreate:Xc}),Pe&&(()=>{let e=T.workspaces.find(e=>e.id===Pe.workspaceId);return e?(0,F.jsx)(cO,{workspace:e,onClose:()=>{Fe(void 0),Ie.current?.focus()},onCreate:e=>{bl(Pe.workspaceId,e),Fe(void 0),Ie.current?.focus()}}):null})(),fl&&(0,F.jsx)(gg,{initialCategory:ml,workspaceId:k,theme:ul,onChooseTheme:e=>dl(e),onClose:()=>{pl(!1),ge()},agentCatalog:ln,subagentCatalog:dn,modelFilterRules:M.settingsSnapshot?.modelFilterRules??[],pendingSettings:f.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Ys({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:M.settingsSnapshot?.defaultModel,modelCatalog:Xt,onSetDefaultModel:e=>Ys({type:`settings.defaultModel`,model:e?{provider:e.provider,modelId:e.modelId}:null},`default-model`,t=>{let n={...t};return e?n.defaultModel=e:delete n.defaultModel,n}),providers:Qt,providerApis:en,onSetProvider:e=>{Js({type:`providers.set`,provider:e})},onRemoveProvider:e=>{Js({type:`providers.remove`,providerId:e})},onRepairProviders:()=>{Js({type:`providers.repair`}),Rs(`正在清理 Pi 不接受的空字段并重新读取模型清单`,`info`)},onToggleProvider:(e,t)=>{Js(t?{type:`providers.enable`,providerId:e}:{type:`providers.disable`,providerId:e}),Rs(t?`已启用供应商「${e}」,它的模型重新出现在选择器里`:`已停用供应商「${e}」:配置已从 Pi 的文件里拿掉并保存在这里,模型不再出现在选择器里`,`info`)},onRemoveProviderModel:(e,t)=>{Js({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:M.settingsSnapshot?.customAgentDirs??[],onSetCustomAgentDirs:e=>Ys({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>Js({type:`agents.rescan`}),userNickname:Lt,onSetUserNickname:zt,terminalShell:M.settingsSnapshot?.terminalShell,onSetTerminalShell:e=>{Js({type:`terminal.shell.set`,command:e})},onCheckBrowserNotifications:o,browserNotificationsEnabled:n,browserNotificationPermission:i,onSetBrowserNotifications:Vs}),gl&&(0,F.jsx)(lh,{onClose:()=>_l(!1)}),ll&&(0,F.jsx)(BO,{workspace:ll,onRemove:()=>il(ll),catalog:dc(Jt,ll),agents:nn,onClose:()=>ol(void 0),onRename:()=>{let e=ll.id;ol(void 0),$c(`workspace`,e)},onSave:(e,t,n)=>vl(ll.id,e,t,n)}),Jr&&(0,F.jsx)(Sk,{image:Jr,onClose:()=>Yr(void 0)}),pr&&!gn&&(0,F.jsx)(`div`,{className:`rail-backdrop`,role:`presentation`,"aria-hidden":`true`,onClick:()=>_n(!0)}),pr?(0,F.jsx)(pk,{...Zl,activeTab:Za,collapsed:gn,onToggle:()=>_n(e=>!e)}):(0,F.jsxs)(F.Fragment,{children:[ao&&(0,F.jsx)(pk,{...Zl,side:`right`,activeTab:ao,collapsed:oo,onToggle:bu,pinned:!qn.unpinned.includes(ao),onArrange:lo}),(0,F.jsx)(Kr,{side:`right`,views:io,unpinned:qn.unpinned,previous:ao,active:oo?void 0:ao,onSelect:e=>co(e,!0),onArrange:lo,onReorder:uo})]}),mn.panel,I!==`group`&&Ec&&L&&(()=>{let e=Ec.key,t=Ec.value,n=br[e]??MO(t);return(0,F.jsx)(FO,{question:{key:e,messageId:Ec.messageId,index:Ec.index,value:t},pendingCount:Tc.length,minimized:Sr===e,floatingRight:pr?`12px`:gn?`24px`:`calc(var(--rail-width, 320px) + 24px)`,onMinimize:()=>Cr(e),onExpand:()=>Cr(null),onLocate:Dc,draft:n,onDraftChange:t=>ic(e,t),onAnswer:(e,t)=>rc(L.id,Ec.messageId,Ec.index,e,t)})})(),Ts===`workspaces`&&(0,F.jsx)(We,{anchor:Ds.current,title:`进入工作区`,onClose:()=>Es(void 0),choices:T.workspaces.filter(e=>!e.closedAt&&!e.id.startsWith(`pending:`)).sort((e,t)=>_e(e.id).localeCompare(_e(t.id))||(e.worktreeOf??e.id).localeCompare(t.worktreeOf??t.id)||Number(!!e.worktreeOf)-Number(!!t.worktreeOf)).map(e=>({id:e.id,label:e.name+(e.id===Da?` · 当前`:``),detail:e.path,group:_e(e.id)+` · `+(T.workspaces.find(t=>t.id===e.worktreeOf)?.name??e.name)})),onChoose:e=>{hu(de(e)),mu(`workspace`,e),ba(e),Es(void 0)},children:(0,F.jsx)(`button`,{type:`button`,onClick:()=>{Es(void 0),je(!0)},children:`添加工作区`})}),Ts===`worktrees`&&ka&&(0,F.jsx)(fn,{anchor:Ds.current,workspaceId:ka,summaries:T.workspaces.filter(e=>de(e.id)===de(ka)).map(e=>({path:e.path,running:T.conversations.filter(t=>t.workspaceId===e.id&&[`running`,`waiting`,`awaiting_background`].includes(t.status)).length})),onClose:()=>Es(void 0),onEnter:e=>{hu(de(e)),mu(`workspace`,e),ba(e),Es(void 0)},onBranches:()=>{Es(void 0),co(`git`),window.setTimeout(()=>window.dispatchEvent(new CustomEvent(`super-pi-status-git-view`,{detail:{workspaceId:ka,view:`branches`}})),0)}}),Ts===`line`&&ys&&(0,F.jsx)(We,{anchor:Ds.current,title:`跳转到行与列`,onClose:()=>Es(void 0),children:(0,F.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=/^(\d+)(?::(\d+))?$/.exec(J.trim());!t||Number(t[1])<1||t[2]&&Number(t[2])<1||(wo({scope:fo,path:ys.path,line:Number(t[1]),column:Number(t[2]??1),request:++ye.current}),Es(void 0))},children:[(0,F.jsxs)(`label`,{children:[`行号或 行号:列号`,(0,F.jsx)(`input`,{autoFocus:!0,"aria-label":`跳转位置`,value:J,onChange:e=>Os(e.target.value),pattern:`[1-9][0-9]*(:[1-9][0-9]*)?`,required:!0})]}),(0,F.jsx)(`button`,{type:`submit`,children:`跳转`})]})}),Ts===`language`&&(0,F.jsx)(We,{anchor:Ds.current,title:`文件语言与语法高亮`,onClose:()=>Es(void 0),choices:[{id:`auto`,label:`自动识别`},{id:`plain`,label:`纯文本`},...[`cpp`,`c`,`js`,`ts`,`tsx`,`py`,`go`,`rs`,`java`,`json`,`md`,`sh`,`css`,`html`,`yaml`,`sql`].map(e=>({id:e,label:Cn(e)||e}))],onChoose:e=>{As(t=>({...t,[bs]:e===`auto`?void 0:e})),Es(void 0)}}),Ts===`diff`&&(0,F.jsxs)(We,{anchor:Ds.current,title:`当前文件差异`,onClose:()=>Es(void 0),children:[(0,F.jsxs)(`p`,{children:[W?.target.comparison,` · `,jo]}),[-1,1].map(e=>(0,F.jsx)(`button`,{type:`button`,onClick:()=>{Es(void 0),window.dispatchEvent(new CustomEvent(`super-pi-status-diff-jump`,{detail:{url:W?.target.url,direction:e}}))},children:e<0?`上一处改动`:`下一处改动`},e))]}),(0,F.jsxs)(`footer`,{className:`workbench-status`,"data-workbench-status":`1`,"aria-label":`工作台状态`,children:[(0,F.jsxs)(`div`,{className:`workbench-status-group`,children:[(0,F.jsx)(Ue,{connected:te,onSelectServer:e=>hu(e),onSettings:()=>{he(),hl(`servers`),pl(!0)}}),_u&&te&&(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-branch`,"data-workbench-branch":_u,title:`进入其他工作树或管理分支`,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`worktrees`?void 0:`worktrees`)},children:[(0,F.jsx)(Gr,{name:`git`}),(0,F.jsx)(`code`,{children:_u}),yu&&(0,F.jsx)(`code`,{children:yu})]}),!!vu&&(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-changes`,"data-workbench-changes":vu,onClick:()=>{co(`git`),window.setTimeout(()=>window.dispatchEvent(new CustomEvent(`super-pi-status-git-view`,{detail:{workspaceId:ka,view:`changes`}})),0)},children:[vu,` 个改动`]}),(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-scope workbench-status-button`,title:js?.path??`选择工作区`,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`workspaces`?void 0:`workspaces`)},children:[(0,F.jsx)(Gr,{name:`files`}),(0,F.jsxs)(`span`,{children:[js?.name??`选择工作区`,Aa?` / `+Aa:``]})]})]}),(0,F.jsxs)(`div`,{className:`workbench-status-group workbench-status-context`,children:[I===`session`&&L&&(0,F.jsx)(RO,{kind:`model`,label:uc?.label??oc?.modelId??`选择模型`,value:oc?`${oc.provider}/${oc.modelId}`:void 0,options:hc,providerOptions:[...new Set(mc.map(e=>e.provider))],disabled:!lc||nc,onChoose:_c}),I===`session`&&L&&(0,F.jsx)(RO,{kind:`thinking`,label:cc??`思考等级`,value:sc,options:gc,disabled:!lc||nc,onChoose:vc}),I===`group`&<&&(0,F.jsx)(`button`,{type:`button`,className:`workbench-status-button`,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-status-group-models`,{detail:{roomId:lt}})),children:`群成员模型`}),I===`file`&&ys&&(ws?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-editor-cursor`,"data-workbench-editor-position":`1`,onClick:e=>{Ds.current=e.currentTarget,Os(`${ws.line}:${ws.column}`),Es(`line`)},children:[`第 `,ws.line,` 行,第 `,ws.column,` 列`]}),(0,F.jsx)(`button`,{type:`button`,className:`workbench-status-button`,"data-file-highlight-status":ws.highlight,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`language`?void 0:`language`)},children:ws.language})]}):(0,F.jsx)(`span`,{title:ys.path,children:ys.name})),G===`diff`&&jo&&(0,F.jsx)(`button`,{type:`button`,className:`workbench-status-button`,title:jo,onClick:e=>{Ds.current=e.currentTarget,Es(e=>e===`diff`?void 0:`diff`)},children:jo}),mn.entry(`workbench-status-button software-update-desktop`),(0,F.jsxs)(`button`,{type:`button`,className:`workbench-version workbench-status-button`,"data-super-pi-version":(mn.status??sn)?.runningVersion??``,title:`查看版本与软件更新`,onClick:mn.open,children:[`v`,(mn.status??sn)?.runningVersion??`…`]})]})]})]})}Qh(Zh()),(0,d.createRoot)(document.getElementById(`root`)).render((0,F.jsx)(u.StrictMode,{children:(0,F.jsx)(lA,{})}));export{ii as a,Cn as c,Be as d,r as f,ti as i,Sn as l,Rp as n,kr as o,Vp as r,Or as s,Xp as t,vn as u};
|