@evandu/super-pi 0.1.162 → 0.1.164

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.
Files changed (39) hide show
  1. package/agents/super-pi-task/core.ts +1 -1
  2. package/agents/super-pi-task/index.ts +1 -1
  3. package/dist/client/.super-pi-client-sources.json +6 -6
  4. package/dist/client/assets/{CodeMirrorEditor-Ch1Ipz3r.js → CodeMirrorEditor-B7hhyG33.js} +2 -2
  5. package/dist/client/assets/{dist-B_k2ubHz.js → dist-7Nz91m3a.js} +1 -1
  6. package/dist/client/assets/{dist-D5kM2io7.js → dist-B5xG-jTK.js} +1 -1
  7. package/dist/client/assets/{dist-CmFGh26v.js → dist-BBfDBMAk.js} +1 -1
  8. package/dist/client/assets/{dist-opu-Ndfn.js → dist-BDy5Nw4_.js} +1 -1
  9. package/dist/client/assets/{dist-Cp0He9AW.js → dist-BLhPsVFt.js} +1 -1
  10. package/dist/client/assets/{dist-B0NwzG2K.js → dist-BhouAfNI.js} +1 -1
  11. package/dist/client/assets/{dist-EWYaYkiN.js → dist-BjlmPyRl.js} +1 -1
  12. package/dist/client/assets/{dist-MIa-fDZ9.js → dist-BmeBkDNB.js} +1 -1
  13. package/dist/client/assets/{dist-Chs1uuQX.js → dist-ByEzPyEi.js} +1 -1
  14. package/dist/client/assets/{dist-L0PobKDk.js → dist-C4ql8ak8.js} +1 -1
  15. package/dist/client/assets/{dist-BelPaaJY.js → dist-CF9zuubZ.js} +1 -1
  16. package/dist/client/assets/{dist-BofmoyAA.js → dist-CGO5Bn1x.js} +1 -1
  17. package/dist/client/assets/{dist-DsvKYPCw.js → dist-CdpuBRoy.js} +1 -1
  18. package/dist/client/assets/{dist-COh20l57.js → dist-CrJV_eES.js} +1 -1
  19. package/dist/client/assets/{dist-BucgltXJ.js → dist-CsBiEr54.js} +1 -1
  20. package/dist/client/assets/{dist-BAxkLl0w.js → dist-CxZb6ATc.js} +1 -1
  21. package/dist/client/assets/{dist-PaqaOBBw.js → dist-D607J8oC.js} +1 -1
  22. package/dist/client/assets/{dist-C_rEORol.js → dist-D6nsZZd3.js} +1 -1
  23. package/dist/client/assets/{dist-sV52WV4g.js → dist-DJ4sWDSy.js} +1 -1
  24. package/dist/client/assets/{dist-CZfh2TpC.js → dist-DaUyp_NN.js} +1 -1
  25. package/dist/client/assets/{dist-BGN6sRpP.js → dist-Foaz_oK2.js} +1 -1
  26. package/dist/client/assets/{dist-phbezeQa.js → dist-qqDS87aN.js} +1 -1
  27. package/dist/client/assets/{index-PN2dNRnQ.js → index-1hS3wVqF.js} +11 -11
  28. package/dist/client/assets/{index-unAm6EaY.css → index-Wtlj0s4R.css} +1 -1
  29. package/dist/client/index.html +2 -2
  30. package/dist/server/application/project-service.d.ts +5 -1
  31. package/dist/server/application/project-service.js +123 -3
  32. package/dist/server/application/run-service.d.ts +3 -0
  33. package/dist/server/application/run-service.js +27 -7
  34. package/dist/server/application/session-watchdog.d.ts +14 -2
  35. package/dist/server/application/session-watchdog.js +42 -2
  36. package/dist/server/index.js +8 -1
  37. package/dist/server/tool-runner.js +11 -2
  38. package/dist/server/types.d.ts +33 -0
  39. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BofmoyAA.js","assets/dist-opu-Ndfn.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-CGO5Bn1x.js","assets/dist-BDy5Nw4_.js"])))=>i.map(i=>d[i]);
2
2
  var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(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 u=o((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 M(e,t){return typeof e==`object`&&e&&e.key!=null?A(``+e.key):t.toString(36)}function N(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 P(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,P(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+M(e,0):a,C(o)?(i=``,c!=null&&(i=c.replace(j,`$&/`)+`/`),P(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+M(a,u),c+=P(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+M(a,u++),c+=P(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return P(N(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 F(e,t,n){if(e==null)return e;var r=[],i=0;return P(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ee(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 te=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 ne(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,te)}catch(e){te(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}}function re(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 ne(re.bind(null,e))}var I={map:F,forEach:function(e,t,n){F(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return F(e,function(){t++}),t},toArray:function(e){return F(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=I,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=re,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:ee}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=ne,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`})),d=o(((e,t)=>{t.exports=u()})),f=o((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}}}})),p=o(((e,t)=>{t.exports=f()})),m=o((e=>{var t=d();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 r(){}var i={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},a=Symbol.for(`react.portal`),o=Symbol.for(`react.recoverable`),s=Symbol.for(`react.optimistic_key`);function c(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:r==null?null:r===s?s:``+r,children:e,containerInfo:t,implementation:n}}var l=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(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=i,e.browser=function(e){return{$$typeof:o,_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 c(e,t,null,r)},e.flushSync=function(e){var t=l.T,n=i.p;try{if(l.T=null,i.p=2,e)return e()}finally{l.T=t,i.p=n,i.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,i.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&i.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=u(n,t.crossOrigin),a=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?i.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:a,fetchPriority:o}):n===`script`&&i.d.X(e,{crossOrigin:r,integrity:a,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=u(t.as,t.crossOrigin);i.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??i.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=u(n,t.crossOrigin);i.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=u(t.as,t.crossOrigin);i.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 i.d.m(e)}},e.requestFormReset=function(e){i.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return l.H.useFormState(e,t,n)},e.useFormStatus=function(){return l.H.useHostTransitionStatus()},e.version=`19.3.1`})),h=o(((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=m()})),g=o((e=>{var t=p(),n=d(),r=h();function i(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 a(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(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 s(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 c(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 l(e){if(o(e)!==e)throw Error(i(188))}function u(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(i(188));return t===e?e:null}for(var n=e,r=t;;){var a=n.return;if(a===null)break;var s=a.alternate;if(s===null){if(r=a.return,r!==null){n=r;continue}break}if(a.child===s.child){for(s=a.child;s;){if(s===n)return l(a),e;if(s===r)return l(a),t;s=s.sibling}throw Error(i(188))}if(n.return!==r.return)n=a,r=s;else{for(var c=!1,u=a.child;u;){if(u===n){c=!0,n=a,r=s;break}if(u===r){c=!0,r=a,n=s;break}u=u.sibling}if(!c){for(u=s.child;u;){if(u===n){c=!0,n=s,r=a;break}if(u===r){c=!0,r=s,n=a;break}u=u.sibling}if(!c)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(n.tag!==3)throw Error(i(188));return n.stateNode.current===n?e:t}function f(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=f(e),t!==null)return t;e=e.sibling}return null}function m(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)&&m(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(i(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`),M=Symbol.for(`react.strict_mode`),N=Symbol.for(`react.profiler`),P=Symbol.for(`react.consumer`),F=Symbol.for(`react.context`),ee=Symbol.for(`react.forward_ref`),te=Symbol.for(`react.suspense`),ne=Symbol.for(`react.suspense_list`),re=Symbol.for(`react.memo`),I=Symbol.for(`react.lazy`),ie=Symbol.for(`react.activity`),ae=Symbol.for(`react.legacy_hidden`),oe=Symbol.for(`react.memo_cache_sentinel`),se=Symbol.for(`react.view_transition`),ce=Symbol.for(`react.recoverable`),le=Symbol.iterator;function ue(e){return typeof e!=`object`||!e?null:(e=le&&e[le]||e[`@@iterator`],typeof e==`function`?e:null)}var de=Symbol.for(`react.client.reference`);function fe(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===de?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case j:return`Fragment`;case N:return`Profiler`;case M:return`StrictMode`;case te:return`Suspense`;case ne:return`SuspenseList`;case ie:return`Activity`;case se:return`ViewTransition`}if(typeof e==`object`)switch(e.$$typeof){case A:return`Portal`;case F:return e.displayName||`Context`;case P:return(e._context.displayName||`Context`)+`.Consumer`;case ee:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case re:return t=e.displayName||null,t===null?fe(e.type)||`Memo`:t;case I:t=e._payload,e=e._init;try{return fe(e(t))}catch{}}return null}var pe=Array.isArray,L=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,me=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,he={pending:!1,data:null,method:null,action:null},ge=[],_e=-1;function ve(e){return{current:e}}function ye(e){0>_e||(e.current=ge[_e],ge[_e]=null,_e--)}function be(e,t){_e++,ge[_e]=e.current,e.current=t}var xe=ve(null),Se=ve(null),Ce=ve(null),we=ve(null);function Te(e,t){switch(be(Ce,t),be(Se,e),be(xe,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?hp(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=hp(t),e=gp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ye(xe),be(xe,e)}function Ee(){ye(xe),ye(Se),ye(Ce)}function De(e){var t=e.memoizedState;t!==null&&(fh._currentValue=t.memoizedState,be(we,e)),t=xe.current;var n=gp(t,e.type);t!==n&&(be(Se,e),be(xe,n))}function Oe(e){Se.current===e&&(ye(xe),ye(Se)),we.current===e&&(ye(we),fh._currentValue=he)}var ke,Ae;function je(e){if(ke===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ke=t&&t[1]||``,Ae=-1<e.stack.indexOf(`
3
3
  at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
4
4
  `+ke+e+Ae}var Me=!1;function Ne(e,t){if(!e||Me)return``;Me=!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(`
@@ -45,11 +45,11 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
45
45
  `)))}return{node:{type:`list`,ordered:n,start:n?Number(r[2]):1,items:a},next:o}}function dm(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&!t.endsWith(`\\|`)&&(t=t.slice(0,-1));let n=[],r=``;for(let e=0;e<t.length;e+=1)t[e]===`\\`&&t[e+1]===`|`?(r+=`|`,e+=1):t[e]===`|`?(n.push(r.trim()),r=``):r+=t[e];return n.push(r.trim()),n}function fm(e){let t=e.startsWith(`:`),n=e.endsWith(`:`);return t&&n?`center`:n?`right`:t?`left`:null}function pm(e,t){let n=e.slice(0,t);for(;n.length<t;)n.push(``);return n}var mm={alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,varepsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,vartheta:`ϑ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,pi:`π`,varpi:`ϖ`,rho:`ρ`,varrho:`ϱ`,sigma:`σ`,varsigma:`ς`,tau:`τ`,upsilon:`υ`,phi:`φ`,varphi:`ϕ`,chi:`χ`,psi:`ψ`,omega:`ω`,Gamma:`Γ`,Delta:`Δ`,Theta:`Θ`,Lambda:`Λ`,Xi:`Ξ`,Pi:`Π`,Sigma:`Σ`,Upsilon:`Υ`,Phi:`Φ`,Psi:`Ψ`,Omega:`Ω`},hm={times:`×`,div:`÷`,pm:`±`,mp:`∓`,cdot:`·`,ast:`∗`,star:`⋆`,circ:`∘`,bullet:`∙`,leq:`≤`,le:`≤`,geq:`≥`,ge:`≥`,neq:`≠`,ne:`≠`,approx:`≈`,sim:`∼`,simeq:`≃`,equiv:`≡`,propto:`∝`,ll:`≪`,gg:`≫`,in:`∈`,notin:`∉`,ni:`∋`,subset:`⊂`,subseteq:`⊆`,supset:`⊃`,supseteq:`⊇`,cup:`∪`,cap:`∩`,setminus:`∖`,emptyset:`∅`,varnothing:`∅`,aleph:`ℵ`,hbar:`ℏ`,ell:`ℓ`,Re:`ℜ`,Im:`ℑ`,sum:`∑`,prod:`∏`,coprod:`∐`,int:`∫`,iint:`∬`,iiint:`∭`,oint:`∮`,bigcup:`⋃`,bigcap:`⋂`,to:`→`,rightarrow:`→`,leftarrow:`←`,gets:`←`,leftrightarrow:`↔`,Rightarrow:`⇒`,Leftarrow:`⇐`,Leftrightarrow:`⇔`,mapsto:`↦`,longrightarrow:`⟶`,longleftarrow:`⟵`,uparrow:`↑`,downarrow:`↓`,ldots:`…`,cdots:`⋯`,vdots:`⋮`,ddots:`⋱`,dots:`…`,therefore:`∴`,because:`∵`,angle:`∠`,triangle:`△`,perp:`⊥`,parallel:`∥`,degree:`°`,prime:`′`,lbrace:`{`,rbrace:`}`,lbrack:`[`,rbrack:`]`,langle:`⟨`,rangle:`⟩`,lfloor:`⌊`,rfloor:`⌋`,lceil:`⌈`,rceil:`⌉`,vert:`|`,Vert:`‖`,backslash:`\\`,oplus:`⊕`,ominus:`⊖`,otimes:`⊗`,oslash:`⊘`,odot:`⊙`,dagger:`†`,ddagger:`‡`,quad:` `,qquad:` `,thinspace:` `,enspace:` `,negthinspace:``},gm=new Set(`arcsin.arccos.arctan.sinh.cosh.tanh.cot.sec.csc.sin.cos.tan.log.ln.lg.exp.lim.limsup.liminf.max.min.det.dim.ker.deg.gcd.hom.arg.Pr.sup.inf`.split(`.`)),_m={C:`ℂ`,H:`ℍ`,N:`ℕ`,P:`ℙ`,Q:`ℚ`,R:`ℝ`,Z:`ℤ`},vm={B:`ℬ`,E:`ℰ`,F:`ℱ`,H:`ℋ`,I:`ℐ`,L:`ℒ`,M:`ℳ`,R:`ℛ`,e:`ℯ`,g:`ℊ`,o:`ℴ`},ym={mathbb:e=>_m[e]??e.toUpperCase(),mathcal:e=>vm[e]??e.toUpperCase(),mathscr:e=>vm[e]??e.toUpperCase()},bm=new Set([`left`,`right`,`big`,`Big`,`bigg`,`Bigg`,`bigl`,`bigr`,`Bigl`,`Bigr`,`biggl`,`biggr`,`Biggl`,`Biggr`,`middle`,`displaystyle`,`textstyle`,`scriptstyle`,`limits`,`nolimits`,`nonumber`,`notag`,`label`]),xm={hat:`^`,widehat:`^`,bar:`‾`,overline:`‾`,tilde:`~`,widetilde:`~`,vec:`→`,dot:`·`,ddot:`··`,check:`ˇ`,breve:`˘`,acute:`´`,grave:"`"},Sm=new Set([`(`,`)`,`[`,`]`,`|`,`/`,`<`,`>`]),Cm=new Set([`pmatrix`,`bmatrix`,`Bmatrix`,`vmatrix`,`Vmatrix`,`matrix`,`array`,`cases`,`aligned`,`align`,`alignat`,`split`,`gather`,`gathered`,`equation`,`smallmatrix`,`dcases`,`subarray`]);function wm(e){let t=[],n=``,r=()=>{n&&=(t.push(...Om(n)),``)},i=e=>{r(),t.push(e)};for(let a=0;a<e.length;){let o=e[a];if(o===`\\`){let t=a,r=/^\\([a-zA-Z]+|.)/.exec(e.slice(a));if(!r){n+=o,a+=1;continue}let s=r[1];if(a+=r[0].length,s===`\\`){i({type:`math-row-break`});continue}if(s===`{`||s===`}`){n+=s;continue}if(s===`,`||s===`;`||s===`:`||s===`!`||s===`&`)continue;if(s===`%`){for(;a<e.length&&e[a]!==`
46
46
  `;)a+=1;continue}if(bm.has(s))continue;if(s===`begin`){let n=zp(e,a),r=n.content,o=`\\end{${r}}`,s=e.indexOf(o,n.next),c=s===-1?e.length:s+o.length;i({type:`math-unsupported`,value:e.slice(t,c),reason:`\\begin{${r}} 不支持`}),a=c;continue}if(s===`frac`||s===`dfrac`||s===`tfrac`||s===`cfrac`){let t=Em(e,a),n=Em(e,t.next);a=n.next,i({type:`math-fraction`,numerator:wm(t.content),denominator:wm(n.content)});continue}if(s===`sqrt`){let t,n=a;if(e[n]===`[`){let r=Tm(e,n);t=wm(r.content),n=r.next}let r=Em(e,n);a=r.next,i({type:`math-root`,...t?{index:t}:{},radicand:wm(r.content)});continue}if(s===`text`||s===`mathrm`||s===`textrm`||s===`mathbf`||s===`mathit`||s===`mathsf`||s===`mathtt`||s===`operatorname`||s===`textbf`){let t=zp(e,a);a=t.next,i({type:`math-text`,value:t.content});continue}if(s in ym){let t=Em(e,a);a=t.next;let n=ym[s];i({type:`math-text`,value:[...t.content].map(n).join(``)});continue}if(s in xm){let t=Em(e,a);a=t.next,i({type:`math-text`,value:`${km(wm(t.content))}${xm[s]}`});continue}if(s in mm){i({type:`math-identifier`,value:mm[s]});continue}if(s in hm){let e=hm[s];/^\d/.test(e)?i({type:`math-number`,value:e}):/^[A-Za-z]/.test(e)?i({type:`math-text`,value:e}):i({type:`math-operator`,value:e});continue}if(gm.has(s)){i({type:`math-function`,value:s});continue}if(Cm.has(s))continue;i({type:`math-unsupported`,value:`\\${s}`,reason:`\\${s} 不支持`})}else if(o===`{`){let n=zp(e,a);t.push(...wm(n.content)),a=n.next}else if(o===`}`||o===`&`||o===`$`)a+=1;else if(o===`^`||o===`_`){r();let n=Em(e,a+1);a=n.next,Dm(t,o===`^`?`sup`:`sub`,wm(n.content))}else Sm.has(o)?(i({type:`math-text`,value:o}),a+=1):(n+=o,a+=1)}return r(),t}function Tm(e,t){let n=e.indexOf(`]`,t+1);return n===-1?{content:``,next:e.length}:{content:e.slice(t+1,n),next:n+1}}function Em(e,t){let n=e[t];if(n===void 0)return{content:``,next:t};if(n===`{`)return zp(e,t);let r=/^\\[a-zA-Z]+/.exec(e.slice(t));return r?{content:r[0],next:t+r[0].length}:{content:n,next:t+1}}function Dm(e,t,n){let r=e.pop();if(r){if(r.type===`math-script`)t===`sub`&&!r.sub?e.push({...r,sub:n}):t===`sup`&&!r.sup?e.push({...r,sup:n}):e.push(r);else if(r.type===`math-identifier`||r.type===`math-text`){let i=[...r.value],a=i.pop()??``;i.length&&e.push({type:r.type,value:i.join(``)}),e.push({type:`math-script`,base:[{type:`math-identifier`,value:a}],...t===`sub`?{sub:n}:{sup:n}})}else e.push({type:`math-script`,base:[r],...t===`sub`?{sub:n}:{sup:n}})}}function Om(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),i=/^\d+(?:\.\d+)?/.exec(r);if(i){t.push({type:`math-number`,value:i[0]}),n+=i[0].length;continue}let a=/^[A-Za-z]+/.exec(r);if(a){t.push(gm.has(a[0])?{type:`math-function`,value:a[0]}:{type:`math-identifier`,value:a[0]}),n+=a[0].length;continue}let o=/^[,;:!.'’|()\-+=<>/*]+/.exec(r);o?(t.push({type:`math-operator`,value:o[0]}),n+=o[0].length):(t.push({type:`math-text`,value:r[0]}),n+=1)}return t.reduce((e,t)=>{let n=e[e.length-1];return n?.type===`math-operator`&&t.type===`math-operator`?n.value+=t.value:e.push({...t}),e},[])}function km(e){return e.map(e=>{switch(e.type){case`math-text`:case`math-number`:case`math-identifier`:case`math-operator`:case`math-function`:return e.value;case`math-script`:return`${km(e.base)}${e.sub?`_{${km(e.sub)}}`:``}${e.sup?`^{${km(e.sup)}}`:``}`;case`math-fraction`:return`\\frac{${km(e.numerator)}}{${km(e.denominator)}}`;case`math-root`:return`\\sqrt{${km(e.radicand)}}`;case`math-row-break`:return`\\\\`;case`math-unsupported`:return e.value;default:return``}}).join(``)}function Am({source:e}){let t=(0,V.useMemo)(()=>cm(e),[e]);return(0,H.jsx)(`div`,{className:`md`,"data-md":`1`,children:t.map((e,t)=>Nm(e,t))})}function jm({source:e}){let t=(0,V.useMemo)(()=>Xp(e),[e]);return(0,H.jsx)(`span`,{className:`md md-inline`,children:t.map((e,t)=>Fm(e,t))})}function Mm(e){return jp(e).map((e,t)=>e.kind===`plain`?(0,H.jsx)(`span`,{children:e.text},t):(0,H.jsx)(`span`,{className:`code-token-${e.kind}`,children:e.text},t))}function Nm(e,t){switch(e.type){case`paragraph`:return(0,H.jsx)(`p`,{className:`md-p`,children:e.children.map((e,t)=>Fm(e,t))},t);case`heading`:{let n=`h${Math.min(6,Math.max(1,e.level))}`;return(0,H.jsx)(n,{className:`md-h md-h${e.level}`,children:e.children.map((e,t)=>Fm(e,t))},t)}case`code-block`:return(0,H.jsx)(`pre`,{className:`md-pre`,"data-md-lang":e.lang||void 0,children:(0,H.jsx)(`code`,{className:`md-code`,children:Mm(e.value)})},t);case`list`:{let n=e.items.map((e,t)=>(0,H.jsx)(`li`,{className:`md-li`,children:e.map((e,t)=>Nm(e,t))},t));return e.ordered?(0,H.jsx)(`ol`,{className:`md-ol`,start:e.start>1?e.start:void 0,children:n},t):(0,H.jsx)(`ul`,{className:`md-ul`,children:n},t)}case`blockquote`:return(0,H.jsx)(`blockquote`,{className:`md-quote`,children:e.children.map((e,t)=>Nm(e,t))},t);case`rule`:return(0,H.jsx)(`hr`,{className:`md-rule`},t);case`table`:return(0,H.jsx)(`div`,{className:`md-table-wrap`,children:(0,H.jsxs)(`table`,{className:`md-table`,children:[(0,H.jsx)(`thead`,{children:(0,H.jsx)(`tr`,{children:e.head.map((t,n)=>(0,H.jsx)(`th`,{style:Pm(e.align[n]),children:t.map((e,t)=>Fm(e,t))},n))})}),(0,H.jsx)(`tbody`,{children:e.rows.map((t,n)=>(0,H.jsx)(`tr`,{children:t.map((t,n)=>(0,H.jsx)(`td`,{style:Pm(e.align[n]),children:t.map((e,t)=>Fm(e,t))},n))},n))})]})},t);case`math-block`:return(0,H.jsx)(Im,{source:e.source},t);default:return null}}var Pm=e=>e?{textAlign:e}:void 0;function Fm(e,t){switch(e.type){case`text`:return(0,H.jsx)(V.Fragment,{children:e.value},t);case`code`:return(0,H.jsx)(`code`,{className:`md-code-inline`,children:e.value},t);case`strong`:return(0,H.jsx)(`strong`,{className:`md-strong`,children:e.children.map((e,t)=>Fm(e,t))},t);case`em`:return(0,H.jsx)(`em`,{className:`md-em`,children:e.children.map((e,t)=>Fm(e,t))},t);case`del`:return(0,H.jsx)(`del`,{className:`md-del`,children:e.children.map((e,t)=>Fm(e,t))},t);case`break`:return(0,H.jsx)(`br`,{className:`md-break`},t);case`math`:return(0,H.jsx)(Lm,{source:e.source},t);case`link`:{let n=Fp(e.href);return n?(0,H.jsx)(`a`,{className:`md-link`,href:n,title:e.title,target:`_blank`,rel:`noopener noreferrer nofollow`,children:e.children.map((e,t)=>Fm(e,t))},t):(0,H.jsx)(V.Fragment,{children:e.children.map((e,t)=>Fm(e,t))},t)}default:return null}}function Im({source:e}){let t=(0,V.useMemo)(()=>wm(e),[e]);return(0,H.jsx)(`div`,{className:`md-math md-math-block`,"data-md-math":`block`,"data-md-math-source":e,children:t.map((e,t)=>Rm(e,t))})}function Lm({source:e}){let t=(0,V.useMemo)(()=>wm(e),[e]);return(0,H.jsx)(`span`,{className:`md-math md-math-inline`,"data-md-math":`inline`,"data-md-math-source":e,children:t.map((e,t)=>Rm(e,t))})}function Rm(e,t){switch(e.type){case`math-text`:return(0,H.jsx)(`span`,{className:`md-m-text`,children:e.value},t);case`math-number`:return(0,H.jsx)(`span`,{className:`md-m-number`,children:e.value},t);case`math-identifier`:return(0,H.jsx)(`i`,{className:`md-m-var`,children:e.value},t);case`math-operator`:return(0,H.jsx)(`span`,{className:`md-m-op`,children:e.value},t);case`math-function`:return(0,H.jsx)(`span`,{className:`md-m-fn`,children:e.value},t);case`math-row-break`:return(0,H.jsx)(`br`,{className:`md-m-rowbreak`},t);case`math-unsupported`:return(0,H.jsx)(`span`,{className:`md-m-unsupported`,"data-md-math-unsupported":`1`,title:e.reason,children:e.value},t);case`math-script`:return(0,H.jsxs)(`span`,{className:`md-m-script`,children:[(0,H.jsx)(`span`,{className:`md-m-base`,children:e.base.map((e,t)=>Rm(e,t))}),e.sup&&(0,H.jsx)(`sup`,{className:`md-m-sup`,children:e.sup.map((e,t)=>Rm(e,t))}),e.sub&&(0,H.jsx)(`sub`,{className:`md-m-sub`,children:e.sub.map((e,t)=>Rm(e,t))})]},t);case`math-fraction`:return(0,H.jsxs)(`span`,{className:`md-m-frac`,children:[(0,H.jsx)(`span`,{className:`md-m-num`,children:e.numerator.map((e,t)=>Rm(e,t))}),(0,H.jsx)(`span`,{className:`md-m-den`,children:e.denominator.map((e,t)=>Rm(e,t))})]},t);case`math-root`:return(0,H.jsxs)(`span`,{className:`md-m-root`,children:[(0,H.jsx)(`span`,{className:`md-m-radical`,children:`√`}),e.index&&(0,H.jsx)(`sup`,{className:`md-m-index`,children:e.index.map((e,t)=>Rm(e,t))}),(0,H.jsx)(`span`,{className:`md-m-body`,children:e.radicand.map((e,t)=>Rm(e,t))})]},t);default:return null}}var zm=[[`help`,`Show help`],[`model`,`Choose model`],[`settings`,`Open settings`],[`clear`,`Clear session`],[`compact`,`Compact context`],[`reload`,`Reload agents`],[`new`,`New session`],[`fork`,`Fork session`],[`resume`,`Resume session`],[`stop`,`Stop run`],[`skill`,`Workspace skill`]].map(([e,t])=>({id:e,label:t,description:t,scope:`builtin`})),Bm=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase();function Vm(e,t){let n=Bm(t.trim());return e.examples?.find(t=>Bm(t).includes(n)&&t!==e.id)??e.id}function Hm(e,t){let n=Bm(t.trim());return n?e.filter(e=>Bm(e.id).includes(n)||Bm(e.label).includes(n)||Bm(e.description).includes(n)||e.examples?.some(e=>Bm(e).includes(n))):e}function Um({query:e,anchorRect:t,command:n,workspaceId:r,promptCatalog:i,onSelect:a,onClose:o}){let[s,c]=(0,V.useState)(0),[l,u]=(0,V.useState)(zm),d=(0,V.useRef)(null),f=(0,V.useRef)([]);(0,V.useEffect)(()=>{r&&n({type:`prompt.catalog.fetch`,workspaceId:r})},[r,n]),(0,V.useEffect)(()=>{let e=!1,t=r?`/api/skills?workspaceId=${encodeURIComponent(r)}`:`/api/skills`;return fetch(t).then(e=>e.ok?e.json():void 0).then(t=>{if(e||!Array.isArray(t?.skills))return;let n=t.skills.map(e=>{let t=e.id?.startsWith(`skill:`)?e.id:`skill:${e.name}`,n=e.description?.trim()||(e.scope===`workspace`?`工作区技能`:`技能`);return{id:t,label:n,description:n,examples:[t]}});u([...zm.filter(e=>e.id!==`skill`),...n])}).catch(()=>{}),()=>{e=!0}},[r]);let p=[{id:`start`,label:`start — 打开浏览器`,description:`在浏览器中打开 Super Pi 控制台`,action:()=>n({type:`super_pi.start`})},{id:`restart`,label:`restart — 重启 Super Pi 服务`,description:`停掉并重新启动服务,加载磁盘上的新代码`,action:()=>n({type:`super_pi.restart`})},{id:`update`,label:`update — 更新 Super Pi`,description:`运行 npm install -g @evandu/super-pi 然后重启`,action:()=>n({type:`super_pi.update`})}],m=(i&&i.workspaceId===r?i.prompts:[]).map(e=>({id:e.name,label:e.description,description:e.description,argumentHint:e.argumentHint,scope:e.scope,shadowed:[...p,...l].some(t=>t.id===e.name)})),h=Hm([...p,...l,...m],e),g=h.length===0?-1:Math.min(Math.max(s,0),h.length-1),_=e=>c(t=>h.length?Math.min(Math.max(t+e,0),h.length-1):0);(0,V.useEffect)(()=>{let e=e=>{d.current?.contains(e.target)||o()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[o]),(0,V.useEffect)(()=>{c(0)},[e]),(0,V.useLayoutEffect)(()=>{g>=0&&f.current[g]?.scrollIntoView({block:`nearest`})},[g]);let v={position:`fixed`,left:Math.max(8,Math.min(t.left,window.innerWidth-360)),bottom:Math.max(8,window.innerHeight-t.top+6),zIndex:200},y=e=>{if(e.key===`Escape`)e.preventDefault(),o();else if(e.key===`ArrowDown`)e.preventDefault(),_(1);else if(e.key===`ArrowUp`)e.preventDefault(),_(-1);else if(e.key===`Home`)e.preventDefault(),c(0);else if(e.key===`End`)e.preventDefault(),c(h.length-1);else if(e.key===`Enter`){e.preventDefault();let t=h[g];if(!t)return;t.action?(t.action(),o()):a(t)}};return(0,V.useEffect)(()=>(window.addEventListener(`keydown`,y),()=>window.removeEventListener(`keydown`,y))),(0,H.jsx)(`div`,{ref:d,className:`slash-menu`,style:v,role:`listbox`,"aria-label":`斜杠命令`,children:h.length===0?(0,H.jsxs)(`div`,{className:`slash-menu-empty`,children:[`没有匹配「`,e,`」的命令`]}):h.map((e,t)=>(0,H.jsxs)(`button`,{ref:e=>{f.current[t]=e},type:`button`,role:`option`,"aria-selected":t===g,className:`slash-menu-item${t===g?` selected`:``}`,"data-slash-command":e.id,onClick:()=>{e.action?(e.action(),o()):a(e)},onMouseEnter:()=>c(t),children:[(0,H.jsxs)(`span`,{className:`slash-menu-item-id`,children:[`/`,e.id,e.argumentHint?` `+e.argumentHint:``]}),(0,H.jsx)(`span`,{className:`slash-menu-item-sep`,"aria-hidden":`true`,children:` — `}),(0,H.jsx)(`span`,{className:`slash-menu-item-label`,children:e.label}),(0,H.jsx)(`span`,{className:`slash-menu-item-scope`,"data-slash-command-scope":e.scope??`builtin`,children:e.shadowed?`Built-in command wins`:e.scope===`project`?`Project prompt`:e.scope===`user`?`User prompt`:`Pi built-in`}),e.examples?.length?(0,H.jsx)(`span`,{className:`slash-menu-item-examples`,children:e.examples.slice(0,2).join(` · `)}):null]},e.id))})}var Wm=class extends V.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,H.jsxs)(`div`,{className:`error-boundary-card`,"data-error-boundary":`1`,children:[(0,H.jsxs)(`div`,{className:`error-boundary-head`,children:[(0,H.jsx)(`span`,{className:`error-boundary-icon`,"aria-hidden":`true`,children:`⚠️`}),(0,H.jsx)(`strong`,{children:`视图渲染遇到异常`})]}),(0,H.jsx)(`p`,{className:`error-boundary-msg`,children:e.message||`未知组件错误`}),(0,H.jsx)(`button`,{type:`button`,className:`error-boundary-retry`,onClick:this.reset,children:`重试`})]}):this.props.children}};function Gm(){}Gm.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(Km(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 Km(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 Gm;var qm=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Jm=/\S/,Ym=new Gm;Ym.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!Jm.test(e)&&!Jm.test(t)},Ym.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]&&qm.test(t[n])&&qm.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var Xm=new Gm;Xm.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
47
47
  `));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 Zm(e,t,n){return Xm.diff(e,t,n)}var Qm=new Gm;Qm.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var $m=new Gm;$m.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function eh(e){"@babel/helpers - typeof";return eh=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},eh(e)}var th=Object.prototype.toString,nh=new Gm;nh.useLongestToken=!0,nh.tokenize=Xm.tokenize,nh.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(rh(e,null,null,i),i,` `)},nh.equals=function(e,t){return Gm.prototype.equals.call(nh,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`))};function rh(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(th.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=rh(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),eh(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]=rh(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var ih=new Gm;ih.tokenize=function(e){return e.slice()},ih.join=ih.removeEmpty=function(e){return e};function ah(e,t){let n=Zm(e??``,t??``),r=[],i=0,a=0,o=1,s=1;for(let e of n){let t=e.value.split(`
48
- `),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 oh(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}}function sh(e){return Array.isArray?Array.isArray(e):_h(e)===`[object Array]`}function ch(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=e+``;return t==`0`&&1/e==-1/0?`-0`:t}function lh(e){return e==null?``:ch(e)}function uh(e){return typeof e==`string`}function dh(e){return typeof e==`number`}function fh(e){return e===!0||e===!1||mh(e)&&_h(e)==`[object Boolean]`}function ph(e){return typeof e==`object`}function mh(e){return ph(e)&&e!==null}function hh(e){return e!=null}function gh(e){return!e.trim().length}function _h(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var vh=`Incorrect 'index' type`,yh=`Invalid doc index: must be a non-negative integer within the bounds of the docs array`,bh=e=>`Invalid value for key ${e}`,xh=e=>`Pattern length exceeds max of ${e}.`,Sh=e=>`Missing ${e} property in key`,Ch=e=>`Property 'weight' in key '${e}' must be a positive integer`,wh=`Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.`,Th=Object.prototype.hasOwnProperty,Eh=class{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(e=>{let n=Dh(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function Dh(e){let t=null,n=null,r=null,i=1,a=null;if(uh(e)||sh(e))r=e,t=Oh(e),n=kh(e);else{if(!Th.call(e,`name`))throw Error(Sh(`name`));let o=e.name;if(r=o,Th.call(e,`weight`)&&e.weight!==void 0&&(i=e.weight,i<=0))throw Error(Ch(kh(o)));t=Oh(o),n=kh(o),a=e.getFn??null}return{path:t,id:n,weight:i,src:r,getFn:a}}function Oh(e){return sh(e)?e:e.split(`.`)}function kh(e){return sh(e)?e.join(`.`):e}function Ah(e,t){let n=[],r=!1,i=(e,t,a,o)=>{if(hh(e)){if(!t[a])n.push(o===void 0?e:{v:e,i:o});else{let s=e[t[a]];if(!hh(s))return;if(a===t.length-1&&(uh(s)||dh(s)||fh(s)||typeof s==`bigint`))n.push(o===void 0?lh(s):{v:lh(s),i:o});else if(sh(s)){r=!0;for(let e=0,n=s.length;e<n;e+=1)i(s[e],t,a+1,e)}else t.length&&i(s,t,a+1,o)}}};return i(e,uh(t)?t.split(`.`):t,0),r?n:n[0]}var jh={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Mh={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx<t.idx?-1:1:e.score<t.score?-1:1},Nh={location:0,threshold:.6,distance:100},Ph={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:`any`,getFn:Ah,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Y=Object.freeze({...Mh,...jh,...Nh,...Ph});function Fh(e){return e>=9&&e<=13||e===32||e===160}function Ih(e=1,t=3){let n=new Map,r=10**t;return{get(t){let i=0,a=!1;for(let e=0;e<t.length;e++)Fh(t.charCodeAt(e))?a=!1:a||=(i++,!0);if(i===0&&(i=1),n.has(i))return n.get(i);let o=Math.round(r/i**(.5*e))/r;return n.set(i,o),o},clear(){n.clear()}}}var Lh=class{constructor({getFn:e=Y.getFn,fieldNormWeight:t=Y.fieldNormWeight}={}){this.norm=Ih(t,3),this.getFn=e,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let e=this.docs.length;this.records=Array(e);let t=0;if(uh(this.docs[0]))for(let n=0;n<e;n++){let e=this._createStringRecord(this.docs[n],n);e&&(this.records[t++]=e)}else for(let n=0;n<e;n++)this.records[t++]=this._createObjectRecord(this.docs[n],n);this.records.length=t,this.norm.clear()}add(e,t){if(!Number.isInteger(t)||t<0)throw Error(yh);if(uh(e)){let n=this._createStringRecord(e,t);return n&&this.records.push(n),n}let n=this._createObjectRecord(e,t);return this.records.push(n),n}removeAt(e){if(!Number.isInteger(e)||e<0)throw Error(yh);for(let t=0,n=this.records.length;t<n;t+=1)if(this.records[t].i===e){this.records.splice(t,1);break}for(let t=0,n=this.records.length;t<n;t+=1)this.records[t].i>e&&--this.records[t].i}removeAll(e){let t=new Set;for(let n of e)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(e=>!t.has(e.i));let n=Array.from(t).sort((e,t)=>e-t);for(let e of this.records){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e.i?t=i+1:r=i}e.i-=t}}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(e,t){return!hh(e)||gh(e)?null:{v:e,i:t,n:this.norm.get(e)}}_createObjectRecord(e,t){let n={i:t,$:{}};for(let t=0,r=this.keys.length;t<r;t++){let r=this.keys[t],i=r.getFn?r.getFn(e):this.getFn(e,r.path);if(hh(i)){if(sh(i)){let e=[];for(let t=0,n=i.length;t<n;t+=1){let n=i[t];if(hh(n)){if(uh(n)){if(!gh(n)){let r={v:n,i:t,n:this.norm.get(n)};e.push(r)}}else if(hh(n.v)){let t=uh(n.v)?n.v:lh(n.v);if(!gh(t)){let r={v:t,i:n.i,n:this.norm.get(t)};e.push(r)}}}}n.$[t]=e}else if(uh(i)&&!gh(i)){let e={v:i,n:this.norm.get(i)};n.$[t]=e}}}return n}toJSON(){return{keys:this.keys.map(({getFn:e,...t})=>t),records:this.records}}};function Rh(e,t,{getFn:n=Y.getFn,fieldNormWeight:r=Y.fieldNormWeight}={}){let i=new Lh({getFn:n,fieldNormWeight:r});return i.setKeys(e.map(Dh)),i.setSources(t),i.create(),i}function zh(e,{getFn:t=Y.getFn,fieldNormWeight:n=Y.fieldNormWeight}={}){let{keys:r,records:i}=e,a=new Lh({getFn:t,fieldNormWeight:n});return a.setKeys(r),a.setIndexRecords(i),a}function Bh(e=[],t=Y.minMatchCharLength){let n=[],r=-1,i=-1,a=0;for(let o=e.length;a<o;a+=1){let o=e[a];o&&r===-1?r=a:!o&&r!==-1&&(i=a-1,i-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}function Vh(e,t,n,{location:r=Y.location,distance:i=Y.distance,threshold:a=Y.threshold,findAllMatches:o=Y.findAllMatches,minMatchCharLength:s=Y.minMatchCharLength,includeMatches:c=Y.includeMatches,ignoreLocation:l=Y.ignoreLocation}={}){if(t.length>32)throw Error(xh(32));let u=t.length,d=e.length,f=Math.max(0,Math.min(r,d)),p=a,m=f,h=(e,t)=>{let n=e/u;if(l)return n;let r=Math.abs(f-t);return i?n+r/i:r?1:n},g=s>1||c,_=g?Array(d):[],v;for(;(v=e.indexOf(t,m))>-1;){let e=h(0,v);if(p=Math.min(e,p),m=v+u,g){let e=0;for(;e<u;)_[v+e]=1,e+=1}}m=-1;let y=[],b=1,x=0,S=u+d,C=1<<u-1;for(let t=0;t<u;t+=1){let r=0,i=S;for(;r<i;)h(t,f+i)<=p?r=i:S=i,i=Math.floor((S-r)/2+r);S=i;let a=Math.max(1,f-i+1),s=o?d:Math.min(f+i,d)+u,c=Array(s+2);c[s+1]=(1<<t)-1;for(let r=s;r>=a;--r){let i=r-1,o=n[e[i]];if(c[r]=(c[r+1]<<1|1)&o,t&&(c[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),c[r]&C&&(b=h(t,i),b<=p)){if(p=b,m=i,x=t,m<=f)break;a=Math.max(1,2*f-m)}}if(h(t+1,f)>p)break;y=c}if(g&&m>=0){let t=Math.min(d-1,m+u-1+x);for(let r=m;r<=t;r+=1)n[e[r]]&&(_[r]=1)}let w={isMatch:m>=0,score:Math.max(.001,b)};if(g){let e=Bh(_,s);e.length?c&&(w.indices=e):w.isMatch=!1}return w}function Hh(e){let t={};for(let n=0,r=e.length;n<r;n+=1){let i=e.charAt(n);t[i]=(t[i]||0)|1<<r-n-1}return t}function Uh(e){if(e.length<=1)return e;e.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let t=[e[0]];for(let n=1,r=e.length;n<r;n+=1){let r=t[t.length-1],i=e[n];i[0]<=r[1]+1?r[1]=Math.max(r[1],i[1]):t.push(i)}return t}var Wh={ł:`l`,Ł:`L`,đ:`d`,Đ:`D`,ø:`o`,Ø:`O`,ħ:`h`,Ħ:`H`,ŧ:`t`,Ŧ:`T`,ı:`i`,ß:`ss`},Gh=RegExp(`[`+Object.keys(Wh).join(``)+`]`,`g`),Kh=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFD`).replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,``).replace(Gh,e=>Wh[e]):e=>e,qh=class{constructor(e,{location:t=Y.location,threshold:n=Y.threshold,distance:r=Y.distance,includeMatches:i=Y.includeMatches,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,isCaseSensitive:s=Y.isCaseSensitive,ignoreDiacritics:c=Y.ignoreDiacritics,ignoreLocation:l=Y.ignoreLocation}={}){if(this.options={location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:s,ignoreDiacritics:c,ignoreLocation:l},e=s?e:e.toLowerCase(),e=c?Kh(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;let u=(e,t)=>{this.chunks.push({pattern:e,alphabet:Hh(e),startIndex:t})},d=this.pattern.length;if(d>32){let e=0,t=d%32,n=d-t;for(;e<n;)u(this.pattern.substr(e,32),e),e+=32;if(t){let e=d-32;u(this.pattern.substr(e),e)}}else u(this.pattern,0)}searchIn(e){let{isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=n?Kh(e):e,this.pattern===e){if(e.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let t={isMatch:!0,score:0};return r&&(t.indices=[[0,e.length-1]]),t}let{location:i,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,ignoreLocation:l}=this.options,u=[],d=0,f=!1;this.chunks.forEach(({pattern:t,alphabet:n,startIndex:p})=>{let{isMatch:m,score:h,indices:g}=Vh(e,t,n,{location:i+p,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,includeMatches:r,ignoreLocation:l});m&&(f=!0),d+=h,m&&g&&u.push(...g)});let p={isMatch:f,score:f?d/this.chunks.length:1};return f&&r&&(p.indices=Uh(u)),p}},Jh=new Set([`fuzzy`,`include`]);function Yh(e){return e.startsWith(`inverse`)}var Xh=[{type:`exact`,multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:e=>({type:`exact`,search(t){let n=t===e;return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`include`,multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:e=>({type:`include`,search(t){let n=0,r,i=[],a=e.length;for(;(r=t.indexOf(e,n))>-1;)n=r+a,i.push([r,n-1]);let o=!!i.length;return{isMatch:o,score:+!o,indices:i}}})},{type:`prefix-exact`,multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:e=>({type:`prefix-exact`,search(t){let n=t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`inverse-prefix-exact`,multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:e=>({type:`inverse-prefix-exact`,search(t){let n=!t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`inverse-suffix-exact`,multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:e=>({type:`inverse-suffix-exact`,search(t){let n=!t.endsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`suffix-exact`,multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:e=>({type:`suffix-exact`,search(t){let n=t.endsWith(e);return{isMatch:n,score:+!n,indices:[t.length-e.length,t.length-1]}}})},{type:`inverse-exact`,multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:e=>({type:`inverse-exact`,search(t){let n=t.indexOf(e)===-1;return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`fuzzy`,multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(e,t={})=>{let n=new qh(e,{location:t.location??Y.location,threshold:t.threshold??Y.threshold,distance:t.distance??Y.distance,includeMatches:t.includeMatches??Y.includeMatches,findAllMatches:t.findAllMatches??Y.findAllMatches,minMatchCharLength:t.minMatchCharLength??Y.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??Y.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??Y.ignoreDiacritics,ignoreLocation:t.ignoreLocation??Y.ignoreLocation});return{type:`fuzzy`,search(e){return n.searchIn(e)}}}}],Zh=Xh.length,Qh=`\0`,$h=`|`;function eg(e){let t=[],n=e.length,r=0;for(;r<n;){for(;r<n&&e[r]===` `;)r++;if(r>=n)break;let i=r;for(;i<n&&e[i]!==` `&&e[i]!==`"`;)i++;if(i<n&&e[i]===`"`){for(i++;i<n;){if(e[i]===`"`){let t=i+1;if(t>=n||e[t]===` `){i++;break}if(e[t]===`$`&&(t+1>=n||e[t+1]===` `)){i+=2;break}}i++}t.push(e.substring(r,i)),r=i}else{for(;i<n&&e[i]!==` `;)i++;t.push(e.substring(r,i)),r=i}}return t}function tg(e,t){let n=e.match(t);return n?n[1]:null}function ng(e,t={}){return e.replace(/\\\|/g,Qh).split($h).map(e=>{let n=eg(e.replace(/\u0000/g,`|`).trim()).filter(e=>e&&!!e.trim()),r=[];for(let e=0,i=n.length;e<i;e+=1){let i=n[e],a=!1,o=-1;for(;!a&&++o<Zh;){let e=Xh[o],n=tg(i,e.multiRegex);n&&(r.push(e.create(n,t)),a=!0)}if(!a)for(o=-1;++o<Zh;){let e=Xh[o],n=tg(i,e.singleRegex);if(n){r.push(e.create(n,t));break}}}return r})}var rg=class{constructor(e,{isCaseSensitive:t=Y.isCaseSensitive,ignoreDiacritics:n=Y.ignoreDiacritics,includeMatches:r=Y.includeMatches,minMatchCharLength:i=Y.minMatchCharLength,ignoreLocation:a=Y.ignoreLocation,findAllMatches:o=Y.findAllMatches,location:s=Y.location,threshold:c=Y.threshold,distance:l=Y.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:s,threshold:c,distance:l},e=t?e:e.toLowerCase(),e=n?Kh(e):e,this.pattern=e,this.query=ng(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?Kh(e):e;let a=0,o=[],s=0,c=!1;for(let r=0,i=t.length;r<i;r+=1){let i=t[r];o.length=0,a=0,c=!1;for(let t=0,r=i.length;t<r;t+=1){let r=i[t],{isMatch:l,indices:u,score:d}=r.search(e);if(l)a+=1,s+=d,Yh(r.type)&&(c=!0),n&&(Jh.has(r.type)?o.push(...u):o.push(u));else{s=0,a=0,o.length=0,c=!1;break}}if(a){let e={isMatch:!0,score:s/a};return c&&(e.hasInverse=!0),n&&(e.indices=Uh(o)),e}}return{isMatch:!1,score:1}}},ig=[];function ag(...e){ig.push(...e)}function og(e,t){for(let n=0,r=ig.length;n<r;n+=1){let r=ig[n];if(r.condition(e,t))return new r(e,t)}return new qh(e,t)}var sg={AND:`$and`,OR:`$or`},cg={PATH:`$path`,PATTERN:`$val`},lg=e=>!!(e[sg.AND]||e[sg.OR]),ug=e=>!!e[cg.PATH],dg=e=>!sh(e)&&ph(e)&&!lg(e),fg=e=>({[sg.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function pg(e,t,{auto:n=!0}={}){let r=e=>{if(uh(e)){let r={keyId:null,pattern:e};return n&&(r.searcher=og(e,t)),r}let i=Object.keys(e),a=ug(e);if(!a&&i.length>1&&!lg(e))return r(fg(e));if(dg(e)){let r=a?e[cg.PATH]:i[0],o=a?e[cg.PATTERN]:e[r];if(!uh(o))throw Error(bh(r));let s={keyId:kh(r),pattern:o};return n&&(s.searcher=og(o,t)),s}let o={children:[],operator:i[0]};return i.forEach(t=>{let n=e[t];sh(n)&&n.forEach(e=>{o.children.push(r(e))})}),o};return lg(e)||(e=fg(e)),r(e)}function mg(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){let n=1;return e.forEach(({key:e,norm:r,score:i})=>{let a=e?e.weight:null;n*=(i===0&&a?2**-52:i)**+((a||1)*(t?1:r))}),n}function hg(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){e.forEach(e=>{e.score=mg(e.matches,{ignoreFieldNorm:t})})}var gg=class{constructor(e,t){this.limit=e,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(e){this.size<this.limit?(this.heap.push(e),this._bubbleUp(this.size-1)):this.comparator(e,this.heap[0])<0&&(this.heap[0]=e,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(e){let t=this.heap;for(;e>0;){let n=e-1>>1;if(this.comparator(t[e],t[n])<=0)break;let r=t[e];t[e]=t[n],t[n]=r,e=n}}_sinkDown(e){let t=this.heap,n=t.length,r=e;do{e=r;let i=2*e+1,a=2*e+2;if(i<n&&this.comparator(t[i],t[r])>0&&(r=i),a<n&&this.comparator(t[a],t[r])>0&&(r=a),r!==e){let n=t[e];t[e]=t[r],t[r]=n}}while(r!==e)}};function _g(e){let t=[];return e.matches.forEach(e=>{if(!hh(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function vg(e,t,{includeMatches:n=Y.includeMatches,includeScore:r=Y.includeScore}={}){return e.map(e=>{let{idx:i}=e,a={item:t[i],refIndex:i};return n&&(a.matches=_g(e)),r&&(a.score=e.score),a})}var yg=/[\p{L}\p{M}\p{N}_]+/gu,bg=new WeakSet;function xg(e){bg.has(e)||(bg.add(e),console.warn(`[Fuse] tokenize regex ${e} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function Sg(e){if(typeof e==`function`){let t=!1;return n=>{let r=e(n);if(!t&&(t=!0,!Array.isArray(r)||r.some(e=>typeof e!=`string`)))throw Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?`array containing non-strings`:typeof r}.`);return r}}return e instanceof RegExp?(e.global||xg(e),t=>t.match(e)||[]):e=>e.match(yg)||[]}function Cg({isCaseSensitive:e=!1,ignoreDiacritics:t=!1,tokenize:n}={}){let r=Sg(n);return{tokenize(n){return e||(n=n.toLowerCase()),t&&(n=Kh(n)),r(n)}}}var wg=class{static condition(e,t){return t.useTokenSearch}constructor(e,t){this.options=t,this.analyzer=Cg({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let n=this.analyzer.tokenize(e),{df:r,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let e of n){this.termSearchers.push(new qh(e,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let n=r.get(e)||0,a=Math.log(1+(i-n+.5)/(n+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch===`all`,this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(e){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],n=0,r=0,i=0,a=0,o=this.combineAll&&!this.useMask?new Set:null;for(let s=0;s<this.termSearchers.length;s++){let c=this.termSearchers[s].searchIn(e),l=this.idfWeights[s];r+=l,c.isMatch&&(i++,n+=l*(1-c.score),c.indices&&t.push(...c.indices),this.combineAll&&(this.useMask?a|=1<<s:o.add(s)))}if(i===0)return{isMatch:!1,score:1};let s=r>0?1-n/r:0,c={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&t.length&&(c.indices=Uh(t)),this.combineAll&&(this.useMask?c.matchedMask=a:c.matchedTerms=o,c.termCount=this.numTerms),c}};function Tg(e,t,n,r){let i=r.tokenize(t);if(!i.length)return;e.fieldCount++,e.docFieldCount.set(n,(e.docFieldCount.get(n)||0)+1);let a=new Set(i),o=e.docTermFieldHits.get(n);o||(o=new Map,e.docTermFieldHits.set(n,o));for(let t of a)o.set(t,(o.get(t)||0)+1),e.df.set(t,(e.df.get(t)||0)+1)}function Eg(e,t,n,r){let{i,v:a,$:o}=t;if(a!==void 0)Tg(e,a,i,r);else if(o)for(let t=0;t<n;t++){let n=o[t];if(n){if(Array.isArray(n))for(let t of n)Tg(e,t.v,i,r);else Tg(e,n.v,i,r)}}}function Dg(e,t,n){let r={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of e)Eg(r,i,t,n);return r}function Og(e,t,n,r){Eg(e,t,n,r)}function kg(e,t){let n=e.docFieldCount.get(t);if(n===void 0)return;e.fieldCount-=n,e.docFieldCount.delete(t);let r=e.docTermFieldHits.get(t);if(r){for(let[t,n]of r){let r=(e.df.get(t)||0)-n;r<=0?e.df.delete(t):e.df.set(t,r)}e.docTermFieldHits.delete(t)}}function Ag(e,t){if(t.length===0)return;let n=Array.from(new Set(t)).sort((e,t)=>e-t);for(let t of n)kg(e,t);let r=e=>{let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e?t=i+1:r=i}return e-t},i=n[0],a=new Map;for(let[t,n]of e.docFieldCount)a.set(t>i?r(t):t,n);e.docFieldCount=a;let o=new Map;for(let[t,n]of e.docTermFieldHits)o.set(t>i?r(t):t,n);e.docTermFieldHits=o}var jg=class{constructor(e,t,n){this.options={...Y,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new Eh(this.options.keys),this._docs=e,this._myIndex=null,this._invertedIndex=null,this.setCollection(e,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(e){if(this._lastQuery===e)return this._lastSearcher;let t=og(e,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=e,this._lastSearcher=t,t}setCollection(e,t){if(this._docs=e,t&&!(t instanceof Lh))throw Error(vh);if(this._myIndex=t||Rh(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=Cg({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=Dg(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(e){if(!hh(e))return;this._docs.push(e);let t=this._myIndex.add(e,this._docs.length-1);if(this._invertedIndex&&t){let e=Cg({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});Og(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(e=()=>!1){let t=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)e(this._docs[r],r)&&(t.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&Ag(this._invertedIndex,n);let e=new Set(n);this._docs=this._docs.filter((t,n)=>!e.has(n)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return t}removeAt(e){if(!Number.isInteger(e)||e<0||e>=this._docs.length)throw Error(yh);this._invertedIndex&&Ag(this._invertedIndex,[e]);let t=this._docs.splice(e,1)[0];return this._myIndex.removeAt(e),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(e=>this._keyStore.get(e.id)||e)}search(e,t){let{limit:n=-1}=t||{},{includeMatches:r,includeScore:i,shouldSort:a,sortFn:o,ignoreFieldNorm:s}=this.options;if(uh(e)&&!e.trim()){let e=this._docs.map((e,t)=>({item:e,refIndex:t}));return dh(n)&&n>-1&&(e=e.slice(0,n)),e}let c=a&&dh(n)&&n>0&&uh(e),l=o,u=(e,t)=>l(e,t)||e.idx-t.idx,d;if(c){let t=new gg(n,u);uh(this._docs[0])?this._searchStringList(e,{heap:t,ignoreFieldNorm:s}):this._searchObjectList(e,{heap:t,ignoreFieldNorm:s}),d=t.extractSorted()}else d=uh(e)?uh(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e),hg(d,{ignoreFieldNorm:s}),a&&d.sort(uh(e)?u:l),dh(n)&&n>-1&&(d=d.slice(0,n));return vg(d,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=t?null:[];return a.forEach(({v:e,i:a,n:s})=>{if(!hh(e))return;let c=r.searchIn(e);if(c.isMatch){let r={score:c.score,value:e,norm:s,indices:c.indices};i&&(r.matchedMask=c.matchedMask,r.matchedTerms=c.matchedTerms,r.termCount=c.termCount);let l=[r];if(!i||this._coversAllTokens(l)){let r={item:e,idx:a,matches:l};t?(r.score=mg(r.matches,{ignoreFieldNorm:n}),t.insert(r)):o.push(r)}}}),o}_searchLogical(e){let t=pg(e,this.options),n=this._normalizedKeys(),r=(e,t,i)=>{if(!(`children`in e)){let{keyId:r,searcher:a}=e,o;return r===null?(o=[],n.forEach((e,n)=>{o.push(...this._findMatches({key:e,value:t[n],searcher:a}))})):o=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(t,r),searcher:a}),o&&o.length?[{idx:i,item:t,matches:o}]:[]}let{children:a,operator:o}=e,s=[];for(let e=0,n=a.length;e<n;e+=1){let n=a[e],c=r(n,t,i);if(c.length)s.push(...c);else if(o===sg.AND)return[]}return s},i=this._myIndex.records,a=new Map,o=[];return i.forEach(({$:e,i:n})=>{if(hh(e)){let i=r(t,e,n);i.length&&(a.has(n)||(a.set(n,{idx:n,item:e,matches:[]}),o.push(a.get(n))),i.forEach(({matches:e})=>{a.get(n).matches.push(...e)}))}}),o}_searchObjectList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=this._normalizedKeys(),s=t?null:[];return a.forEach(({$:e,i:a})=>{if(!hh(e))return;let c=[],l=!1,u=!1;if(o.forEach((t,n)=>{let i=this._findMatches({key:t,value:e[n],searcher:r});i.length?(c.push(...i),i[0].hasInverse&&(u=!0)):l=!0}),!(u&&l)&&c.length&&(!i||this._coversAllTokens(c))){let r={idx:a,item:e,matches:c};t?(r.score=mg(r.matches,{ignoreFieldNorm:n}),t.insert(r)):s.push(r)}}),s}_findMatches({key:e,value:t,searcher:n}){if(!hh(t))return[];let r=[];if(sh(t))t.forEach(({v:t,i,n:a})=>{if(!hh(t))return;let o=n.searchIn(t);if(o.isMatch){let n={score:o.score,key:e,value:t,idx:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(n.matchedMask=o.matchedMask,n.matchedTerms=o.matchedTerms,n.termCount=o.termCount),r.push(n)}});else{let{v:i,n:a}=t,o=n.searchIn(i);if(o.isMatch){let t={score:o.score,key:e,value:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(t.matchedMask=o.matchedMask,t.matchedTerms=o.matchedTerms,t.termCount=o.termCount),r.push(t)}}return r}_coversAllTokens(e){let t=e.length?e[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let t=0;t<e.length;t++)n|=e[t].matchedMask||0;return n===2**t-1}let n=new Set;for(let t=0;t<e.length;t++){let r=e[t].matchedTerms;if(r)for(let e of r)n.add(e)}return n.size===t}};jg.version=`7.5.0`,jg.createIndex=Rh,jg.parseIndex=zh,jg.config=Y,jg.match=function(e,t,n){if(n&&n.useTokenSearch)throw Error(wh);return og(e,{...Y,...n}).searchIn(t)},jg.parseQuery=pg,ag(rg),ag(wg),jg.use=function(...e){e.forEach(e=>ag(e))};var Mg=jg,Ng=`modulepreload`,Pg=function(e){return`/`+e},Fg={},Ig=function(e){return e.pathname.endsWith(`.css`)},Lg=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},Rg=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Pg(t,n);let r=s(t),i=Ig(r);return Lg(Fg,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:Ng,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},zg=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.name=`BlameApiError`,this.status=e,this.body=t}},Bg=class extends Error{constructor(){super(`Blame 请求已取消`),this.name=`BlameCancelledError`}},Vg=(e,t,n=``)=>`/api/git?workspaceId=${encodeURIComponent(e)}&op=blame&path=${encodeURIComponent(t)}${n?`&cwd=${encodeURIComponent(n)}`:``}`;async function Hg(e,t,n={}){if(n.signal?.aborted)throw new Bg;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 fetch(Vg(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 zg(r.status,{error:e.error||`HTTP ${r.status}`,...e.code?{code:e.code}:{}})}return a}catch(e){throw n.signal?.aborted?new Bg:a?new zg(408,{error:`请求超时:${Math.round(r/1e3)} 秒内服务端没有响应`,code:`timeout`}):e}finally{clearTimeout(o),n.signal?.removeEventListener(`abort`,s)}}var Ug=`\0`,Wg=(e,t,n)=>[e,t,n??``].join(Ug),Gg=24,Kg=new Map;function qg(e){let t=Kg.get(e);if(t)return Kg.delete(e),Kg.set(e,t),t}function Jg(e,t){for(Kg.delete(e),Kg.set(e,t);Kg.size>Gg;){let e=Kg.keys().next();if(e.done)break;Kg.delete(e.value)}}var Yg={untracked:`这个文件尚未被 Git 跟踪`,binary:`二进制文件不支持 Blame`,too_large:`文件过大,未显示 Blame`,no_head:`仓库还没有提交`,not_in_revision:`这个版本里没有这个文件`},Xg=`此工作区不是 Git 仓库`;function Zg(e){return e&&Yg[e]?{code:e,text:Yg[e]}:{code:`unsupported`,text:`这个文件暂时不能显示 Blame`}}function Qg(e){return e instanceof zg&&e.body.code===`not_a_repo`?{state:`unsupported`,note:{code:`not_a_repo`,text:Xg}}:{state:`error`,note:{code:`error`,text:`读取 Blame 失败:${e instanceof Error&&e.message?e.message:`未知错误`}`}}}var $g=`${Ug}uncommitted`;function e_(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?$g:n.commit??`${Ug}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 t_(e){let t=0;for(let n of e.lines)n.line>t&&(t=n.line);return t}function n_(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 r_(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,i_(t.date),t.summary?.trim()||`(没有提交摘要)`]}function i_(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 a_(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 o_(e,t,n=!1){return!t||!t.supported?!1:n||a_(e)!==t.totalLines}var s_=new WeakMap;function c_(e){let t=s_.get(e);if(t)return t;let n={response:e,models:e_(e),covered:t_(e)};return s_.set(e,n),n}function l_(e,t){if(!e||t<1)return null;let n=e.models[t-1];return n&&n.line===t?n:null}var u_=`a1b2c3d · Author`;async function d_(){let[e,t]=await Promise.all([Rg(()=>import(`./dist-opu-Ndfn.js`).then(e=>e.x),[]),Rg(()=>import(`./dist-BofmoyAA.js`).then(e=>e.s),__vite__mapDeps([0,1]))]),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=r_(this.model);return e.setAttribute(`title`,t.join(`
49
- `)),e.setAttribute(`aria-label`,t.join(` · `)),e.textContent=n_(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=u_,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=l_(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=l_(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:f_(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 f_(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 r_(e)){let e=document.createElement(`div`);e.className=`cm-blame-tooltip-row`,e.textContent=n,t.appendChild(e)}return t}var p_=4e3,m_=(0,V.lazy)(()=>Rg(()=>import(`./CodeMirrorEditor-Ch1Ipz3r.js`).then(e=>({default:e.CodeMirrorEditor})),[])),h_=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},g_=15e3,__=e=>new h_(408,{error:`请求超时:${g_/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function v_(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),g_);try{let r=await fetch(e,{...t,signal:n.signal}),i;try{i=await r.json()}catch{i=void 0}if(!r.ok)throw new h_(r.status,i??{error:`HTTP ${r.status}`});return i}catch(t){throw n.signal.aborted?__(e):t}finally{clearTimeout(r)}}var y_=e=>e instanceof h_?e:new h_(0,{error:e instanceof Error?e.message:`读取失败`}),b_=e=>encodeURIComponent(e),x_=e=>e?`&cwd=${b_(e)}`:``,S_=(e,t,n)=>`/api/files?workspaceId=${b_(e)}&path=${b_(t)}${x_(n)}`,C_=(e,t,n)=>`/api/file?workspaceId=${b_(e)}&path=${b_(t)}${x_(n)}`,w_=(e,t,n)=>`/api/file?workspaceId=${b_(e)}&path=${b_(t)}&meta=1${x_(n)}`,T_=(e,t,n)=>`/api/files?workspaceId=${b_(e)}&q=${b_(t)}${x_(n)}`,E_=e=>e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`,D_=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function O_({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d}){let f=r[t],p=i.has(t);return(0,V.useEffect)(()=>{p&&f===void 0&&o(t)},[p,t,f,o]),(0,H.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":p,style:{paddingLeft:`${8+d*13}px`},title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:p?`▾`:`▸`}),(0,H.jsx)(cp,{category:`folder`}),(0,H.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,H.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),p&&(0,H.jsx)(`ul`,{className:`file-children`,children:f===void 0?(0,H.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in f?(0,H.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,title:np(f.error.message),children:tp(f.error.message,`这个目录读取失败。`)}):f.entries.length===0?(0,H.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,H.jsxs)(H.Fragment,{children:[f.truncated&&(0,H.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),f.entries.map(t=>t.kind===`directory`?(0,H.jsx)(O_,{workspaceId:e,entryPath:t.path,name:t.name,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d+1},t.path):(0,H.jsx)(k_,{entry:t,depth:d+1,openPaths:s,changedPaths:l,onOpen:u},t.path))]})})]})}function k_({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i}){if(e.kind===`symlink`)return(0,H.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-outside":e.path,children:(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 是一个指向 workspace 之外的符号链接,不能打开`,style:{paddingLeft:`${8+t*13}px`},children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`file-name`,children:e.name}),(0,H.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let a=n.has(e.path),o=r.has(e.path);return(0,H.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-row-open":a?`1`:`0`,"data-file-row-changed":o?`1`:`0`,children:(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,disabled:!e.text,title:e.text?o?`${e.path}(agent 改过这个文件,点击查看改动)`:a?`${e.path}(已经打开,点击切换到它)`:e.path:`${e.name} 是二进制文件,无法以文本打开`,style:{paddingLeft:`${8+t*13}px`},onClick:()=>i(e),children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,H.jsx)(cp,{path:e.path}),(0,H.jsx)(`span`,{className:`file-name`,children:e.name}),a&&(0,H.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),o&&(0,H.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),e.document&&(0,H.jsx)(`span`,{className:`file-badge`,"data-file-document":`1`,"aria-label":`文档文件`,children:`文档`}),!e.text&&!e.document&&(0,H.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]})})}function A_({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c,workspaceId:l,cwd:u=``}){let[d,f]=(0,V.useState)(!0),p=(0,V.useRef)(null),[m,h]=(0,V.useState)({}),[g,_]=(0,V.useState)(null),v=(0,V.useRef)(0),y=m[e.path]===!0&&!!l,b=l?u?`${l}:${u}`:l:``;(0,V.useEffect)(()=>{let t=++v.current;if(!y||!l){_(null);return}let n=new AbortController,i=Wg(b,e.path,e.etag),a=r?void 0:qg(i);if(a)_({state:a.supported?`ready`:`unsupported`,response:a,path:e.path,workspaceId:b,note:a.supported?null:Zg(a.reason)});else return _({state:`loading`,response:null,path:e.path,workspaceId:b,note:null}),Hg(l,e.path,{signal:n.signal,cwd:u}).then(n=>{t===v.current&&(r||Jg(i,n),_({state:n.supported?`ready`:`unsupported`,response:n,path:e.path,workspaceId:b,note:n.supported?null:Zg(n.reason)}))}).catch(n=>{if(t!==v.current||n instanceof Bg)return;let r=Qg(n);_({state:r.state,response:null,path:e.path,workspaceId:b,note:r.note})}),()=>{n.abort()}},[y,l,u,b,e.path,e.etag,r]);let x=g&&g.path===e.path&&g.workspaceId===b?g:null,S=y?x?.state??`loading`:`off`,C=S===`ready`&&o_(e.content,x?.response??null,e.dirty||r),w=[];x?.note&&w.push(x.note),S===`ready`&&x?.response?.truncated&&w.push({code:`truncated`,text:`Blame 数据已截断,只显示了前面一部分(共 ${x.response.totalLines} 行)`}),C&&w.push({code:`stale`,text:`内容已改动,Blame 对应的是磁盘上的版本`});let T=S===`loading`?`⌛ Blame`:S===`ready`?`✓ Blame`:S===`off`?`Blame`:`! Blame`;(0,V.useEffect)(()=>{i&&f(!1)},[e.path,i]),(0,V.useEffect)(()=>{let e=p.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
48
+ `),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 oh(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}}function sh(e){return Array.isArray?Array.isArray(e):_h(e)===`[object Array]`}function ch(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=e+``;return t==`0`&&1/e==-1/0?`-0`:t}function lh(e){return e==null?``:ch(e)}function uh(e){return typeof e==`string`}function dh(e){return typeof e==`number`}function fh(e){return e===!0||e===!1||mh(e)&&_h(e)==`[object Boolean]`}function ph(e){return typeof e==`object`}function mh(e){return ph(e)&&e!==null}function hh(e){return e!=null}function gh(e){return!e.trim().length}function _h(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var vh=`Incorrect 'index' type`,yh=`Invalid doc index: must be a non-negative integer within the bounds of the docs array`,bh=e=>`Invalid value for key ${e}`,xh=e=>`Pattern length exceeds max of ${e}.`,Sh=e=>`Missing ${e} property in key`,Ch=e=>`Property 'weight' in key '${e}' must be a positive integer`,wh=`Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.`,Th=Object.prototype.hasOwnProperty,Eh=class{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(e=>{let n=Dh(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function Dh(e){let t=null,n=null,r=null,i=1,a=null;if(uh(e)||sh(e))r=e,t=Oh(e),n=kh(e);else{if(!Th.call(e,`name`))throw Error(Sh(`name`));let o=e.name;if(r=o,Th.call(e,`weight`)&&e.weight!==void 0&&(i=e.weight,i<=0))throw Error(Ch(kh(o)));t=Oh(o),n=kh(o),a=e.getFn??null}return{path:t,id:n,weight:i,src:r,getFn:a}}function Oh(e){return sh(e)?e:e.split(`.`)}function kh(e){return sh(e)?e.join(`.`):e}function Ah(e,t){let n=[],r=!1,i=(e,t,a,o)=>{if(hh(e)){if(!t[a])n.push(o===void 0?e:{v:e,i:o});else{let s=e[t[a]];if(!hh(s))return;if(a===t.length-1&&(uh(s)||dh(s)||fh(s)||typeof s==`bigint`))n.push(o===void 0?lh(s):{v:lh(s),i:o});else if(sh(s)){r=!0;for(let e=0,n=s.length;e<n;e+=1)i(s[e],t,a+1,e)}else t.length&&i(s,t,a+1,o)}}};return i(e,uh(t)?t.split(`.`):t,0),r?n:n[0]}var jh={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Mh={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx<t.idx?-1:1:e.score<t.score?-1:1},Nh={location:0,threshold:.6,distance:100},Ph={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:`any`,getFn:Ah,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Y=Object.freeze({...Mh,...jh,...Nh,...Ph});function Fh(e){return e>=9&&e<=13||e===32||e===160}function Ih(e=1,t=3){let n=new Map,r=10**t;return{get(t){let i=0,a=!1;for(let e=0;e<t.length;e++)Fh(t.charCodeAt(e))?a=!1:a||=(i++,!0);if(i===0&&(i=1),n.has(i))return n.get(i);let o=Math.round(r/i**(.5*e))/r;return n.set(i,o),o},clear(){n.clear()}}}var Lh=class{constructor({getFn:e=Y.getFn,fieldNormWeight:t=Y.fieldNormWeight}={}){this.norm=Ih(t,3),this.getFn=e,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let e=this.docs.length;this.records=Array(e);let t=0;if(uh(this.docs[0]))for(let n=0;n<e;n++){let e=this._createStringRecord(this.docs[n],n);e&&(this.records[t++]=e)}else for(let n=0;n<e;n++)this.records[t++]=this._createObjectRecord(this.docs[n],n);this.records.length=t,this.norm.clear()}add(e,t){if(!Number.isInteger(t)||t<0)throw Error(yh);if(uh(e)){let n=this._createStringRecord(e,t);return n&&this.records.push(n),n}let n=this._createObjectRecord(e,t);return this.records.push(n),n}removeAt(e){if(!Number.isInteger(e)||e<0)throw Error(yh);for(let t=0,n=this.records.length;t<n;t+=1)if(this.records[t].i===e){this.records.splice(t,1);break}for(let t=0,n=this.records.length;t<n;t+=1)this.records[t].i>e&&--this.records[t].i}removeAll(e){let t=new Set;for(let n of e)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(e=>!t.has(e.i));let n=Array.from(t).sort((e,t)=>e-t);for(let e of this.records){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e.i?t=i+1:r=i}e.i-=t}}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(e,t){return!hh(e)||gh(e)?null:{v:e,i:t,n:this.norm.get(e)}}_createObjectRecord(e,t){let n={i:t,$:{}};for(let t=0,r=this.keys.length;t<r;t++){let r=this.keys[t],i=r.getFn?r.getFn(e):this.getFn(e,r.path);if(hh(i)){if(sh(i)){let e=[];for(let t=0,n=i.length;t<n;t+=1){let n=i[t];if(hh(n)){if(uh(n)){if(!gh(n)){let r={v:n,i:t,n:this.norm.get(n)};e.push(r)}}else if(hh(n.v)){let t=uh(n.v)?n.v:lh(n.v);if(!gh(t)){let r={v:t,i:n.i,n:this.norm.get(t)};e.push(r)}}}}n.$[t]=e}else if(uh(i)&&!gh(i)){let e={v:i,n:this.norm.get(i)};n.$[t]=e}}}return n}toJSON(){return{keys:this.keys.map(({getFn:e,...t})=>t),records:this.records}}};function Rh(e,t,{getFn:n=Y.getFn,fieldNormWeight:r=Y.fieldNormWeight}={}){let i=new Lh({getFn:n,fieldNormWeight:r});return i.setKeys(e.map(Dh)),i.setSources(t),i.create(),i}function zh(e,{getFn:t=Y.getFn,fieldNormWeight:n=Y.fieldNormWeight}={}){let{keys:r,records:i}=e,a=new Lh({getFn:t,fieldNormWeight:n});return a.setKeys(r),a.setIndexRecords(i),a}function Bh(e=[],t=Y.minMatchCharLength){let n=[],r=-1,i=-1,a=0;for(let o=e.length;a<o;a+=1){let o=e[a];o&&r===-1?r=a:!o&&r!==-1&&(i=a-1,i-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}function Vh(e,t,n,{location:r=Y.location,distance:i=Y.distance,threshold:a=Y.threshold,findAllMatches:o=Y.findAllMatches,minMatchCharLength:s=Y.minMatchCharLength,includeMatches:c=Y.includeMatches,ignoreLocation:l=Y.ignoreLocation}={}){if(t.length>32)throw Error(xh(32));let u=t.length,d=e.length,f=Math.max(0,Math.min(r,d)),p=a,m=f,h=(e,t)=>{let n=e/u;if(l)return n;let r=Math.abs(f-t);return i?n+r/i:r?1:n},g=s>1||c,_=g?Array(d):[],v;for(;(v=e.indexOf(t,m))>-1;){let e=h(0,v);if(p=Math.min(e,p),m=v+u,g){let e=0;for(;e<u;)_[v+e]=1,e+=1}}m=-1;let y=[],b=1,x=0,S=u+d,C=1<<u-1;for(let t=0;t<u;t+=1){let r=0,i=S;for(;r<i;)h(t,f+i)<=p?r=i:S=i,i=Math.floor((S-r)/2+r);S=i;let a=Math.max(1,f-i+1),s=o?d:Math.min(f+i,d)+u,c=Array(s+2);c[s+1]=(1<<t)-1;for(let r=s;r>=a;--r){let i=r-1,o=n[e[i]];if(c[r]=(c[r+1]<<1|1)&o,t&&(c[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),c[r]&C&&(b=h(t,i),b<=p)){if(p=b,m=i,x=t,m<=f)break;a=Math.max(1,2*f-m)}}if(h(t+1,f)>p)break;y=c}if(g&&m>=0){let t=Math.min(d-1,m+u-1+x);for(let r=m;r<=t;r+=1)n[e[r]]&&(_[r]=1)}let w={isMatch:m>=0,score:Math.max(.001,b)};if(g){let e=Bh(_,s);e.length?c&&(w.indices=e):w.isMatch=!1}return w}function Hh(e){let t={};for(let n=0,r=e.length;n<r;n+=1){let i=e.charAt(n);t[i]=(t[i]||0)|1<<r-n-1}return t}function Uh(e){if(e.length<=1)return e;e.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let t=[e[0]];for(let n=1,r=e.length;n<r;n+=1){let r=t[t.length-1],i=e[n];i[0]<=r[1]+1?r[1]=Math.max(r[1],i[1]):t.push(i)}return t}var Wh={ł:`l`,Ł:`L`,đ:`d`,Đ:`D`,ø:`o`,Ø:`O`,ħ:`h`,Ħ:`H`,ŧ:`t`,Ŧ:`T`,ı:`i`,ß:`ss`},Gh=RegExp(`[`+Object.keys(Wh).join(``)+`]`,`g`),Kh=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFD`).replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,``).replace(Gh,e=>Wh[e]):e=>e,qh=class{constructor(e,{location:t=Y.location,threshold:n=Y.threshold,distance:r=Y.distance,includeMatches:i=Y.includeMatches,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,isCaseSensitive:s=Y.isCaseSensitive,ignoreDiacritics:c=Y.ignoreDiacritics,ignoreLocation:l=Y.ignoreLocation}={}){if(this.options={location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:s,ignoreDiacritics:c,ignoreLocation:l},e=s?e:e.toLowerCase(),e=c?Kh(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;let u=(e,t)=>{this.chunks.push({pattern:e,alphabet:Hh(e),startIndex:t})},d=this.pattern.length;if(d>32){let e=0,t=d%32,n=d-t;for(;e<n;)u(this.pattern.substr(e,32),e),e+=32;if(t){let e=d-32;u(this.pattern.substr(e),e)}}else u(this.pattern,0)}searchIn(e){let{isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=n?Kh(e):e,this.pattern===e){if(e.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let t={isMatch:!0,score:0};return r&&(t.indices=[[0,e.length-1]]),t}let{location:i,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,ignoreLocation:l}=this.options,u=[],d=0,f=!1;this.chunks.forEach(({pattern:t,alphabet:n,startIndex:p})=>{let{isMatch:m,score:h,indices:g}=Vh(e,t,n,{location:i+p,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,includeMatches:r,ignoreLocation:l});m&&(f=!0),d+=h,m&&g&&u.push(...g)});let p={isMatch:f,score:f?d/this.chunks.length:1};return f&&r&&(p.indices=Uh(u)),p}},Jh=new Set([`fuzzy`,`include`]);function Yh(e){return e.startsWith(`inverse`)}var Xh=[{type:`exact`,multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:e=>({type:`exact`,search(t){let n=t===e;return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`include`,multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:e=>({type:`include`,search(t){let n=0,r,i=[],a=e.length;for(;(r=t.indexOf(e,n))>-1;)n=r+a,i.push([r,n-1]);let o=!!i.length;return{isMatch:o,score:+!o,indices:i}}})},{type:`prefix-exact`,multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:e=>({type:`prefix-exact`,search(t){let n=t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`inverse-prefix-exact`,multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:e=>({type:`inverse-prefix-exact`,search(t){let n=!t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`inverse-suffix-exact`,multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:e=>({type:`inverse-suffix-exact`,search(t){let n=!t.endsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`suffix-exact`,multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:e=>({type:`suffix-exact`,search(t){let n=t.endsWith(e);return{isMatch:n,score:+!n,indices:[t.length-e.length,t.length-1]}}})},{type:`inverse-exact`,multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:e=>({type:`inverse-exact`,search(t){let n=t.indexOf(e)===-1;return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`fuzzy`,multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(e,t={})=>{let n=new qh(e,{location:t.location??Y.location,threshold:t.threshold??Y.threshold,distance:t.distance??Y.distance,includeMatches:t.includeMatches??Y.includeMatches,findAllMatches:t.findAllMatches??Y.findAllMatches,minMatchCharLength:t.minMatchCharLength??Y.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??Y.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??Y.ignoreDiacritics,ignoreLocation:t.ignoreLocation??Y.ignoreLocation});return{type:`fuzzy`,search(e){return n.searchIn(e)}}}}],Zh=Xh.length,Qh=`\0`,$h=`|`;function eg(e){let t=[],n=e.length,r=0;for(;r<n;){for(;r<n&&e[r]===` `;)r++;if(r>=n)break;let i=r;for(;i<n&&e[i]!==` `&&e[i]!==`"`;)i++;if(i<n&&e[i]===`"`){for(i++;i<n;){if(e[i]===`"`){let t=i+1;if(t>=n||e[t]===` `){i++;break}if(e[t]===`$`&&(t+1>=n||e[t+1]===` `)){i+=2;break}}i++}t.push(e.substring(r,i)),r=i}else{for(;i<n&&e[i]!==` `;)i++;t.push(e.substring(r,i)),r=i}}return t}function tg(e,t){let n=e.match(t);return n?n[1]:null}function ng(e,t={}){return e.replace(/\\\|/g,Qh).split($h).map(e=>{let n=eg(e.replace(/\u0000/g,`|`).trim()).filter(e=>e&&!!e.trim()),r=[];for(let e=0,i=n.length;e<i;e+=1){let i=n[e],a=!1,o=-1;for(;!a&&++o<Zh;){let e=Xh[o],n=tg(i,e.multiRegex);n&&(r.push(e.create(n,t)),a=!0)}if(!a)for(o=-1;++o<Zh;){let e=Xh[o],n=tg(i,e.singleRegex);if(n){r.push(e.create(n,t));break}}}return r})}var rg=class{constructor(e,{isCaseSensitive:t=Y.isCaseSensitive,ignoreDiacritics:n=Y.ignoreDiacritics,includeMatches:r=Y.includeMatches,minMatchCharLength:i=Y.minMatchCharLength,ignoreLocation:a=Y.ignoreLocation,findAllMatches:o=Y.findAllMatches,location:s=Y.location,threshold:c=Y.threshold,distance:l=Y.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:s,threshold:c,distance:l},e=t?e:e.toLowerCase(),e=n?Kh(e):e,this.pattern=e,this.query=ng(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?Kh(e):e;let a=0,o=[],s=0,c=!1;for(let r=0,i=t.length;r<i;r+=1){let i=t[r];o.length=0,a=0,c=!1;for(let t=0,r=i.length;t<r;t+=1){let r=i[t],{isMatch:l,indices:u,score:d}=r.search(e);if(l)a+=1,s+=d,Yh(r.type)&&(c=!0),n&&(Jh.has(r.type)?o.push(...u):o.push(u));else{s=0,a=0,o.length=0,c=!1;break}}if(a){let e={isMatch:!0,score:s/a};return c&&(e.hasInverse=!0),n&&(e.indices=Uh(o)),e}}return{isMatch:!1,score:1}}},ig=[];function ag(...e){ig.push(...e)}function og(e,t){for(let n=0,r=ig.length;n<r;n+=1){let r=ig[n];if(r.condition(e,t))return new r(e,t)}return new qh(e,t)}var sg={AND:`$and`,OR:`$or`},cg={PATH:`$path`,PATTERN:`$val`},lg=e=>!!(e[sg.AND]||e[sg.OR]),ug=e=>!!e[cg.PATH],dg=e=>!sh(e)&&ph(e)&&!lg(e),fg=e=>({[sg.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function pg(e,t,{auto:n=!0}={}){let r=e=>{if(uh(e)){let r={keyId:null,pattern:e};return n&&(r.searcher=og(e,t)),r}let i=Object.keys(e),a=ug(e);if(!a&&i.length>1&&!lg(e))return r(fg(e));if(dg(e)){let r=a?e[cg.PATH]:i[0],o=a?e[cg.PATTERN]:e[r];if(!uh(o))throw Error(bh(r));let s={keyId:kh(r),pattern:o};return n&&(s.searcher=og(o,t)),s}let o={children:[],operator:i[0]};return i.forEach(t=>{let n=e[t];sh(n)&&n.forEach(e=>{o.children.push(r(e))})}),o};return lg(e)||(e=fg(e)),r(e)}function mg(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){let n=1;return e.forEach(({key:e,norm:r,score:i})=>{let a=e?e.weight:null;n*=(i===0&&a?2**-52:i)**+((a||1)*(t?1:r))}),n}function hg(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){e.forEach(e=>{e.score=mg(e.matches,{ignoreFieldNorm:t})})}var gg=class{constructor(e,t){this.limit=e,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(e){this.size<this.limit?(this.heap.push(e),this._bubbleUp(this.size-1)):this.comparator(e,this.heap[0])<0&&(this.heap[0]=e,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(e){let t=this.heap;for(;e>0;){let n=e-1>>1;if(this.comparator(t[e],t[n])<=0)break;let r=t[e];t[e]=t[n],t[n]=r,e=n}}_sinkDown(e){let t=this.heap,n=t.length,r=e;do{e=r;let i=2*e+1,a=2*e+2;if(i<n&&this.comparator(t[i],t[r])>0&&(r=i),a<n&&this.comparator(t[a],t[r])>0&&(r=a),r!==e){let n=t[e];t[e]=t[r],t[r]=n}}while(r!==e)}};function _g(e){let t=[];return e.matches.forEach(e=>{if(!hh(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function vg(e,t,{includeMatches:n=Y.includeMatches,includeScore:r=Y.includeScore}={}){return e.map(e=>{let{idx:i}=e,a={item:t[i],refIndex:i};return n&&(a.matches=_g(e)),r&&(a.score=e.score),a})}var yg=/[\p{L}\p{M}\p{N}_]+/gu,bg=new WeakSet;function xg(e){bg.has(e)||(bg.add(e),console.warn(`[Fuse] tokenize regex ${e} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function Sg(e){if(typeof e==`function`){let t=!1;return n=>{let r=e(n);if(!t&&(t=!0,!Array.isArray(r)||r.some(e=>typeof e!=`string`)))throw Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?`array containing non-strings`:typeof r}.`);return r}}return e instanceof RegExp?(e.global||xg(e),t=>t.match(e)||[]):e=>e.match(yg)||[]}function Cg({isCaseSensitive:e=!1,ignoreDiacritics:t=!1,tokenize:n}={}){let r=Sg(n);return{tokenize(n){return e||(n=n.toLowerCase()),t&&(n=Kh(n)),r(n)}}}var wg=class{static condition(e,t){return t.useTokenSearch}constructor(e,t){this.options=t,this.analyzer=Cg({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let n=this.analyzer.tokenize(e),{df:r,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let e of n){this.termSearchers.push(new qh(e,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let n=r.get(e)||0,a=Math.log(1+(i-n+.5)/(n+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch===`all`,this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(e){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],n=0,r=0,i=0,a=0,o=this.combineAll&&!this.useMask?new Set:null;for(let s=0;s<this.termSearchers.length;s++){let c=this.termSearchers[s].searchIn(e),l=this.idfWeights[s];r+=l,c.isMatch&&(i++,n+=l*(1-c.score),c.indices&&t.push(...c.indices),this.combineAll&&(this.useMask?a|=1<<s:o.add(s)))}if(i===0)return{isMatch:!1,score:1};let s=r>0?1-n/r:0,c={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&t.length&&(c.indices=Uh(t)),this.combineAll&&(this.useMask?c.matchedMask=a:c.matchedTerms=o,c.termCount=this.numTerms),c}};function Tg(e,t,n,r){let i=r.tokenize(t);if(!i.length)return;e.fieldCount++,e.docFieldCount.set(n,(e.docFieldCount.get(n)||0)+1);let a=new Set(i),o=e.docTermFieldHits.get(n);o||(o=new Map,e.docTermFieldHits.set(n,o));for(let t of a)o.set(t,(o.get(t)||0)+1),e.df.set(t,(e.df.get(t)||0)+1)}function Eg(e,t,n,r){let{i,v:a,$:o}=t;if(a!==void 0)Tg(e,a,i,r);else if(o)for(let t=0;t<n;t++){let n=o[t];if(n){if(Array.isArray(n))for(let t of n)Tg(e,t.v,i,r);else Tg(e,n.v,i,r)}}}function Dg(e,t,n){let r={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of e)Eg(r,i,t,n);return r}function Og(e,t,n,r){Eg(e,t,n,r)}function kg(e,t){let n=e.docFieldCount.get(t);if(n===void 0)return;e.fieldCount-=n,e.docFieldCount.delete(t);let r=e.docTermFieldHits.get(t);if(r){for(let[t,n]of r){let r=(e.df.get(t)||0)-n;r<=0?e.df.delete(t):e.df.set(t,r)}e.docTermFieldHits.delete(t)}}function Ag(e,t){if(t.length===0)return;let n=Array.from(new Set(t)).sort((e,t)=>e-t);for(let t of n)kg(e,t);let r=e=>{let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e?t=i+1:r=i}return e-t},i=n[0],a=new Map;for(let[t,n]of e.docFieldCount)a.set(t>i?r(t):t,n);e.docFieldCount=a;let o=new Map;for(let[t,n]of e.docTermFieldHits)o.set(t>i?r(t):t,n);e.docTermFieldHits=o}var jg=class{constructor(e,t,n){this.options={...Y,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new Eh(this.options.keys),this._docs=e,this._myIndex=null,this._invertedIndex=null,this.setCollection(e,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(e){if(this._lastQuery===e)return this._lastSearcher;let t=og(e,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=e,this._lastSearcher=t,t}setCollection(e,t){if(this._docs=e,t&&!(t instanceof Lh))throw Error(vh);if(this._myIndex=t||Rh(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=Cg({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=Dg(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(e){if(!hh(e))return;this._docs.push(e);let t=this._myIndex.add(e,this._docs.length-1);if(this._invertedIndex&&t){let e=Cg({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});Og(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(e=()=>!1){let t=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)e(this._docs[r],r)&&(t.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&Ag(this._invertedIndex,n);let e=new Set(n);this._docs=this._docs.filter((t,n)=>!e.has(n)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return t}removeAt(e){if(!Number.isInteger(e)||e<0||e>=this._docs.length)throw Error(yh);this._invertedIndex&&Ag(this._invertedIndex,[e]);let t=this._docs.splice(e,1)[0];return this._myIndex.removeAt(e),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(e=>this._keyStore.get(e.id)||e)}search(e,t){let{limit:n=-1}=t||{},{includeMatches:r,includeScore:i,shouldSort:a,sortFn:o,ignoreFieldNorm:s}=this.options;if(uh(e)&&!e.trim()){let e=this._docs.map((e,t)=>({item:e,refIndex:t}));return dh(n)&&n>-1&&(e=e.slice(0,n)),e}let c=a&&dh(n)&&n>0&&uh(e),l=o,u=(e,t)=>l(e,t)||e.idx-t.idx,d;if(c){let t=new gg(n,u);uh(this._docs[0])?this._searchStringList(e,{heap:t,ignoreFieldNorm:s}):this._searchObjectList(e,{heap:t,ignoreFieldNorm:s}),d=t.extractSorted()}else d=uh(e)?uh(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e),hg(d,{ignoreFieldNorm:s}),a&&d.sort(uh(e)?u:l),dh(n)&&n>-1&&(d=d.slice(0,n));return vg(d,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=t?null:[];return a.forEach(({v:e,i:a,n:s})=>{if(!hh(e))return;let c=r.searchIn(e);if(c.isMatch){let r={score:c.score,value:e,norm:s,indices:c.indices};i&&(r.matchedMask=c.matchedMask,r.matchedTerms=c.matchedTerms,r.termCount=c.termCount);let l=[r];if(!i||this._coversAllTokens(l)){let r={item:e,idx:a,matches:l};t?(r.score=mg(r.matches,{ignoreFieldNorm:n}),t.insert(r)):o.push(r)}}}),o}_searchLogical(e){let t=pg(e,this.options),n=this._normalizedKeys(),r=(e,t,i)=>{if(!(`children`in e)){let{keyId:r,searcher:a}=e,o;return r===null?(o=[],n.forEach((e,n)=>{o.push(...this._findMatches({key:e,value:t[n],searcher:a}))})):o=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(t,r),searcher:a}),o&&o.length?[{idx:i,item:t,matches:o}]:[]}let{children:a,operator:o}=e,s=[];for(let e=0,n=a.length;e<n;e+=1){let n=a[e],c=r(n,t,i);if(c.length)s.push(...c);else if(o===sg.AND)return[]}return s},i=this._myIndex.records,a=new Map,o=[];return i.forEach(({$:e,i:n})=>{if(hh(e)){let i=r(t,e,n);i.length&&(a.has(n)||(a.set(n,{idx:n,item:e,matches:[]}),o.push(a.get(n))),i.forEach(({matches:e})=>{a.get(n).matches.push(...e)}))}}),o}_searchObjectList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=this._normalizedKeys(),s=t?null:[];return a.forEach(({$:e,i:a})=>{if(!hh(e))return;let c=[],l=!1,u=!1;if(o.forEach((t,n)=>{let i=this._findMatches({key:t,value:e[n],searcher:r});i.length?(c.push(...i),i[0].hasInverse&&(u=!0)):l=!0}),!(u&&l)&&c.length&&(!i||this._coversAllTokens(c))){let r={idx:a,item:e,matches:c};t?(r.score=mg(r.matches,{ignoreFieldNorm:n}),t.insert(r)):s.push(r)}}),s}_findMatches({key:e,value:t,searcher:n}){if(!hh(t))return[];let r=[];if(sh(t))t.forEach(({v:t,i,n:a})=>{if(!hh(t))return;let o=n.searchIn(t);if(o.isMatch){let n={score:o.score,key:e,value:t,idx:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(n.matchedMask=o.matchedMask,n.matchedTerms=o.matchedTerms,n.termCount=o.termCount),r.push(n)}});else{let{v:i,n:a}=t,o=n.searchIn(i);if(o.isMatch){let t={score:o.score,key:e,value:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(t.matchedMask=o.matchedMask,t.matchedTerms=o.matchedTerms,t.termCount=o.termCount),r.push(t)}}return r}_coversAllTokens(e){let t=e.length?e[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let t=0;t<e.length;t++)n|=e[t].matchedMask||0;return n===2**t-1}let n=new Set;for(let t=0;t<e.length;t++){let r=e[t].matchedTerms;if(r)for(let e of r)n.add(e)}return n.size===t}};jg.version=`7.5.0`,jg.createIndex=Rh,jg.parseIndex=zh,jg.config=Y,jg.match=function(e,t,n){if(n&&n.useTokenSearch)throw Error(wh);return og(e,{...Y,...n}).searchIn(t)},jg.parseQuery=pg,ag(rg),ag(wg),jg.use=function(...e){e.forEach(e=>ag(e))};var Mg=jg,Ng=`modulepreload`,Pg=function(e){return`/`+e},Fg={},Ig=function(e){return e.pathname.endsWith(`.css`)},Lg=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},Rg=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Pg(t,n);let r=s(t),i=Ig(r);return Lg(Fg,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:Ng,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},zg=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.name=`BlameApiError`,this.status=e,this.body=t}},Bg=class extends Error{constructor(){super(`Blame 请求已取消`),this.name=`BlameCancelledError`}},Vg=(e,t,n=``)=>`/api/git?workspaceId=${encodeURIComponent(e)}&op=blame&path=${encodeURIComponent(t)}${n?`&cwd=${encodeURIComponent(n)}`:``}`;async function Hg(e,t,n={}){if(n.signal?.aborted)throw new Bg;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 fetch(Vg(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 zg(r.status,{error:e.error||`HTTP ${r.status}`,...e.code?{code:e.code}:{}})}return a}catch(e){throw n.signal?.aborted?new Bg:a?new zg(408,{error:`请求超时:${Math.round(r/1e3)} 秒内服务端没有响应`,code:`timeout`}):e}finally{clearTimeout(o),n.signal?.removeEventListener(`abort`,s)}}var Ug=`\0`,Wg=(e,t,n)=>[e,t,n??``].join(Ug),Gg=24,Kg=new Map;function qg(e){let t=Kg.get(e);if(t)return Kg.delete(e),Kg.set(e,t),t}function Jg(e,t){for(Kg.delete(e),Kg.set(e,t);Kg.size>Gg;){let e=Kg.keys().next();if(e.done)break;Kg.delete(e.value)}}var Yg={untracked:`这个文件尚未被 Git 跟踪`,binary:`二进制文件不支持 Blame`,too_large:`文件过大,未显示 Blame`,no_head:`仓库还没有提交`,not_in_revision:`这个版本里没有这个文件`},Xg=`此工作区不是 Git 仓库`;function Zg(e){return e&&Yg[e]?{code:e,text:Yg[e]}:{code:`unsupported`,text:`这个文件暂时不能显示 Blame`}}function Qg(e){return e instanceof zg&&e.body.code===`not_a_repo`?{state:`unsupported`,note:{code:`not_a_repo`,text:Xg}}:{state:`error`,note:{code:`error`,text:`读取 Blame 失败:${e instanceof Error&&e.message?e.message:`未知错误`}`}}}var $g=`${Ug}uncommitted`;function e_(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?$g:n.commit??`${Ug}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 t_(e){let t=0;for(let n of e.lines)n.line>t&&(t=n.line);return t}function n_(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 r_(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,i_(t.date),t.summary?.trim()||`(没有提交摘要)`]}function i_(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 a_(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 o_(e,t,n=!1){return!t||!t.supported?!1:n||a_(e)!==t.totalLines}var s_=new WeakMap;function c_(e){let t=s_.get(e);if(t)return t;let n={response:e,models:e_(e),covered:t_(e)};return s_.set(e,n),n}function l_(e,t){if(!e||t<1)return null;let n=e.models[t-1];return n&&n.line===t?n:null}var u_=`a1b2c3d · Author`;async function d_(){let[e,t]=await Promise.all([Rg(()=>import(`./dist-BDy5Nw4_.js`).then(e=>e.x),[]),Rg(()=>import(`./dist-CGO5Bn1x.js`).then(e=>e.s),__vite__mapDeps([0,1]))]),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=r_(this.model);return e.setAttribute(`title`,t.join(`
49
+ `)),e.setAttribute(`aria-label`,t.join(` · `)),e.textContent=n_(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=u_,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=l_(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=l_(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:f_(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 f_(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 r_(e)){let e=document.createElement(`div`);e.className=`cm-blame-tooltip-row`,e.textContent=n,t.appendChild(e)}return t}var p_=4e3,m_=(0,V.lazy)(()=>Rg(()=>import(`./CodeMirrorEditor-B7hhyG33.js`).then(e=>({default:e.CodeMirrorEditor})),[])),h_=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},g_=15e3,__=e=>new h_(408,{error:`请求超时:${g_/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function v_(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),g_);try{let r=await fetch(e,{...t,signal:n.signal}),i;try{i=await r.json()}catch{i=void 0}if(!r.ok)throw new h_(r.status,i??{error:`HTTP ${r.status}`});return i}catch(t){throw n.signal.aborted?__(e):t}finally{clearTimeout(r)}}var y_=e=>e instanceof h_?e:new h_(0,{error:e instanceof Error?e.message:`读取失败`}),b_=e=>encodeURIComponent(e),x_=e=>e?`&cwd=${b_(e)}`:``,S_=(e,t,n)=>`/api/files?workspaceId=${b_(e)}&path=${b_(t)}${x_(n)}`,C_=(e,t,n)=>`/api/file?workspaceId=${b_(e)}&path=${b_(t)}${x_(n)}`,w_=(e,t,n)=>`/api/file?workspaceId=${b_(e)}&path=${b_(t)}&meta=1${x_(n)}`,T_=(e,t,n)=>`/api/files?workspaceId=${b_(e)}&q=${b_(t)}${x_(n)}`,E_=e=>e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`,D_=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function O_({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d}){let f=r[t],p=i.has(t);return(0,V.useEffect)(()=>{p&&f===void 0&&o(t)},[p,t,f,o]),(0,H.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":p,style:{paddingLeft:`${8+d*13}px`},title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:p?`▾`:`▸`}),(0,H.jsx)(cp,{category:`folder`}),(0,H.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,H.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),p&&(0,H.jsx)(`ul`,{className:`file-children`,children:f===void 0?(0,H.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in f?(0,H.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,title:np(f.error.message),children:tp(f.error.message,`这个目录读取失败。`)}):f.entries.length===0?(0,H.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,H.jsxs)(H.Fragment,{children:[f.truncated&&(0,H.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),f.entries.map(t=>t.kind===`directory`?(0,H.jsx)(O_,{workspaceId:e,entryPath:t.path,name:t.name,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d+1},t.path):(0,H.jsx)(k_,{entry:t,depth:d+1,openPaths:s,changedPaths:l,onOpen:u},t.path))]})})]})}function k_({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i}){if(e.kind===`symlink`)return(0,H.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-outside":e.path,children:(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 是一个指向 workspace 之外的符号链接,不能打开`,style:{paddingLeft:`${8+t*13}px`},children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`file-name`,children:e.name}),(0,H.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let a=n.has(e.path),o=r.has(e.path);return(0,H.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-row-open":a?`1`:`0`,"data-file-row-changed":o?`1`:`0`,children:(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,disabled:!e.text,title:e.text?o?`${e.path}(agent 改过这个文件,点击查看改动)`:a?`${e.path}(已经打开,点击切换到它)`:e.path:`${e.name} 是二进制文件,无法以文本打开`,style:{paddingLeft:`${8+t*13}px`},onClick:()=>i(e),children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,H.jsx)(cp,{path:e.path}),(0,H.jsx)(`span`,{className:`file-name`,children:e.name}),a&&(0,H.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),o&&(0,H.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),e.document&&(0,H.jsx)(`span`,{className:`file-badge`,"data-file-document":`1`,"aria-label":`文档文件`,children:`文档`}),!e.text&&!e.document&&(0,H.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]})})}function A_({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c,workspaceId:l,cwd:u=``}){let[d,f]=(0,V.useState)(!0),p=(0,V.useRef)(null),[m,h]=(0,V.useState)({}),[g,_]=(0,V.useState)(null),v=(0,V.useRef)(0),y=m[e.path]===!0&&!!l,b=l?u?`${l}:${u}`:l:``;(0,V.useEffect)(()=>{let t=++v.current;if(!y||!l){_(null);return}let n=new AbortController,i=Wg(b,e.path,e.etag),a=r?void 0:qg(i);if(a)_({state:a.supported?`ready`:`unsupported`,response:a,path:e.path,workspaceId:b,note:a.supported?null:Zg(a.reason)});else return _({state:`loading`,response:null,path:e.path,workspaceId:b,note:null}),Hg(l,e.path,{signal:n.signal,cwd:u}).then(n=>{t===v.current&&(r||Jg(i,n),_({state:n.supported?`ready`:`unsupported`,response:n,path:e.path,workspaceId:b,note:n.supported?null:Zg(n.reason)}))}).catch(n=>{if(t!==v.current||n instanceof Bg)return;let r=Qg(n);_({state:r.state,response:null,path:e.path,workspaceId:b,note:r.note})}),()=>{n.abort()}},[y,l,u,b,e.path,e.etag,r]);let x=g&&g.path===e.path&&g.workspaceId===b?g:null,S=y?x?.state??`loading`:`off`,C=S===`ready`&&o_(e.content,x?.response??null,e.dirty||r),w=[];x?.note&&w.push(x.note),S===`ready`&&x?.response?.truncated&&w.push({code:`truncated`,text:`Blame 数据已截断,只显示了前面一部分(共 ${x.response.totalLines} 行)`}),C&&w.push({code:`stale`,text:`内容已改动,Blame 对应的是磁盘上的版本`});let T=S===`loading`?`⌛ Blame`:S===`ready`?`✓ Blame`:S===`off`?`Blame`:`! Blame`;(0,V.useEffect)(()=>{i&&f(!1)},[e.path,i]),(0,V.useEffect)(()=>{let e=p.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
50
50
  `).length),n=e.value.split(`
51
51
  `),r=n.slice(0,t-1).reduce((e,t)=>e+t.length+1,0);e.focus(),e.setSelectionRange(r,r+n[t-1].length);let a=parseFloat(getComputedStyle(e).lineHeight);e.scrollTop=Math.max(0,(t-1)*a-e.clientHeight/2),e.scrollLeft=0;let o=e.previousElementSibling;o instanceof HTMLElement&&(o.scrollTop=e.scrollTop,o.scrollLeft=0)},[e.path,i,d]);let E=/\.md$/i.test(e.path);return(0,H.jsxs)(`div`,{className:`file-editor`,"data-file-editor":e.path,"data-save-state":t,children:[(0,H.jsxs)(`div`,{className:`file-editor-head`,children:[(0,H.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,H.jsxs)(`span`,{className:`file-editor-flags`,children:[E&&(0,H.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:()=>f(e=>!e),children:d?`原文`:`预览`}),(0,H.jsx)(`button`,{type:`button`,className:`file-blame-toggle`,"data-file-blame-toggle":e.path,"data-file-blame-state":S,"aria-pressed":y,"aria-label":y?`关闭 Git Blame`:`显示 Git Blame`,onClick:()=>h(t=>({...t,[e.path]:t[e.path]!==!0})),children:T}),e.dirty&&(0,H.jsx)(`span`,{className:`file-dirty`,"data-file-dirty":`1`,children:`未保存`}),(0,H.jsx)(`button`,{type:`button`,className:`file-save`,"data-file-save":e.path,onClick:o,disabled:t===`saving`,children:t===`saving`?`保存中…`:`保存`})]})]}),w.length>0&&(0,H.jsx)(`p`,{className:`file-blame-note`,"data-file-blame-reason":w.map(e=>e.code).join(` `),role:`status`,children:w.map(e=>e.text).join(`;`)}),r&&t!==`conflict`&&(0,H.jsxs)(`div`,{className:`file-conflict`,"data-file-external":e.path,role:`alert`,children:[(0,H.jsx)(`p`,{children:`这个文件在磁盘上已经被改过了,你的修改还没有覆盖它。`}),(0,H.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,H.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,H.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),t===`conflict`&&(0,H.jsxs)(`div`,{className:`file-conflict`,"data-file-conflict":e.path,role:`alert`,children:[(0,H.jsx)(`p`,{children:`保存被拒绝:这个文件在磁盘上已经被改过了,覆盖会丢掉对方的改动。`}),(0,H.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,H.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,H.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),n&&t!==`conflict`&&!r&&(0,H.jsx)(`p`,{className:`file-editor-message file-message-${t}`,"data-file-message":t,role:`status`,children:n}),E&&d?(0,H.jsx)(`div`,{className:`file-markdown-preview`,"data-file-preview":`markdown`,children:(0,H.jsx)(Am,{source:e.content})}):(0,H.jsx)(Wm,{fallback:(t,n)=>(0,H.jsxs)(`div`,{className:`file-editor-fallback`,"data-file-editor-fallback":`1`,children:[(0,H.jsxs)(`div`,{className:`file-editor-fallback-bar`,children:[(0,H.jsxs)(`span`,{children:[`⚠️ 高级编辑器加载异常(`,t.message||`未知错误`,`),已自动降级为安全模式`]}),(0,H.jsx)(`button`,{type:`button`,onClick:n,children:`重新加载`})]}),(0,H.jsx)(`textarea`,{className:`file-textarea`,value:e.content,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),o())}})]}),children:(0,H.jsx)(V.Suspense,{fallback:(0,H.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,H.jsx)(`span`,{className:`file-cm-status`,"data-file-editor-loading":`1`,children:`⌛ 正在加载编辑器…`})}),children:(0,H.jsx)(m_,{path:e.path,value:e.content,onChange:a,jumpToLine:i,onSave:o,workspaceId:l,blame:y&&x&&!C?{state:x.state,response:x.response,path:x.path,workspaceId:l??``}:void 0})})})]})}function j_({line:e}){if(e.kind===`fold`)return(0,H.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,H.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,H.jsx)(`span`,{className:`file-diff-mark`,"aria-hidden":`true`,children:t}),(0,H.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.oldLine??``}),(0,H.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.newLine??``}),(0,H.jsx)(`span`,{className:`file-diff-text`,children:e.text}),e.noNewline&&(0,H.jsx)(`span`,{className:`file-diff-no-newline`,title:`这个版本的末尾没有换行`,children:`(末尾无换行)`})]})}function M_({diff:e,loading:t,error:n,bufferContent:r,mode:i,onMode:a}){if(t)return(0,H.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`loading`,children:(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-diff-loading":`1`,children:`正在读取差异…`})});if(n)return(0,H.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`error`,children:(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-diff-error":`1`,title:np(n),children:tp(n,`这个文件的差异读取失败。`)})});if(!e)return(0,H.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`empty`,children:(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-diff-empty":`1`,children:`没有选中的差异。`})});let o=typeof r==`string`,s=i===`buffer`&&o,c=s?e.after:e.before,l=s?r:e.after,u=s?`我未保存的修改`:e.label,d=s?`buffer`:e.baseline,f=o&&e.baseline!==`none`?(0,H.jsxs)(`span`,{className:`file-diff-switch`,"data-file-diff-switch":`1`,children:[(0,H.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${s?``:` file-diff-switch-active`}`,"data-file-diff-base":`server`,"aria-pressed":!s,onClick:()=>a(`server`),children:`agent 的改动`}),(0,H.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${s?` file-diff-switch-active`:``}`,"data-file-diff-base":`buffer`,"aria-pressed":s,onClick:()=>a(`buffer`),children:`我的修改`})]}):null;if(d===`none`)return(0,H.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`none`,"data-file-diff-baseline":d,children:[(0,H.jsxs)(`div`,{className:`file-editor-head`,children:[(0,H.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,H.jsx)(`span`,{className:`file-editor-flags`,children:f})]}),(0,H.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-nobaseline":`1`,children:u})]});let p=ah(c,l),m=oh(p);return(0,H.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`ready`,"data-file-diff-baseline":d,"data-file-diff-added":p.added,"data-file-diff-removed":p.removed,children:[(0,H.jsxs)(`div`,{className:`file-editor-head`,children:[(0,H.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,H.jsxs)(`span`,{className:`file-editor-flags`,children:[f,(0,H.jsx)(`span`,{className:`file-diff-baseline`,"data-file-diff-label":`1`,children:u}),(0,H.jsxs)(`span`,{className:`file-diff-count`,"data-file-diff-count":`1`,children:[`+`,p.added,` / -`,p.removed]})]})]}),e.beforeUnknown&&!s&&(0,H.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-before-unknown":`1`,role:`status`,children:`读不到改动前的版本(文件太大或无法读取),这里只显示现在的内容。`}),e.before===null&&!e.beforeUnknown&&!s&&(0,H.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-is-new":`1`,role:`status`,children:`这个文件是新建的,下面是它的全部内容。`}),p.identical?(0,H.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-identical":`1`,children:`两个版本没有区别。`}):(0,H.jsx)(`div`,{className:`file-diff-body`,"data-file-diff-body":`1`,children:m.lines.map((e,t)=>(0,H.jsx)(j_,{line:e},t))})]})}function N_({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,H.jsxs)(`div`,{className:`rail-empty file-problem`,"data-file-root-error":`1`,"data-file-error-kind":r,role:`alert`,children:[r===`missing`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`工作区路径不存在,无法读取文件。`}),(0,H.jsx)(`p`,{className:`file-problem-hint`,children:`请确认这个路径是写错了,还是目录被移动或删除了:`}),(0,H.jsx)(`code`,{className:`file-problem-path`,"data-file-error-path":`1`,children:n||tp(e.message,`路径未知`)})]}),r===`timeout`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取超时,服务端没有回应。`}),(0,H.jsxs)(`p`,{className:`file-problem-hint`,children:[`已经等了 `,g_/1e3,` 秒。如果这个工作区在网络盘上,请检查它是否已连接,然后点上面的 ↻ 重试。`]})]}),r===`failed`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取失败。`}),(0,H.jsx)(`p`,{className:`file-problem-hint`,title:np(e.message),children:tp(e.message,`读取失败,请稍后重试。`)})]})]})}function P_(e,t=``){let n=t.trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``),r=e?n?`${e}:${n}`:e:void 0,i=(0,V.useRef)(r);i.current=r;let[a,o]=(0,V.useState)([]),[s,c]=(0,V.useState)(),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)({}),[p,m]=(0,V.useState)({}),[h,g]=(0,V.useState)({}),[_,v]=(0,V.useState)(()=>new Set),[y,b]=(0,V.useState)(``),[x,S]=(0,V.useState)(null),[C,w]=(0,V.useState)(null),[T,E]=(0,V.useState)(!1),[D,O]=(0,V.useState)([]),[k,A]=(0,V.useState)(!1),[j,M]=(0,V.useState)([]),N=(0,V.useRef)(void 0),P=(0,V.useRef)(-1),F=(0,V.useRef)(!1),ee=(0,V.useCallback)(e=>{N.current?N.current.buffered.push(e):!F.current||e.version<=P.current||(P.current=e.version,O(t=>{let n=new Map(t.map(e=>[e.path,e]));for(let t of e.changed)n.set(t.path,t);for(let t of e.removed)n.delete(t);return[...n.values()]}),A(e.complete),M(e.skipped))},[]),te=(0,V.useCallback)(()=>{let e=N.current;N.current=void 0,e?.controller.abort()},[]);(0,V.useEffect)(()=>(te(),F.current=!1,P.current=-1,O([]),A(!1),M([]),te),[r,te]);let ne=(0,V.useCallback)((t=!1)=>{if(!e||!r||N.current?.scopeKey===r||!t&&F.current)return;let i={workspaceId:e,scopeKey:r,controller:new AbortController,buffered:[]};N.current=i,fetch(`/api/files/index?workspaceId=${encodeURIComponent(e)}${x_(n)}`,{signal:i.controller.signal}).then(e=>{if(!e.ok)throw Error(`文件索引请求失败(${e.status})`);return e.json()}).then(e=>{if(N.current!==i)return;let t=new Map((e.changed??[]).map(e=>[e.path,e]));for(let n of e.removed??[])t.delete(n);let n=e.version??-1,r=e.complete===!0,a=e.skipped??[];for(let e of i.buffered.sort((e,t)=>e.version-t.version))if(!(e.version<=n)){for(let n of e.changed)t.set(n.path,n);for(let n of e.removed)t.delete(n);n=e.version,r=e.complete,a=e.skipped}N.current=void 0,F.current=!0,P.current=n,O([...t.values()]),A(r),M(a)}).catch(()=>{N.current===i&&(N.current=void 0)})},[e,n,r]),[re,I]=(0,V.useState)({});(0,V.useEffect)(()=>{if(o([]),c(void 0),u(``),f({}),m({}),g({}),v(new Set),S(null),w(null),b(``),E(!1),!e)return;let t=!0;return v_(S_(e,``,n)).then(e=>{t&&g({"":e})}).catch(e=>{t&&g({"":{error:y_(e)}})}),()=>{t=!1}},[e,n,r]);let ie=(0,V.useRef)(void 0),[ae,oe]=(0,V.useState)(void 0);(0,V.useEffect)(()=>{if(!e||!r||ie.current===r)return;ie.current=r;let t=I_()[r];t&&(t.expanded.length&&v(new Set(t.expanded)),typeof t.listHeight==`number`&&S(t.listHeight),t.open.length&&(async()=>{for(let e of t.open)if(await ue({path:e,name:e.split(`/`).pop()??e,text:!0}),i.current!==r)return;t.active&&i.current===r&&(c(t.active),oe(t.active))})())},[e,n,r]),(0,V.useEffect)(()=>{if(!e||!r)return;let t=setTimeout(()=>{let e=I_();e[r]={open:a.map(e=>e.path),expanded:[..._],...s?{active:s}:{},...x===null?{}:{listHeight:x}},L_(e)},400);return()=>{clearTimeout(t)}},[e,r,a,_,s,x]);let se=(0,V.useCallback)(t=>{e&&v_(S_(e,t,n)).then(e=>{i.current===r&&g(n=>({...n,[t]:e}))}).catch(e=>{i.current===r&&g(n=>({...n,[t]:{error:y_(e)}}))})},[e,n,r]),ce=(0,V.useCallback)(e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),le=(0,V.useCallback)(()=>{e&&(g({}),v(new Set),v_(S_(e,``,n)).then(e=>{i.current===r&&g({"":e})}).catch(e=>{i.current===r&&g({"":{error:y_(e)}})}))},[e,n,r]);(0,V.useEffect)(()=>{let t=y.trim();if(!e||!t){w(null),E(!1);return}let r=!0;E(!0);let i=setTimeout(()=>{v_(T_(e,t,n)).then(e=>{r&&(w(e),E(!1))}).catch(e=>{r&&(w({mode:`search`,query:t,hits:[],total:0,indexed:!1}),E(!1),u(`搜索失败:${e instanceof Error?e.message:`未知错误`}`))})},80);return()=>{r=!1,clearTimeout(i)}},[y,e,n]);let ue=(0,V.useCallback)(async t=>{if(e){if(t.text===!1)u(`「${t.name}」不支持以文本打开(二进制文件)。`);else if(a.some(e=>e.path===t.path))c(t.path);else{u(``);try{let a=await v_(C_(e,t.path,n));if(i.current!==r)return;o(e=>e.some(e=>e.path===t.path)?e:[...e,{path:a.path,name:t.name,content:a.content,etag:a.meta.etag,dirty:!1}]),c(a.path),m(e=>({...e,[a.path]:!1}))}catch(e){i.current===r&&u(`打不开「${t.name}」:${e instanceof Error?e.message:`未知错误`}`)}}}},[e,n,r,a]),de=(0,V.useCallback)(e=>{o(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===s&&c(i.length===0?void 0:i[Math.min(r,i.length-1)]?.path),i})},[s]),fe=(0,V.useCallback)((e,t)=>{o(n=>n.map(n=>n.path===e?{...n,content:t,dirty:!0}:n))},[]),pe=(0,V.useRef)(a);pe.current=a,(0,V.useEffect)(()=>{if(!e||a.length===0)return;let t=!0,r=setInterval(()=>{for(let r of pe.current.map(e=>e.path))v_(w_(e,r,n)).then(e=>{if(!t)return;let n=pe.current.find(e=>e.path===r);n&&e.etag!==n.etag&&m(e=>({...e,[r]:!0}))}).catch(()=>{})},p_);return()=>{t=!1,clearInterval(r)}},[e,n,a.length]);let L=(0,V.useCallback)(async(t,s)=>{if(!e)return;let c=a.find(e=>e.path===t);if(!c)return;f(e=>({...e,[t]:{state:`saving`,message:``}}));let l=c.etag;if(s)try{l=(await v_(w_(e,t,n))).etag}catch(e){i.current===r&&f(n=>({...n,[t]:{state:`error`,message:`无法读取磁盘上的最新版本:${e instanceof Error?e.message:`未知错误`}`}}));return}let u=c.content;try{let a=await v_(C_(e,t,n),{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({path:t,content:u,baseEtag:l})});if(i.current!==r)return;let s=pe.current.find(e=>e.path===t),c=s!==void 0&&s.content!==u;o(e=>e.map(e=>e.path===t?{...e,etag:a.meta.etag,dirty:e.content!==u}:e)),m(e=>({...e,[t]:!1})),f(e=>({...e,[t]:{state:`saved`,message:c?`已保存,但你又改了;最新修改仍未保存`:`已保存 ${D_(a.meta.modifiedAt)}`}}))}catch(e){if(i.current!==r)return;let n=e instanceof h_&&e.body.code===`stale`;f(r=>({...r,[t]:{state:n?`conflict`:`error`,message:e instanceof Error?e.message:`保存失败`}})),n&&m(e=>({...e,[t]:!0}))}},[e,n,r,a]),me=(0,V.useCallback)(async t=>{if(!e)return;let a=pe.current.find(e=>e.path===t)?.content;try{let s=await v_(C_(e,t,n));if(i.current!==r)return;let c=pe.current.find(e=>e.path===t),l=c!==void 0&&c.content!==a;o(e=>e.map(e=>e.path===t?{...e,content:l?e.content:s.content,etag:s.meta.etag,dirty:l}:e)),m(e=>({...e,[t]:!1})),f(e=>({...e,[t]:{state:`saved`,message:l?`已读取磁盘版本;你后来输入的修改仍未保存`:`已重新载入磁盘版本`}}))}catch(e){i.current===r&&f(n=>({...n,[t]:{state:`error`,message:e instanceof Error?e.message:`重新载入失败`}}))}},[e,n,r]),he=a.find(e=>e.path===s),ge=(0,V.useMemo)(()=>a.map(e=>({id:e.path,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,H.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[a]),_e=(0,V.useMemo)(()=>new Set(a.map(e=>e.path)),[a]),ve=(0,V.useCallback)((e,t,n)=>{I(r=>({...r,[e]:{changes:t,dropped:n}}))},[]),ye=e?re[e]:void 0,be=(0,V.useMemo)(()=>{let e=ye?.changes??[];if(!n)return e;let t=`${n}/`;return e.flatMap(e=>e.path.startsWith(t)?[{...e,path:e.path.slice(t.length)}]:[])},[ye,n]),xe=ye?.dropped??0;return{open:a,activePath:s,active:he,tabItems:ge,openPaths:_e,notice:l,setNotice:u,saves:d,external:p,openFile:ue,setActivePath:c,closeFile:de,updateBuffer:fe,save:L,reload:me,listings:h,expanded:_,toggleDirectory:ce,loadDirectory:se,refreshTree:le,listHeight:x,setListHeight:S,query:y,setQuery:b,hits:C,searching:T,changed:be,changedPaths:(0,V.useMemo)(()=>new Set(be.map(e=>e.path)),[be]),changedDirs:(0,V.useMemo)(()=>{let e=new Set;for(let t of be){let n=t.path.split(`/`);for(let t=1;t<n.length;t++)e.add(n.slice(0,t).join(`/`))}return e},[be]),changedDropped:xe,setChangedFor:ve,index:D,indexComplete:k,indexSkipped:j,requestIndex:ne,cancelIndexRequest:te,setIndex:ee,restoredActive:ae}}var F_=`super-pi.file-workbench.v1`;function I_(){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=Array.isArray(e.expanded)?e.expanded.filter(e=>typeof e==`string`):[],o=typeof e.listHeight==`number`&&Number.isFinite(e.listHeight)&&e.listHeight>0?Math.round(e.listHeight):void 0;t[n]={open:i,expanded:a,...typeof e.active==`string`?{active:e.active}:{},...o?{listHeight:o}:{}}}return t}catch{return{}}}function L_(e){try{typeof window<`u`&&window.localStorage.setItem(F_,JSON.stringify(e))}catch{}}function R_({height:e,onHeight:t,panelRef:n,min:r=120}){let[i,a]=(0,V.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,H.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))}}})}function z_({workspaceId:e,files:t,onOpenFile:n,onOpenChanged:r}){let{open:i,openPaths:a,notice:o,setNotice:s,openFile:c,listings:l,expanded:u,toggleDirectory:d,loadDirectory:f,refreshTree:p,listHeight:m,setListHeight:h,query:g,setQuery:_,hits:v,searching:y,changed:b,changedPaths:x,changedDirs:S,changedDropped:C}=t,w=(0,V.useCallback)(e=>{n?n(e):c(e)},[n,c]),T=l[``],E=g.trim(),D=(0,V.useRef)(null),O=(0,V.useCallback)(e=>{let t=D.current;if(!t)return;let n=e.target?.closest(`.file-row`);if(!n)return;let r=[...t.querySelectorAll(`.file-row`)],i=r.indexOf(n);if(i<0)return;let a=e=>{let t=Math.max(0,Math.min(r.length-1,e));r[t]?.focus()};if(e.key===`ArrowDown`)e.preventDefault(),a(i+1);else if(e.key===`ArrowUp`)e.preventDefault(),a(i-1);else if(e.key===`Home`)e.preventDefault(),a(0);else if(e.key===`End`)e.preventDefault(),a(r.length-1);else if(e.key===`ArrowRight`){let t=n.getAttribute(`data-file-dir-toggle`);t&&n.getAttribute(`aria-expanded`)===`false`&&(e.preventDefault(),d(t))}else if(e.key===`ArrowLeft`){let r=n.getAttribute(`data-file-dir-toggle`);if(r&&n.getAttribute(`aria-expanded`)===`true`){e.preventDefault(),d(r);return}let i=n.getAttribute(`data-file-open`)??n.getAttribute(`data-file-hit`);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()}}},[d]),[k,A]=(0,V.useState)(200);(0,V.useEffect)(()=>{A(200)},[E,e]);let j=(0,V.useRef)(null);(0,V.useEffect)(()=>{if(E===``)return;let e=j.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&A(e=>e>=(v?.hits.length??0)?e:e+200)},{rootMargin:`200px`});return t.observe(e),()=>t.disconnect()},[E,v]);let M=(0,V.useMemo)(()=>{if(E){if(y||!v)return(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-searching":`1`,children:`搜索中…`});if(v.hits.length===0)return(0,H.jsxs)(`p`,{className:`rail-empty`,"data-file-search-empty":`1`,children:[`没有匹配「`,E,`」的文件。`]});let e=v.hits.slice(0,k),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,H.jsxs)(H.Fragment,{children:[t.map(e=>(0,H.jsxs)(`section`,{className:`file-group`,"data-file-search-group":e.directory,children:[(0,H.jsxs)(`h3`,{className:`file-group-head`,"data-file-search-group-head":e.directory,children:[(0,H.jsx)(`span`,{className:`file-group-name`,children:e.directory||`/`}),(0,H.jsx)(`span`,{className:`file-group-count`,children:e.hits.length})]}),(0,H.jsx)(`ul`,{className:`file-list`,children:e.hits.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-hit":e.path,"data-file-hit-open":a.has(e.path)?`1`:`0`,onClick:()=>w({path:e.path,name:e.name,text:!0}),children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,H.jsx)(cp,{path:e.path}),(0,H.jsx)(`span`,{className:`file-name`,children:e.name}),a.has(e.path)&&(0,H.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`})]})},e.path))})]},e.directory||`/`)),e.length<v.hits.length&&(0,H.jsx)(`div`,{ref:j,className:`file-sentinel`,"data-file-search-more":`1`,children:`正在载入更多…`})]})}return e?T===void 0?(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-root-loading":`1`,children:`读取工作区…`}):`error`in T?(0,H.jsx)(N_,{error:T.error}):(0,H.jsxs)(H.Fragment,{children:[T.truncated&&(0,H.jsx)(`p`,{className:`file-search-note`,"data-file-truncated-root":`1`,children:`条目过多,只显示前一部分。`}),T.entries.length===0?(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-root-empty":`1`,children:`这个工作区是空的,没有文件也没有子目录。`}):(0,H.jsx)(`ul`,{className:`file-list`,children:T.entries.map(t=>t.kind===`directory`?(0,H.jsx)(O_,{workspaceId:e,entryPath:t.path,name:t.name,listings:l,expanded:u,toggle:d,loadDirectory:f,openPaths:a,changedDirs:S,changedPaths:x,onOpen:e=>w(e),depth:0},t.path):(0,H.jsx)(k_,{entry:t,depth:0,openPaths:a,changedPaths:x,onOpen:e=>w(e)},t.path))})]}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-no-workspace":`1`,children:`先在左侧选一个工作区,这里会显示它的文件。`})},[E,y,v,k,e,T,l,u,d,f,w,a,S,x]);return(0,H.jsxs)(`div`,{className:`files-panel`,"data-files-panel":`1`,"data-files-open-count":i.length,"data-files-changed-count":b.length,ref:D,onKeyDown:O,children:[(0,H.jsxs)(`div`,{className:`files-search`,children:[(0,H.jsx)(`span`,{className:`files-search-icon`,"aria-hidden":`true`,children:(0,H.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,strokeLinecap:`round`,children:[(0,H.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.6`}),(0,H.jsx)(`path`,{d:`M10.4 10.4 14 14`})]})}),(0,H.jsx)(`input`,{type:`search`,className:`files-search-input`,"data-file-search-input":`1`,value:g,placeholder:`按文件名搜索…`,"aria-label":`按文件名搜索`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),_(``))},onChange:e=>_(e.target.value)}),(0,H.jsx)(`button`,{type:`button`,className:`files-refresh`,"data-file-refresh":`1`,title:`重新读取目录`,"aria-label":`重新读取目录`,disabled:!e,onClick:()=>p(),children:`↻`})]}),E&&v&&!y&&(0,H.jsxs)(`p`,{className:`files-count`,"data-file-search-count":`1`,role:`status`,children:[(0,H.jsx)(`b`,{children:v.total.toLocaleString(`zh-CN`)}),` 个结果`,v.indexed===!1&&(0,H.jsx)(`span`,{className:`files-count-note`,"data-file-search-indexing":`1`,children:`正在建立索引…`})]}),b.length>0&&(0,H.jsxs)(`div`,{className:`files-changed`,"data-file-changed-list":`1`,children:[(0,H.jsxs)(`p`,{className:`files-changed-head`,"data-file-changed-head":`1`,children:[`agent 改了 `,b.length,` 个文件`]}),C>0&&(0,H.jsxs)(`p`,{className:`file-search-note`,"data-file-changed-dropped":`1`,children:[`还有 `,C,` 个改动没有记录(超过保留上限)。`]}),(0,H.jsx)(`ul`,{className:`file-list`,children:b.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-changed-open":e.path,title:`${e.path}(点击查看改动)`,onClick:()=>r?.(e.path),children:[(0,H.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,H.jsx)(cp,{path:e.path}),(0,H.jsx)(`span`,{className:`file-name`,children:e.path.split(`/`).pop()}),(0,H.jsx)(`span`,{className:`file-badge-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)||`/`}),(0,H.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed-kind":e.path,children:e.baseline===null&&!e.baselineUnknown?`新建`:`已改`})]})},e.path))})]}),o&&(0,H.jsx)(`p`,{className:`rail-empty`,"data-file-notice":`1`,children:o}),(0,H.jsxs)(`div`,{className:`files-tree`,"data-file-tree":E?`search`:`browse`,style:m===null?void 0:{height:`${m}px`,flex:`0 0 auto`},children:[(0,H.jsx)(`div`,{className:`files-tree-body`,children:M}),i.length===0&&(0,H.jsx)(`p`,{className:`rail-empty file-hint`,"data-file-none-open":`1`,children:`点一个文本文件,它会在上面的标签栏开一个标签,正文显示在中间主画面。`}),i.length>0&&(0,H.jsxs)(`p`,{className:`files-hint file-hint`,"data-file-open-hint":`1`,children:[`已打开 `,i.length,` 个文件,正文显示在中间主画面;点上面的标签切换,点这里的行切换。`]})]}),(0,H.jsx)(R_,{height:m,onHeight:h,panelRef:D}),(0,H.jsxs)(`p`,{className:`files-footnote`,"data-files-footnote":`1`,children:[`只支持纯文本(md / 代码),二进制文件不会打开。写入只允许覆盖已存在的文件,不新建,不删除。`,i.length>0&&` 当前打开 ${i.length} 个文件,占 ${E_(i.reduce((e,t)=>e+t.content.length,0))}。`]})]})}function B_({workspaceId:e,cwd:t=``,onOpen:n,onClose:r}){let[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(null),[c,l]=(0,V.useState)(``),[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(0),m=(0,V.useRef)(null),h=(0,V.useRef)(null);(0,V.useEffect)(()=>{m.current?.focus()},[]),(0,V.useEffect)(()=>{h.current?.scrollIntoView({block:`nearest`})},[f]),(0,V.useEffect)(()=>{let n=i.trim();if(s(null),l(``),p(0),!e||!n){d(!1);return}let r=!0;d(!0);let a=setTimeout(()=>{v_(`/api/files/search?workspaceId=${b_(e)}&q=${b_(n)}${x_(t)}`).then(e=>{r&&(s(e),d(!1))}).catch(e=>{r&&(l(tp(e,`搜索没有完成`)),d(!1))})},220);return()=>{r=!1,clearTimeout(a)}},[i,e,t]);let g=e=>{e&&(n(e),r())},_=o?.truncated||o?.complete===!1,v={index:`索引未完整`,size:`文件超过 512KB`,depth:`目录超过 12 层`,time:`搜索超过 10 秒`,results:`达到 500 条上限`,output:`SDK 输出达到上限`,line:`长行已截断`,unreadable:`部分文件无法读取`};return(0,H.jsx)(`div`,{className:`quick-open-backdrop`,"data-content-search":`1`,role:`presentation`,onMouseDown:r,children:(0,H.jsxs)(`div`,{className:`quick-open content-search`,role:`dialog`,"aria-modal":`true`,"aria-label":`内容搜索`,onMouseDown:e=>e.stopPropagation(),children:[(0,H.jsx)(`input`,{ref:m,className:`quick-open-input`,"data-content-search-input":`1`,value:i,maxLength:256,placeholder:`内容搜索(区分大小写,按字面匹配)`,"aria-label":`内容搜索`,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),r()):e.key===`ArrowDown`?(e.preventDefault(),p(e=>Math.min(e+1,Math.max(0,(o?.hits.length??0)-1)))):e.key===`ArrowUp`?(e.preventDefault(),p(e=>Math.max(0,e-1))):e.key===`Enter`&&(e.preventDefault(),g(o?.hits[f]))}}),(0,H.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":c?`error`:u?`searching`:_?`partial`:`complete`,children:[c?`✕ 搜索失败:`+c:u?`… 搜索中`:e?_?`⚠ 结果不完整`:o?`✓ 搜索完成`:`○ 输入要搜索的内容`:`○ 请先选择工作区`,o?` · ${o.hits.length} 条命中`:``,` · Esc 关闭`]}),_&&(0,H.jsxs)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:[`⚠ 结果不完整:`,o?.reasons.map(e=>v[e]??e).join(`;`)]}),o&&o.skipped.length>0&&(0,H.jsxs)(`details`,{className:`quick-open-status`,"data-content-search-skipped":`1`,children:[(0,H.jsxs)(`summary`,{children:[`↷ 已跳过 `,o.skipped.length,` 个文件或目录`]}),(0,H.jsx)(`p`,{className:`content-search-skipped-paths`,children:o.skipped.join(`
52
- `)})]}),o&&!u&&o.hits.length===0&&(0,H.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`○ 没有匹配的行`}),(0,H.jsx)(`ul`,{className:`quick-open-results content-search-results`,role:`listbox`,children:o?.hits.map((e,t)=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`button`,{ref:t===f?h:void 0,type:`button`,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${f===t?` quick-open-result-active`:``}`,"aria-selected":f===t,onMouseEnter:()=>p(t),onClick:()=>g(e),children:[(0,H.jsxs)(`span`,{children:[e.path,`:`,e.line]}),(0,H.jsx)(`small`,{title:e.text,children:e.text})]})},`${e.path}:${e.line}`))})]})})}function V_({entries:e,complete:t,skipped:n,onOpen:r,onClose:i}){let[a,o]=(0,V.useState)(``),[s,c]=(0,V.useState)(0),l=(0,V.useRef)(null),u=(0,V.useMemo)(()=>e.filter(e=>e.kind===`file`&&e.text!==!1),[e]),d=(0,V.useMemo)(()=>a.trim()?new Mg(u,{keys:[`path`],threshold:.38,ignoreLocation:!0}).search(a).slice(0,20).map(e=>e.item):u.slice(0,20),[u,a]);(0,V.useEffect)(()=>{l.current?.focus(),c(0)},[a]);let f=(0,V.useCallback)(e=>{e&&(r({path:e.path,name:e.path.split(`/`).pop()??e.path,text:e.text}),i())},[r,i]);return(0,H.jsx)(`div`,{className:`quick-open-backdrop`,"data-quick-open":`1`,role:`presentation`,onMouseDown:i,children:(0,H.jsxs)(`div`,{className:`quick-open`,role:`dialog`,"aria-modal":`true`,"aria-label":`快速打开`,onMouseDown:e=>e.stopPropagation(),children:[(0,H.jsx)(`input`,{ref:l,className:`quick-open-input`,"data-quick-open-input":`1`,value:a,placeholder:`快速打开:输入文件名或路径`,"aria-label":`快速打开文件路径`,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),i()):e.key===`ArrowDown`?(e.preventDefault(),c(e=>Math.min(e+1,Math.max(0,d.length-1)))):e.key===`ArrowUp`?(e.preventDefault(),c(e=>Math.max(e-1,0))):e.key===`Enter`&&(e.preventDefault(),f(d[s]))}}),(0,H.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-status":t?`complete`:`partial`,children:[t?`✓ 索引完整`:`⚠ 索引不完整`,` · `,u.length,` 个文件 · Esc 关闭`]}),n.length>0&&(0,H.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-skipped":`1`,title:n.join(`, `),children:[`↷ 已跳过:`,n.join(`, `)]}),(0,H.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:d.map((e,t)=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`button`,{type:`button`,"data-quick-open-result":e.path,className:t===s?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===s,onMouseEnter:()=>c(t),onClick:()=>f(e),children:[(0,H.jsx)(`span`,{children:e.path.split(`/`).pop()}),(0,H.jsx)(`small`,{children:e.path})]})},e.path))})]})})}function H_(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 U_(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 W_(e,t,n=88,r=200){let[i,a]=(0,V.useState)(()=>H_(e,0,n,r)),[o,s]=(0,V.useState)(null),c=(0,V.useCallback)(()=>{let i=H_(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,V.useRef)(t);(0,V.useEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let u=(0,V.useRef)(null);return(0,V.useEffect)(()=>{let t=u.current;u.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function G_({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:u}){let d=(0,V.useRef)(null),[f,p]=(0,V.useState)(0),{layout:m,frozen:h,recompute:g}=W_(e.length,f,o,s);(0,V.useLayoutEffect)(()=>{let e=d.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&p(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let _=U_(e,m.perRow),v=(e,t)=>t===void 0?{}:{[`data-${c}-${e}`]:t},y=e.filter(e=>e.kind===`file`).length,b=e.filter(e=>e.kind===`session`||!e.kind).length,x=t=>({[`data-${t}-strip`]:`1`,...h?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?y:t===`session-tab`?b:e.length,[`data-${t}-min`]:o,[`data-${t}-max`]:s,[`data-${t}-per-row`]:m.perRow,[`data-${t}-width`]:Math.round(m.width*100)/100}),S=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&g()},C=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&g()};(0,V.useEffect)(()=>{if(!h)return;let e=d.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||g()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[h,g]);let w=[`${c}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,u].filter(Boolean).join(` `);return(0,H.jsx)(`div`,{ref:d,className:w,role:`tablist`,"aria-label":a??`工作区标签页`,...v(`strip`,`1`),...x(`workspace-tab`),...x(`session-tab`),...x(`file-tab`),style:{"--tab-w":`${m.width}px`},onMouseEnter:S,onMouseLeave:C,children:_.map((a,o)=>(0,H.jsx)(`div`,{className:`${c}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,...v(`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,H.jsxs)(`div`,{role:`tab`,id:`${l}-${a.id}`,"aria-selected":o,"aria-controls":`${l}-panel-${a.id}`,tabIndex:o?0:-1,className:p,...v(`id`,d),...v(`index`,f),...o?v(`active`,`1`):{},...v(`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:m.width,boxSizing:`border-box`},onClick:()=>n?.(a.id),onDoubleClick:()=>{(u===`session`||u===void 0)&&i?.(a.id)},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&&n?.(i.id)},children:[a.icon&&(0,H.jsx)(`span`,{className:`${c}-icon workspace-tab-icon`,children:a.icon}),a.badge,(0,H.jsx)(`span`,{className:`${c}-label workspace-tab-label ${u?`${u}-tab-label`:``}`,...v(`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,H.jsx)(`button`,{type:`button`,className:`${c}-close workspace-tab-close ${u?`${u}-tab-close`:``}`,...v(`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 K_={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},q_={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},J_={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},Y_={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function X_(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 Z_(e){let t=e.status===`running`,[n,r]=(0,V.useState)(0);(0,V.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 Q_({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,H.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,H.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:J_[e.status]}),(0,H.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,H.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,H.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,H.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,H.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:K_[e.status]}),e.status===`failed`&&r?.error&&(0,H.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,title:np(r.error),children:tp(r.error,`这一步没有完成。`)})]})}function $_({nodes:e,steps:t,names:n}){return(0,H.jsx)(`ol`,{className:`workflow-steps`,children:e.map((e,r)=>{if(e.kind===`step`){let r=t[e.stepIndex];return r?(0,H.jsx)(Q_,{step:r,names:n},`step-${e.stepIndex}`):null}return e.kind===`loop`?(0,H.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,H.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`↻`}),(0,H.jsx)(`strong`,{children:`循环`}),(0,H.jsxs)(`span`,{children:[`直到「`,e.until,`」`]}),(0,H.jsxs)(`span`,{"data-workflow-loop-progress":!0,children:[`已跑 `,e.rounds.length,`/`,e.max,` 轮`]})]}),e.rounds.map(e=>(0,H.jsxs)(`section`,{className:`workflow-round`,"data-workflow-round":e.n,"data-workflow-round-met":e.untilMet?`true`:`false`,children:[(0,H.jsxs)(`div`,{className:`workflow-round-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:e.untilMet?`✓`:`○`}),`第 `,e.n,` 轮 · `,e.untilMet?`条件满足`:`条件未满足`]}),(0,H.jsx)($_,{nodes:e.nodes,steps:t,names:n})]},e.n))]},`loop-${r}`):(0,H.jsxs)(`li`,{className:`workflow-node workflow-foreach`,"data-workflow-foreach":!0,"data-workflow-foreach-count":e.items.length,children:[(0,H.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`≡`}),(0,H.jsx)(`strong`,{children:`逐项执行`}),(0,H.jsxs)(`span`,{children:[e.items.length,` 个由 primary 给出的项目`]})]}),e.iterations.map((e,r)=>(0,H.jsxs)(`section`,{className:`workflow-item`,"data-workflow-item":r+1,"data-workflow-item-value":e.item,children:[(0,H.jsxs)(`div`,{className:`workflow-item-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),`第 `,r+1,` 项 · `,e.item]}),(0,H.jsx)($_,{nodes:e.nodes,steps:t,names:n})]},`${r}-${e.item}`))]},`foreach-${r}`)})})}function ev({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=Z_(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,H.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,H.jsxs)(`div`,{className:`workflow-head`,children:[(0,H.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,H.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,H.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,H.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:q_[e.status]??`未知状态`}),(0,H.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:Y_[e.onFailure]??e.onFailure}),a!==void 0&&(0,H.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,X_(a)]}),i&&(0,H.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),e.nodes?(0,H.jsx)($_,{nodes:e.nodes,steps:e.steps,names:t}):(0,H.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,H.jsx)(Q_,{step:e,names:t},e.index))})]})}var tv=[{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 nv({onClose:e}){let[t,n]=(0,V.useState)(`agents`);(0,V.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=tv.find(e=>e.id===t)??tv[0];return(0,H.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,H.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,H.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,H.jsxs)(`div`,{className:`help-head-title`,children:[(0,H.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,H.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,H.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,H.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,H.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,H.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),tv.map(e=>(0,H.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,H.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,H.jsx)(`span`,{children:e.label})]},e.id))]}),(0,H.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,H.jsxs)(`div`,{className:`help-panel-header`,children:[(0,H.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,H.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,H.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,H.jsx)(av,{}),r.id===`workspace`&&(0,H.jsx)(ov,{}),r.id===`subagents`&&(0,H.jsx)(cv,{}),r.id===`model-policy`&&(0,H.jsx)(sv,{}),r.id===`memory`&&(0,H.jsx)(rv,{}),r.id===`knowledge`&&(0,H.jsx)(iv,{}),r.id===`feishu`&&(0,H.jsx)(lv,{}),r.id===`tools`&&(0,H.jsx)(uv,{}),r.id===`cli`&&(0,H.jsx)(dv,{}),r.id===`themes`&&(0,H.jsx)(fv,{})]}),(0,H.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,H.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function rv(){return(0,H.jsxs)(`div`,{className:`help-section-group`,children:[(0,H.jsxs)(`div`,{className:`help-card highlight`,children:[(0,H.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,H.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,H.jsx)(`code`,{children:`memory`}),` 和 `,(0,H.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,H.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,H.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`权限与审批`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,H.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,H.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function iv(){return(0,H.jsxs)(`div`,{className:`help-section-group`,children:[(0,H.jsxs)(`div`,{className:`help-card highlight`,children:[(0,H.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,H.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库的内容来自工作区里真实存在的文档。`})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`怎么用`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文、手动填写相对路径,或者直接对 Agent 说“把某某文件加入知识库”——它会用 `,(0,H.jsx)(`code`,{children:`knowledge_import`}),` 导入,走的是同一条服务端校验。`]}),(0,H.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,H.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,H.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,H.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`语义检索是内置的`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,H.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,H.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,H.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`它不知道的事`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,H.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,H.jsxs)(`li`,{children:[`Agent 可以按你的要求把工作区文件导入知识库(`,(0,H.jsx)(`code`,{children:`knowledge_import`}),`,只接受文本类文件),但`,(0,H.jsx)(`strong`,{children:`不能删除`}),`——删除文档只有你能在“设置 → 知识库”里做。`]})]})]})]})}function av(){return(0,H.jsxs)(`div`,{className:`help-section-group`,children:[(0,H.jsxs)(`div`,{className:`help-card highlight`,children:[(0,H.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,H.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,H.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,H.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,H.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,H.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,H.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,H.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,H.jsxs)(`div`,{className:`help-steps`,children:[(0,H.jsxs)(`div`,{className:`help-step`,children:[(0,H.jsx)(`span`,{className:`step-num`,children:`1`}),(0,H.jsxs)(`div`,{className:`step-body`,children:[(0,H.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,H.jsxs)(`p`,{children:[`在 `,(0,H.jsx)(`code`,{children:`agents/`}),` 或 `,(0,H.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,H.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-step`,children:[(0,H.jsx)(`span`,{className:`step-num`,children:`2`}),(0,H.jsxs)(`div`,{className:`step-body`,children:[(0,H.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,H.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,H.jsx)(`pre`,{className:`help-code-block`,children:(0,H.jsx)(`code`,{children:`---
52
+ `)})]}),o&&!u&&o.hits.length===0&&(0,H.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`○ 没有匹配的行`}),(0,H.jsx)(`ul`,{className:`quick-open-results content-search-results`,role:`listbox`,children:o?.hits.map((e,t)=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`button`,{ref:t===f?h:void 0,type:`button`,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${f===t?` quick-open-result-active`:``}`,"aria-selected":f===t,onMouseEnter:()=>p(t),onClick:()=>g(e),children:[(0,H.jsxs)(`span`,{children:[e.path,`:`,e.line]}),(0,H.jsx)(`small`,{title:e.text,children:e.text})]})},`${e.path}:${e.line}`))})]})})}function V_({entries:e,complete:t,skipped:n,onOpen:r,onClose:i}){let[a,o]=(0,V.useState)(``),[s,c]=(0,V.useState)(0),l=(0,V.useRef)(null),u=(0,V.useMemo)(()=>e.filter(e=>e.kind===`file`&&e.text!==!1),[e]),d=(0,V.useMemo)(()=>a.trim()?new Mg(u,{keys:[`path`],threshold:.38,ignoreLocation:!0}).search(a).slice(0,20).map(e=>e.item):u.slice(0,20),[u,a]);(0,V.useEffect)(()=>{l.current?.focus(),c(0)},[a]);let f=(0,V.useCallback)(e=>{e&&(r({path:e.path,name:e.path.split(`/`).pop()??e.path,text:e.text}),i())},[r,i]);return(0,H.jsx)(`div`,{className:`quick-open-backdrop`,"data-quick-open":`1`,role:`presentation`,onMouseDown:i,children:(0,H.jsxs)(`div`,{className:`quick-open`,role:`dialog`,"aria-modal":`true`,"aria-label":`快速打开`,onMouseDown:e=>e.stopPropagation(),children:[(0,H.jsx)(`input`,{ref:l,className:`quick-open-input`,"data-quick-open-input":`1`,value:a,placeholder:`快速打开:输入文件名或路径`,"aria-label":`快速打开文件路径`,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),i()):e.key===`ArrowDown`?(e.preventDefault(),c(e=>Math.min(e+1,Math.max(0,d.length-1)))):e.key===`ArrowUp`?(e.preventDefault(),c(e=>Math.max(e-1,0))):e.key===`Enter`&&(e.preventDefault(),f(d[s]))}}),(0,H.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-status":t?`complete`:`partial`,children:[t?`✓ 索引完整`:`⚠ 索引不完整`,` · `,u.length,` 个文件 · Esc 关闭`]}),n.length>0&&(0,H.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-skipped":`1`,title:n.join(`, `),children:[`↷ 已跳过:`,n.join(`, `)]}),(0,H.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:d.map((e,t)=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`button`,{type:`button`,"data-quick-open-result":e.path,className:t===s?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===s,onMouseEnter:()=>c(t),onClick:()=>f(e),children:[(0,H.jsx)(`span`,{children:e.path.split(`/`).pop()}),(0,H.jsx)(`small`,{children:e.path})]})},e.path))})]})})}function H_(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 U_(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 W_(e,t,n=88,r=200){let[i,a]=(0,V.useState)(()=>H_(e,0,n,r)),[o,s]=(0,V.useState)(null),c=(0,V.useCallback)(()=>{let i=H_(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,V.useRef)(t);(0,V.useLayoutEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let u=(0,V.useRef)(null);return(0,V.useLayoutEffect)(()=>{let t=u.current;u.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function G_({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:u}){let d=(0,V.useRef)(null),[f,p]=(0,V.useState)(0),{layout:m,frozen:h,recompute:g}=W_(e.length,f,o,s);(0,V.useLayoutEffect)(()=>{let e=d.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&p(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let _=U_(e,m.perRow),v=(e,t)=>t===void 0?{}:{[`data-${c}-${e}`]:t},y=e.filter(e=>e.kind===`file`).length,b=e.filter(e=>e.kind===`session`||!e.kind).length,x=t=>({[`data-${t}-strip`]:`1`,...h?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?y:t===`session-tab`?b:e.length,[`data-${t}-min`]:o,[`data-${t}-max`]:s,[`data-${t}-per-row`]:m.perRow,[`data-${t}-width`]:Math.round(m.width*100)/100}),S=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&g()},C=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&g()};(0,V.useEffect)(()=>{if(!h)return;let e=d.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||g()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[h,g]);let w=[`${c}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,u].filter(Boolean).join(` `);return(0,H.jsx)(`div`,{ref:d,className:w,role:`tablist`,"aria-label":a??`工作区标签页`,...v(`strip`,`1`),...x(`workspace-tab`),...x(`session-tab`),...x(`file-tab`),style:{"--tab-w":`${m.width}px`},onMouseEnter:S,onMouseLeave:C,children:_.map((a,o)=>(0,H.jsx)(`div`,{className:`${c}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,...v(`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,H.jsxs)(`div`,{role:`tab`,id:`${l}-${a.id}`,"aria-selected":o,"aria-controls":`${l}-panel-${a.id}`,tabIndex:o?0:-1,className:p,...v(`id`,d),...v(`index`,f),...o?v(`active`,`1`):{},...v(`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:m.width,boxSizing:`border-box`},onClick:()=>n?.(a.id),onDoubleClick:()=>{(u===`session`||u===void 0)&&i?.(a.id)},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&&n?.(i.id)},children:[a.icon&&(0,H.jsx)(`span`,{className:`${c}-icon workspace-tab-icon`,children:a.icon}),a.badge,(0,H.jsx)(`span`,{className:`${c}-label workspace-tab-label ${u?`${u}-tab-label`:``}`,...v(`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,H.jsx)(`button`,{type:`button`,className:`${c}-close workspace-tab-close ${u?`${u}-tab-close`:``}`,...v(`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 K_={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},q_={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},J_={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},Y_={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function X_(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 Z_(e){let t=e.status===`running`,[n,r]=(0,V.useState)(0);(0,V.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 Q_({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,H.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,H.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:J_[e.status]}),(0,H.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,H.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,H.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,H.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,H.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:K_[e.status]}),e.status===`failed`&&r?.error&&(0,H.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,title:np(r.error),children:tp(r.error,`这一步没有完成。`)})]})}function $_({nodes:e,steps:t,names:n}){return(0,H.jsx)(`ol`,{className:`workflow-steps`,children:e.map((e,r)=>{if(e.kind===`step`){let r=t[e.stepIndex];return r?(0,H.jsx)(Q_,{step:r,names:n},`step-${e.stepIndex}`):null}return e.kind===`loop`?(0,H.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,H.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`↻`}),(0,H.jsx)(`strong`,{children:`循环`}),(0,H.jsxs)(`span`,{children:[`直到「`,e.until,`」`]}),(0,H.jsxs)(`span`,{"data-workflow-loop-progress":!0,children:[`已跑 `,e.rounds.length,`/`,e.max,` 轮`]})]}),e.rounds.map(e=>(0,H.jsxs)(`section`,{className:`workflow-round`,"data-workflow-round":e.n,"data-workflow-round-met":e.untilMet?`true`:`false`,children:[(0,H.jsxs)(`div`,{className:`workflow-round-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:e.untilMet?`✓`:`○`}),`第 `,e.n,` 轮 · `,e.untilMet?`条件满足`:`条件未满足`]}),(0,H.jsx)($_,{nodes:e.nodes,steps:t,names:n})]},e.n))]},`loop-${r}`):(0,H.jsxs)(`li`,{className:`workflow-node workflow-foreach`,"data-workflow-foreach":!0,"data-workflow-foreach-count":e.items.length,children:[(0,H.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`≡`}),(0,H.jsx)(`strong`,{children:`逐项执行`}),(0,H.jsxs)(`span`,{children:[e.items.length,` 个由 primary 给出的项目`]})]}),e.iterations.map((e,r)=>(0,H.jsxs)(`section`,{className:`workflow-item`,"data-workflow-item":r+1,"data-workflow-item-value":e.item,children:[(0,H.jsxs)(`div`,{className:`workflow-item-head`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),`第 `,r+1,` 项 · `,e.item]}),(0,H.jsx)($_,{nodes:e.nodes,steps:t,names:n})]},`${r}-${e.item}`))]},`foreach-${r}`)})})}function ev({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=Z_(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,H.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,H.jsxs)(`div`,{className:`workflow-head`,children:[(0,H.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,H.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,H.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,H.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:q_[e.status]??`未知状态`}),(0,H.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:Y_[e.onFailure]??e.onFailure}),a!==void 0&&(0,H.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,X_(a)]}),i&&(0,H.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),e.nodes?(0,H.jsx)($_,{nodes:e.nodes,steps:e.steps,names:t}):(0,H.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,H.jsx)(Q_,{step:e,names:t},e.index))})]})}var tv=[{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 nv({onClose:e}){let[t,n]=(0,V.useState)(`agents`);(0,V.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=tv.find(e=>e.id===t)??tv[0];return(0,H.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,H.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,H.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,H.jsxs)(`div`,{className:`help-head-title`,children:[(0,H.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,H.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,H.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,H.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,H.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,H.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),tv.map(e=>(0,H.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,H.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,H.jsx)(`span`,{children:e.label})]},e.id))]}),(0,H.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,H.jsxs)(`div`,{className:`help-panel-header`,children:[(0,H.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,H.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,H.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,H.jsx)(av,{}),r.id===`workspace`&&(0,H.jsx)(ov,{}),r.id===`subagents`&&(0,H.jsx)(cv,{}),r.id===`model-policy`&&(0,H.jsx)(sv,{}),r.id===`memory`&&(0,H.jsx)(rv,{}),r.id===`knowledge`&&(0,H.jsx)(iv,{}),r.id===`feishu`&&(0,H.jsx)(lv,{}),r.id===`tools`&&(0,H.jsx)(uv,{}),r.id===`cli`&&(0,H.jsx)(dv,{}),r.id===`themes`&&(0,H.jsx)(fv,{})]}),(0,H.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,H.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function rv(){return(0,H.jsxs)(`div`,{className:`help-section-group`,children:[(0,H.jsxs)(`div`,{className:`help-card highlight`,children:[(0,H.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,H.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,H.jsx)(`code`,{children:`memory`}),` 和 `,(0,H.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,H.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,H.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`权限与审批`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,H.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,H.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function iv(){return(0,H.jsxs)(`div`,{className:`help-section-group`,children:[(0,H.jsxs)(`div`,{className:`help-card highlight`,children:[(0,H.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,H.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库的内容来自工作区里真实存在的文档。`})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`怎么用`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文、手动填写相对路径,或者直接对 Agent 说“把某某文件加入知识库”——它会用 `,(0,H.jsx)(`code`,{children:`knowledge_import`}),` 导入,走的是同一条服务端校验。`]}),(0,H.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,H.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,H.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,H.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`语义检索是内置的`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,H.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,H.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,H.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`它不知道的事`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,H.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,H.jsxs)(`li`,{children:[`Agent 可以按你的要求把工作区文件导入知识库(`,(0,H.jsx)(`code`,{children:`knowledge_import`}),`,只接受文本类文件),但`,(0,H.jsx)(`strong`,{children:`不能删除`}),`——删除文档只有你能在“设置 → 知识库”里做。`]})]})]})]})}function av(){return(0,H.jsxs)(`div`,{className:`help-section-group`,children:[(0,H.jsxs)(`div`,{className:`help-card highlight`,children:[(0,H.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,H.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,H.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,H.jsxs)(`ul`,{className:`help-list`,children:[(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,H.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,H.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,H.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,H.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,H.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-card`,children:[(0,H.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,H.jsxs)(`div`,{className:`help-steps`,children:[(0,H.jsxs)(`div`,{className:`help-step`,children:[(0,H.jsx)(`span`,{className:`step-num`,children:`1`}),(0,H.jsxs)(`div`,{className:`step-body`,children:[(0,H.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,H.jsxs)(`p`,{children:[`在 `,(0,H.jsx)(`code`,{children:`agents/`}),` 或 `,(0,H.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,H.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,H.jsxs)(`div`,{className:`help-step`,children:[(0,H.jsx)(`span`,{className:`step-num`,children:`2`}),(0,H.jsxs)(`div`,{className:`step-body`,children:[(0,H.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,H.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,H.jsx)(`pre`,{className:`help-code-block`,children:(0,H.jsx)(`code`,{children:`---
53
53
  name: 系统架构师
54
54
  description: 专注于系统架构拆解、模块解耦与技术选型分析
55
55
  ---
@@ -89,14 +89,14 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
89
89
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),Cw&&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=Kw(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=sw(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,-qw),qw),t/=qw,t/Math.abs(t)+Math.round(t*(Jw-1)))}shouldForceSelection(e){return yw?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(),Yw)}_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&&!(yw&&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<Xw&&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=Mw(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=Kw(n,this._bufferService.cols)}};Qw=_y([X(3,Wy),X(4,Ky),X(5,ib),X(6,Xy),X(7,ab),X(8,rb)],Qw);var $w=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={}}},eT=class{constructor(){this._color=new $w,this._css=new $w}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()}},tT=Object.freeze((()=>{let e=[kC.toColor(`#2e3436`),kC.toColor(`#cc0000`),kC.toColor(`#4e9a06`),kC.toColor(`#c4a000`),kC.toColor(`#3465a4`),kC.toColor(`#75507b`),kC.toColor(`#06989a`),kC.toColor(`#d3d7cf`),kC.toColor(`#555753`),kC.toColor(`#ef2929`),kC.toColor(`#8ae234`),kC.toColor(`#fce94f`),kC.toColor(`#729fcf`),kC.toColor(`#ad7fa8`),kC.toColor(`#34e2e2`),kC.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:DC.toCss(r,i,a),rgba:DC.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:DC.toCss(n,n,n),rgba:DC.toRgba(n,n,n)})}return e})()),nT=kC.toColor(`#ffffff`),rT=kC.toColor(`#000000`),iT=kC.toColor(`#ffffff`),aT=rT,oT={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},sT=nT,cT=class extends Nb{constructor(e){super(),this._optionsService=e,this._contrastCache=new eT,this._halfContrastCache=new eT,this._onChangeColors=this._register(new Z),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:nT,background:rT,cursor:iT,cursorAccent:aT,selectionForeground:void 0,selectionBackgroundTransparent:oT,selectionBackgroundOpaque:OC.blend(rT,oT),selectionInactiveBackgroundTransparent:oT,selectionInactiveBackgroundOpaque:OC.blend(rT,oT),scrollbarSliderBackground:OC.opacity(nT,.2),scrollbarSliderHoverBackground:OC.opacity(nT,.4),scrollbarSliderActiveBackground:OC.opacity(nT,.5),overviewRulerBorder:nT,ansi:tT.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=lT(e.foreground,nT),t.background=lT(e.background,rT),t.cursor=OC.blend(t.background,lT(e.cursor,iT)),t.cursorAccent=OC.blend(t.background,lT(e.cursorAccent,aT)),t.selectionBackgroundTransparent=lT(e.selectionBackground,oT),t.selectionBackgroundOpaque=OC.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=lT(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=OC.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?lT(e.selectionForeground,EC):void 0,t.selectionForeground===EC&&(t.selectionForeground=void 0),OC.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=OC.opacity(t.selectionBackgroundTransparent,.3)),OC.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=OC.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=lT(e.scrollbarSliderBackground,OC.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=lT(e.scrollbarSliderHoverBackground,OC.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=lT(e.scrollbarSliderActiveBackground,OC.opacity(t.foreground,.5)),t.overviewRulerBorder=lT(e.overviewRulerBorder,sT),t.ansi=tT.slice(),t.ansi[0]=lT(e.black,tT[0]),t.ansi[1]=lT(e.red,tT[1]),t.ansi[2]=lT(e.green,tT[2]),t.ansi[3]=lT(e.yellow,tT[3]),t.ansi[4]=lT(e.blue,tT[4]),t.ansi[5]=lT(e.magenta,tT[5]),t.ansi[6]=lT(e.cyan,tT[6]),t.ansi[7]=lT(e.white,tT[7]),t.ansi[8]=lT(e.brightBlack,tT[8]),t.ansi[9]=lT(e.brightRed,tT[9]),t.ansi[10]=lT(e.brightGreen,tT[10]),t.ansi[11]=lT(e.brightYellow,tT[11]),t.ansi[12]=lT(e.brightBlue,tT[12]),t.ansi[13]=lT(e.brightMagenta,tT[13]),t.ansi[14]=lT(e.brightCyan,tT[14]),t.ansi[15]=lT(e.brightWhite,tT[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]=lT(e.extendedAnsi[r],tT[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()}}};cT=_y([X(0,Xy)],cT);function lT(e,t){if(e!==void 0)try{return kC.toColor(e)}catch{}return t}var uT=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)}},dT=class{constructor(){this._services=new uT,this._services.set(Jy,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Vy(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)}},fT={trace:0,debug:1,info:2,warn:3,error:4,off:5},pT=`xterm.js: `,mT=class extends Nb{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),hT=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=fT[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?``:pT)+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)}};mT=_y([X(0,Xy)],mT);var hT,gT=class extends Nb{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Z),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Z),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Z),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}},_T=3,vT=Object.freeze(new Fy),yT=0,bT=2,xT=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*_T);let r=t||Ly.fromCharData([0,Ny,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*_T+0],n=t&2097151;return[this._data[e*_T+1],t&2097152?this._combined[e]:n?ky(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*_T+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*_T+0]=e|2097152|t[2]<<22):this._data[e*_T+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*_T+0]>>22}hasWidth(e){return this._data[e*_T+0]&12582912}getFg(e){return this._data[e*_T+1]}getBg(e){return this._data[e*_T+2]}hasContent(e){return this._data[e*_T+0]&4194303}getCodePoint(e){let t=this._data[e*_T+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*_T+0]&2097152}getString(e){let t=this._data[e*_T+0];return t&2097152?this._combined[e]:t&2097151?ky(t&2097151):``}isProtected(e){return this._data[e*_T+2]&536870912}loadCell(e,t){return yT=e*_T,t.content=this._data[yT+0],t.fg=this._data[yT+1],t.bg=this._data[yT+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*_T+0]=t.content,this._data[e*_T+1]=t.fg,this._data[e*_T+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*_T+0]=t|n<<22,this._data[e*_T+1]=r.fg,this._data[e*_T+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*_T+0];r&2097152?this._combined[e]+=ky(t):r&2097151?(this._combined[e]=ky(r&2097151)+ky(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*_T+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 Ly;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 Ly;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*bT<this._data.buffer.byteLength;let n=e*_T;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*bT<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*bT<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*_T+0]&4194303)return e+(this._data[e*_T+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*_T+0]&4194303||this._data[e*_T+2]&50331648)return e+(this._data[e*_T+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<_T;e++)this._data[(n+i)*_T+e]=a[(t+i)*_T+e];a[(t+i)*_T+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<_T;e++)this._data[(n+i)*_T+e]=a[(t+i)*_T+e];a[(t+i)*_T+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*_T+0],n=e&2097151,a=e&2097152?this._combined[t]:n?ky(n):Py;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 ST(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=ET(u,d,t),p=1,m=0;for(;p<u.length;){let e=ET(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 CT(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 wT(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 TT(e,t,n){let r=[],i=e.map((n,r)=>ET(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=ET(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 ET(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 DT=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Z),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Ob(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};DT._nextId=1;var OT=DT,kT={},AT=kT.B;kT[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:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},kT.A={"#":`£`},kT.B=void 0,kT[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},kT.C=kT[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},kT.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},kT.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},kT.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},kT.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},kT.E=kT[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},kT.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},kT.H=kT[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},kT[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var jT=4294967295,MT=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=vT.clone(),this.savedCharset=AT,this.markers=[],this._nullCell=Ly.fromCharData([0,Ny,1,0]),this._whitespaceCell=Ly.fromCharData([0,Py,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ow,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new gT(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 Iy),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 Iy),this._whitespaceCell}getBlankLine(e,t){return new xT(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>jT?jT:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=vT);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 gT(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(vT),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 xT(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 xT(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=ST(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(vT),n);if(r.length>0){let n=CT(this.lines,r);wT(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(vT),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new xT(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(vT),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=TT(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(vT,!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--,_=ET(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 OT(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)}},NT=class extends Nb{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Z),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 MT(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new MT(!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)}},PT=2,FT=1,IT=class extends Nb{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,PT),this.rows=Math.max(e.rawOptions.rows||0,FT),this.buffers=this._register(new NT(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))}};IT=_y([X(0,Xy)],IT);var LT={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:yw,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},RT=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],zT=class extends Nb{constructor(e){super(),this._onOptionChange=this._register(new Z),this.onOptionChange=this._onOptionChange.event;let t={...LT};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(Ab(()=>{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 LT))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in LT))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||=LT[e],!BT(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=LT[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=RT.includes(t)?t:LT[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 BT(e){return e===`block`||e===`underline`||e===`bar`}function VT(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]&&VT(e[r],t-1);return n}var HT=Object.freeze({insertMode:!1}),UT=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),WT=class extends Nb{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 Z),this.onData=this._onData.event,this._onUserInput=this._register(new Z),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Z),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=VT(HT),this.decPrivateModes=VT(UT)}reset(){this.modes=VT(HT),this.decPrivateModes=VT(UT)}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))}};WT=_y([X(0,Wy),X(1,Yy),X(2,Xy)],WT);var GT={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 KT(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 qT=String.fromCharCode,JT={DEFAULT:e=>{let t=[KT(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${qT(t[0])}${qT(t[1])}${qT(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${KT(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${KT(e,!0)};${e.x};${e.y}${t}`}},YT=class extends Nb{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 Z),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(GT))this.addProtocol(e,GT[e]);for(let e of Object.keys(JT))this.addEncoding(e,JT[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}};YT=_y([X(0,Wy),X(1,Ky),X(2,Xy)],YT);var XT=[[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]],ZT=[[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]],QT;function $T(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 eE=class{constructor(){if(this.version=`6`,!QT){QT=new Uint8Array(65536),QT.fill(1),QT[0]=0,QT.fill(0,1,32),QT.fill(0,127,160),QT.fill(2,4352,4448),QT[9001]=2,QT[9002]=2,QT.fill(2,11904,42192),QT[12351]=1,QT.fill(2,44032,55204),QT.fill(2,63744,64256),QT.fill(2,65040,65050),QT.fill(2,65072,65136),QT.fill(2,65280,65377),QT.fill(2,65504,65511);for(let e=0;e<XT.length;++e)QT.fill(0,XT[e][0],XT[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?QT[e]:$T(e,ZT)?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=tE.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return tE.createPropertyValue(0,n,r)}},tE=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Z,this.onChange=this._onChange.event;let e=new eE;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)}},nE=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 rE(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 iE=2147483647,aE=256,oE=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>aE)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>iE?iE: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>iE?iE: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,iE):e}},sE=[],cE=class{constructor(){this._state=0,this._active=sE,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=sE}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=sE,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||sE,!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`,Ay(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=sE,this._id=-1,this._state=0}}},lE=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+=Ay(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}},uE=[],dE=class{constructor(){this._handlers=Object.create(null),this._active=uE,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=uE}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=uE,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||uE,!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`,Ay(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=uE,this._ident=0}},fE=new oE;fE.addParam(0);var pE=class{constructor(e){this._handler=e,this._data=``,this._params=fE,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():fE,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Ay(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=fE,this._data=``,this._hitLimit=!1,e));return this._params=fE,this._data=``,this._hitLimit=!1,t}},mE=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}},hE=160,gE=function(){let e=new mE(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(hE,0,2,0),e.add(hE,8,5,8),e.add(hE,6,0,6),e.add(hE,11,0,11),e.add(hE,13,13,13),e}(),_E=class extends Nb{constructor(e=gE){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 oE,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(Ab(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new cE),this._dcsParser=this._register(new dE),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:hE)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<hE||++i>=t||(r=e[i])<32||r>126&&r<hE||++i>=t||(r=e[i])<32||r>126&&r<hE||++i>=t||(r=e[i])<32||r>126&&r<hE){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<hE){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<hE){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}}},vE=/^([\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})$/,yE=/^[\da-f]+$/;function bE(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=vE.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),yE.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 xE(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 SE(e,t=16){let[n,r,i]=e;return`rgb:${xE(n,t)}/${xE(r,t)}/${xE(i,t)}`}var CE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},wE=131072,TE=10;function EE(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 DE=5e3,OE=0,kE=class extends Nb{constructor(e,t,n,r,i,a,o,s,c=new _E){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 jy,this._utf8Decoder=new My,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=vT.clone(),this._eraseAttrDataInternal=vT.clone(),this._onRequestBell=this._register(new Z),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Z),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Z),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Z),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Z),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Z),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Z),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Z),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Z),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 AE(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(yC.IND,()=>this.index()),this._parser.setExecuteHandler(yC.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(yC.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new lE(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new lE(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new lE(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new lE(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new lE(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new lE(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new lE(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new lE(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new lE(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new lE(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new lE(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new lE(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 kT)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 pE((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`),DE))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${DE} 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>wE&&(a=this._parseStack.position+wE)}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<wE&&(this._parseBuffer=new Uint32Array(Math.min(e.length,wE))),o||this._dirtyRowTracker.clearRange(),e.length>wE)for(let t=a;t<e.length;t+=wE){let a=t+wE<e.length?t+wE: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=tE.extractWidth(t);let n=tE.extractShouldJoin(t),m=n?tE.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(ky(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 xT&&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=>!EE(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new pE(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new lE(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(vT));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=tE.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,AT),this._charsetService.setgCharset(1,AT),this._charsetService.setgCharset(2,AT),this._charsetService.setgCharset(3,AT);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|=Fy.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=vT.fg,e.bg=vT.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|=vT.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=vT.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|=vT.fg&16777215,r.bg&=-67108864,r.bg|=vT.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=vT.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(!EE(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>TE&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>TE&&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(jE(n)){if(r===`?`)t.push({type:0,index:n});else{let e=bE(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=bE(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]);jE(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,AT),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(CE[e[0]],kT[e[1]]||AT),!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=vT.clone(),this._eraseAttrDataInternal=vT.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 Ly;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)}},AE=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&&(OE=e,e=t,t=OE),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};AE=_y([X(0,Wy)],AE);function jE(e){return 0<=e&&e<256}var ME=5e7,NE=12,PE=50,FE=class extends Nb{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 Z),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>ME)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>=NE?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>=NE)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>PE&&(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()}},IE=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)))}};IE=_y([X(0,Wy)],IE);var LE=!1,RE=class extends Nb{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Pb),this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onData=this._register(new Z),this.onData=this._onData.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Z),this._instantiationService=new dT,this.optionsService=this._register(new zT(e)),this._instantiationService.setService(Xy,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(IT)),this._instantiationService.setService(Wy,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(mT)),this._instantiationService.setService(Yy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(WT)),this._instantiationService.setService(Ky,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(YT)),this._instantiationService.setService(Gy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(tE)),this._instantiationService.setService(Qy,this.unicodeService),this._charsetService=this._instantiationService.createInstance(nE),this._instantiationService.setService(qy,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(IE),this._instantiationService.setService(Zy,this._oscLinkService),this._inputHandler=this._register(new kE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Vb.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Vb.forward(this._bufferService.onResize,this._onResize)),this._register(Vb.forward(this.coreService.onData,this._onData)),this._register(Vb.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 FE((e,t)=>this._inputHandler.parse(e,t))),this._register(Vb.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Z),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&&!LE&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),LE=!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,PT),t=Math.max(t,FT),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(rE.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(rE(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Ab(()=>{for(let t of e)t.dispose()})}}},zE={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 BE(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=zE[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 VE=0,HE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ow,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ow,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||(VE=this._search(t),VE===-1)||this._getKey(this._array[VE])!==t)return!1;do if(this._array[VE]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(VE),!0;while(++VE<this._array.length&&this._getKey(this._array[VE])===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&&(VE=this._search(e),!(VE<0||VE>=this._array.length)&&this._getKey(this._array[VE])===e))do yield this._array[VE];while(++VE<this._array.length&&this._getKey(this._array[VE])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(VE=this._search(e),!(VE<0||VE>=this._array.length)&&this._getKey(this._array[VE])===e))do t(this._array[VE]);while(++VE<this._array.length&&this._getKey(this._array[VE])===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}},UE=0,WE=0,GE=class extends Nb{constructor(){super(),this._decorations=new HE(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Z),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Z),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Ab(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new KE(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=>{UE=t.options.x??0,WE=UE+(t.options.width??1),e>=UE&&e<WE&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},KE=class extends Mb{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Z),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Z),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?kC.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?kC.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},qE=1e3,JE=class{constructor(e,t=qE){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)}},YE=20,XE=class extends Nb{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 JE(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(`
90
90
  `))),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(Q(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Ab(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<YE+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
91
91
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===YE+1&&(this._liveRegion.textContent+=xy.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})`}};XE=_y([X(1,Jy),X(2,rb),X(3,ab)],XE);var ZE=class extends Nb{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 Z),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Z),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Ab(()=>{Ob(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(Q(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Q(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Q(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Q(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&&QE(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,Ob(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}}};ZE=_y([X(1,ib),X(2,ab),X(3,Wy),X(4,lb)],ZE);function QE(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 $E=class extends RE{constructor(e={}){super(e),this._linkifier=this._register(new Pb),this.browser=dw,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Pb),this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Z),this.onKey=this._onKey.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Z),this.onBell=this._onBell.event,this._onFocus=this._register(new Z),this._onBlur=this._register(new Z),this._onA11yCharEmitter=this._register(new Z),this._onA11yTabEmitter=this._register(new Z),this._onWillOpen=this._register(new Z),this._setup(),this._decorationService=this._instantiationService.createInstance(GE),this._instantiationService.setService($y,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(ow),this._instantiationService.setService(lb,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(eb)),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(Vb.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Vb.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Vb.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Vb.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(Ab(()=>{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=OC.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${SE(r)}${bC.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=DC.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=DC.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(XE,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(Q(this.element,`copy`,e=>{this.hasSelection()&&wy(e,this._selectionService)}));let e=e=>Ty(e,this.textarea,this.coreService,this.optionsService);this._register(Q(this.textarea,`paste`,e)),this._register(Q(this.element,`paste`,e)),hw?this._register(Q(this.element,`mousedown`,e=>{e.button===2&&Oy(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Q(this.element,`contextmenu`,e=>{Oy(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Cw&&this._register(Q(this.element,`auxclick`,e=>{e.button===1&&Dy(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Q(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Q(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Q(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Q(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Q(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Q(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Q(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(Q(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`,yy.get()),ww||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(iw,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(rb,this._coreBrowserService),this._register(Q(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Q(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ew,this._document,this._helperContainer),this._instantiationService.setService(nb,this._charSizeService),this._themeService=this._instantiationService.createInstance(cT),this._instantiationService.setService(cb,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(FC),this._instantiationService.setService(sb,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Aw,this.rows,this.screenElement)),this._instantiationService.setService(ab,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(xC,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(lw),this._instantiationService.setService(ib,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(ZE,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(fC,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(Qw,this.element,this.screenElement,r)),this._instantiationService.setService(ob,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(Vb.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(pC,this.screenElement)),this._register(Q(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(XE,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vC,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vC,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance($C,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(Q(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(Q(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){Ey(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=BE(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)&&(eD(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(vT));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 eD(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var tD=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)}},nD=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 Ly)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},rD=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 nD(t)}getNullCell(){return new Ly}},iD=class extends Nb{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Z),this.onBufferChange=this._onBufferChange.event,this._normal=new rD(this._core.buffers.normal,`normal`),this._alternate=new rD(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)}},aD=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)}},oD=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}},sD=[`cols`,`rows`],cD=0,lD=class extends Nb{constructor(e){super(),this._core=this._register(new $E(e)),this._addonManager=this._register(new tD),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(sD.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 aD(this._core),this._parser}get unicode(){return this._checkProposedApi(),new oD(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 iD(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
92
- `,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 yy.get()},set promptLabel(e){yy.set(e)},get tooMuchOutput(){return xy.get()},set tooMuchOutput(e){xy.set(e)}}}_verifyIntegers(...e){for(cD of e)if(cD===1/0||isNaN(cD)||cD%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(cD of e)if(cD&&(cD===1/0||isNaN(cD)||cD%1!=0||cD<0))throw Error(`This API only accepts positive integers`)}},uD=2,dD=1,fD=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(uD,Math.floor(u/e.css.cell.width)),rows:Math.max(dD,Math.floor(l/e.css.cell.height))}}},pD=5,mD=20,hD=5,gD=240,_D=120,vD={checking:`检查中`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`},yD=new Map,bD=e=>{let t=yD.get(e);if(!t){let n={id:`${e}-1`,title:`1`,phase:`checking`};t={slots:[n],activeId:n.id,opened:new Set,terminals:new Map,fits:new Map},yD.set(e,t)}return t};function xD({workspaceId:e,workspaceLabel:t,cwd:n=``,connected:r,sendCommand:i,registerSink:a,conversationId:o,terminalShell:s}){let c=o?`term-${o}`:`terminal-right-rail`,l=bD(c),[u,d]=(0,V.useState)(()=>l.slots),[f,p]=(0,V.useState)(()=>l.activeId),m=(0,V.useRef)(f);m.current=f,l.activeId=f;let h=(0,V.useRef)(u);h.current=u,l.slots=u;let g=(0,V.useRef)(e);g.current=e;let _=(0,V.useRef)(n);_.current=n;let v=(0,V.useRef)(i);v.current=i;let y=(0,V.useRef)(l.opened);y.current=l.opened;let b=(0,V.useRef)(!1),x=(0,V.useRef)(l.terminals);x.current=l.terminals;let S=(0,V.useRef)(l.fits);S.current=l.fits;let C=(0,V.useRef)(new Map),[w,T]=(0,V.useState)(0),[E,D]=(0,V.useState)(``),O=(0,V.useRef)(r),k=(0,V.useCallback)(e=>{x.current.get(e)?.dispose(),x.current.delete(e),S.current.delete(e),C.current.delete(e)},[]),A=(0,V.useCallback)(e=>{let t=x.current.get(e),n=S.current.get(e);if(!t||!n)return;let r=C.current.get(e);if(!(!r||r.clientWidth<2||r.clientHeight<2)){try{n.fit()}catch{return}t.cols<mD||t.rows<hD||t.cols>gD||t.rows>_D||y.current.has(e)&&v.current({type:`terminal.resize`,sessionId:e,cols:t.cols,rows:t.rows})}},[]),j=(0,V.useCallback)((e,t)=>{if(!t){C.current.delete(e);return}C.current.set(e,t);let n=x.current.get(e);if(n){n.element&&!t.contains(n.element)&&(t.innerHTML=``,t.appendChild(n.element),requestAnimationFrame(()=>A(e)));return}let r=getComputedStyle(t),i=(e,t)=>r.getPropertyValue(e).trim()||t,a=new lD({cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:i(`--term-fg`,`#dbe4f0`),cursor:i(`--term-fg`,`#dbe4f0`),selectionBackground:i(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),o=new fD;a.loadAddon(o),a.open(t),a.onData(t=>{y.current.has(e)&&v.current({type:`terminal.input`,sessionId:e,data:t})}),a.onResize(({cols:t,rows:n})=>{y.current.has(e)&&v.current({type:`terminal.resize`,sessionId:e,cols:t,rows:n})}),x.current.set(e,a),S.current.set(e,o),requestAnimationFrame(()=>A(e)),T(e=>e+1)},[A]),M=(0,V.useCallback)(e=>{x.current.get(e)?.reset()},[]),N=(0,V.useCallback)(e=>{let t=g.current,n=x.current.get(e);if(!t||!n||y.current.has(e))return;n.reset(),A(e),d(t=>t.map(t=>t.id===e?{...t,phase:`starting`,exitCode:void 0,reason:``}:t));let r=Math.max(mD,Math.min(gD,n.cols||80)),i=Math.max(hD,Math.min(_D,n.rows||24));v.current({type:`terminal.open`,sessionId:e,workspaceId:t,..._.current?{cwd:_.current}:{},cols:r,rows:i})?(y.current.add(e),d(t=>t.map(t=>t.id===e?{...t,phase:`running`}:t))):d(t=>t.map(t=>t.id===e?{...t,phase:`exited`,reason:`Super Pi 服务的连接尚未就绪`}:t))},[A]);(0,V.useEffect)(()=>{let e=!1;return fetch(`/api/terminal`).then(e=>e.json()).then(t=>{e||(t.enabled?(b.current=!0,d(e=>e.map(e=>e.phase===`checking`?{...e,phase:`starting`}:e))):d(e=>e.map(e=>({...e,phase:`unavailable`,reason:t.reason??`终端未启用`}))))}).catch(()=>{e||d(e=>e.map(e=>({...e,phase:`unavailable`,reason:`无法读取终端状态`})))}),()=>{e=!0}},[]);let P=(0,V.useRef)(void 0),F=(0,V.useCallback)(()=>{fetch(`/api/terminal-shell`).then(e=>e.json()).then(e=>D(e.shell?`${e.shell.file}${e.shell.args.length?` ${e.shell.args.join(` `)}`:``}(${e.source??``})`:``)).catch(()=>void 0)},[]);(0,V.useEffect)(()=>{F()},[F]),(0,V.useEffect)(()=>{let e=s?`${s.file}\u0000${s.args.join(`\0`)}`:``;P.current!==void 0&&P.current!==e&&F(),P.current=e},[s,F]),(0,V.useEffect)(()=>{if(b.current)for(let e of u)(e.phase===`checking`||e.phase===`starting`)&&!y.current.has(e.id)&&N(e.id)},[u,N,w]);let ee=(0,V.useCallback)(e=>{if(e.type===`terminal.output`)for(let t of yD.values()){let n=t.terminals.get(e.sessionId);if(n){n.write(e.data);return}}else if(e.type===`terminal.exit`){for(let t of yD.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t));M(e.sessionId),d(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t))}else if(e.type===`terminal.error`){for(let t of yD.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t));M(e.sessionId),d(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t))}else e.type===`terminal.status`&&!e.enabled&&d(t=>t.map(t=>({...t,phase:`unavailable`,reason:e.reason??`终端未启用`})))},[M,F]);(0,V.useEffect)(()=>(a(ee),()=>a(void 0)),[ee,a]),(0,V.useEffect)(()=>()=>{C.current.clear()},[]),(0,V.useEffect)(()=>{let e=r&&!O.current;O.current=r,e&&d(e=>e.map(e=>e.phase===`exited`&&!e.deliberate?{...e,phase:`starting`,reason:``}:e))},[r]),(0,V.useLayoutEffect)(()=>{let e=new ResizeObserver(()=>A(m.current));for(let t of C.current.values())e.observe(t);return A(m.current),()=>e.disconnect()},[A,u,w]);let te=(0,V.useCallback)(e=>{p(e),requestAnimationFrame(()=>A(e))},[A]),ne=(0,V.useCallback)(()=>{let e=new Set(h.current.map(e=>e.title)),t=1;for(;e.has(String(t));)t+=1;let n={id:`${c}-${t}`,title:String(t),phase:`checking`};d(e=>e.length>=pD?e:[...e,n]),p(n.id)},[c]),re=(0,V.useCallback)(e=>{v.current({type:`terminal.close`,sessionId:e}),y.current.delete(e),k(e),d(t=>{let n=t.findIndex(t=>t.id===e),r=t.filter(t=>t.id!==e);return m.current===e&&r.length&&p(r[Math.min(n,r.length-1)].id),m.current===e&&!r.length&&p(``),r})},[k]),I=u.find(e=>e.id===f)??u[0];return(0,H.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":I?.phase??`empty`,children:[(0,H.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[u.map(e=>(0,H.jsxs)(`div`,{className:`terminal-tab${e.id===f?` is-active`:``}`,children:[(0,H.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===f,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>te(e.id),title:vD[e.phase],children:[(0,H.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.phase}`,"aria-hidden":`true`}),e.title]}),(0,H.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>re(e.id),children:`×`})]},e.id)),u.length<pD&&(0,H.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,"data-terminal-add":`1`,onClick:ne,title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,H.jsxs)(`div`,{className:`terminal-toolbar`,children:[I?(0,H.jsxs)(`span`,{className:`terminal-status terminal-status-${I.phase}`,"data-terminal-status":I.phase,children:[(0,H.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),vD[I.phase]]}):(0,H.jsx)(`span`,{className:`terminal-status terminal-status-empty`,"data-terminal-status":`empty`,children:`没有打开的终端`}),(0,H.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[E&&(0,H.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-shell-hint":`1`,title:E,children:E}),t&&(0,H.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),I?I.phase===`running`?null:(0,H.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,onClick:()=>N(I.id),children:`重新打开`}):null]})]}),I?.reason&&(0,H.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,title:np(I.reason),children:tp(I.reason,`终端出错了。`)}),I?.phase===`exited`&&I.exitCode!==void 0&&I.exitCode!==0&&(0,H.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,I.exitCode,`。`]}),(0,H.jsxs)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:[u.map(e=>(0,H.jsx)(`div`,{ref:t=>j(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===f?`block`:`none`}},e.id)),!I&&(0,H.jsx)(`div`,{className:`terminal-surface-empty`,"data-terminal-empty":`1`,children:(0,H.jsx)(`p`,{className:`rail-empty`,children:`没有打开的终端`})}),I?.phase===`checking`&&(0,H.jsx)(`p`,{className:`rail-empty terminal-surface-message`,"data-terminal-phase":`checking`,children:`正在检查终端状态…`}),I?.phase===`unavailable`&&(0,H.jsxs)(`div`,{className:`terminal-unavailable terminal-surface-message`,"data-terminal-phase":`unavailable`,children:[(0,H.jsx)(`p`,{className:`terminal-unavailable-reason`,title:np(I.reason),children:tp(I.reason,`终端没有启动。`)}),(0,H.jsx)(`p`,{className:`rail-empty`,children:`终端仅接受本机与局域网连接。`})]})]})]})}var SD=[{day:1,label:`一`},{day:2,label:`二`},{day:3,label:`三`},{day:4,label:`四`},{day:5,label:`五`},{day:6,label:`六`},{day:0,label:`日`}];function CD(e){return e.kind===`interval`?`每隔 ${e.everyMinutes} 分钟`:e.kind===`daily`?`每天 ${e.time}`:e.kind===`weekly`?`每周${e.weekdays.map(e=>SD.find(t=>t.day===e)?.label??`?`).join(`、`)} ${e.time}`:`仅一次:${wD(e.at)}`}function wD(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 TD(){return typeof Intl<`u`?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function ED(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 DD(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 OD(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 kD(e,t,n){let r=DD(e,n),i=AD(e,t,n);return i===0?`今天 ${r}`:i===1?`明天 ${r}`:ED(e,n)}function AD(e,t,n){let r=e=>{let[t]=ED(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 jD(e,t,n){if(!e||!t||e===t)return``;let r=OD(e,n),i=OD(t,n);return DD(n,e)===DD(n,t)?`服务器在 ${r} 时区,你的时区也是 ${i},下面的时间按你的时区显示`:`服务器在 ${r} 时区,下面的时间按你的时区(${i})显示`}function MD(e,t,n){return e.enabled?e.nextRunAt===void 0?{glyph:`✓`,word:`已结束`,detail:``}:{glyph:`●`,word:`启用中`,detail:`下次 ${kD(e.nextRunAt,t,n)}`}:e.schedule.kind===`once`&&e.lastRunAt!==void 0?{glyph:`✓`,word:`已结束`,detail:e.lastRunAt?`上次 ${ED(e.lastRunAt,n)}`:``}:{glyph:`○`,word:`已停用`,detail:``}}function ND(e,t){if(e.lastRunAt===void 0)return``;let n=ED(e.lastRunAt,t);return e.lastRunStatus===`failed`?`上次 ${n} · 失败${e.lastRunMessage?`:${e.lastRunMessage}`:``}`:`上次 ${n} · 成功`}function PD({tasks:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,serverTimeZone:o}){let[s,c]=(0,V.useState)(()=>Date.now()),[l,u]=(0,V.useState)();(0,V.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let d=TD(),f=jD(o,d,s),p=e=>{i({type:`scheduledTask.toggle`,id:e.id,enabled:!e.enabled})},m=e=>{i({type:`scheduledTask.trigger`,id:e.id}),a(`已触发「${e.name}」,结果会出现在它自己的会话里。`,`info`)},h=e=>{i({type:`scheduledTask.delete`,id:e.id}),a(`已删除定时任务「${e.name}」,它的会话和结果保留着。`,`info`)};return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`定时任务`}),(0,H.jsx)(`span`,{className:`rail-section-count`,"data-sched-count":`1`,children:e.length?`${e.length} 个`:`0 个`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-add`,"data-sched-add":`1`,title:`新建定时任务`,onClick:()=>u(`new`),children:`+ 新建`})]}),f&&(0,H.jsx)(`p`,{className:`scheduled-zone-note`,"data-sched-zone-note":`1`,children:f}),e.length>0?(0,H.jsx)(`ul`,{className:`scheduled-list`,"data-sched-list":`1`,children:e.map(e=>{let t=MD(e,s,d),n=ND(e,d);return(0,H.jsxs)(`li`,{className:`scheduled-item`,"data-scheduled-task":e.id,children:[(0,H.jsx)(`button`,{type:`button`,className:`scheduled-toggle`,"data-sched-toggle":`1`,title:e.enabled?`点击停用`:`点击启用`,"aria-label":e.enabled?`停用 ${e.name}`:`启用 ${e.name}`,onClick:()=>p(e),children:t.glyph}),(0,H.jsxs)(`div`,{className:`scheduled-main`,children:[(0,H.jsxs)(`div`,{className:`scheduled-name-row`,children:[(0,H.jsx)(`span`,{className:`scheduled-name`,children:e.name}),(0,H.jsx)(`span`,{className:`scheduled-status-word`,"data-sched-word":`1`,children:t.word}),e.createdBy===`agent`&&(0,H.jsx)(`span`,{className:`scheduled-by`,title:`这个定时任务是 agent 创建的,你可以像编辑自己建的一样编辑它`,children:`agent`})]}),(0,H.jsxs)(`div`,{className:`scheduled-meta`,"data-sched-meta":`1`,children:[CD(e.schedule),t.detail?` · ${t.detail}`:``]}),n&&(0,H.jsx)(`div`,{className:`scheduled-last`,"data-sched-last":`1`,children:n})]}),(0,H.jsxs)(`div`,{className:`scheduled-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-trigger":`1`,title:`立即执行一次(不改变周期)`,"aria-label":`立即执行 ${e.name}`,onClick:()=>m(e),children:`⚡`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-edit":`1`,title:`编辑`,"aria-label":`编辑 ${e.name}`,onClick:()=>u(e),children:`✎`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-action scheduled-action-danger`,"data-sched-delete":`1`,title:`删除(会话与结果保留)`,"aria-label":`删除 ${e.name}`,onClick:()=>h(e),children:`✕`})]})]},e.id)})}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-sched-empty":`1`,children:`还没有定时任务。建一个,让它在你不在的时候替你跑:每天汇总提交、每周检查依赖、每隔十分钟看一眼构建。`}),l!==void 0&&(0,H.jsx)(RD,{task:l===`new`?void 0:l,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:()=>u(void 0)},l===`new`?`new`:l.id)]})}function FD(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`?ID(t.at):``,modelKey:e?.model?`${e.model.provider}/${e.model.modelId}`:``,agentId:e?.agentId??``}}function ID(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 LD(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 RD({task:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:o}){let[s,c]=(0,V.useState)(()=>FD(e)),[l,u]=(0,V.useState)();(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let d=e=>{c(t=>({...t,...e})),u(void 0)};return(0,sa.createPortal)((0,H.jsx)(`div`,{className:`tool-overlay`,"data-sched-dialog-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&o()},children:(0,H.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`scheduled-dialog-title`,"data-sched-dialog":`1`,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsx)(`h2`,{className:`tool-dialog-title`,id:`scheduled-dialog-title`,children:e?`编辑定时任务`:`新建定时任务`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-sched-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭定时任务编辑`,onClick:o,children:`✕`})]}),(0,H.jsxs)(`div`,{className:`tool-dialog-body scheduled-form`,children:[(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`名称`}),(0,H.jsx)(`input`,{className:`scheduled-input`,"data-sched-field":`name`,value:s.name,placeholder:`留空则取提示词首句`,onChange:e=>d({name:e.target.value})})]}),(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`提示词`}),(0,H.jsx)(`textarea`,{className:`scheduled-textarea`,"data-sched-field":`prompt`,rows:5,value:s.prompt,placeholder:`到点时这段话会作为用户消息发给 agent,所以它要是一条完整、自包含的指令`,onChange:e=>d({prompt:e.target.value})})]}),(0,H.jsxs)(`div`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`周期`}),(0,H.jsx)(`div`,{className:`scheduled-kind-row`,role:`radiogroup`,"aria-label":`周期类型`,children:[[`interval`,`每隔 N 分钟`],[`daily`,`每天`],[`weekly`,`每周`],[`once`,`仅一次`]].map(([e,t])=>(0,H.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:()=>d({kind:e}),children:t},e))})]}),s.kind===`interval`&&(0,H.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`间隔`}),(0,H.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`everyMinutes`,inputMode:`numeric`,value:s.everyMinutes,onChange:e=>d({everyMinutes:e.target.value})}),(0,H.jsx)(`span`,{className:`scheduled-hint`,children:`分钟(1 – 10080)`})]}),(s.kind===`daily`||s.kind===`weekly`)&&(0,H.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,H.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`time`,inputMode:`numeric`,placeholder:`09:00`,value:s.time,onChange:e=>d({time:e.target.value})}),(0,H.jsx)(`span`,{className:`scheduled-hint`,children:`服务器本地时间,每天/每周的这一天到点触发`})]}),s.kind===`weekly`&&(0,H.jsxs)(`div`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`星期`}),(0,H.jsx)(`div`,{className:`scheduled-weekdays`,children:SD.map(({day:e,label:t})=>{let n=s.weekdays.includes(e);return(0,H.jsx)(`button`,{type:`button`,"aria-pressed":n,className:`scheduled-weekday${n?` scheduled-weekday-on`:``}`,"data-sched-weekday":e,onClick:()=>d({weekdays:n?s.weekdays.filter(t=>t!==e):[...s.weekdays,e]}),children:t},e)})})]}),s.kind===`once`&&(0,H.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,H.jsx)(`input`,{className:`scheduled-input`,type:`datetime-local`,"data-sched-field":`onceAt`,value:s.onceAt,onChange:e=>d({onceAt:e.target.value})}),(0,H.jsx)(`span`,{className:`scheduled-hint`,children:`这一次运行之后就结束`})]}),(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`模型`}),(0,H.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`model`,value:s.modelKey,onChange:e=>d({modelKey:e.target.value}),children:[(0,H.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(n?.models??[]).map(e=>(0,H.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,`(`,e.detail,`)`]},`${e.provider}/${e.modelId}`))]})]}),(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`Agent`}),(0,H.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`agent`,value:s.agentId,onChange:e=>d({agentId:e.target.value}),children:[(0,H.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(r?.agents??[]).map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.name??e.id},e.id))]})]}),l&&(0,H.jsx)(`p`,{className:`scheduled-error`,"data-sched-error":`1`,role:`alert`,children:l}),(0,H.jsxs)(`div`,{className:`scheduled-actions-row`,children:[(0,H.jsx)(`button`,{type:`button`,className:`scheduled-cancel`,onClick:o,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-save`,"data-sched-save":`1`,onClick:()=>{let r=s.prompt.trim();if(!r){u(`定时任务需要一段提示词:到点时这段话会被当作用户消息发给 agent。`);return}if(!t){u(`先选一个工作区,再建定时任务。`);return}let c=LD(s);if(!c.ok){u(c.reason);return}let l=n?.models.find(e=>`${e.provider}/${e.modelId}`===s.modelKey),d=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:d,agentId:f}:{type:`scheduledTask.create`,name:p,prompt:r,schedule:c.schedule,workspaceId:t,model:d,agentId:f})?(a(e?`已保存对「${s.name.trim()||e.name}」的修改。`:`定时任务已创建,到点会自动运行。`,`info`),o()):u(`连接已断开,没能保存。等重连后再试一次。`)},children:e?`保存修改`:`创建任务`})]})]})]})}),document.body)}function zD(...e){for(let t of e){let e=typeof t==`string`?t.trim():``;if(e)return e}}function BD(e){return e?!!(zD(e.agentId)||zD(e.cwd)||zD(e.thinkingLevel)||zD(e.model?.provider)||zD(e.model?.modelId)||typeof e.watchdogTimeoutSeconds==`number`&&Number.isFinite(e.watchdogTimeoutSeconds)&&e.watchdogTimeoutSeconds>0):!1}function VD(e,t){let n=zD(e?.provider,t?.provider),r=zD(e?.modelId,t?.modelId);if(!n&&!r)return;let i={};return n&&(i.provider=n),r&&(i.modelId=r),i}function HD(e,t){if(!e&&!t)return;let n={agentId:zD(e?.agentId,t?.agentId),cwd:zD(e?.cwd,t?.cwd),model:VD(e?.model,t?.model),thinkingLevel:zD(e?.thinkingLevel,t?.thinkingLevel),watchdogTimeoutSeconds:typeof e?.watchdogTimeoutSeconds==`number`&&Number.isFinite(e.watchdogTimeoutSeconds)&&e.watchdogTimeoutSeconds>0?e.watchdogTimeoutSeconds:typeof t?.watchdogTimeoutSeconds==`number`&&Number.isFinite(t.watchdogTimeoutSeconds)&&t.watchdogTimeoutSeconds>0?t.watchdogTimeoutSeconds:void 0};return BD(n)?n:void 0}function UD(e,t,n){return e==null?HD(t,n):BD(e)?e:void 0}function WD(e){if(!e)return``;let t=[],n=zD(e.agentId);n&&t.push(n);let r=zD(e.model?.provider),i=zD(e.model?.modelId);r&&i?t.push(`模型 ${r}/${i}`):r?t.push(`模型 ${r}`):i&&t.push(`模型 ${i}`);let a=zD(e.cwd);a&&t.push(`目录 ${a}`);let o=zD(e.thinkingLevel);return o&&t.push(`思考 ${o}`),typeof e.watchdogTimeoutSeconds==`number`&&Number.isFinite(e.watchdogTimeoutSeconds)&&e.watchdogTimeoutSeconds>0&&t.push(`看门狗 ${e.watchdogTimeoutSeconds} 秒`),t.join(` · `)}function GD(e){let t=Array.isArray(e)?e:[],n=new Set(t.map(e=>e.id)),r=new Map;for(let e of t){let t=e.parentConversationId;r.set(e.id,t&&n.has(t)&&t!==e.id?t:void 0)}let i=new Map;for(let e of t){let t=r.get(e.id);if(!t)continue;let n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Set,o=(e,t,n)=>{a.add(e.id);let r={session:e,children:[],depth:t};for(let a of i.get(e.id)??[])n.has(a.id)||r.children.push(o(a,t+1,new Set([...n,e.id])));return r},s=[];for(let e of t)r.get(e.id)||s.push(o(e,0,new Set([e.id])));for(let e of t)a.has(e.id)||s.push(o(e,0,new Set([e.id])));return s}var KD={ready:`待派发`,pending:`等待依赖`,in_progress:`执行中`,draft:`待澄清`,planning:`待规划`,planned:`已规划`,assigned:`已委派`,running:`执行中`,active:`执行中`,waiting_dependency:`等待依赖`,waiting_approval:`等待审批`,awaiting_approval:`等待审批`,blocked:`已阻塞`,review:`待验收`,awaiting_review:`待验收`,rework:`返工中`,completed:`已完成`,closed:`已关闭`,failed:`失败`,cancelled:`已取消`,idle:`空闲`,waiting:`排队中`,awaiting_background:`等待回传`,stopped:`已停止`};function qD(e){return KD[e??``]??e??`未知状态`}function JD({sessions:e,onOpenSession:t,emptyText:n}){let r=(0,V.useMemo)(()=>GD(e),[e]);return r.length?(0,H.jsx)(`ul`,{className:`session-tree`,"data-session-tree":`1`,children:r.map(e=>(0,H.jsx)(YD,{node:e,onOpenSession:t},e.session.id))}):(0,H.jsx)(`p`,{className:`project-muted`,children:n??`该项目还没有会话。`})}function YD({node:e,onOpenSession:t}){let{session:n,children:r,depth:i}=e;return(0,H.jsxs)(`li`,{className:`session-tree-item`,"data-session-node":n.id,"data-session-depth":i,"data-session-role":n.role??``,children:[(0,H.jsxs)(`div`,{className:`session-node-row`,children:[(0,H.jsx)(`span`,{className:`session-node-role`,children:n.role??`会话`}),(0,H.jsx)(`button`,{type:`button`,className:`session-node-title`,"data-session-title":n.id,disabled:!t,onClick:()=>t?.(n.id),children:n.title})]}),(0,H.jsxs)(`div`,{className:`session-node-meta`,children:[(0,H.jsx)(`span`,{className:`project-status project-status-${n.status??`idle`}`,children:qD(n.status)}),(0,H.jsxs)(`span`,{className:`session-node-tokens`,"data-session-tokens":n.tokens??0,children:[(n.tokens??0).toLocaleString(),` Token`]}),n.contextPercent==null?null:(0,H.jsxs)(`span`,{className:`session-node-context`,"data-session-context":n.id,children:[`上下文 `,Math.round(n.contextPercent),`%`]})]}),r.length===0?null:(0,H.jsxs)(`details`,{className:`session-tree-branch`,open:i===0,"data-session-branch":n.id,children:[(0,H.jsxs)(`summary`,{className:`session-tree-toggle`,"data-session-toggle":n.id,children:[(0,H.jsx)(`span`,{className:`project-fold-arrow`,"aria-hidden":`true`,children:`▸`}),r.length,` 个下级`]}),(0,H.jsx)(`ul`,{className:`session-tree-children`,children:r.map(e=>(0,H.jsx)(YD,{node:e,onOpenSession:t},e.session.id))})]})]})}function XD(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 ZD(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`请求失败(${e.status})`);return t}var QD={decision:`要你决定`,blocked:`卡住了`,completed:`已完成`},$D={decision:0,blocked:1,completed:2},eO=864e5,tO=5;function nO(e,t=60){let n=(e??``).replace(/\s+/g,` `).trim();return n?n.length<=t?n:`${n.slice(0,t-1)}…`:``}function rO(e){let t=e.summary?.trim();if(t)return nO(t);let n=e.reports??[],r=n.find(e=>e.kind===`delivery`);if(r?.progress?.trim())return nO(r.progress);for(let e of[...n].reverse()){let t=e.progress?.trim()||e.summary?.trim();if(t)return nO(t)}for(let t of[...e.tasks??[]].reverse()){let e=t.review?.summary?.trim();if(e)return nO(e)}return`已完成`}function iO(e,t){let n=(e.escalations??[]).filter(e=>e.status===`open`),r=Date.parse(e.updatedAt??``)||0;if(n.length){let t=n[0];return{projectId:e.id,projectTitle:e.title,kind:`decision`,label:QD.decision,detail:nO(t.reason||t.title||`有例外等你处理`),actionLabel:`去看看`,target:{kind:`exception`,escalationId:t.id},updatedAt:r}}let i=e.status===`completed`,a=i?void 0:(e.tasks??[]).find(e=>e.status===`blocked`);if(!i&&(e.status===`blocked`||a))return{projectId:e.id,projectTitle:e.title,kind:`blocked`,label:QD.blocked,detail:nO(a?.title||e.objective||e.title),actionLabel:`去看看`,target:a?{kind:`task`,taskId:a.id}:{kind:`top`},updatedAt:r};if(i){let n=Date.parse(e.closedAt||e.updatedAt||``);return!Number.isFinite(n)||t-n>eO?null:{projectId:e.id,projectTitle:e.title,kind:`completed`,label:QD.completed,detail:rO(e),actionLabel:`查看交付`,target:{kind:`top`},updatedAt:r}}return null}function aO(e){let t=e.tasks??[],n=t.filter(e=>e.status===`completed`).length,r=e.resources?.activeWorkers??0,i=e.resources?.tokens??0,a=e.budget?.maxTokens;return{done:n,total:t.length,workers:r,tokens:i,budget:a,tokenText:`${i.toLocaleString()} / ${a?a.toLocaleString():`未设限`}`}}function oO({project:e,workspaceId:t,notify:n,onOpenSession:r,onChanged:i}){let[a,o]=(0,V.useState)(`100000`),[s,c]=(0,V.useState)(`2`),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)(!1),[h,g]=(0,V.useState)(``),_=(e.escalations??[]).filter(e=>e.status===`open`),v=[`completed`,`cancelled`,`failed`].includes(e.status),y=e.resources?.tokens??0,b=e.budget?.maxTokens,x=typeof b==`number`&&y>=b,S=_.filter(e=>(e.reason??``).includes(`预算`)),C=e.suggestedMaxTokens,w=!v&&typeof C==`number`&&(x||S.length>0),T=async(r,a={})=>{u(r),g(``);try{await fetch(`/api/projects/${encodeURIComponent(e.id)}/${r}`,{method:r.startsWith(`escalations/`)||r===`budget`||!r||r.startsWith(`tasks/`)&&!r.endsWith(`/dispatch`)&&!r.endsWith(`/review`)?`PATCH`:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...a,workspaceId:t})}).then(ZD),await i?.(),n?.(`项目操作已执行`,`info`)}catch(e){g(e instanceof Error?e.message:`任务派发失败`)}finally{u(``)}};return(0,H.jsxs)(`div`,{className:`project-detail`,"data-project-detail":e.id,children:[(0,H.jsxs)(`div`,{className:`project-detail-title`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h3`,{children:e.title}),(0,H.jsx)(`p`,{children:e.objective||`未填写目标`})]}),(0,H.jsxs)(`span`,{className:`project-detail-flags`,children:[e.mode===`lightweight`?(0,H.jsx)(`span`,{className:`project-mode-tag`,"data-project-mode":`lightweight`,children:`轻量`}):null,(0,H.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:qD(e.status)})]})]}),e.acceptanceCriteria?.length?(0,H.jsxs)(`p`,{className:`project-acceptance`,children:[(0,H.jsx)(`strong`,{children:`验收:`}),e.acceptanceCriteria.join(`;`)]}):null,(0,H.jsxs)(`div`,{className:`project-employees`,"data-project-employees":e.id,children:[(0,H.jsxs)(`span`,{className:`project-employee`,"data-project-employee":`executor`,children:[(0,H.jsx)(`b`,{children:`执行员工`}),WD(e.defaultExecutorProfile)||`未指定(用默认)`]}),(0,H.jsxs)(`span`,{className:`project-employee`,"data-project-employee":`reviewer`,children:[(0,H.jsx)(`b`,{children:`复核员工`}),WD(e.defaultReviewerProfile)||`未指定(用默认)`]})]}),(0,H.jsxs)(`div`,{className:`project-detail-summary`,children:[(0,H.jsxs)(`span`,{children:[`任务 `,(e.tasks??[]).length]}),(0,H.jsxs)(`span`,{children:[`待处理例外 `,_.length]}),(0,H.jsxs)(`span`,{children:[`最近更新 `,XD(e.updatedAt)||`暂无`]})]}),(0,H.jsx)(`div`,{className:`project-detail-summary`,"data-project-budget":e.id,children:(0,H.jsxs)(`span`,{"data-project-budget-used":e.id,children:[`Token `,y.toLocaleString(),` / `,b?b.toLocaleString():`未设限`]})}),(0,H.jsx)(`p`,{className:`project-muted`,"data-project-budget-basis":`1`,children:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`}),(0,H.jsxs)(`div`,{className:`project-detail-actions`,children:[e.ownerConversationId&&r&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,onClick:()=>r(e.ownerConversationId),children:`查看负责人会话`}),!v&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void T(`start`),children:e.ownerConversationId?`唤起负责人继续执行`:`启动负责人会话`}),!v&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void T(``,{status:`cancelled`}),children:`停止项目及子会话`}),w&&(0,H.jsxs)(`button`,{type:`button`,className:`project-task-action`,"data-project-budget-raise":e.id,disabled:!!l,onClick:()=>void T(`budget/continue`),children:[x?`预算用完了`:`预算挡住了派发`,`:提到 `,C.toLocaleString(),` Token 并继续`]}),!v&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,title:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`,onClick:()=>{o(String(e.budget?.maxTokens??1e5)),c(String(e.budget?.maxConcurrent??2)),m(e=>!e)},children:`调整派发预算`})]}),p&&!v&&(0,H.jsxs)(`div`,{className:`project-form`,children:[(0,H.jsx)(`p`,{className:`project-muted`,"data-project-budget-basis-form":`1`,children:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`}),(0,H.jsxs)(`label`,{className:`project-field`,children:[(0,H.jsx)(`span`,{children:`Token 预算`}),(0,H.jsx)(`input`,{type:`number`,min:`1`,value:a,onChange:e=>o(e.target.value)})]}),(0,H.jsxs)(`label`,{className:`project-field`,children:[(0,H.jsx)(`span`,{children:`执行并发`}),(0,H.jsx)(`input`,{type:`number`,min:`1`,value:s,onChange:e=>c(e.target.value)})]}),(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void T(`budget`,{maxTokens:Number(a),maxConcurrent:Number(s)}),children:`保存预算`})]}),h?(0,H.jsx)(`p`,{className:`project-error`,role:`alert`,children:h}):null,(0,H.jsxs)(`details`,{className:`project-section`,open:!0,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`执行团队`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(0,H.jsx)(JD,{sessions:e.resources?.sessions,onOpenSession:r,emptyText:`该项目还没有会话。`})})]}),(0,H.jsxs)(`details`,{className:`project-section`,open:!0,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`任务流转`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(e.tasks??[]).length===0?(0,H.jsx)(`p`,{className:`project-muted`,children:`秘书尚未拆解任务。`}):(0,H.jsx)(`ol`,{className:`project-task-list`,children:(e.tasks??[]).map(t=>(0,H.jsxs)(`li`,{className:`project-task`,"data-project-task":t.id,children:[(0,H.jsxs)(`div`,{className:`project-task-main`,children:[(0,H.jsx)(`span`,{className:`project-task-title`,children:t.title}),(0,H.jsx)(`span`,{className:`project-status project-status-${t.status}`,children:qD(t.status)}),(0,H.jsx)(`span`,{className:`project-task-owner`,children:t.ownerRole||(t.ownerConversationId?`已分配`:`待定负责人`)})]}),(0,H.jsxs)(`p`,{children:[t.role===`leader`?`分支 Leader`:`执行任务`,t.parentTaskId?` · 上级任务:${(e.tasks??[]).find(e=>e.id===t.parentTaskId)?.title??t.parentTaskId}`:` · 项目负责人直属`]}),t.acceptanceCriteria?.length?(0,H.jsx)(`p`,{children:t.acceptanceCriteria.join(`;`)}):null,t.blockedReason&&(0,H.jsxs)(`p`,{className:`project-blocker`,children:[`阻塞:`,t.blockedReason]}),t.review?.lightweight?(0,H.jsx)(`span`,{className:`project-delivery-tag project-delivery-tag-self`,"data-project-task-delivery":t.id,children:`自评交付 · 无独立复核`}):t.review?.verdict===`accepted`?(0,H.jsx)(`span`,{className:`project-delivery-tag`,"data-project-task-delivery":t.id,children:`已验收`}):null,t.review&&!t.review.lightweight?(0,H.jsxs)(`p`,{children:[`复核:`,t.review.summary]}):null,t.status===`ready`&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void T(`tasks/${encodeURIComponent(t.id)}/dispatch`),children:`派发`}),t.status===`awaiting_review`&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void T(`tasks/${encodeURIComponent(t.id)}/review`),children:`独立复核`}),[`blocked`,`failed`,`in_progress`].includes(t.status)&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void T(`tasks/${encodeURIComponent(t.id)}`,{status:`ready`}),children:`恢复为待派发`})]},t.id))})})]}),_.length>0&&(0,H.jsxs)(`details`,{className:`project-section`,"data-project-exception-section":e.id,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsxs)(`h4`,{className:`project-section-title project-exception-heading`,"data-project-exception-heading":e.id,children:[`例外收件箱 `,(0,H.jsx)(`span`,{children:_.length})]})}),(0,H.jsxs)(`div`,{className:`project-section-body`,children:[(0,H.jsxs)(`label`,{className:`project-field`,children:[(0,H.jsx)(`span`,{children:`Boss 决策意见`}),(0,H.jsx)(`textarea`,{value:d,onChange:e=>f(e.target.value),placeholder:`明确决定、边界和后续动作`})]}),(0,H.jsx)(`ul`,{className:`project-exception-list`,children:_.map(e=>(0,H.jsxs)(`li`,{"data-project-exception":e.id,children:[(0,H.jsx)(`strong`,{children:e.reason||`需要处理`}),e.severity&&(0,H.jsxs)(`p`,{children:[`风险等级:`,e.severity]}),(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l||!d.trim(),onClick:()=>void T(`escalations/${encodeURIComponent(e.id)}`,{decision:d,status:`resolved`}),children:`记录决策并交回负责人`})]},e.id))})]})]}),(e.reports??[]).length>0&&(0,H.jsxs)(`details`,{className:`project-section`,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`最近汇报`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(0,H.jsx)(`div`,{className:`project-report-list`,children:(e.reports??[]).slice(0,3).map(e=>(0,H.jsxs)(`article`,{className:`project-report`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:e.summary||qD(e.kind)}),(0,H.jsx)(`span`,{children:XD(e.createdAt)})]}),e.progress&&(0,H.jsxs)(`p`,{children:[`进展:`,e.progress]}),e.decisionNeeded?(0,H.jsxs)(`p`,{children:[`待决策:`,e.decisionNeeded]}):null]},e.id))})})]}),(e.events??[]).length>0&&(0,H.jsxs)(`details`,{className:`project-section`,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`事件时间线`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(0,H.jsx)(`ul`,{className:`project-event-list`,children:(e.events??[]).slice(0,12).map(e=>(0,H.jsxs)(`li`,{"data-project-event":e.id,children:[(0,H.jsx)(`strong`,{children:e.summary}),(0,H.jsx)(`span`,{children:XD(e.createdAt)})]},e.id))})})]})]})}function sO({workspaceId:e,notify:t,onOpenSession:n}){let[r,i]=(0,V.useState)([]),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(``),[l,u]=(0,V.useState)([]),d=(0,V.useRef)(!1),[f,p]=(0,V.useState)([]),m=(0,V.useCallback)(async t=>{if(!e)i([]);else{o(!0),c(``);try{let n=await fetch(`/api/projects?workspaceId=${encodeURIComponent(e)}`,{signal:t}).then(ZD),r=Array.isArray(n)?n:Array.isArray(n.projects)?n.projects:[];i(r),!d.current&&r.length&&(d.current=!0,u([r[0].id]))}catch(e){e.name!==`AbortError`&&c(e instanceof Error?e.message:`项目列表加载失败`)}finally{t?.aborted||o(!1)}}},[e]);(0,V.useEffect)(()=>{let e=new AbortController;return m(e.signal),()=>e.abort()},[m]),(0,V.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>void m(),5e3);return()=>window.clearInterval(t)},[m,e]);let h=(0,V.useMemo)(()=>{let e=Date.now();return r.map(t=>iO(t,e)).filter(e=>!!e).filter(e=>!f.includes(`${e.projectId}:${e.kind}`)).sort((e,t)=>$D[e.kind]-$D[t.kind]||t.updatedAt-e.updatedAt)},[r,f]),g=(0,V.useMemo)(()=>h.slice(0,tO),[h]),_=h.length-g.length,[v,y]=(0,V.useState)(!1),b=v?h:g,x=(0,V.useRef)(null),[S,C]=(0,V.useState)(0),w=e=>{u(t=>t.includes(e.projectId)?t:[...t,e.projectId]),x.current={projectId:e.projectId,target:e.target},C(e=>e+1)};return(0,V.useEffect)(()=>{if(!S)return;let e=x.current;if(x.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)}else e.target.kind===`task`&&e.target.taskId&&(n=t.querySelector(`[data-project-task="${e.target.taskId}"]`));let r=n??t,i=window.requestAnimationFrame(()=>{r.scrollIntoView({block:e.target.kind===`top`?`start`:`center`,inline:`nearest`})});return()=>window.cancelAnimationFrame(i)},[S]),(0,H.jsxs)(`section`,{className:`project-panel`,"data-project-panel":`1`,children:[(0,H.jsx)(`div`,{className:`rail-section-head project-panel-head`,children:(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`项目控制面`}),(0,H.jsx)(`p`,{className:`project-panel-subtitle`,children:`一次触发,一次交付;这里只显示需要管理的流转和例外。`})]})}),h.length>0&&(0,H.jsxs)(`div`,{className:`project-pending`,"data-project-pending":`1`,"data-project-pending-count":h.length,children:[b.map(e=>(0,H.jsxs)(`div`,{className:`project-pending-item`,"data-project-pending-item":e.projectId,"data-project-pending-kind":e.kind,children:[(0,H.jsxs)(`div`,{className:`project-pending-row`,children:[(0,H.jsx)(`span`,{className:`project-pending-kind project-pending-kind-${e.kind}`,"data-project-pending-label":e.kind,children:e.label}),(0,H.jsx)(`span`,{className:`project-pending-title`,"data-project-pending-title":e.projectId,children:e.projectTitle}),(0,H.jsx)(`button`,{type:`button`,className:`project-pending-action`,"data-project-pending-action":e.projectId,onClick:()=>w(e),children:e.actionLabel}),(0,H.jsx)(`button`,{type:`button`,className:`project-pending-close`,"data-project-pending-dismiss":e.projectId,"aria-label":`关闭「${e.projectTitle}」的这条提醒`,title:`关闭这条提醒(不改变项目状态)`,onClick:()=>p(t=>[...t,`${e.projectId}:${e.kind}`]),children:`×`})]}),(0,H.jsx)(`p`,{className:`project-pending-detail`,"data-project-pending-detail":e.projectId,children:e.detail})]},`${e.projectId}:${e.kind}`)),_>0&&(0,H.jsx)(`button`,{type:`button`,className:`project-pending-more`,"data-project-pending-more":`1`,"aria-expanded":v,onClick:()=>y(e=>!e),children:v?`收起`:`还有 ${_} 个`})]}),(0,H.jsx)(`p`,{className:`project-empty-hint`,"data-project-empty-hint":`1`,children:`在对话里告诉 AI 你要做什么,它会创建项目、拆解任务并组织分工。项目会挂在这条会话下面。`}),s&&(0,H.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-error":`1`,children:s}),e?a&&r.length===0?(0,H.jsx)(`p`,{className:`rail-empty`,children:`正在加载项目…`}):r.length===0?(0,H.jsx)(`p`,{className:`rail-empty`,"data-project-empty":`1`,children:`当前没有项目。`}):(0,H.jsx)(H.Fragment,{children:(0,H.jsx)(`div`,{className:`project-list`,"data-project-count":r.length,children:r.map(r=>{let i=aO(r),a=l.includes(r.id);return(0,H.jsxs)(`details`,{className:`project-block`,"data-project-block":r.id,open:a,onToggle:e=>{let t=e.currentTarget.open;u(e=>e.includes(r.id)===t?e:t?[...e,r.id]:e.filter(e=>e!==r.id))},children:[(0,H.jsxs)(`summary`,{className:`project-block-summary`,"data-project-summary":r.id,"data-project-row":r.id,children:[(0,H.jsxs)(`span`,{className:`project-block-head`,children:[(0,H.jsx)(`span`,{className:`project-list-title`,children:r.title}),r.mode===`lightweight`?(0,H.jsx)(`span`,{className:`project-mode-tag`,"data-project-mode":`lightweight`,children:`轻量`}):null,(0,H.jsx)(`span`,{className:`project-status project-status-${r.status}`,children:qD(r.status)})]}),(0,H.jsxs)(`span`,{className:`project-block-progress`,"data-project-progress":r.id,children:[(0,H.jsxs)(`span`,{"data-project-progress-tasks":`${i.done}/${i.total}`,children:[`完成 `,i.done,`/`,i.total]}),(0,H.jsxs)(`span`,{"data-project-progress-workers":i.workers,children:[`进行中 `,i.workers]}),(0,H.jsxs)(`span`,{"data-project-progress-tokens":i.tokenText,children:[`Token `,i.tokenText]}),(0,H.jsx)(`span`,{"data-project-progress-updated":r.updatedAt??``,children:XD(r.updatedAt)||`暂无更新`})]})]}),(0,H.jsx)(oO,{project:r,workspaceId:e,notify:t,onOpenSession:n,onChanged:()=>void m()})]},r.id)})})}):(0,H.jsx)(`p`,{className:`rail-empty`,children:`请先选择工作区。`})]})}var cO=[{id:`overview`,glyph:`▣`,name:`项目总览`,description:`目标、状态和交付进度`},{id:`dependencies`,glyph:`⇢`,name:`依赖图`,description:`谁在等待谁`},{id:`responsibility`,glyph:`◎`,name:`责任查询`,description:`负责人、验收人与复核人`},{id:`exceptions`,glyph:`!`,name:`例外收件箱`,description:`阻塞、审批和风险`},{id:`evidence`,glyph:`✓`,name:`交付证据`,description:`产物、验证和引用`},{id:`resources`,glyph:`◫`,name:`资源护栏`,description:`Token、并发和容量`},{id:`timeline`,glyph:`≋`,name:`事件时间线`,description:`最近报告和状态变化`}],lO={planning:`待规划`,active:`执行中`,blocked:`已阻塞`,awaiting_approval:`等待审批`,awaiting_review:`待验收`,completed:`已完成`,failed:`失败`,cancelled:`已取消`,pending:`等待依赖`,ready:`待派发`,in_progress:`执行中`,running:`运行中`,idle:`空闲`,waiting:`排队中`,awaiting_background:`等待回传`,stopped:`已停止`,progress:`进展`,review:`复核`,delivery:`交付`,decision_request:`请求决策`},uO=e=>lO[e??``]??e??`未知`,dO=e=>{if(!e)return``;let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Math.max(0,Math.floor((Date.now()-t)/6e4));if(n<1)return`刚刚`;if(n<60)return`${n} 分钟前`;let r=Math.floor(n/60);return r<24?`${r} 小时前`:`${Math.floor(r/24)} 天前`};async function fO(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`查询失败(${e.status})`);return t}function pO(e){let t=e.tasks??[];return{total:t.length,done:t.filter(e=>e.status===`completed`).length,active:t.filter(e=>[`ready`,`in_progress`,`awaiting_review`].includes(e.status)).length,blocked:t.filter(e=>e.status===`blocked`).length,openEscalations:(e.escalations??[]).filter(e=>e.status===`open`).length}}function mO({tasks:e}){let t=new Map,n=(r,i=new Set)=>{if(t.has(r.id))return t.get(r.id);if(i.has(r.id))return 0;let a=new Set(i).add(r.id),o=Math.max(0,...[...r.dependencies??[],...r.parentTaskId?[r.parentTaskId]:[]].map(t=>{let r=e.find(e=>e.id===t);return r?n(r,a)+1:0}));return t.set(r.id,o),o},r=new Map,i=e.map(e=>{let t=n(e),i=r.get(t)??0;return r.set(t,i+1),{...e,x:i*190+10,y:t*100+10}}),a=Math.max(300,...i.map(e=>e.x+180)),o=Math.max(80,...i.map(e=>e.y+70));return(0,H.jsx)(`div`,{className:`tool-dependency-scroll`,tabIndex:0,"aria-label":`可滚动任务依赖图`,children:(0,H.jsxs)(`svg`,{width:a,height:o,role:`img`,"aria-label":`任务依赖图,箭头由前置任务指向后续任务`,children:[(0,H.jsx)(`title`,{children:`任务依赖图,完成独立验收后解锁下游`}),(0,H.jsx)(`defs`,{children:(0,H.jsx)(`marker`,{id:`project-dependency-arrow`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`})})}),i.flatMap(e=>(e.dependencies??[]).map(t=>{let n=i.find(e=>e.id===t);return n?(0,H.jsx)(`path`,{className:`tool-dependency-edge`,d:`M ${n.x+85} ${n.y+60} C ${n.x+85} ${n.y+80}, ${e.x+85} ${e.y-20}, ${e.x+85} ${e.y}`,markerEnd:`url(#project-dependency-arrow)`},`${t}:${e.id}`):null})),i.filter(e=>e.parentTaskId).map(e=>{let t=i.find(t=>t.id===e.parentTaskId);return t?(0,H.jsx)(`path`,{className:`tool-organization-edge`,d:`M ${t.x+85} ${t.y+60} L ${e.x+85} ${e.y}`,children:(0,H.jsxs)(`title`,{children:[t.title,` 管理 `,e.title]})},`org:${e.id}`):null}),i.map(e=>(0,H.jsxs)(`g`,{className:`tool-dependency-node tool-dependency-${e.status}`,children:[(0,H.jsxs)(`title`,{children:[e.title,`:`,uO(e.status)]}),(0,H.jsx)(`rect`,{x:e.x,y:e.y,width:`170`,height:`60`,rx:`7`}),(0,H.jsx)(`text`,{x:e.x+9,y:e.y+23,children:e.title.length>18?`${e.title.slice(0,17)}…`:e.title}),(0,H.jsx)(`text`,{x:e.x+9,y:e.y+44,children:uO(e.status)})]},e.id))]})})}function hO({workspaceId:e,onOpenSession:t}){let[n,r]=(0,V.useState)([]),[i,a]=(0,V.useState)(),[o,s]=(0,V.useState)(`overview`),[c,l]=(0,V.useState)(``),[u,d]=(0,V.useState)(``),[f,p]=(0,V.useState)(``),m=(0,V.useCallback)(async t=>{if(!e)r([]);else try{let n=await fetch(`/api/projects?workspaceId=${encodeURIComponent(e)}`,{signal:t}).then(fO),i=Array.isArray(n?.projects)?n.projects:[];r(i),a(e=>e&&i.some(t=>t.id===e)?e:i[0]?.id),l(``)}catch(e){e.name!==`AbortError`&&l(e instanceof Error?e.message:`项目查询失败`)}},[e]);(0,V.useEffect)(()=>{let e=new AbortController;return m(e.signal),()=>e.abort()},[m]),(0,V.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>void m(),5e3);return()=>window.clearInterval(t)},[m,e]);let h=(0,V.useMemo)(()=>n.find(e=>e.id===i),[n,i]),g=h?.tasks??[],_=e=>h?.resources?.sessions.find(t=>t.id===e)?.title??e??`待分配`,v=e=>e&&t?(0,H.jsx)(`button`,{type:`button`,className:`tool-session-link`,onClick:()=>t(e),children:_(e)}):_(e),y=e=>e.toLocaleLowerCase().includes(u.trim().toLocaleLowerCase()),b=e=>WD(UD(e.effectiveExecutorProfile,e.executorProfile,h?.defaultExecutorProfile)),x=e=>WD(UD(e.effectiveReviewerProfile,e.reviewerProfile,h?.defaultReviewerProfile)),S=g.filter(e=>(!f||e.status===f)&&y([e.title,e.output,e.blockedReason,_(e.ownerConversationId),_(e.reviewerConversationId),b(e),x(e),...e.evidenceRefs??[],e.review?.summary,e.review?.verdict===`accepted`?`通过`:e.review?.verdict===`changes_requested`?`返工`:``,...e.review?.evidenceRefs??[]].filter(Boolean).join(` `))),C=h?pO(h):void 0,w=(h?.escalations??[]).filter(e=>e.status===`open`).filter(e=>{let t=e.taskId?g.find(t=>t.id===e.taskId):void 0;return y([e.reason,e.decision,e.severity,t?.title,e.taskId,_(e.requestedByConversationId)].filter(Boolean).join(` `))}),T=g.filter(e=>e.status===`blocked`).filter(e=>y([e.title,e.blockedReason,_(e.ownerConversationId),_(e.reviewerConversationId)].filter(Boolean).join(` `))),E=S.flatMap(e=>[...(e.evidenceRefs??[]).map(t=>({label:e.title,value:t,type:`引用`})),...e.output?[{label:e.title,value:e.output,type:`交付物`}]:[],...e.review?[{label:e.title,value:`${e.review.verdict===`accepted`?`通过`:`返工`}:${e.review.summary}`,type:`独立复核`},...e.review.evidenceRefs.map(t=>({label:e.title,value:t,type:`验证引用`}))]:[]]).filter(e=>y([e.label,e.value,e.type].join(` `)));return(0,H.jsxs)(`section`,{className:`tool-execution`,"data-tool-execution":`1`,children:[(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`企业执行工具`}),(0,H.jsx)(`p`,{className:`tool-execution-subtitle`,children:`只读查询项目状态、责任、依赖、证据和例外。`})]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-execution-refresh`,onClick:()=>void m(),disabled:!e,children:`刷新`})]}),c&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-execution-error":`1`,children:c}),n.length>0&&(0,H.jsxs)(`label`,{className:`tool-execution-project`,children:[(0,H.jsx)(`span`,{children:`当前项目`}),(0,H.jsx)(`select`,{value:i??``,onChange:e=>a(e.target.value),children:n.map(e=>(0,H.jsxs)(`option`,{value:e.id,children:[e.title,` · `,uO(e.status)]},e.id))})]}),(0,H.jsx)(`div`,{className:`tool-execution-grid`,role:`tablist`,"aria-label":`企业执行查询工具`,children:cO.map(e=>(0,H.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===e.id,className:`tool-execution-tile${o===e.id?` tool-execution-tile-active`:``}`,"data-exec-tool":e.id,onClick:()=>s(e.id),children:[(0,H.jsx)(`span`,{className:`tool-execution-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.jsx)(`small`,{children:e.description})]})]},e.id))}),h&&(0,H.jsxs)(`div`,{className:`tool-execution-query`,children:[(0,H.jsxs)(`label`,{children:[`搜索任务、负责人、复核或例外`,(0,H.jsx)(`input`,{type:`search`,value:u,onChange:e=>d(e.target.value)})]}),[`dependencies`,`responsibility`,`evidence`].includes(o)&&(0,H.jsxs)(`label`,{children:[`任务状态`,(0,H.jsxs)(`select`,{value:f,onChange:e=>p(e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`全部状态`}),[`pending`,`ready`,`in_progress`,`awaiting_review`,`blocked`,`completed`,`failed`].map(e=>(0,H.jsx)(`option`,{value:e,children:uO(e)},e))]})]})]}),(0,H.jsx)(`div`,{className:`tool-execution-body`,role:`tabpanel`,"data-exec-tool-body":o,children:(()=>{if(!h)return(0,H.jsx)(`p`,{className:`tool-execution-empty`,children:`当前工作区还没有项目。先在「项目」tab 触发一个项目。`});if(o===`overview`)return(0,H.jsxs)(`div`,{className:`tool-execution-overview`,children:[(0,H.jsx)(`p`,{className:`tool-execution-objective`,children:h.objective}),(0,H.jsxs)(`div`,{className:`tool-execution-metrics`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`strong`,{children:[C?.done??0,`/`,C?.total??0]}),(0,H.jsx)(`span`,{children:`任务完成`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:C?.active??0}),(0,H.jsx)(`span`,{children:`进行中`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:C?.blocked??0}),(0,H.jsx)(`span`,{children:`已阻塞`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:C?.openEscalations??0}),(0,H.jsx)(`span`,{children:`待处理例外`})]})]}),(0,H.jsxs)(`p`,{className:`tool-execution-note`,children:[`项目状态:`,(0,H.jsx)(`b`,{children:uO(h.status)}),` · 风险:`,(0,H.jsx)(`b`,{children:h.risk}),` · 更新:`,dO(h.updatedAt)||`暂无`]})]});if(o===`dependencies`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`tool-execution-note`,children:`实线箭头:前置交付依赖;虚线:直属管理关系。前置任务验收通过后才能开始后续任务。`}),g.length>0&&(0,H.jsx)(mO,{tasks:g}),(0,H.jsx)(`ol`,{className:`tool-execution-list`,children:S.length===0?(0,H.jsx)(`li`,{children:`暂无匹配任务。`}):S.map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:e.title}),(0,H.jsx)(`span`,{className:`tool-execution-status`,children:uO(e.status)}),(0,H.jsx)(`small`,{children:e.dependencies?.length?`等待:${e.dependencies.map(e=>g.find(t=>t.id===e)?.title??e).join(`、`)}`:`无前置依赖`}),e.parentTaskId&&(0,H.jsxs)(`small`,{children:[`直属上级任务:`,g.find(t=>t.id===e.parentTaskId)?.title]})]},e.id))})]});if(o===`responsibility`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`p`,{className:`tool-execution-note`,children:[`项目负责人:`,v(h.ownerConversationId)]}),(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:S.length===0?(0,H.jsx)(`li`,{children:`暂无匹配的责任分配。`}):S.map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsxs)(`strong`,{children:[e.title,` · `,e.role===`leader`?`分支 Leader`:`执行任务`]}),(0,H.jsxs)(`small`,{children:[`执行:`,v(e.ownerConversationId)]}),(0,H.jsxs)(`small`,{children:[`最终负责:`,v(e.accountableConversationId)]}),(0,H.jsxs)(`small`,{children:[`独立复核:`,v(e.reviewerConversationId)]}),(0,H.jsxs)(`small`,{className:`tool-task-employee`,"data-task-employee":`executor`,children:[`执行员工:`,WD(UD(e.effectiveExecutorProfile,e.executorProfile,h.defaultExecutorProfile))||`未指定`]}),(0,H.jsxs)(`small`,{className:`tool-task-employee`,"data-task-employee":`reviewer`,children:[`复核员工:`,WD(UD(e.effectiveReviewerProfile,e.reviewerProfile,h.defaultReviewerProfile))||`未指定`]}),e.parentTaskId&&(0,H.jsxs)(`small`,{children:[`上级任务:`,g.find(t=>t.id===e.parentTaskId)?.title]})]},e.id))})]});if(o===`exceptions`)return(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:w.length===0&&T.length===0?(0,H.jsx)(`li`,{children:u.trim()?`暂无匹配的例外事项。`:`当前没有需要 Boss 处理的例外。`}):(0,H.jsxs)(H.Fragment,{children:[w.map(e=>(0,H.jsxs)(`li`,{className:`tool-execution-exception`,children:[(0,H.jsx)(`strong`,{children:e.reason}),(0,H.jsxs)(`span`,{children:[e.severity,` · 待处理`]}),(0,H.jsx)(`small`,{children:e.taskId?g.find(t=>t.id===e.taskId)?.title??e.taskId:`项目级事项`})]},e.id)),T.map(e=>(0,H.jsxs)(`li`,{className:`tool-execution-exception`,children:[(0,H.jsx)(`strong`,{children:e.title}),(0,H.jsx)(`span`,{children:`任务阻塞`}),(0,H.jsx)(`small`,{children:e.blockedReason??`执行者未提供原因`})]},e.id))]})});if(o===`evidence`)return(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:E.length===0?(0,H.jsx)(`li`,{children:`暂无交付证据。任务完成时应附上产物或验证引用。`}):E.map((e,t)=>(0,H.jsxs)(`li`,{children:[(0,H.jsxs)(`strong`,{children:[e.type,` · `,e.label]}),(0,H.jsx)(`small`,{children:e.value})]},`${e.label}:${e.value}:${t}`))});if(o===`resources`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`tool-execution-resource`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`strong`,{children:[h.resources?.tokens.toLocaleString()??`0`,` / `,h.budget?.maxTokens?.toLocaleString()??`未设限`]}),(0,H.jsx)(`span`,{children:`已报告 Token / 派发预算`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`strong`,{children:[h.resources?.activeWorkers??0,` / `,h.budget?.maxConcurrent??`未设限`]}),(0,H.jsx)(`span`,{children:`运行中执行者 / 并发上限`})]}),(0,H.jsxs)(`p`,{children:[`负责人保留独立协调容量。达到预算或并发上限时拒绝新派发;运行中的请求可能超过预算。`,!h.resources?.usageKnown&&`部分用量尚未上报,显示已知用量。`]}),(0,H.jsx)(`p`,{className:`project-muted`,"data-tool-budget-basis":`1`,children:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`})]}),(0,H.jsx)(JD,{sessions:h.resources?.sessions.filter(e=>y(e.title)),onOpenSession:t,emptyText:u.trim()?`没有匹配的会话。`:`该项目还没有会话。`})]});let e=[...h.events??[]].filter(e=>y(e.summary)).sort((e,t)=>Date.parse(t.createdAt)-Date.parse(e.createdAt));return(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:e.length===0?(0,H.jsx)(`li`,{children:`暂无匹配事件。`}):e.map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:e.summary}),(0,H.jsxs)(`small`,{children:[dO(e.createdAt),e.taskId?` · ${g.find(t=>t.id===e.taskId)?.title??e.taskId}`:``]})]},e.id))})})()})]})}function gO(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function _O(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}var vO=(e,t)=>e.updatedAt<t.updatedAt?1:e.updatedAt>t.updatedAt?-1:0;function yO(e,t){let n=new Set(e.map(e=>e.id)),r=new Map,i=[];for(let t of e){let e=t.parentConversationId;if(e&&n.has(e)){let n=r.get(e);n?n.push(t):r.set(e,[t])}else i.push(t)}for(let e of r.values())e.sort(vO);i.sort(vO);let a=[],o=new Set,s=(e,n,i,c=!0)=>{if(o.has(e.id))return;o.add(e.id);let l=r.get(e.id)??[];c&&a.push({conversation:e,depth:Math.min(n,8),childCount:l.length,isLastSibling:i});let u=!c||t.has(e.id);for(let[e,t]of l.entries())s(t,n+1,e===l.length-1,!u)};for(let e of i)s(e,0,!1);let c=e.filter(e=>!o.has(e.id)).sort(vO);for(let e of c)s(e,0,!1);return a}var bO=`super-pi:tool-shortcuts:v1`,xO=new Set([`Control`,`Alt`,`Shift`,`Meta`,`AltGraph`,`CapsLock`,`Fn`,`FnLock`,`Hyper`,`Super`,`Symbol`,`SymbolLock`]),SO=new Set([`Escape`]),CO=new Set([`Enter`,` `,`Tab`]),wO={" ":`Space`,ArrowUp:`↑`,ArrowDown:`↓`,ArrowLeft:`←`,ArrowRight:`→`,Escape:`Esc`},TO={ctrl:`⌃`,alt:`⌥`,shift:`⇧`,meta:`⌘`};function EO(e){if(e===` `)return` `;let t=e.trim();return t?t.length===1?t.toLowerCase():t:``}function DO(e){return xO.has(e)}function OO(e){let t=e.key;if(!t||t===`Unidentified`||t===`Dead`||DO(t))return;let n=EO(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 kO(e){return wO[e]||(e.length===1||/^f\d{1,2}$/.test(e)?e.toUpperCase():e)}function AO(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(kO(e.key)),t.join(`+`)}function jO(e){let t=``;return e.ctrl&&(t+=TO.ctrl),e.alt&&(t+=TO.alt),e.shift&&(t+=TO.shift),e.meta&&(t+=TO.meta),t+kO(e.key)}function MO(e,t){return e.key===t.key&&!!e.ctrl==!!t.ctrl&&!!e.alt==!!t.alt&&!!e.shift==!!t.shift&&!!e.meta==!!t.meta}function NO(e){return!!(e.ctrl||e.alt||e.shift||e.meta)}function PO(e){return e.key?SO.has(e.key)?{ok:!1,reason:`Esc 是所有弹窗的退出键,不能拿来当工具快捷键。`}:!NO(e)&&CO.has(e.key)?{ok:!1,reason:`「${FO(e.key)}」是当前焦点控件的激活键,加一个修饰键(Ctrl / Alt / Shift)才能当快捷键用。`}:{ok:!0}:{ok:!1,reason:`这个组合键不完整,请按一个具体的键。`}}function FO(e){return kO(e)}function IO(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 LO(e,t){if(t.isComposing||t.defaultPrevented)return!1;let n=OO(t);return!(!n||!MO(e,n)||!NO(e)&&IO(t.target??null))}function RO(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=EO(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),PO(a).ok&&(n[e]=a)}return n}function zO(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 BO(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&MO(i,t))return r}var VO=`super-pi:tool-settings-size:v1`,HO={width:480,height:320};function UO(){try{if(typeof window>`u`)return vv.slice();let e=wv(window.localStorage.getItem(xv));return window.localStorage.getItem(`super-pi:tools:v1`)===null?vv.slice():e}catch{return vv.slice()}}function WO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(xv,Tv(e))}catch{}}function GO(){try{return typeof window>`u`?{}:RO(window.localStorage.getItem(bO))}catch{return{}}}function KO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(bO,zO(e))}catch{}}function qO(){try{if(typeof window>`u`)return;let e=window.localStorage.getItem(VO);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<HO.width||t.height<HO.height?void 0:{width:Math.round(t.width),height:Math.round(t.height)}}catch{return}}function JO(e){try{if(typeof window>`u`)return;e?window.localStorage.setItem(VO,JSON.stringify({width:Math.round(e.width),height:Math.round(e.height)})):window.localStorage.removeItem(VO)}catch{}}function YO(e,t,n){let r=Math.max(HO.width,t-32),i=Math.max(HO.height,n-32);return{width:Math.round(Math.min(Math.max(e.width,HO.width),r)),height:Math.round(Math.min(Math.max(e.height,HO.height),i))}}var XO={tools:UO(),mountedTools:[],settingsOpen:!1,shortcuts:GO()},ZO=new Set;function QO(e){XO={...XO,...e};for(let e of ZO)e()}function $O(e){return ZO.add(e),()=>{ZO.delete(e)}}var ek=()=>XO;function tk(){return(0,V.useSyncExternalStore)($O,ek,ek)}var nk={setTools(e){WO(e),QO({tools:e})},removeTool(e){let t=kv(XO.tools,e);if(XO.shortcuts[e]){let t={...XO.shortcuts};delete t[e],KO(t),QO({shortcuts:t})}WO(t),QO({tools:t,openToolId:XO.openToolId===e?void 0:XO.openToolId})},setMountedTools(e){QO({mountedTools:e})},openTool(e){QO({openToolId:e,settingsOpen:!1})},closeTool(){QO({openToolId:void 0})},toggleTool(e){XO.openToolId===e?nk.closeTool():nk.openTool(e)},openSettings(){QO({settingsOpen:!0,openToolId:void 0})},closeSettings(){QO({settingsOpen:!1})},setShortcut(e,t){let n={...XO.shortcuts,[e]:t};KO(n),QO({shortcuts:n})},clearShortcut(e){if(!XO.shortcuts[e])return;let t={...XO.shortcuts};delete t[e],KO(t),QO({shortcuts:t})},persistTools(){WO(XO.tools)}};async function rk(){try{let e=await fetch(`/api/tools`),t=await e.json();e.ok&&Array.isArray(t.tools)&&nk.setMountedTools(t.tools.filter(e=>e.enabled))}catch{}}async function ik(e){try{let t=await fetch(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);nk.closeTool(),await rk();return}catch(e){return e instanceof Error?e.message:String(e)}}var ak=`.super-pi-tool.json`,ok=512e3,sk=/^[a-z0-9][a-z0-9-]{0,63}$/,ck=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function lk(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${ak})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i=typeof r.format==`string`?r.format:void 0;if(i!==void 0&&i!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${i})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let a=typeof r.slug==`string`?r.slug.trim():``,o=typeof r.name==`string`?r.name.trim():``;if(!a)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!o)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 s=[],c=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(s.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(c+=new TextEncoder().encode(t.content).length,c>512e3)return{ok:!1,reason:`工具文件合计超过 ${_k(ok)} 的上限。`};s.push({path:n,content:t.content})}let l=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!l.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!s.some(e=>e.path===l))return{ok:!1,reason:`工具包里没有包含入口文件 ${l}。`};let u;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(!s.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};u={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let d;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`||!ck.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;d={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let f=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:i===void 0,bundle:{...i===void 0?{}:{format:i},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:a,name:o,...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:l,files:s,script:u,environment:d,...f?{permissions:f}:{}}}}function uk(e){let t=e.trim().toLowerCase();return t?sk.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function dk(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 fk(e){return`${e.slug}${ak}`}function pk(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}${ak}`}:{ok:!1,reason:`请填写文件名。`}}function mk(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function hk(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 gk(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 _k(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function vk(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var yk={workspaces:[],conversations:[],subagentRuns:[]},bk=e=>e.nativeEvent.isComposing||e.keyCode===229,xk=(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},Sk=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)},Ck=6e4,wk=60*Ck,Tk=24*wk,Ek=7*Tk,Dk=30*Tk,Ok=365*Tk,kk=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<wk?`${Math.max(1,Math.floor(r/Ck))}m ago`:r<Tk?`${Math.floor(r/wk)}h ago`:r<Ek?`${Math.floor(r/Tk)}d ago`:r<Dk?`${Math.floor(r/Ek)}w ago`:r<Ok?`${Math.floor(r/Dk)}mo ago`:`${Math.floor(r/Ok)}y ago`},Ak=(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},jk=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`)}`},Mk=1e3,Nk=3e4,Pk=async e=>{try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0;pointer-events:none`,document.body.appendChild(t);try{return t.select(),t.setSelectionRange(0,t.value.length),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}};function Fk({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,V.useRef)(null),[o,s]=(0,V.useState)({left:t,top:n});(0,V.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,V.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 Pk(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,H.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,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,H.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function Ik({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a,sendCommand:o,orchestrated:s,childCount:c}){let l=(0,V.useRef)(null),[u,d]=(0,V.useState)({left:t,top:n});(0,V.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let r=e.getBoundingClientRect();d({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,V.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 f=async e=>{try{let t=await fetch(`/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(`停止失败:${tp(e)}`,`error`)}},p=async e=>{try{let t=await fetch(`/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(`停止子树失败:${tp(e)}`,`error`)}},m=async()=>{let t=await Pk(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,H.jsxs)(`div`,{ref:l,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:u.left,top:u.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void m(),children:`复制会话 ID`}),(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),(0,H.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,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-queue":e.id,onClick:()=>{a(),f(e.id)},children:`停止会话(含排队消息)`}),c>0&&(0,H.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-tree":e.id,onClick:()=>{a(),p(e.id)},children:[`停止整棵子树(`,c,` 个下属)`]}),(0,H.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var Lk={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},Rk=`请从刚才被截断的地方接着写完,不要重复已经写过的内容。`,zk={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},Bk={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},Vk=`图文`,Hk=e=>e.imageInput?Vk:void 0,Uk=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),Wk=(e,t)=>{let n=Uk(t.trim());return n?e.filter(e=>Uk(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function Gk({workspaceId:e,value:t,onChange:n}){let[r,i]=(0,V.useState)([]),[a,o]=(0,V.useState)(``);(0,V.useEffect)(()=>{i([]),o(``)},[e]),(0,V.useEffect)(()=>{let n=!0;return o(``),fetch(`/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,H.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,H.jsx)(`label`,{htmlFor:`empty-session-cwd`,children:`工作目录:`}),(0,H.jsxs)(`select`,{id:`empty-session-cwd`,"data-session-cwd-select":`1`,"aria-label":`会话工作目录(可选)`,value:t,onChange:e=>n(e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`工作区根目录`}),s.map(e=>(0,H.jsx)(`option`,{value:e,children:e},e))]}),a&&(0,H.jsx)(`span`,{role:`status`,children:a})]})}function Kk({workspace:e,onClose:t,onCreate:n}){let[r,i]=(0,V.useState)(``),a=(0,V.useRef)(null);return(0,V.useEffect)(()=>{i(``)},[e.id]),(0,V.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,H.jsx)(`div`,{className:`overlay session-create-overlay`,onClick:t,children:(0,H.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,H.jsx)(`h2`,{id:`session-create-title`,children:`新建会话`}),(0,H.jsxs)(`p`,{className:`session-create-workspace`,children:[`工作区:`,e.name,(0,H.jsx)(`small`,{children:e.path})]}),(0,H.jsx)(Gk,{workspaceId:e.id,value:r,onChange:i}),(0,H.jsxs)(`div`,{className:`session-create-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`session-create-cancel`,onClick:t,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`session-create-confirm picker-ok`,onClick:()=>n(r),children:`创建会话`})]})]})})}function qk({onClose:e,onCreate:t}){let[n,r]=(0,V.useState)(),[i,a]=(0,V.useState)(!0),[o,s]=(0,V.useState)(),[c,l]=(0,V.useState)(``),[u,d]=(0,V.useState)(``),f=async e=>{a(!0),s(void 0);try{let t=await fetch(`/api/fs/dirs${e?`?path=${encodeURIComponent(e)}`:``}`),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let i=n;r(i),d(i.path),l(i.suggestedName)}catch(e){s(e instanceof Error?e.message:`目录加载失败`)}finally{a(!1)}};(0,V.useEffect)(()=>{f()},[]),(0,V.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let p=e=>{e?.preventDefault();let t=u.trim();t&&f(t)};return(0,H.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,H.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`h2`,{children:`选择工作区目录`}),(0,H.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:p,children:[(0,H.jsx)(`input`,{className:`picker-path-input`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(bk(e)?e.preventDefault():(e.preventDefault(),p()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,H.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!u.trim()||i,children:`跳转`}),(0,H.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!n?.parent||i,onClick:()=>n?.parent&&void f(n.parent),title:`返回上一级目录`,children:`上一级`})]}),n?.drives?.length||n?.homeDir?(0,H.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,H.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),n?.homeDir&&(0,H.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(`~`),title:n.homeDir,children:`🏠 主目录`}),n?.drives?.map(e=>(0,H.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(e),children:e},e))]}):null,(0,H.jsxs)(`div`,{className:`picker-list`,children:[i&&(0,H.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!i&&o&&(0,H.jsxs)(`div`,{className:`picker-error`,children:[o,(0,H.jsx)(`button`,{onClick:()=>void f(n?.path||u),children:`重试`})]}),!i&&!o&&n?.entries.map(e=>(0,H.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void f(e.path),children:[`📁 `,e.name]},e.path)),!i&&!o&&n&&n.entries.length===0&&(0,H.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!i&&!o&&n?.truncated&&(0,H.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,H.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,H.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(bk(e)?e.preventDefault():(e.preventDefault(),c.trim()&&n&&t(c.trim(),n.path)))},placeholder:`工作区名称`})]}),(0,H.jsxs)(`div`,{className:`picker-actions`,children:[(0,H.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,H.jsx)(`button`,{className:`picker-ok`,disabled:!c.trim()||i||!!o||!n,onClick:()=>n&&t(c.trim(),n.path),children:`使用这个目录`})]})]})})}var Jk={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},Yk=10;function Xk(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(`
93
- `).find(e=>e.trim().startsWith(`-`))?.trim()??`详情见设置`}`;if(e===`模型`&&n)return`此会话已包含图片,仅显示支持图文的模型`}function Zk(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 Qk=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function $k(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 eA={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function tA(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 nA({task:e,initialOutput:t,expanded:n}){let[r,i]=(0,V.useState)(t);(0,V.useEffect)(()=>{let n=t,r,a=t=>{let a=t.detail;a.sessionId===e.id&&(n=(n+a.data).slice(-512e3),r===void 0&&(r=requestAnimationFrame(()=>{r=void 0,i(n)})))};return window.addEventListener(`super-pi-exec-output`,a),()=>{window.removeEventListener(`super-pi-exec-output`,a),r!==void 0&&cancelAnimationFrame(r)}},[e.id]);let a=e.output??r;return(0,H.jsxs)(H.Fragment,{children:[!n&&a&&(0,H.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:tA(a)}),n&&(0,H.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:a||`等待输出…`})]})}function rA({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,H.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,H.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,H.jsxs)(`div`,{className:`call-head-row`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,H.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,H.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,H.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,H.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,H.jsx)(`span`,{className:`call-duration`,children:$k(e.durationMs)}),e.backgroundTask&&(0,H.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,e.backgroundTask.status===`running`?`运行中`:e.backgroundTask.status===`completed`?`已完成`:`失败`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,H.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,H.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,H.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:tA(e.live)}),n&&(0,H.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,H.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,H.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,H.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,H.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,H.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,H.jsxs)(`div`,{className:`call-result-head`,children:[(0,H.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,H.jsx)(iA,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,H.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,H.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,H.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function iA({index:e,text:t}){let[n,r]=(0,V.useState)(!1);return(0,H.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await Pk(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function aA({messageId:e,nestedCount:t,liveCall:n,liveAwaitingReader:r,liveExtra:i,preview:a,expanded:o,onToggle:s,children:c}){return(0,H.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":o?`true`:`false`,"data-thinking-calls":t,children:[(0,H.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":o,"aria-label":`${o?`折叠`:`展开`}这段思考`,title:o?`折叠这段思考`:`展开这段思考`,onClick:s}),(0,H.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":o,title:o?`折叠这段思考`:`展开这段思考`,onClick:s,children:[(0,H.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`}),(0,H.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,H.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!o&&n&&(0,H.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,H.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:r?`?`:`⚙`}),r?`等你回答`:`正在执行 ${n}`,i?` 等 ${i+1} 个`:``]}),!o&&a&&(0,H.jsx)(`span`,{className:`thinking-preview`,title:a,children:a})]}),o&&(0,H.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:c})]})}function oA({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`,u=e.output??``,d=e.dispatchedBy===`model`,[f,p]=(0,V.useState)(0);(0,V.useEffect)(()=>{if(!l)return;p(Date.now());let e=window.setInterval(()=>p(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let m=Date.parse(e.startedAt),h=l&&f>0&&Number.isFinite(m)?f-m:void 0,g=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,H.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${d?` 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":d?`model`:`human`,children:[(0,H.jsxs)(`div`,{className:`subagent-head`,children:[(0,H.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,H.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,H.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,H.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,H.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?h!==void 0&&(0,H.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":h,children:[`已运行 `,$k(h)]}):e.durationMs!==void 0&&(0,H.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,$k(e.durationMs)]}),l&&(0,H.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,H.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,H.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,H.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,H.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,H.jsx)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:u||(l?`…`:e.outputTruncated?`(已按 50 KB 上限截断,浏览器仍收到完整内容)`:`(没有输出)`)}),e.failure&&(0,H.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,H.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,H.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:eA[e.failure.stage]}),e.failure.stage===`tool`&&g&&(0,H.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,g]}),o.length>0&&(0,H.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,H.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,title:np(e.error),children:tp(e.error,`这条子任务没有完成。`)}),o.length>0&&(0,H.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,H.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,H.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,H.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,H.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,H.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,H.jsx)(`span`,{className:`subagent-tool-duration`,children:$k(e.durationMs)})]},`${t}:${e.label}`))]}),e.usage&&(0,H.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,H.jsxs)(`span`,{children:[e.usage.turns,` 轮`]}),(0,H.jsxs)(`span`,{title:`输入 token`,children:[`↑`,Qk(e.usage.input)]}),(0,H.jsxs)(`span`,{title:`输出 token`,children:[`↓`,Qk(e.usage.output)]}),e.usage.cacheRead>0&&(0,H.jsxs)(`span`,{title:`缓存读取`,children:[`缓存读 `,Qk(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,H.jsxs)(`span`,{title:`缓存写入`,children:[`缓存写 `,Qk(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,H.jsxs)(`span`,{title:`本轮花费`,children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,H.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function sA({messages:e,running:t,pendingInterrupts:n=[],onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:s}){let[c,l]=(0,V.useState)(!1);if(!e.length)return null;let u=e.filter(e=>e.delivery===`sending`).length;return(0,H.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-interrupt-pending":n.length,"data-queue-count":e.length,"data-queue-sending":u,"aria-label":`排队等待回答的消息`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!c,onClick:()=>l(e=>!e),children:[(0,H.jsx)(`span`,{className:`chevron`,children:c?`▸`:`▾`}),(0,H.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),u>0&&(0,H.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,u,` 条`]}),c&&(0,H.jsx)(`span`,{className:`queue-dock-preview`,children:cA(e[0])})]}),!c&&(0,H.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((c,l)=>(0,H.jsx)(uA,{message:c,order:l+1,total:e.length,interrupting:n.includes(c.id),running:t,onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:s},c.id))})]})}function cA(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function lA(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};if(!/<task id="[^"]+" state="[^"]+"/.test(e.content))return{label:(e.content.split(`
94
- `).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 uA({message:e,order:t,total:n,running:r,interrupting:i=!1,onSteer:a,onInterrupt:o,onSend:s,onCancel:c,onEdit:l}){let[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(e.content),m=e.delivery===`sending`,h=e.role===`tool`,{label:g,state:_}=h?lA(e):{label:cA(e),state:`user`},v=()=>{let t=f.trim();t&&t!==e.content&&l(e.id,t),d(!1)};return(0,H.jsxs)(`li`,{className:`queue-row ${m?`queue-row-sending`:`queue-row-queued`} ${h?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":h?_:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[(0,H.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),h?(0,H.jsxs)(`span`,{className:`queue-bg-result`,title:g,children:[(0,H.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:_===`error`?`✕`:`↩`}),(0,H.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,H.jsx)(`span`,{className:`bg-result-summary`,children:g})]}):u?(0,H.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,H.jsx)(`textarea`,{value:f,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>p(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),p(e.content),d(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),v())}}),(0,H.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:v,children:`保存`}),(0,H.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{p(e.content),d(!1)},children:`取消`})]}):(0,H.jsx)(`span`,{className:`queue-text`,title:g,children:g}),(0,H.jsx)(`span`,{className:`queue-state`,"data-waiting-state":m?`sending`:`queued`,children:m?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),m?(0,H.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,H.jsxs)(H.Fragment,{children:[r?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,disabled:i,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${g}」`,onClick:()=>o(e.id),children:i?`◌ 打断中…`:`打断并回答`}),(0,H.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${g}」`:`让「${g}」插到最前`,onClick:()=>a(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,H.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${g}」`,onClick:()=>s(e.id),children:`现在就回答`}),!h&&(0,H.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${g}」`,onClick:()=>{p(e.content),d(!0)},children:`改字`}),(0,H.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${g}」`,onClick:()=>c(e.id),children:`撤回`})]})]})}function dA({question:e,index:t,expanded:n,onToggle:r,onAnswer:i}){return(0,H.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,H.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:r}),(0,H.jsxs)(`div`,{className:`call-head-row`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,H.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,H.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,H.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,H.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,H.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),n&&(0,H.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,H.jsx)(fA,{question:e,onAnswer:i})})]})}function fA({question:e,onAnswer:t}){let[n,r]=(0,V.useState)(()=>Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected]))),[i,a]=(0,V.useState)(()=>e.answers?.map(e=>e.note??``).join(`
95
- `)??``),o=(e,t,n)=>{r(r=>{let i=r[e]??[];return n?{...r,[e]:i.includes(t)?i.filter(e=>e!==t):[...i,t]}:{...r,[e]:[t]}})},s=()=>{t(e.items.map(e=>({id:e.id,selected:n[e.id]??[],...e.extraNote&&i.trim()?{note:i.trim()}:{}})),!1)},c=e.items.some(e=>(n[e.id]??[]).length>0);return(0,H.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(t=>(0,H.jsxs)(`div`,{className:`question-item`,children:[(0,H.jsx)(`div`,{className:`question-text`,children:t.header?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`question-header`,children:t.header}),(0,H.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,H.jsx)(Am,{source:t.question})]}):(0,H.jsx)(Am,{source:t.question})}),(0,H.jsx)(`div`,{className:`question-options`,"data-question-options":t.id,children:t.options.map(r=>{let i=(n[t.id]??[]).includes(r),a=e.status!==`pending`;return(0,H.jsxs)(`label`,{className:i?`is-chosen`:``,"data-chosen":a&&i?`1`:void 0,children:[(0,H.jsx)(`input`,{type:t.multiple?`checkbox`:`radio`,name:`q-${t.id}`,checked:i,disabled:a,onChange:()=>o(t.id,r,t.multiple)}),(0,H.jsx)(jm,{source:r}),a&&i?(0,H.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},r)})}),e.status===`pending`&&t.extraNote?(0,H.jsx)(`textarea`,{value:i,placeholder:`补充说明(可选)`,onChange:e=>a(e.target.value)}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,H.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,H.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},t.id)),e.status===`pending`&&(0,H.jsxs)(`div`,{className:`question-actions`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:s,disabled:!c,children:`提交`}),(0,H.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>t([],!0),children:`跳过`})]})]})}function pA({request:e,onAnswer:t,pending:n}){let[r,i]=(0,V.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,H.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,H.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,H.jsxs)(`div`,{className:`extui-head`,children:[(0,H.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,H.jsxs)(`span`,{className:`extui-deadline`,children:[Math.round(e.timeoutMs/1e3),`s 超时`]})]}),n&&(0,H.jsx)(`p`,{className:`extui-pending`,role:`status`,children:`提交中…`}),(0,H.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,H.jsx)(`h3`,{className:`extui-title`,children:e.title||wA[e.method]}),e.method===`confirm`&&(0,H.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,H.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,H.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,H.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,H.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,H.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&bk(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,H.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&bk(e)&&e.preventDefault()}}),(0,H.jsxs)(`div`,{className:`extui-actions`,children:[(0,H.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,H.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,H.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,H.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function mA({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,V.useState)(e),o=(0,V.useRef)(null),s=(0,V.useRef)(!1);(0,V.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},u=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,H.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,H.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(bk(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,H.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,H.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function hA({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c}){let[l,u]=(0,V.useState)(!1),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)(0),h=(0,V.useRef)(null),g=(0,V.useRef)(null),_=(0,V.useRef)(null),v=(0,V.useRef)(null),y=(0,V.useRef)([]),b=i.find(e=>e.selected),x=Wk(i,d),S=x.length===0?-1:Math.min(Math.max(p,0),x.length-1),C=S<0?void 0:x[S],w=(e=!1)=>{u(!1),e&&g.current?.focus()},T=()=>{f(``),m(Math.max(i.findIndex(e=>e.selected),0)),u(!0)},E=e=>m(t=>x.length?Math.min(Math.max(t+e,0),x.length-1):0);(0,V.useEffect)(()=>{if(!l)return;let e=e=>{h.current?.contains(e.target)||w()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[l]),(0,V.useEffect)(()=>{if(!l)return;let e=h.current,t=t=>{e?.contains(t.relatedTarget)||w()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[l]),(0,V.useEffect)(()=>{l&&v.current?.focus()},[l]),(0,V.useEffect)(()=>{l&&S>=0&&y.current[S]?.scrollIntoView({block:`nearest`})},[l,S]),(0,V.useLayoutEffect)(()=>{if(!l)return;let e=_.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`)},[l,x.length,i.length]);let D=e=>{if(l){if(e.key===`Escape`)e.preventDefault(),w(!0);else if(e.key===`ArrowDown`)e.preventDefault(),E(1);else if(e.key===`ArrowUp`)e.preventDefault(),E(-1);else if(e.key===`Home`)e.preventDefault(),m(0);else if(e.key===`End`)e.preventDefault(),m(Math.max(x.length-1,0));else if(e.key===`Enter`){if(bk(e))return;e.preventDefault(),C&&(s(C.key),w(!0))}}},O=`picker-list-${c??e}`,k=t=>`picker-option-${c??e}-${t}`;return(0,H.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:h,onKeyDown:l?D:void 0,children:[(0,H.jsxs)(`button`,{ref:g,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":l,title:o??`${Lk[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>l?w():T(),children:[(0,H.jsx)(`span`,{className:`session-picker-kind`,children:Lk[e]}),(0,H.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,H.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,H.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),l&&(0,H.jsxs)(`div`,{className:`picker-menu`,ref:_,"data-picker-menu":e,"data-picker-highlight":S,children:[(0,H.jsxs)(`div`,{className:`picker-filter`,children:[(0,H.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,H.jsx)(`input`,{ref:v,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${zk[e]}选项`,"aria-expanded":`true`,"aria-controls":O,"aria-autocomplete":`list`,"aria-activedescendant":C?k(S):void 0,value:d,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{f(e.target.value),m(0)}}),d&&(0,H.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{f(``),m(0),v.current?.focus()},children:`✕`})]}),b&&!x.some(e=>e.key===b.key)&&(0,H.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":b.key,children:[(0,H.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,H.jsx)(`span`,{className:`picker-current-value`,children:b.label})]}),(0,H.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:O,"aria-label":Bk[e],children:[x.map((e,t)=>(0,H.jsxs)(`button`,{id:k(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{y.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===S&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===S,onClick:()=>{s(e.key),w(!0)},children:[e.color&&(0,H.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,H.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,H.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,H.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),x.length===0&&(0,H.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:`没有匹配「${d.trim()}」的${zk[e]}`})]})]})]})}var gA=`__pi_default__`;function _A({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onClose:a}){let[o,s]=(0,V.useState)(e.defaultAgentId),[c,l]=(0,V.useState)(e.defaultModel),[u,d]=(0,V.useState)(e.defaultThinkingLevel);(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let f=t?.source===`pi`,p=[{key:gA,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:c===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Hk(e),selected:c?.provider===e.provider&&c.modelId===e.modelId}))],m=[{key:gA,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:u===void 0},...(t?.levels??[]).map(e=>({key:e,label:e,selected:e===u}))],h=e=>{if(e===gA){l(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);n&&l({provider:n.provider,modelId:n.modelId,label:n.label})},g=e=>d(e===gA?void 0:e),_=[{key:gA,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:o===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:o===e.id}))];return(0,H.jsx)(`div`,{className:`overlay`,onClick:a,children:(0,H.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`h2`,{children:`工作区设置`}),(0,H.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,H.jsxs)(`div`,{className:`settings-row`,children:[(0,H.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,H.jsx)(hA,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===o)?.name??`跟随 Pi 默认`,value:o??gA,detail:o?`${n?.agents.find(e=>e.id===o)?.toolSummary??``}`:void 0,options:_,disabled:!n||n.source===`unavailable`,note:Zk(n),onChoose:e=>s(e===gA?void 0:e)})]}),(0,H.jsxs)(`div`,{className:`settings-row`,children:[(0,H.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,H.jsx)(hA,{kind:`model`,scope:`settings-model`,label:c?.label??`跟随 Pi 默认`,value:c?`${c.provider}/${c.modelId}`:gA,detail:c?`${c.provider}/${c.modelId}`:void 0,options:p,disabled:!f,note:Xk(`模型`,t),onChoose:h})]}),(0,H.jsxs)(`div`,{className:`settings-row`,children:[(0,H.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,H.jsx)(hA,{kind:`thinking`,scope:`settings-thinking`,label:u??`跟随 Pi 默认`,value:u??gA,options:m,disabled:!f,note:Xk(`思考等级`,t),onChoose:g})]}),(0,H.jsxs)(`div`,{className:`picker-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,H.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:a,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(o,c,u),children:`保存`})]})]})})}var vA=[{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`}],yA={waiting:`⋯`,running:``,failed:``,question:`?`,completed:``,unread:`•`,idle:``,awaiting_background:`⚙`},bA={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,completed:`已完成`,unread:`有未读`,idle:`空闲`,awaiting_background:`等待后台任务`},xA={idle:`就绪`,waiting:`等待 LLM`,running:`正在生成`,completed:`已完成`,stopped:`已停止`,failed:`运行失败`,awaiting_background:`等待后台任务`},SA=e=>e?.status===`running`||e?.status===`waiting`,CA={running:`运行中`,completed:`已完成`,failed:`失败`,stopped:`已停止`,cancelled:`已取消`},wA={select:`请选择一项`,confirm:`请确认`,input:`请输入内容`,editor:`请输入内容`,notify:`扩展通知`,setStatus:`扩展状态`,setWidget:`扩展内容`,setTitle:`扩展标题`,set_editor_text:`扩展输入`};function TA(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 EA(e,t,n){if(t)return`question`;if(e.status===`failed`)return`failed`;if(e.status===`waiting`)return`waiting`;if(e.status===`running`)return`running`;if(e.status===`awaiting_background`)return`awaiting_background`;let r=n??``;return e.status===`completed`&&e.updatedAt>r?`completed`:e.updatedAt>r?`unread`:`idle`}function DA({state:e}){let t=yA[e];return e===`idle`?null:(0,H.jsx)(`i`,{className:`session-state session-state-${e}`,"data-session-state":e,title:bA[e],"aria-label":bA[e],...e===`awaiting_background`?{style:{color:`var(--accent)`}}:{},children:(0,H.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:t})})}function OA(e,t){return(0,H.jsxs)(H.Fragment,{children:[e.origin===`orchestrator`&&(0,H.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`orchestrator`,title:`编排会话:由上级智能体创建`,"aria-label":`编排会话:由上级智能体创建`,children:`编排`}),t&&(0,H.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`scheduled`,title:`定时任务会话:${t.name}`,"aria-label":`定时任务会话:${t.name}`,children:`定时`})]})}function kA(e,t){let n=[];return e.origin===`orchestrator`&&n.push(`编排会话`),t&&n.push(`定时任务会话:${t.name}`),n.length?`(${n.join(`;`)})`:``}var AA={pending:`未开始`,in_progress:`运行中`,completed:`已完成`},jA={pending:`○`,in_progress:`◐`,completed:`✓`},MA={high:`高`,medium:`中`,low:`低`};function NA(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function PA({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,H.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,title:`状态:${AA[e.status]}`,children:[(0,H.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:jA[e.status]}),(0,H.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,H.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:AA[e.status]}),e.priority&&(0,H.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:MA[e.priority]})]})}function FA(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 IA({tasks:e,messages:t,execOutputs:n,onStop:r}){return(0,H.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?CA[o]??(/[\u3400-\u9fff]/.test(o)?o:`未知状态`):`未知状态`;return(0,H.jsx)(LA,{task:e,status:s,messages:t,execOutputs:n,onStop:r},a)})})}function LA({task:e,status:t,messages:n,execOutputs:r,onStop:i}){let[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(()=>r.get(e.id)??``);(0,V.useEffect)(()=>{let t=r.get(e.id)??``;c(t);let n,i=r=>{let i=r.detail;i.sessionId===e.id&&(t=(t+i.data).slice(-512e3),n===void 0&&(n=requestAnimationFrame(()=>{n=void 0,c(t)})))};return window.addEventListener(`super-pi-exec-output`,i),()=>{window.removeEventListener(`super-pi-exec-output`,i),n!==void 0&&cancelAnimationFrame(n)}},[e.id,r]);let l=e.originMessageId!==void 0&&e.originCallRow!==void 0?n.find(t=>t.id===e.originMessageId)?.toolCalls?.[e.originCallRow]:void 0,u=(l?.backgroundTask?.id===e.id?l.backgroundTask.output:void 0)??s,d=e.status?.trim()??``,f=d===`running`?`运行中,暂无输出`:d in CA?`任务已结束,输出未保留`:`暂无可显示的输出`;return(0,H.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,H.jsxs)(`button`,{type:`button`,className:`bg-item-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,"aria-label":`展开后台任务详情`,children:[(0,H.jsxs)(`div`,{className:`bg-item-header`,children:[(0,H.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务`}),i&&(0,H.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:t=>{t.stopPropagation(),i(e.id)},children:`终止`})]}),(0,H.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,H.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,H.jsx)(`span`,{className:`bg-status`,children:t})]})]}),a&&(0,H.jsx)(`pre`,{className:`bg-output`,"data-bg-output":e.id,children:u||f})]})}function RA({todos:e,tasks:t,messages:n,execOutputs:r,scheduledTasks:i,scheduledCatalog:a,scheduledAgents:o,collapsed:s,onToggle:c,workspaceId:l,workspaceLabel:u,cwd:d=``,conversationId:f,connected:p,files:m,onOpenFile:h,onOpenChanged:g,activeTab:_,onSelectTab:v,sendCommand:y,registerTerminalSink:b,terminalShell:x,notify:S,serverTimeZone:C,onOpenSession:w}){let T=vA;return T.some(e=>e.id===_)||T[0].id,(0,H.jsx)(`div`,{className:`right-rail${s?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":`右侧栏`,"data-right-rail":`1`,"data-right-rail-collapsed":s,children:s?(0,H.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:c,children:`‹`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`right-rail-head`,children:[(0,H.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":T.length,children:T.map(e=>(0,H.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===_?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===_,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>v(e.id),children:e.label},e.id))}),(0,H.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":`收起右侧栏`,onClick:c,children:`›`})]}),vA.filter(e=>e.id===_).map(s=>(0,H.jsxs)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${s.id}`,"aria-labelledby":`right-tab-${s.id}`,"data-right-panel":s.id,children:[s.id===`main`&&(0,H.jsxs)(H.Fragment,{children:[(e.length>0||t.length>0)&&(0,H.jsxs)(`p`,{className:`rail-legend`,"data-rail-legend":`1`,children:[(0,H.jsx)(`span`,{className:`rail-legend-label`,children:`左侧竖条=状态`}),(0,H.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,H.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-pending`,"aria-hidden":`true`}),`未开始`]}),(0,H.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,H.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-running`,"aria-hidden":`true`}),`运行中`]}),(0,H.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,H.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-done`,"aria-hidden":`true`}),`已完成`]})]}),(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`待办任务`}),(0,H.jsx)(`span`,{className:`rail-section-count`,"data-todo-summary":`1`,children:NA(e)})]}),e.length>0?(0,H.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,H.jsx)(PA,{todo:e,index:t},e.id??`todo_${t}`))}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。Agent 开始处理多步骤任务时,会自己把待办写到这里。`}),(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`后台任务`}),(0,H.jsx)(`span`,{className:`rail-section-count`,"data-bg-summary":`1`,children:t.length?`${t.filter(e=>e.status===`running`).length} 个运行中 / 共 ${t.length} 个`:`0 个`})]}),t.length>0?(0,H.jsx)(IA,{tasks:t,messages:n,execOutputs:r,onStop:e=>y({type:`backgroundTask.stop`,taskId:e})}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`}),(0,H.jsx)(PD,{tasks:i,workspaceId:l,catalog:a,agents:o,sendCommand:y,notify:S,serverTimeZone:C})]}),s.id===`projects`&&(0,H.jsx)(sO,{workspaceId:l,notify:S,onOpenSession:w},l),s.id===`tools`&&(0,H.jsx)(zA,{workspaceId:l,onOpenSession:w},l),s.id===`files`&&(0,H.jsx)(z_,{workspaceId:l,files:m,onOpenFile:h,onOpenChanged:g}),s.id===`git`&&(0,H.jsx)(Ap,{workspaceId:l??null,conversationId:f,cwd:d,onOpenChanged:g},f||`global`),s.id===`terminal`&&(0,H.jsx)(xD,{workspaceId:l,workspaceLabel:u,cwd:d,conversationId:f,connected:p,sendCommand:y,registerSink:b,terminalShell:x},f||`global`)]},s.id))]})})}function zA({workspaceId:e,onOpenSession:t}){let{tools:n,mountedTools:r,openToolId:i,shortcuts:a}=tk(),[o,s]=(0,V.useState)(),c=async e=>{s(void 0);let t=await ik(e);t&&s(`移除工具失败:${tp(t)}`)},l=(e,t)=>t?`打开${e}(快捷键 ${AO(t)})`:`打开${e}`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(hO,{workspaceId:e,onOpenSession:t}),(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,H.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[n.length+r.length,` 个`]})]}),n.length+r.length>0?(0,H.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":n.length+r.length,children:[n.map(e=>(0,H.jsxs)(`li`,{className:`tool-slot`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":i===e.id?`open`:`idle`,title:l(e.name,a[e.id]),"aria-label":l(e.name,a[e.id]),"aria-current":i===e.id?`true`:void 0,onClick:()=>nk.toggleTool(e.id),children:[(0,H.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),a[e.id]&&(0,H.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${AO(a[e.id])}`,children:jO(a[e.id])}),e.kind===`link`&&(0,H.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>nk.removeTool(e.id),children:`✕`})]},e.id)),r.map(e=>(0,H.jsxs)(`li`,{className:`tool-slot`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,"data-tool-state":i===e.id?`open`:`idle`,title:l(e.name,a[e.id]),"aria-label":l(e.name,a[e.id]),onClick:()=>nk.toggleTool(e.id),children:[(0,H.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,H.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),a[e.id]&&(0,H.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${AO(a[e.id])}`,children:jO(a[e.id])}),(0,H.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void c(e.id),children:`✕`})]},e.id))]}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,H.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具、快捷键与说明`,"aria-label":`打开工具设置`,onClick:()=>nk.openSettings(),children:`⚙ 工具设置`}),o&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-error":`1`,children:o})]})}function BA({onClose:e}){let{tools:t,mountedTools:n,shortcuts:r}=tk(),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(``),[c,l]=(0,V.useState)(),[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(),[m,h]=(0,V.useState)(),[g,_]=(0,V.useState)(),[v,y]=(0,V.useState)(``),[b,x]=(0,V.useState)(),[S,C]=(0,V.useState)(),[w,T]=(0,V.useState)(!1),[E,D]=(0,V.useState)(),[O,k]=(0,V.useState)(),A=(0,V.useRef)(null),j=(0,V.useRef)(null),[M,N]=(0,V.useState)(),[P,F]=(0,V.useState)(),ee=(0,V.useRef)(null),[te,ne]=(0,V.useState)(()=>{let e=qO();return!e||typeof window>`u`?e:YO(e,window.innerWidth,window.innerHeight)}),re=async()=>{let e=await Pk(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
92
+ `,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 yy.get()},set promptLabel(e){yy.set(e)},get tooMuchOutput(){return xy.get()},set tooMuchOutput(e){xy.set(e)}}}_verifyIntegers(...e){for(cD of e)if(cD===1/0||isNaN(cD)||cD%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(cD of e)if(cD&&(cD===1/0||isNaN(cD)||cD%1!=0||cD<0))throw Error(`This API only accepts positive integers`)}},uD=2,dD=1,fD=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(uD,Math.floor(u/e.css.cell.width)),rows:Math.max(dD,Math.floor(l/e.css.cell.height))}}},pD=5,mD=20,hD=5,gD=240,_D=120,vD={checking:`检查中`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`},yD=new Map,bD=e=>{let t=yD.get(e);if(!t){let n={id:`${e}-1`,title:`1`,phase:`checking`};t={slots:[n],activeId:n.id,opened:new Set,terminals:new Map,fits:new Map},yD.set(e,t)}return t};function xD({workspaceId:e,workspaceLabel:t,cwd:n=``,connected:r,sendCommand:i,registerSink:a,conversationId:o,terminalShell:s}){let c=o?`term-${o}`:`terminal-right-rail`,l=bD(c),[u,d]=(0,V.useState)(()=>l.slots),[f,p]=(0,V.useState)(()=>l.activeId),m=(0,V.useRef)(f);m.current=f,l.activeId=f;let h=(0,V.useRef)(u);h.current=u,l.slots=u;let g=(0,V.useRef)(e);g.current=e;let _=(0,V.useRef)(n);_.current=n;let v=(0,V.useRef)(i);v.current=i;let y=(0,V.useRef)(l.opened);y.current=l.opened;let b=(0,V.useRef)(!1),x=(0,V.useRef)(l.terminals);x.current=l.terminals;let S=(0,V.useRef)(l.fits);S.current=l.fits;let C=(0,V.useRef)(new Map),[w,T]=(0,V.useState)(0),[E,D]=(0,V.useState)(``),O=(0,V.useRef)(r),k=(0,V.useCallback)(e=>{x.current.get(e)?.dispose(),x.current.delete(e),S.current.delete(e),C.current.delete(e)},[]),A=(0,V.useCallback)(e=>{let t=x.current.get(e),n=S.current.get(e);if(!t||!n)return;let r=C.current.get(e);if(!(!r||r.clientWidth<2||r.clientHeight<2)){try{n.fit()}catch{return}t.cols<mD||t.rows<hD||t.cols>gD||t.rows>_D||y.current.has(e)&&v.current({type:`terminal.resize`,sessionId:e,cols:t.cols,rows:t.rows})}},[]),j=(0,V.useCallback)((e,t)=>{if(!t){C.current.delete(e);return}C.current.set(e,t);let n=x.current.get(e);if(n){n.element&&!t.contains(n.element)&&(t.innerHTML=``,t.appendChild(n.element),requestAnimationFrame(()=>A(e)));return}let r=getComputedStyle(t),i=(e,t)=>r.getPropertyValue(e).trim()||t,a=new lD({cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:i(`--term-fg`,`#dbe4f0`),cursor:i(`--term-fg`,`#dbe4f0`),selectionBackground:i(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),o=new fD;a.loadAddon(o),a.open(t),a.onData(t=>{y.current.has(e)&&v.current({type:`terminal.input`,sessionId:e,data:t})}),a.onResize(({cols:t,rows:n})=>{y.current.has(e)&&v.current({type:`terminal.resize`,sessionId:e,cols:t,rows:n})}),x.current.set(e,a),S.current.set(e,o),requestAnimationFrame(()=>A(e)),T(e=>e+1)},[A]),M=(0,V.useCallback)(e=>{x.current.get(e)?.reset()},[]),N=(0,V.useCallback)(e=>{let t=g.current,n=x.current.get(e);if(!t||!n||y.current.has(e))return;n.reset(),A(e),d(t=>t.map(t=>t.id===e?{...t,phase:`starting`,exitCode:void 0,reason:``}:t));let r=Math.max(mD,Math.min(gD,n.cols||80)),i=Math.max(hD,Math.min(_D,n.rows||24));v.current({type:`terminal.open`,sessionId:e,workspaceId:t,..._.current?{cwd:_.current}:{},cols:r,rows:i})?(y.current.add(e),d(t=>t.map(t=>t.id===e?{...t,phase:`running`}:t))):d(t=>t.map(t=>t.id===e?{...t,phase:`exited`,reason:`Super Pi 服务的连接尚未就绪`}:t))},[A]);(0,V.useEffect)(()=>{let e=!1;return fetch(`/api/terminal`).then(e=>e.json()).then(t=>{e||(t.enabled?(b.current=!0,d(e=>e.map(e=>e.phase===`checking`?{...e,phase:`starting`}:e))):d(e=>e.map(e=>({...e,phase:`unavailable`,reason:t.reason??`终端未启用`}))))}).catch(()=>{e||d(e=>e.map(e=>({...e,phase:`unavailable`,reason:`无法读取终端状态`})))}),()=>{e=!0}},[]);let P=(0,V.useRef)(void 0),F=(0,V.useCallback)(()=>{fetch(`/api/terminal-shell`).then(e=>e.json()).then(e=>D(e.shell?`${e.shell.file}${e.shell.args.length?` ${e.shell.args.join(` `)}`:``}(${e.source??``})`:``)).catch(()=>void 0)},[]);(0,V.useEffect)(()=>{F()},[F]),(0,V.useEffect)(()=>{let e=s?`${s.file}\u0000${s.args.join(`\0`)}`:``;P.current!==void 0&&P.current!==e&&F(),P.current=e},[s,F]),(0,V.useEffect)(()=>{if(b.current)for(let e of u)(e.phase===`checking`||e.phase===`starting`)&&!y.current.has(e.id)&&N(e.id)},[u,N,w]);let ee=(0,V.useCallback)(e=>{if(e.type===`terminal.output`)for(let t of yD.values()){let n=t.terminals.get(e.sessionId);if(n){n.write(e.data);return}}else if(e.type===`terminal.exit`){for(let t of yD.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t));M(e.sessionId),d(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t))}else if(e.type===`terminal.error`){for(let t of yD.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t));M(e.sessionId),d(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t))}else e.type===`terminal.status`&&!e.enabled&&d(t=>t.map(t=>({...t,phase:`unavailable`,reason:e.reason??`终端未启用`})))},[M,F]);(0,V.useEffect)(()=>(a(ee),()=>a(void 0)),[ee,a]),(0,V.useEffect)(()=>()=>{C.current.clear()},[]),(0,V.useEffect)(()=>{let e=r&&!O.current;O.current=r,e&&d(e=>e.map(e=>e.phase===`exited`&&!e.deliberate?{...e,phase:`starting`,reason:``}:e))},[r]),(0,V.useLayoutEffect)(()=>{let e=new ResizeObserver(()=>A(m.current));for(let t of C.current.values())e.observe(t);return A(m.current),()=>e.disconnect()},[A,u,w]);let te=(0,V.useCallback)(e=>{p(e),requestAnimationFrame(()=>A(e))},[A]),ne=(0,V.useCallback)(()=>{let e=new Set(h.current.map(e=>e.title)),t=1;for(;e.has(String(t));)t+=1;let n={id:`${c}-${t}`,title:String(t),phase:`checking`};d(e=>e.length>=pD?e:[...e,n]),p(n.id)},[c]),re=(0,V.useCallback)(e=>{v.current({type:`terminal.close`,sessionId:e}),y.current.delete(e),k(e),d(t=>{let n=t.findIndex(t=>t.id===e),r=t.filter(t=>t.id!==e);return m.current===e&&r.length&&p(r[Math.min(n,r.length-1)].id),m.current===e&&!r.length&&p(``),r})},[k]),I=u.find(e=>e.id===f)??u[0];return(0,H.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":I?.phase??`empty`,children:[(0,H.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[u.map(e=>(0,H.jsxs)(`div`,{className:`terminal-tab${e.id===f?` is-active`:``}`,children:[(0,H.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===f,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>te(e.id),title:vD[e.phase],children:[(0,H.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.phase}`,"aria-hidden":`true`}),e.title]}),(0,H.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>re(e.id),children:`×`})]},e.id)),u.length<pD&&(0,H.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,"data-terminal-add":`1`,onClick:ne,title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,H.jsxs)(`div`,{className:`terminal-toolbar`,children:[I?(0,H.jsxs)(`span`,{className:`terminal-status terminal-status-${I.phase}`,"data-terminal-status":I.phase,children:[(0,H.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),vD[I.phase]]}):(0,H.jsx)(`span`,{className:`terminal-status terminal-status-empty`,"data-terminal-status":`empty`,children:`没有打开的终端`}),(0,H.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[E&&(0,H.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-shell-hint":`1`,title:E,children:E}),t&&(0,H.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),I?I.phase===`running`?null:(0,H.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,onClick:()=>N(I.id),children:`重新打开`}):null]})]}),I?.reason&&(0,H.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,title:np(I.reason),children:tp(I.reason,`终端出错了。`)}),I?.phase===`exited`&&I.exitCode!==void 0&&I.exitCode!==0&&(0,H.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,I.exitCode,`。`]}),(0,H.jsxs)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:[u.map(e=>(0,H.jsx)(`div`,{ref:t=>j(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===f?`block`:`none`}},e.id)),!I&&(0,H.jsx)(`div`,{className:`terminal-surface-empty`,"data-terminal-empty":`1`,children:(0,H.jsx)(`p`,{className:`rail-empty`,children:`没有打开的终端`})}),I?.phase===`checking`&&(0,H.jsx)(`p`,{className:`rail-empty terminal-surface-message`,"data-terminal-phase":`checking`,children:`正在检查终端状态…`}),I?.phase===`unavailable`&&(0,H.jsxs)(`div`,{className:`terminal-unavailable terminal-surface-message`,"data-terminal-phase":`unavailable`,children:[(0,H.jsx)(`p`,{className:`terminal-unavailable-reason`,title:np(I.reason),children:tp(I.reason,`终端没有启动。`)}),(0,H.jsx)(`p`,{className:`rail-empty`,children:`终端仅接受本机与局域网连接。`})]})]})]})}var SD=[{day:1,label:`一`},{day:2,label:`二`},{day:3,label:`三`},{day:4,label:`四`},{day:5,label:`五`},{day:6,label:`六`},{day:0,label:`日`}];function CD(e){return e.kind===`interval`?`每隔 ${e.everyMinutes} 分钟`:e.kind===`daily`?`每天 ${e.time}`:e.kind===`weekly`?`每周${e.weekdays.map(e=>SD.find(t=>t.day===e)?.label??`?`).join(`、`)} ${e.time}`:`仅一次:${wD(e.at)}`}function wD(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 TD(){return typeof Intl<`u`?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function ED(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 DD(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 OD(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 kD(e,t,n){let r=DD(e,n),i=AD(e,t,n);return i===0?`今天 ${r}`:i===1?`明天 ${r}`:ED(e,n)}function AD(e,t,n){let r=e=>{let[t]=ED(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 jD(e,t,n){if(!e||!t||e===t)return``;let r=OD(e,n),i=OD(t,n);return DD(n,e)===DD(n,t)?`服务器在 ${r} 时区,你的时区也是 ${i},下面的时间按你的时区显示`:`服务器在 ${r} 时区,下面的时间按你的时区(${i})显示`}function MD(e,t,n){return e.enabled?e.nextRunAt===void 0?{glyph:`✓`,word:`已结束`,detail:``}:{glyph:`●`,word:`启用中`,detail:`下次 ${kD(e.nextRunAt,t,n)}`}:e.schedule.kind===`once`&&e.lastRunAt!==void 0?{glyph:`✓`,word:`已结束`,detail:e.lastRunAt?`上次 ${ED(e.lastRunAt,n)}`:``}:{glyph:`○`,word:`已停用`,detail:``}}function ND(e,t){if(e.lastRunAt===void 0)return``;let n=ED(e.lastRunAt,t);return e.lastRunStatus===`failed`?`上次 ${n} · 失败${e.lastRunMessage?`:${e.lastRunMessage}`:``}`:`上次 ${n} · 成功`}function PD({tasks:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,serverTimeZone:o}){let[s,c]=(0,V.useState)(()=>Date.now()),[l,u]=(0,V.useState)();(0,V.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let d=TD(),f=jD(o,d,s),p=e=>{i({type:`scheduledTask.toggle`,id:e.id,enabled:!e.enabled})},m=e=>{i({type:`scheduledTask.trigger`,id:e.id}),a(`已触发「${e.name}」,结果会出现在它自己的会话里。`,`info`)},h=e=>{i({type:`scheduledTask.delete`,id:e.id}),a(`已删除定时任务「${e.name}」,它的会话和结果保留着。`,`info`)};return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`定时任务`}),(0,H.jsx)(`span`,{className:`rail-section-count`,"data-sched-count":`1`,children:e.length?`${e.length} 个`:`0 个`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-add`,"data-sched-add":`1`,title:`新建定时任务`,onClick:()=>u(`new`),children:`+ 新建`})]}),f&&(0,H.jsx)(`p`,{className:`scheduled-zone-note`,"data-sched-zone-note":`1`,children:f}),e.length>0?(0,H.jsx)(`ul`,{className:`scheduled-list`,"data-sched-list":`1`,children:e.map(e=>{let t=MD(e,s,d),n=ND(e,d);return(0,H.jsxs)(`li`,{className:`scheduled-item`,"data-scheduled-task":e.id,children:[(0,H.jsx)(`button`,{type:`button`,className:`scheduled-toggle`,"data-sched-toggle":`1`,title:e.enabled?`点击停用`:`点击启用`,"aria-label":e.enabled?`停用 ${e.name}`:`启用 ${e.name}`,onClick:()=>p(e),children:t.glyph}),(0,H.jsxs)(`div`,{className:`scheduled-main`,children:[(0,H.jsxs)(`div`,{className:`scheduled-name-row`,children:[(0,H.jsx)(`span`,{className:`scheduled-name`,children:e.name}),(0,H.jsx)(`span`,{className:`scheduled-status-word`,"data-sched-word":`1`,children:t.word}),e.createdBy===`agent`&&(0,H.jsx)(`span`,{className:`scheduled-by`,title:`这个定时任务是 agent 创建的,你可以像编辑自己建的一样编辑它`,children:`agent`})]}),(0,H.jsxs)(`div`,{className:`scheduled-meta`,"data-sched-meta":`1`,children:[CD(e.schedule),t.detail?` · ${t.detail}`:``]}),n&&(0,H.jsx)(`div`,{className:`scheduled-last`,"data-sched-last":`1`,children:n})]}),(0,H.jsxs)(`div`,{className:`scheduled-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-trigger":`1`,title:`立即执行一次(不改变周期)`,"aria-label":`立即执行 ${e.name}`,onClick:()=>m(e),children:`⚡`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-edit":`1`,title:`编辑`,"aria-label":`编辑 ${e.name}`,onClick:()=>u(e),children:`✎`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-action scheduled-action-danger`,"data-sched-delete":`1`,title:`删除(会话与结果保留)`,"aria-label":`删除 ${e.name}`,onClick:()=>h(e),children:`✕`})]})]},e.id)})}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-sched-empty":`1`,children:`还没有定时任务。建一个,让它在你不在的时候替你跑:每天汇总提交、每周检查依赖、每隔十分钟看一眼构建。`}),l!==void 0&&(0,H.jsx)(RD,{task:l===`new`?void 0:l,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:()=>u(void 0)},l===`new`?`new`:l.id)]})}function FD(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`?ID(t.at):``,modelKey:e?.model?`${e.model.provider}/${e.model.modelId}`:``,agentId:e?.agentId??``}}function ID(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 LD(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 RD({task:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:o}){let[s,c]=(0,V.useState)(()=>FD(e)),[l,u]=(0,V.useState)();(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let d=e=>{c(t=>({...t,...e})),u(void 0)};return(0,sa.createPortal)((0,H.jsx)(`div`,{className:`tool-overlay`,"data-sched-dialog-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&o()},children:(0,H.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`scheduled-dialog-title`,"data-sched-dialog":`1`,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsx)(`h2`,{className:`tool-dialog-title`,id:`scheduled-dialog-title`,children:e?`编辑定时任务`:`新建定时任务`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-sched-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭定时任务编辑`,onClick:o,children:`✕`})]}),(0,H.jsxs)(`div`,{className:`tool-dialog-body scheduled-form`,children:[(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`名称`}),(0,H.jsx)(`input`,{className:`scheduled-input`,"data-sched-field":`name`,value:s.name,placeholder:`留空则取提示词首句`,onChange:e=>d({name:e.target.value})})]}),(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`提示词`}),(0,H.jsx)(`textarea`,{className:`scheduled-textarea`,"data-sched-field":`prompt`,rows:5,value:s.prompt,placeholder:`到点时这段话会作为用户消息发给 agent,所以它要是一条完整、自包含的指令`,onChange:e=>d({prompt:e.target.value})})]}),(0,H.jsxs)(`div`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`周期`}),(0,H.jsx)(`div`,{className:`scheduled-kind-row`,role:`radiogroup`,"aria-label":`周期类型`,children:[[`interval`,`每隔 N 分钟`],[`daily`,`每天`],[`weekly`,`每周`],[`once`,`仅一次`]].map(([e,t])=>(0,H.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:()=>d({kind:e}),children:t},e))})]}),s.kind===`interval`&&(0,H.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`间隔`}),(0,H.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`everyMinutes`,inputMode:`numeric`,value:s.everyMinutes,onChange:e=>d({everyMinutes:e.target.value})}),(0,H.jsx)(`span`,{className:`scheduled-hint`,children:`分钟(1 – 10080)`})]}),(s.kind===`daily`||s.kind===`weekly`)&&(0,H.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,H.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`time`,inputMode:`numeric`,placeholder:`09:00`,value:s.time,onChange:e=>d({time:e.target.value})}),(0,H.jsx)(`span`,{className:`scheduled-hint`,children:`服务器本地时间,每天/每周的这一天到点触发`})]}),s.kind===`weekly`&&(0,H.jsxs)(`div`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`星期`}),(0,H.jsx)(`div`,{className:`scheduled-weekdays`,children:SD.map(({day:e,label:t})=>{let n=s.weekdays.includes(e);return(0,H.jsx)(`button`,{type:`button`,"aria-pressed":n,className:`scheduled-weekday${n?` scheduled-weekday-on`:``}`,"data-sched-weekday":e,onClick:()=>d({weekdays:n?s.weekdays.filter(t=>t!==e):[...s.weekdays,e]}),children:t},e)})})]}),s.kind===`once`&&(0,H.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,H.jsx)(`input`,{className:`scheduled-input`,type:`datetime-local`,"data-sched-field":`onceAt`,value:s.onceAt,onChange:e=>d({onceAt:e.target.value})}),(0,H.jsx)(`span`,{className:`scheduled-hint`,children:`这一次运行之后就结束`})]}),(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`模型`}),(0,H.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`model`,value:s.modelKey,onChange:e=>d({modelKey:e.target.value}),children:[(0,H.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(n?.models??[]).map(e=>(0,H.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,`(`,e.detail,`)`]},`${e.provider}/${e.modelId}`))]})]}),(0,H.jsxs)(`label`,{className:`scheduled-field`,children:[(0,H.jsx)(`span`,{className:`scheduled-label`,children:`Agent`}),(0,H.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`agent`,value:s.agentId,onChange:e=>d({agentId:e.target.value}),children:[(0,H.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(r?.agents??[]).map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.name??e.id},e.id))]})]}),l&&(0,H.jsx)(`p`,{className:`scheduled-error`,"data-sched-error":`1`,role:`alert`,children:l}),(0,H.jsxs)(`div`,{className:`scheduled-actions-row`,children:[(0,H.jsx)(`button`,{type:`button`,className:`scheduled-cancel`,onClick:o,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`scheduled-save`,"data-sched-save":`1`,onClick:()=>{let r=s.prompt.trim();if(!r){u(`定时任务需要一段提示词:到点时这段话会被当作用户消息发给 agent。`);return}if(!t){u(`先选一个工作区,再建定时任务。`);return}let c=LD(s);if(!c.ok){u(c.reason);return}let l=n?.models.find(e=>`${e.provider}/${e.modelId}`===s.modelKey),d=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:d,agentId:f}:{type:`scheduledTask.create`,name:p,prompt:r,schedule:c.schedule,workspaceId:t,model:d,agentId:f})?(a(e?`已保存对「${s.name.trim()||e.name}」的修改。`:`定时任务已创建,到点会自动运行。`,`info`),o()):u(`连接已断开,没能保存。等重连后再试一次。`)},children:e?`保存修改`:`创建任务`})]})]})]})}),document.body)}function zD(...e){for(let t of e){let e=typeof t==`string`?t.trim():``;if(e)return e}}function BD(e){return e?!!(zD(e.agentId)||zD(e.cwd)||zD(e.thinkingLevel)||zD(e.model?.provider)||zD(e.model?.modelId)||typeof e.watchdogTimeoutSeconds==`number`&&Number.isFinite(e.watchdogTimeoutSeconds)&&e.watchdogTimeoutSeconds>0):!1}function VD(e,t){let n=zD(e?.provider,t?.provider),r=zD(e?.modelId,t?.modelId);if(!n&&!r)return;let i={};return n&&(i.provider=n),r&&(i.modelId=r),i}function HD(e,t){if(!e&&!t)return;let n={agentId:zD(e?.agentId,t?.agentId),cwd:zD(e?.cwd,t?.cwd),model:VD(e?.model,t?.model),thinkingLevel:zD(e?.thinkingLevel,t?.thinkingLevel),watchdogTimeoutSeconds:typeof e?.watchdogTimeoutSeconds==`number`&&Number.isFinite(e.watchdogTimeoutSeconds)&&e.watchdogTimeoutSeconds>0?e.watchdogTimeoutSeconds:typeof t?.watchdogTimeoutSeconds==`number`&&Number.isFinite(t.watchdogTimeoutSeconds)&&t.watchdogTimeoutSeconds>0?t.watchdogTimeoutSeconds:void 0};return BD(n)?n:void 0}function UD(e,t,n){return e==null?HD(t,n):BD(e)?e:void 0}function WD(e){if(!e)return``;let t=[],n=zD(e.agentId);n&&t.push(n);let r=zD(e.model?.provider),i=zD(e.model?.modelId);r&&i?t.push(`模型 ${r}/${i}`):r?t.push(`模型 ${r}`):i&&t.push(`模型 ${i}`);let a=zD(e.cwd);a&&t.push(`目录 ${a}`);let o=zD(e.thinkingLevel);return o&&t.push(`思考 ${o}`),typeof e.watchdogTimeoutSeconds==`number`&&Number.isFinite(e.watchdogTimeoutSeconds)&&e.watchdogTimeoutSeconds>0&&t.push(`看门狗 ${e.watchdogTimeoutSeconds} 秒`),t.join(` · `)}function GD(e){let t=Array.isArray(e)?e:[],n=new Set(t.map(e=>e.id)),r=new Map;for(let e of t){let t=e.parentConversationId;r.set(e.id,t&&n.has(t)&&t!==e.id?t:void 0)}let i=new Map;for(let e of t){let t=r.get(e.id);if(!t)continue;let n=i.get(t)??[];n.push(e),i.set(t,n)}let a=new Set,o=(e,t,n)=>{a.add(e.id);let r={session:e,children:[],depth:t};for(let a of i.get(e.id)??[])n.has(a.id)||r.children.push(o(a,t+1,new Set([...n,e.id])));return r},s=[];for(let e of t)r.get(e.id)||s.push(o(e,0,new Set([e.id])));for(let e of t)a.has(e.id)||s.push(o(e,0,new Set([e.id])));return s}var KD={ready:`待派发`,pending:`等待依赖`,in_progress:`执行中`,draft:`待澄清`,planning:`待规划`,planned:`已规划`,assigned:`已委派`,running:`执行中`,active:`执行中`,waiting_dependency:`等待依赖`,waiting_approval:`等待审批`,awaiting_approval:`等待审批`,blocked:`已阻塞`,review:`待验收`,awaiting_review:`待验收`,rework:`返工中`,completed:`已完成`,closed:`已关闭`,failed:`失败`,cancelled:`已取消`,idle:`空闲`,waiting:`排队中`,awaiting_background:`等待回传`,stopped:`已停止`};function qD(e){return KD[e??``]??e??`未知状态`}var JD={project:`独立记忆树`,shared:`共享主对话记忆`};function YD({sessions:e,onOpenSession:t,emptyText:n}){let r=(0,V.useMemo)(()=>GD(e),[e]);return r.length?(0,H.jsx)(`ul`,{className:`session-tree`,"data-session-tree":`1`,children:r.map(e=>(0,H.jsx)(XD,{node:e,onOpenSession:t},e.session.id))}):(0,H.jsx)(`p`,{className:`project-muted`,children:n??`该项目还没有会话。`})}function XD({node:e,onOpenSession:t}){let{session:n,children:r,depth:i}=e;return(0,H.jsxs)(`li`,{className:`session-tree-item`,"data-session-node":n.id,"data-session-depth":i,"data-session-role":n.role??``,children:[(0,H.jsxs)(`div`,{className:`session-node-row`,children:[(0,H.jsx)(`span`,{className:`session-node-role`,children:n.role??`会话`}),n.memoryScope?(0,H.jsx)(`span`,{className:`session-node-memory`,"data-memory-scope":n.memoryScope,children:JD[n.memoryScope]??n.memoryScope}):null,(0,H.jsx)(`button`,{type:`button`,className:`session-node-title`,"data-session-title":n.id,disabled:!t,onClick:()=>t?.(n.id),children:n.title})]}),(0,H.jsxs)(`div`,{className:`session-node-meta`,children:[(0,H.jsx)(`span`,{className:`project-status project-status-${n.status??`idle`}`,children:qD(n.status)}),(0,H.jsxs)(`span`,{className:`session-node-tokens`,"data-session-tokens":n.tokens??0,children:[(n.tokens??0).toLocaleString(),` Token`]}),n.contextPercent==null?null:(0,H.jsxs)(`span`,{className:`session-node-context`,"data-session-context":n.id,children:[`上下文 `,Math.round(n.contextPercent),`%`]})]}),r.length===0?null:(0,H.jsxs)(`details`,{className:`session-tree-branch`,open:i===0,"data-session-branch":n.id,children:[(0,H.jsxs)(`summary`,{className:`session-tree-toggle`,"data-session-toggle":n.id,children:[(0,H.jsx)(`span`,{className:`project-fold-arrow`,"aria-hidden":`true`,children:`▸`}),r.length,` 个下级`]}),(0,H.jsx)(`ul`,{className:`session-tree-children`,children:r.map(e=>(0,H.jsx)(XD,{node:e,onOpenSession:t},e.session.id))})]})]})}function ZD(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 QD(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`请求失败(${e.status})`);return t}async function $D(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 eO(e,t){return`/api/projects/${encodeURIComponent(e)}/report?workspaceId=${encodeURIComponent(t??``)}`}var tO={decision:`要你决定`,blocked:`卡住了`,completed:`已完成`},nO={decision:0,blocked:1,completed:2},rO=864e5,iO=5;function aO(e,t=60){let n=(e??``).replace(/\s+/g,` `).trim();return n?n.length<=t?n:`${n.slice(0,t-1)}…`:``}function oO(e){let t=e.summary?.trim();if(t)return aO(t);let n=e.reports??[],r=n.find(e=>e.kind===`delivery`);if(r?.progress?.trim())return aO(r.progress);for(let e of[...n].reverse()){let t=e.progress?.trim()||e.summary?.trim();if(t)return aO(t)}for(let t of[...e.tasks??[]].reverse()){let e=t.review?.summary?.trim();if(e)return aO(e)}return`已完成`}function sO(e,t){let n=(e.escalations??[]).filter(e=>e.status===`open`),r=Date.parse(e.updatedAt??``)||0;if(n.length){let t=n[0];return{projectId:e.id,projectTitle:e.title,kind:`decision`,label:tO.decision,detail:aO(t.reason||t.title||`有例外等你处理`),actionLabel:`去看看`,target:{kind:`exception`,escalationId:t.id},updatedAt:r}}let i=e.status===`completed`,a=i?void 0:(e.tasks??[]).find(e=>e.status===`blocked`);if(!i&&(e.status===`blocked`||a))return{projectId:e.id,projectTitle:e.title,kind:`blocked`,label:tO.blocked,detail:aO(a?.title||e.objective||e.title),actionLabel:`去看看`,target:a?{kind:`task`,taskId:a.id}:{kind:`top`},updatedAt:r};if(i){let n=Date.parse(e.closedAt||e.updatedAt||``);return!Number.isFinite(n)||t-n>rO?null:{projectId:e.id,projectTitle:e.title,kind:`completed`,label:tO.completed,detail:oO(e),actionLabel:`查看交付`,target:{kind:`top`},updatedAt:r}}return null}function cO(e){let t=e.tasks??[],n=t.filter(e=>e.status===`completed`).length,r=e.resources?.activeWorkers??0,i=e.resources?.tokens??0,a=e.budget?.maxTokens;return{done:n,total:t.length,workers:r,tokens:i,budget:a,tokenText:`${i.toLocaleString()} / ${a?a.toLocaleString():`未设限`}`}}function lO({project:e,workspaceId:t,notify:n,onOpenSession:r,onChanged:i}){let[a,o]=(0,V.useState)(`100000`),[s,c]=(0,V.useState)(`2`),[l,u]=(0,V.useState)(``),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)(!1),[h,g]=(0,V.useState)(``),[_,v]=(0,V.useState)(``),[y,b]=(0,V.useState)(``),[x,S]=(0,V.useState)(!1),C=(0,V.useRef)(``),w=(e.escalations??[]).filter(e=>e.status===`open`),T=[`completed`,`cancelled`,`failed`].includes(e.status),E=e.resources?.tokens??0,D=e.budget?.maxTokens,O=typeof D==`number`&&E>=D,k=w.filter(e=>(e.reason??``).includes(`预算`)),A=e.suggestedMaxTokens,j=!T&&typeof A==`number`&&(O||k.length>0),M=async(r,a={})=>{u(r),g(``);try{await fetch(`/api/projects/${encodeURIComponent(e.id)}/${r}`,{method:r.startsWith(`escalations/`)||r===`budget`||!r||r.startsWith(`tasks/`)&&!r.endsWith(`/dispatch`)&&!r.endsWith(`/review`)?`PATCH`:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...a,workspaceId:t})}).then(QD),await i?.(),n?.(`项目操作已执行`,`info`)}catch(e){g(e instanceof Error?e.message:`任务派发失败`)}finally{u(``)}},N=async()=>{if(x)return;let n=eO(e.id,t);S(!0),v(``);try{let e=await fetch(n);if(!e.ok){v(await $D(e));return}let t=await e.text(),r=URL.createObjectURL(new Blob([t],{type:`text/plain;charset=utf-8`}));C.current&&URL.revokeObjectURL(C.current),C.current=r,b(r),window.open(r,`_blank`,`noopener`)}catch(e){v(e instanceof Error?e.message:`报告打不开`)}finally{S(!1)}};return(0,H.jsxs)(`div`,{className:`project-detail`,"data-project-detail":e.id,children:[(0,H.jsxs)(`div`,{className:`project-detail-title`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h3`,{children:e.title}),(0,H.jsx)(`p`,{children:e.objective||`未填写目标`})]}),(0,H.jsxs)(`span`,{className:`project-detail-flags`,children:[e.mode===`lightweight`?(0,H.jsx)(`span`,{className:`project-mode-tag`,"data-project-mode":`lightweight`,children:`轻量`}):null,(0,H.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:qD(e.status)})]})]}),e.acceptanceCriteria?.length?(0,H.jsxs)(`p`,{className:`project-acceptance`,children:[(0,H.jsx)(`strong`,{children:`验收:`}),e.acceptanceCriteria.join(`;`)]}):null,(0,H.jsxs)(`div`,{className:`project-employees`,"data-project-employees":e.id,children:[(0,H.jsxs)(`span`,{className:`project-employee`,"data-project-employee":`executor`,children:[(0,H.jsx)(`b`,{children:`执行员工`}),WD(e.defaultExecutorProfile)||`未指定(用默认)`]}),(0,H.jsxs)(`span`,{className:`project-employee`,"data-project-employee":`reviewer`,children:[(0,H.jsx)(`b`,{children:`复核员工`}),WD(e.defaultReviewerProfile)||`未指定(用默认)`]})]}),(0,H.jsxs)(`div`,{className:`project-detail-summary`,children:[(0,H.jsxs)(`span`,{children:[`任务 `,(e.tasks??[]).length]}),(0,H.jsxs)(`span`,{children:[`待处理例外 `,w.length]}),(0,H.jsxs)(`span`,{children:[`最近更新 `,ZD(e.updatedAt)||`暂无`]})]}),(0,H.jsx)(`div`,{className:`project-detail-summary`,"data-project-budget":e.id,children:(0,H.jsxs)(`span`,{"data-project-budget-used":e.id,children:[`Token `,E.toLocaleString(),` / `,D?D.toLocaleString():`未设限`]})}),(0,H.jsx)(`p`,{className:`project-muted`,"data-project-budget-basis":`1`,children:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`}),(0,H.jsxs)(`div`,{className:`project-detail-actions`,children:[e.ownerConversationId&&r&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,onClick:()=>r(e.ownerConversationId),children:`查看负责人会话`}),!T&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void M(`start`),children:e.ownerConversationId?`唤起负责人继续执行`:`启动负责人会话`}),!T&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void M(``,{status:`cancelled`}),children:`停止项目及子会话`}),j&&(0,H.jsxs)(`button`,{type:`button`,className:`project-task-action`,"data-project-budget-raise":e.id,disabled:!!l,onClick:()=>void M(`budget/continue`),children:[O?`预算用完了`:`预算挡住了派发`,`:提到 `,A.toLocaleString(),` Token 并继续`]}),!T&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,title:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`,onClick:()=>{o(String(e.budget?.maxTokens??1e5)),c(String(e.budget?.maxConcurrent??2)),m(e=>!e)},children:`调整派发预算`}),(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,"data-project-report":e.id,disabled:x,onClick:()=>void N(),children:`复盘报告`})]}),p&&!T&&(0,H.jsxs)(`div`,{className:`project-form`,children:[(0,H.jsx)(`p`,{className:`project-muted`,"data-project-budget-basis-form":`1`,children:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`}),(0,H.jsxs)(`label`,{className:`project-field`,children:[(0,H.jsx)(`span`,{children:`Token 预算`}),(0,H.jsx)(`input`,{type:`number`,min:`1`,value:a,onChange:e=>o(e.target.value)})]}),(0,H.jsxs)(`label`,{className:`project-field`,children:[(0,H.jsx)(`span`,{children:`执行并发`}),(0,H.jsx)(`input`,{type:`number`,min:`1`,value:s,onChange:e=>c(e.target.value)})]}),(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void M(`budget`,{maxTokens:Number(a),maxConcurrent:Number(s)}),children:`保存预算`})]}),h?(0,H.jsx)(`p`,{className:`project-error`,role:`alert`,children:h}):null,_?(0,H.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-report-error":e.id,children:_}):null,y?(0,H.jsxs)(`p`,{className:`project-muted`,"data-project-report-note":e.id,children:[`如未自动打开新标签页,可点击此链接:`,(0,H.jsx)(`a`,{className:`md-link`,href:y,target:`_blank`,rel:`noopener`,"data-project-report-link":e.id,children:`在新标签页打开复盘报告`})]}):null,(0,H.jsxs)(`details`,{className:`project-section`,open:!0,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`执行团队`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(0,H.jsx)(YD,{sessions:e.resources?.sessions,onOpenSession:r,emptyText:`该项目还没有会话。`})})]}),(0,H.jsxs)(`details`,{className:`project-section`,open:!0,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`任务流转`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(e.tasks??[]).length===0?(0,H.jsx)(`p`,{className:`project-muted`,children:`秘书尚未拆解任务。`}):(0,H.jsx)(`ol`,{className:`project-task-list`,children:(e.tasks??[]).map(t=>(0,H.jsxs)(`li`,{className:`project-task`,"data-project-task":t.id,children:[(0,H.jsxs)(`div`,{className:`project-task-main`,children:[(0,H.jsx)(`span`,{className:`project-task-title`,children:t.title}),(0,H.jsx)(`span`,{className:`project-status project-status-${t.status}`,children:qD(t.status)}),(0,H.jsx)(`span`,{className:`project-task-owner`,children:t.ownerRole||(t.ownerConversationId?`已分配`:`待定负责人`)})]}),(0,H.jsxs)(`p`,{children:[t.role===`leader`?`分支 Leader`:`执行任务`,t.parentTaskId?` · 上级任务:${(e.tasks??[]).find(e=>e.id===t.parentTaskId)?.title??t.parentTaskId}`:` · 项目负责人直属`]}),t.acceptanceCriteria?.length?(0,H.jsx)(`p`,{children:t.acceptanceCriteria.join(`;`)}):null,t.blockedReason&&(0,H.jsxs)(`p`,{className:`project-blocker`,children:[`阻塞:`,t.blockedReason]}),t.review?.lightweight?(0,H.jsx)(`span`,{className:`project-delivery-tag project-delivery-tag-self`,"data-project-task-delivery":t.id,children:`自评交付 · 无独立复核`}):t.review?.verdict===`accepted`?(0,H.jsx)(`span`,{className:`project-delivery-tag`,"data-project-task-delivery":t.id,children:`已验收`}):null,t.review&&!t.review.lightweight?(0,H.jsxs)(`p`,{children:[`复核:`,t.review.summary]}):null,t.status===`ready`&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void M(`tasks/${encodeURIComponent(t.id)}/dispatch`),children:`派发`}),t.status===`awaiting_review`&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void M(`tasks/${encodeURIComponent(t.id)}/review`),children:`独立复核`}),[`blocked`,`failed`,`in_progress`].includes(t.status)&&(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l,onClick:()=>void M(`tasks/${encodeURIComponent(t.id)}`,{status:`ready`}),children:`恢复为待派发`})]},t.id))})})]}),w.length>0&&(0,H.jsxs)(`details`,{className:`project-section`,"data-project-exception-section":e.id,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsxs)(`h4`,{className:`project-section-title project-exception-heading`,"data-project-exception-heading":e.id,children:[`例外收件箱 `,(0,H.jsx)(`span`,{children:w.length})]})}),(0,H.jsxs)(`div`,{className:`project-section-body`,children:[(0,H.jsxs)(`label`,{className:`project-field`,children:[(0,H.jsx)(`span`,{children:`Boss 决策意见`}),(0,H.jsx)(`textarea`,{value:d,onChange:e=>f(e.target.value),placeholder:`明确决定、边界和后续动作`})]}),(0,H.jsx)(`ul`,{className:`project-exception-list`,children:w.map(e=>(0,H.jsxs)(`li`,{"data-project-exception":e.id,children:[(0,H.jsx)(`strong`,{children:e.reason||`需要处理`}),e.severity&&(0,H.jsxs)(`p`,{children:[`风险等级:`,e.severity]}),(0,H.jsx)(`button`,{type:`button`,className:`project-task-action`,disabled:!!l||!d.trim(),onClick:()=>void M(`escalations/${encodeURIComponent(e.id)}`,{decision:d,status:`resolved`}),children:`记录决策并交回负责人`})]},e.id))})]})]}),(e.reports??[]).length>0&&(0,H.jsxs)(`details`,{className:`project-section`,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`最近汇报`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(0,H.jsx)(`div`,{className:`project-report-list`,children:(e.reports??[]).slice(0,3).map(e=>(0,H.jsxs)(`article`,{className:`project-report`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:e.summary||qD(e.kind)}),(0,H.jsx)(`span`,{children:ZD(e.createdAt)})]}),e.progress&&(0,H.jsxs)(`p`,{children:[`进展:`,e.progress]}),e.decisionNeeded?(0,H.jsxs)(`p`,{children:[`待决策:`,e.decisionNeeded]}):null]},e.id))})})]}),(e.events??[]).length>0&&(0,H.jsxs)(`details`,{className:`project-section`,children:[(0,H.jsx)(`summary`,{className:`project-section-summary`,children:(0,H.jsx)(`h4`,{className:`project-section-title`,children:`事件时间线`})}),(0,H.jsx)(`div`,{className:`project-section-body`,children:(0,H.jsx)(`ul`,{className:`project-event-list`,children:(e.events??[]).slice(0,12).map(e=>(0,H.jsxs)(`li`,{"data-project-event":e.id,children:[(0,H.jsx)(`strong`,{children:e.summary}),(0,H.jsx)(`span`,{children:ZD(e.createdAt)})]},e.id))})})]})]})}function uO({workspaceId:e,notify:t,onOpenSession:n}){let[r,i]=(0,V.useState)([]),[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(``),[l,u]=(0,V.useState)([]),d=(0,V.useRef)(!1),[f,p]=(0,V.useState)([]),m=(0,V.useCallback)(async t=>{if(!e)i([]);else{o(!0),c(``);try{let n=await fetch(`/api/projects?workspaceId=${encodeURIComponent(e)}`,{signal:t}).then(QD),r=Array.isArray(n)?n:Array.isArray(n.projects)?n.projects:[];i(r),!d.current&&r.length&&(d.current=!0,u([r[0].id]))}catch(e){e.name!==`AbortError`&&c(e instanceof Error?e.message:`项目列表加载失败`)}finally{t?.aborted||o(!1)}}},[e]);(0,V.useEffect)(()=>{let e=new AbortController;return m(e.signal),()=>e.abort()},[m]),(0,V.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>void m(),5e3);return()=>window.clearInterval(t)},[m,e]);let h=(0,V.useMemo)(()=>{let e=Date.now();return r.map(t=>sO(t,e)).filter(e=>!!e).filter(e=>!f.includes(`${e.projectId}:${e.kind}`)).sort((e,t)=>nO[e.kind]-nO[t.kind]||t.updatedAt-e.updatedAt)},[r,f]),g=(0,V.useMemo)(()=>h.slice(0,iO),[h]),_=h.length-g.length,[v,y]=(0,V.useState)(!1),b=v?h:g,[x,S]=(0,V.useState)(!1),C=(0,V.useMemo)(()=>{let e=new Set(r.filter(e=>![`completed`,`cancelled`,`failed`].includes(e.status)).map(e=>e.id));for(let t of h)e.add(t.projectId);return e},[r,h]),w=(0,V.useMemo)(()=>x?r.filter(e=>C.has(e.id)):r,[x,r,C]),T=(0,V.useRef)(null),[E,D]=(0,V.useState)(0),O=e=>{u(t=>t.includes(e.projectId)?t:[...t,e.projectId]),T.current={projectId:e.projectId,target:e.target},D(e=>e+1)};return(0,V.useEffect)(()=>{if(!E)return;let e=T.current;if(T.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)}else e.target.kind===`task`&&e.target.taskId&&(n=t.querySelector(`[data-project-task="${e.target.taskId}"]`));let r=n??t,i=window.requestAnimationFrame(()=>{r.scrollIntoView({block:e.target.kind===`top`?`start`:`center`,inline:`nearest`})});return()=>window.cancelAnimationFrame(i)},[E]),(0,H.jsxs)(`section`,{className:`project-panel`,"data-project-panel":`1`,children:[(0,H.jsx)(`div`,{className:`rail-section-head project-panel-head`,children:(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`项目控制面`}),(0,H.jsx)(`p`,{className:`project-panel-subtitle`,children:`一次触发,一次交付;这里只显示需要管理的流转和例外。`})]})}),h.length>0&&(0,H.jsxs)(`div`,{className:`project-pending`,"data-project-pending":`1`,"data-project-pending-count":h.length,children:[b.map(e=>(0,H.jsxs)(`div`,{className:`project-pending-item`,"data-project-pending-item":e.projectId,"data-project-pending-kind":e.kind,children:[(0,H.jsxs)(`div`,{className:`project-pending-row`,children:[(0,H.jsx)(`span`,{className:`project-pending-kind project-pending-kind-${e.kind}`,"data-project-pending-label":e.kind,children:e.label}),(0,H.jsx)(`span`,{className:`project-pending-title`,"data-project-pending-title":e.projectId,children:e.projectTitle}),(0,H.jsx)(`button`,{type:`button`,className:`project-pending-action`,"data-project-pending-action":e.projectId,onClick:()=>O(e),children:e.actionLabel}),(0,H.jsx)(`button`,{type:`button`,className:`project-pending-close`,"data-project-pending-dismiss":e.projectId,"aria-label":`关闭「${e.projectTitle}」的这条提醒`,title:`关闭这条提醒(不改变项目状态)`,onClick:()=>p(t=>[...t,`${e.projectId}:${e.kind}`]),children:`×`})]}),(0,H.jsx)(`p`,{className:`project-pending-detail`,"data-project-pending-detail":e.projectId,children:e.detail})]},`${e.projectId}:${e.kind}`)),_>0&&(0,H.jsx)(`button`,{type:`button`,className:`project-pending-more`,"data-project-pending-more":`1`,"aria-expanded":v,onClick:()=>y(e=>!e),children:v?`收起`:`还有 ${_} 个`})]}),(0,H.jsxs)(`label`,{className:`project-pending-filter`,"data-project-pending-only-label":`1`,children:[(0,H.jsx)(`input`,{type:`checkbox`,"data-project-pending-only":`1`,checked:x,onChange:e=>S(e.target.checked)}),(0,H.jsx)(`span`,{className:`project-pending-filter-name`,children:`只看待办`}),(0,H.jsx)(`span`,{className:`project-pending-filter-state`,"data-project-pending-only-state":x?`on`:`off`,children:x?`已开启`:`已关闭`})]}),(0,H.jsx)(`p`,{className:`project-empty-hint`,"data-project-empty-hint":`1`,children:`在对话里告诉 AI 你要做什么,它会创建项目、拆解任务并组织分工。项目会挂在这条会话下面。`}),s&&(0,H.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-error":`1`,children:s}),e?a&&r.length===0?(0,H.jsx)(`p`,{className:`rail-empty`,children:`正在加载项目…`}):r.length===0?(0,H.jsx)(`p`,{className:`rail-empty`,"data-project-empty":`1`,children:`当前没有项目。`}):w.length===0?(0,H.jsx)(`p`,{className:`rail-empty`,"data-project-pending-empty":`1`,children:`没有需要关注的项目。`}):(0,H.jsx)(H.Fragment,{children:(0,H.jsx)(`div`,{className:`project-list`,"data-project-count":w.length,children:w.map(r=>{let i=cO(r),a=l.includes(r.id);return(0,H.jsxs)(`details`,{className:`project-block`,"data-project-block":r.id,open:a,onToggle:e=>{let t=e.currentTarget.open;u(e=>e.includes(r.id)===t?e:t?[...e,r.id]:e.filter(e=>e!==r.id))},children:[(0,H.jsxs)(`summary`,{className:`project-block-summary`,"data-project-summary":r.id,"data-project-row":r.id,children:[(0,H.jsxs)(`span`,{className:`project-block-head`,children:[(0,H.jsx)(`span`,{className:`project-list-title`,children:r.title}),r.mode===`lightweight`?(0,H.jsx)(`span`,{className:`project-mode-tag`,"data-project-mode":`lightweight`,children:`轻量`}):null,(0,H.jsx)(`span`,{className:`project-status project-status-${r.status}`,children:qD(r.status)})]}),(0,H.jsxs)(`span`,{className:`project-block-progress`,"data-project-progress":r.id,children:[(0,H.jsxs)(`span`,{"data-project-progress-tasks":`${i.done}/${i.total}`,children:[`完成 `,i.done,`/`,i.total]}),(0,H.jsxs)(`span`,{"data-project-progress-workers":i.workers,children:[`进行中 `,i.workers]}),(0,H.jsxs)(`span`,{"data-project-progress-tokens":i.tokenText,children:[`Token `,i.tokenText]}),(0,H.jsx)(`span`,{"data-project-progress-updated":r.updatedAt??``,children:ZD(r.updatedAt)||`暂无更新`})]})]}),(0,H.jsx)(lO,{project:r,workspaceId:e,notify:t,onOpenSession:n,onChanged:()=>void m()})]},r.id)})})}):(0,H.jsx)(`p`,{className:`rail-empty`,children:`请先选择工作区。`})]})}var dO=[{id:`overview`,glyph:`▣`,name:`项目总览`,description:`目标、状态和交付进度`},{id:`dependencies`,glyph:`⇢`,name:`依赖图`,description:`谁在等待谁`},{id:`responsibility`,glyph:`◎`,name:`责任查询`,description:`负责人、验收人与复核人`},{id:`exceptions`,glyph:`!`,name:`例外收件箱`,description:`阻塞、审批和风险`},{id:`evidence`,glyph:`✓`,name:`交付证据`,description:`产物、验证和引用`},{id:`resources`,glyph:`◫`,name:`资源护栏`,description:`Token、并发和容量`},{id:`timeline`,glyph:`≋`,name:`事件时间线`,description:`最近报告和状态变化`}],fO={planning:`待规划`,active:`执行中`,blocked:`已阻塞`,awaiting_approval:`等待审批`,awaiting_review:`待验收`,completed:`已完成`,failed:`失败`,cancelled:`已取消`,pending:`等待依赖`,ready:`待派发`,in_progress:`执行中`,running:`运行中`,idle:`空闲`,waiting:`排队中`,awaiting_background:`等待回传`,stopped:`已停止`,progress:`进展`,review:`复核`,delivery:`交付`,decision_request:`请求决策`},pO=e=>fO[e??``]??e??`未知`,mO=e=>{if(!e)return``;let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Math.max(0,Math.floor((Date.now()-t)/6e4));if(n<1)return`刚刚`;if(n<60)return`${n} 分钟前`;let r=Math.floor(n/60);return r<24?`${r} 小时前`:`${Math.floor(r/24)} 天前`};async function hO(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`查询失败(${e.status})`);return t}function gO(e){let t=e.tasks??[];return{total:t.length,done:t.filter(e=>e.status===`completed`).length,active:t.filter(e=>[`ready`,`in_progress`,`awaiting_review`].includes(e.status)).length,blocked:t.filter(e=>e.status===`blocked`).length,openEscalations:(e.escalations??[]).filter(e=>e.status===`open`).length}}function _O({tasks:e}){let t=new Map,n=(r,i=new Set)=>{if(t.has(r.id))return t.get(r.id);if(i.has(r.id))return 0;let a=new Set(i).add(r.id),o=Math.max(0,...[...r.dependencies??[],...r.parentTaskId?[r.parentTaskId]:[]].map(t=>{let r=e.find(e=>e.id===t);return r?n(r,a)+1:0}));return t.set(r.id,o),o},r=new Map,i=e.map(e=>{let t=n(e),i=r.get(t)??0;return r.set(t,i+1),{...e,x:i*190+10,y:t*100+10}}),a=Math.max(300,...i.map(e=>e.x+180)),o=Math.max(80,...i.map(e=>e.y+70));return(0,H.jsx)(`div`,{className:`tool-dependency-scroll`,tabIndex:0,"aria-label":`可滚动任务依赖图`,children:(0,H.jsxs)(`svg`,{width:a,height:o,role:`img`,"aria-label":`任务依赖图,箭头由前置任务指向后续任务`,children:[(0,H.jsx)(`title`,{children:`任务依赖图,完成独立验收后解锁下游`}),(0,H.jsx)(`defs`,{children:(0,H.jsx)(`marker`,{id:`project-dependency-arrow`,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,H.jsx)(`path`,{d:`M 0 0 L 10 5 L 0 10 z`})})}),i.flatMap(e=>(e.dependencies??[]).map(t=>{let n=i.find(e=>e.id===t);return n?(0,H.jsx)(`path`,{className:`tool-dependency-edge`,d:`M ${n.x+85} ${n.y+60} C ${n.x+85} ${n.y+80}, ${e.x+85} ${e.y-20}, ${e.x+85} ${e.y}`,markerEnd:`url(#project-dependency-arrow)`},`${t}:${e.id}`):null})),i.filter(e=>e.parentTaskId).map(e=>{let t=i.find(t=>t.id===e.parentTaskId);return t?(0,H.jsx)(`path`,{className:`tool-organization-edge`,d:`M ${t.x+85} ${t.y+60} L ${e.x+85} ${e.y}`,children:(0,H.jsxs)(`title`,{children:[t.title,` 管理 `,e.title]})},`org:${e.id}`):null}),i.map(e=>(0,H.jsxs)(`g`,{className:`tool-dependency-node tool-dependency-${e.status}`,children:[(0,H.jsxs)(`title`,{children:[e.title,`:`,pO(e.status)]}),(0,H.jsx)(`rect`,{x:e.x,y:e.y,width:`170`,height:`60`,rx:`7`}),(0,H.jsx)(`text`,{x:e.x+9,y:e.y+23,children:e.title.length>18?`${e.title.slice(0,17)}…`:e.title}),(0,H.jsx)(`text`,{x:e.x+9,y:e.y+44,children:pO(e.status)})]},e.id))]})})}function vO({workspaceId:e,onOpenSession:t}){let[n,r]=(0,V.useState)([]),[i,a]=(0,V.useState)(),[o,s]=(0,V.useState)(`overview`),[c,l]=(0,V.useState)(``),[u,d]=(0,V.useState)(``),[f,p]=(0,V.useState)(``),m=(0,V.useCallback)(async t=>{if(!e)r([]);else try{let n=await fetch(`/api/projects?workspaceId=${encodeURIComponent(e)}`,{signal:t}).then(hO),i=Array.isArray(n?.projects)?n.projects:[];r(i),a(e=>e&&i.some(t=>t.id===e)?e:i[0]?.id),l(``)}catch(e){e.name!==`AbortError`&&l(e instanceof Error?e.message:`项目查询失败`)}},[e]);(0,V.useEffect)(()=>{let e=new AbortController;return m(e.signal),()=>e.abort()},[m]),(0,V.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>void m(),5e3);return()=>window.clearInterval(t)},[m,e]);let h=(0,V.useMemo)(()=>n.find(e=>e.id===i),[n,i]),g=h?.tasks??[],_=e=>h?.resources?.sessions.find(t=>t.id===e)?.title??e??`待分配`,v=e=>e&&t?(0,H.jsx)(`button`,{type:`button`,className:`tool-session-link`,onClick:()=>t(e),children:_(e)}):_(e),y=e=>e.toLocaleLowerCase().includes(u.trim().toLocaleLowerCase()),b=e=>WD(UD(e.effectiveExecutorProfile,e.executorProfile,h?.defaultExecutorProfile)),x=e=>WD(UD(e.effectiveReviewerProfile,e.reviewerProfile,h?.defaultReviewerProfile)),S=g.filter(e=>(!f||e.status===f)&&y([e.title,e.output,e.blockedReason,_(e.ownerConversationId),_(e.reviewerConversationId),b(e),x(e),...e.evidenceRefs??[],e.review?.summary,e.review?.verdict===`accepted`?`通过`:e.review?.verdict===`changes_requested`?`返工`:``,...e.review?.evidenceRefs??[]].filter(Boolean).join(` `))),C=h?gO(h):void 0,w=(h?.escalations??[]).filter(e=>e.status===`open`).filter(e=>{let t=e.taskId?g.find(t=>t.id===e.taskId):void 0;return y([e.reason,e.decision,e.severity,t?.title,e.taskId,_(e.requestedByConversationId)].filter(Boolean).join(` `))}),T=g.filter(e=>e.status===`blocked`).filter(e=>y([e.title,e.blockedReason,_(e.ownerConversationId),_(e.reviewerConversationId)].filter(Boolean).join(` `))),E=S.flatMap(e=>[...(e.evidenceRefs??[]).map(t=>({label:e.title,value:t,type:`引用`})),...e.output?[{label:e.title,value:e.output,type:`交付物`}]:[],...e.review?[{label:e.title,value:`${e.review.verdict===`accepted`?`通过`:`返工`}:${e.review.summary}`,type:`独立复核`},...e.review.evidenceRefs.map(t=>({label:e.title,value:t,type:`验证引用`}))]:[]]).filter(e=>y([e.label,e.value,e.type].join(` `)));return(0,H.jsxs)(`section`,{className:`tool-execution`,"data-tool-execution":`1`,children:[(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`企业执行工具`}),(0,H.jsx)(`p`,{className:`tool-execution-subtitle`,children:`只读查询项目状态、责任、依赖、证据和例外。`})]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-execution-refresh`,onClick:()=>void m(),disabled:!e,children:`刷新`})]}),c&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-execution-error":`1`,children:c}),n.length>0&&(0,H.jsxs)(`label`,{className:`tool-execution-project`,children:[(0,H.jsx)(`span`,{children:`当前项目`}),(0,H.jsx)(`select`,{value:i??``,onChange:e=>a(e.target.value),children:n.map(e=>(0,H.jsxs)(`option`,{value:e.id,children:[e.title,` · `,pO(e.status)]},e.id))})]}),(0,H.jsx)(`div`,{className:`tool-execution-grid`,role:`tablist`,"aria-label":`企业执行查询工具`,children:dO.map(e=>(0,H.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===e.id,className:`tool-execution-tile${o===e.id?` tool-execution-tile-active`:``}`,"data-exec-tool":e.id,onClick:()=>s(e.id),children:[(0,H.jsx)(`span`,{className:`tool-execution-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.jsx)(`small`,{children:e.description})]})]},e.id))}),h&&(0,H.jsxs)(`div`,{className:`tool-execution-query`,children:[(0,H.jsxs)(`label`,{children:[`搜索任务、负责人、复核或例外`,(0,H.jsx)(`input`,{type:`search`,value:u,onChange:e=>d(e.target.value)})]}),[`dependencies`,`responsibility`,`evidence`].includes(o)&&(0,H.jsxs)(`label`,{children:[`任务状态`,(0,H.jsxs)(`select`,{value:f,onChange:e=>p(e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`全部状态`}),[`pending`,`ready`,`in_progress`,`awaiting_review`,`blocked`,`completed`,`failed`].map(e=>(0,H.jsx)(`option`,{value:e,children:pO(e)},e))]})]})]}),(0,H.jsx)(`div`,{className:`tool-execution-body`,role:`tabpanel`,"data-exec-tool-body":o,children:(()=>{if(!h)return(0,H.jsx)(`p`,{className:`tool-execution-empty`,children:`当前工作区还没有项目。先在「项目」tab 触发一个项目。`});if(o===`overview`)return(0,H.jsxs)(`div`,{className:`tool-execution-overview`,children:[(0,H.jsx)(`p`,{className:`tool-execution-objective`,children:h.objective}),(0,H.jsxs)(`div`,{className:`tool-execution-metrics`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`strong`,{children:[C?.done??0,`/`,C?.total??0]}),(0,H.jsx)(`span`,{children:`任务完成`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:C?.active??0}),(0,H.jsx)(`span`,{children:`进行中`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:C?.blocked??0}),(0,H.jsx)(`span`,{children:`已阻塞`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:C?.openEscalations??0}),(0,H.jsx)(`span`,{children:`待处理例外`})]})]}),(0,H.jsxs)(`p`,{className:`tool-execution-note`,children:[`项目状态:`,(0,H.jsx)(`b`,{children:pO(h.status)}),` · 风险:`,(0,H.jsx)(`b`,{children:h.risk}),` · 更新:`,mO(h.updatedAt)||`暂无`]})]});if(o===`dependencies`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{className:`tool-execution-note`,children:`实线箭头:前置交付依赖;虚线:直属管理关系。前置任务验收通过后才能开始后续任务。`}),g.length>0&&(0,H.jsx)(_O,{tasks:g}),(0,H.jsx)(`ol`,{className:`tool-execution-list`,children:S.length===0?(0,H.jsx)(`li`,{children:`暂无匹配任务。`}):S.map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:e.title}),(0,H.jsx)(`span`,{className:`tool-execution-status`,children:pO(e.status)}),(0,H.jsx)(`small`,{children:e.dependencies?.length?`等待:${e.dependencies.map(e=>g.find(t=>t.id===e)?.title??e).join(`、`)}`:`无前置依赖`}),e.parentTaskId&&(0,H.jsxs)(`small`,{children:[`直属上级任务:`,g.find(t=>t.id===e.parentTaskId)?.title]})]},e.id))})]});if(o===`responsibility`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`p`,{className:`tool-execution-note`,children:[`项目负责人:`,v(h.ownerConversationId)]}),(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:S.length===0?(0,H.jsx)(`li`,{children:`暂无匹配的责任分配。`}):S.map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsxs)(`strong`,{children:[e.title,` · `,e.role===`leader`?`分支 Leader`:`执行任务`]}),(0,H.jsxs)(`small`,{children:[`执行:`,v(e.ownerConversationId)]}),(0,H.jsxs)(`small`,{children:[`最终负责:`,v(e.accountableConversationId)]}),(0,H.jsxs)(`small`,{children:[`独立复核:`,v(e.reviewerConversationId)]}),(0,H.jsxs)(`small`,{className:`tool-task-employee`,"data-task-employee":`executor`,children:[`执行员工:`,WD(UD(e.effectiveExecutorProfile,e.executorProfile,h.defaultExecutorProfile))||`未指定`]}),(0,H.jsxs)(`small`,{className:`tool-task-employee`,"data-task-employee":`reviewer`,children:[`复核员工:`,WD(UD(e.effectiveReviewerProfile,e.reviewerProfile,h.defaultReviewerProfile))||`未指定`]}),e.parentTaskId&&(0,H.jsxs)(`small`,{children:[`上级任务:`,g.find(t=>t.id===e.parentTaskId)?.title]})]},e.id))})]});if(o===`exceptions`)return(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:w.length===0&&T.length===0?(0,H.jsx)(`li`,{children:u.trim()?`暂无匹配的例外事项。`:`当前没有需要 Boss 处理的例外。`}):(0,H.jsxs)(H.Fragment,{children:[w.map(e=>(0,H.jsxs)(`li`,{className:`tool-execution-exception`,children:[(0,H.jsx)(`strong`,{children:e.reason}),(0,H.jsxs)(`span`,{children:[e.severity,` · 待处理`]}),(0,H.jsx)(`small`,{children:e.taskId?g.find(t=>t.id===e.taskId)?.title??e.taskId:`项目级事项`})]},e.id)),T.map(e=>(0,H.jsxs)(`li`,{className:`tool-execution-exception`,children:[(0,H.jsx)(`strong`,{children:e.title}),(0,H.jsx)(`span`,{children:`任务阻塞`}),(0,H.jsx)(`small`,{children:e.blockedReason??`执行者未提供原因`})]},e.id))]})});if(o===`evidence`)return(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:E.length===0?(0,H.jsx)(`li`,{children:`暂无交付证据。任务完成时应附上产物或验证引用。`}):E.map((e,t)=>(0,H.jsxs)(`li`,{children:[(0,H.jsxs)(`strong`,{children:[e.type,` · `,e.label]}),(0,H.jsx)(`small`,{children:e.value})]},`${e.label}:${e.value}:${t}`))});if(o===`resources`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`tool-execution-resource`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`strong`,{children:[h.resources?.tokens.toLocaleString()??`0`,` / `,h.budget?.maxTokens?.toLocaleString()??`未设限`]}),(0,H.jsx)(`span`,{children:`已报告 Token / 派发预算`})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`strong`,{children:[h.resources?.activeWorkers??0,` / `,h.budget?.maxConcurrent??`未设限`]}),(0,H.jsx)(`span`,{children:`运行中执行者 / 并发上限`})]}),(0,H.jsxs)(`p`,{children:[`负责人保留独立协调容量。达到预算或并发上限时拒绝新派发;运行中的请求可能超过预算。`,!h.resources?.usageKnown&&`部分用量尚未上报,显示已知用量。`]}),(0,H.jsx)(`p`,{className:`project-muted`,"data-tool-budget-basis":`1`,children:`口径:输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1(等效计费 Token)`})]}),(0,H.jsx)(YD,{sessions:h.resources?.sessions.filter(e=>y(e.title)),onOpenSession:t,emptyText:u.trim()?`没有匹配的会话。`:`该项目还没有会话。`})]});let e=[...h.events??[]].filter(e=>y(e.summary)).sort((e,t)=>Date.parse(t.createdAt)-Date.parse(e.createdAt));return(0,H.jsx)(`ul`,{className:`tool-execution-list`,children:e.length===0?(0,H.jsx)(`li`,{children:`暂无匹配事件。`}):e.map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsx)(`strong`,{children:e.summary}),(0,H.jsxs)(`small`,{children:[mO(e.createdAt),e.taskId?` · ${g.find(t=>t.id===e.taskId)?.title??e.taskId}`:``]})]},e.id))})})()})]})}function yO(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function bO(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}var xO=(e,t)=>e.updatedAt<t.updatedAt?1:e.updatedAt>t.updatedAt?-1:0;function SO(e,t){let n=new Set(e.map(e=>e.id)),r=new Map,i=[];for(let t of e){let e=t.parentConversationId;if(e&&n.has(e)){let n=r.get(e);n?n.push(t):r.set(e,[t])}else i.push(t)}for(let e of r.values())e.sort(xO);i.sort(xO);let a=[],o=new Set,s=(e,n,i,c=!0)=>{if(o.has(e.id))return;o.add(e.id);let l=r.get(e.id)??[];c&&a.push({conversation:e,depth:Math.min(n,8),childCount:l.length,isLastSibling:i});let u=!c||t.has(e.id);for(let[e,t]of l.entries())s(t,n+1,e===l.length-1,!u)};for(let e of i)s(e,0,!1);let c=e.filter(e=>!o.has(e.id)).sort(xO);for(let e of c)s(e,0,!1);return a}var CO=`super-pi:tool-shortcuts:v1`,wO=new Set([`Control`,`Alt`,`Shift`,`Meta`,`AltGraph`,`CapsLock`,`Fn`,`FnLock`,`Hyper`,`Super`,`Symbol`,`SymbolLock`]),TO=new Set([`Escape`]),EO=new Set([`Enter`,` `,`Tab`]),DO={" ":`Space`,ArrowUp:`↑`,ArrowDown:`↓`,ArrowLeft:`←`,ArrowRight:`→`,Escape:`Esc`},OO={ctrl:`⌃`,alt:`⌥`,shift:`⇧`,meta:`⌘`};function kO(e){if(e===` `)return` `;let t=e.trim();return t?t.length===1?t.toLowerCase():t:``}function AO(e){return wO.has(e)}function jO(e){let t=e.key;if(!t||t===`Unidentified`||t===`Dead`||AO(t))return;let n=kO(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 MO(e){return DO[e]||(e.length===1||/^f\d{1,2}$/.test(e)?e.toUpperCase():e)}function NO(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(MO(e.key)),t.join(`+`)}function PO(e){let t=``;return e.ctrl&&(t+=OO.ctrl),e.alt&&(t+=OO.alt),e.shift&&(t+=OO.shift),e.meta&&(t+=OO.meta),t+MO(e.key)}function FO(e,t){return e.key===t.key&&!!e.ctrl==!!t.ctrl&&!!e.alt==!!t.alt&&!!e.shift==!!t.shift&&!!e.meta==!!t.meta}function IO(e){return!!(e.ctrl||e.alt||e.shift||e.meta)}function LO(e){return e.key?TO.has(e.key)?{ok:!1,reason:`Esc 是所有弹窗的退出键,不能拿来当工具快捷键。`}:!IO(e)&&EO.has(e.key)?{ok:!1,reason:`「${RO(e.key)}」是当前焦点控件的激活键,加一个修饰键(Ctrl / Alt / Shift)才能当快捷键用。`}:{ok:!0}:{ok:!1,reason:`这个组合键不完整,请按一个具体的键。`}}function RO(e){return MO(e)}function zO(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 BO(e,t){if(t.isComposing||t.defaultPrevented)return!1;let n=jO(t);return!(!n||!FO(e,n)||!IO(e)&&zO(t.target??null))}function VO(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=kO(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),LO(a).ok&&(n[e]=a)}return n}function HO(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 UO(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&FO(i,t))return r}var WO=`super-pi:tool-settings-size:v1`,GO={width:480,height:320};function KO(){try{if(typeof window>`u`)return vv.slice();let e=wv(window.localStorage.getItem(xv));return window.localStorage.getItem(`super-pi:tools:v1`)===null?vv.slice():e}catch{return vv.slice()}}function qO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(xv,Tv(e))}catch{}}function JO(){try{return typeof window>`u`?{}:VO(window.localStorage.getItem(CO))}catch{return{}}}function YO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(CO,HO(e))}catch{}}function XO(){try{if(typeof window>`u`)return;let e=window.localStorage.getItem(WO);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<GO.width||t.height<GO.height?void 0:{width:Math.round(t.width),height:Math.round(t.height)}}catch{return}}function ZO(e){try{if(typeof window>`u`)return;e?window.localStorage.setItem(WO,JSON.stringify({width:Math.round(e.width),height:Math.round(e.height)})):window.localStorage.removeItem(WO)}catch{}}function QO(e,t,n){let r=Math.max(GO.width,t-32),i=Math.max(GO.height,n-32);return{width:Math.round(Math.min(Math.max(e.width,GO.width),r)),height:Math.round(Math.min(Math.max(e.height,GO.height),i))}}var $O={tools:KO(),mountedTools:[],settingsOpen:!1,shortcuts:JO()},ek=new Set;function tk(e){$O={...$O,...e};for(let e of ek)e()}function nk(e){return ek.add(e),()=>{ek.delete(e)}}var rk=()=>$O;function ik(){return(0,V.useSyncExternalStore)(nk,rk,rk)}var ak={setTools(e){qO(e),tk({tools:e})},removeTool(e){let t=kv($O.tools,e);if($O.shortcuts[e]){let t={...$O.shortcuts};delete t[e],YO(t),tk({shortcuts:t})}qO(t),tk({tools:t,openToolId:$O.openToolId===e?void 0:$O.openToolId})},setMountedTools(e){tk({mountedTools:e})},openTool(e){tk({openToolId:e,settingsOpen:!1})},closeTool(){tk({openToolId:void 0})},toggleTool(e){$O.openToolId===e?ak.closeTool():ak.openTool(e)},openSettings(){tk({settingsOpen:!0,openToolId:void 0})},closeSettings(){tk({settingsOpen:!1})},setShortcut(e,t){let n={...$O.shortcuts,[e]:t};YO(n),tk({shortcuts:n})},clearShortcut(e){if(!$O.shortcuts[e])return;let t={...$O.shortcuts};delete t[e],YO(t),tk({shortcuts:t})},persistTools(){qO($O.tools)}};async function ok(){try{let e=await fetch(`/api/tools`),t=await e.json();e.ok&&Array.isArray(t.tools)&&ak.setMountedTools(t.tools.filter(e=>e.enabled))}catch{}}async function sk(e){try{let t=await fetch(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);ak.closeTool(),await ok();return}catch(e){return e instanceof Error?e.message:String(e)}}var ck=`.super-pi-tool.json`,lk=512e3,uk=/^[a-z0-9][a-z0-9-]{0,63}$/,dk=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function fk(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${ck})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i=typeof r.format==`string`?r.format:void 0;if(i!==void 0&&i!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${i})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let a=typeof r.slug==`string`?r.slug.trim():``,o=typeof r.name==`string`?r.name.trim():``;if(!a)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!o)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 s=[],c=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(s.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(c+=new TextEncoder().encode(t.content).length,c>512e3)return{ok:!1,reason:`工具文件合计超过 ${bk(lk)} 的上限。`};s.push({path:n,content:t.content})}let l=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!l.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!s.some(e=>e.path===l))return{ok:!1,reason:`工具包里没有包含入口文件 ${l}。`};let u;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(!s.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};u={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let d;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`||!dk.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;d={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let f=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:i===void 0,bundle:{...i===void 0?{}:{format:i},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:a,name:o,...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:l,files:s,script:u,environment:d,...f?{permissions:f}:{}}}}function pk(e){let t=e.trim().toLowerCase();return t?uk.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function mk(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 hk(e){return`${e.slug}${ck}`}function gk(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}${ck}`}:{ok:!1,reason:`请填写文件名。`}}function _k(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function vk(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 yk(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 bk(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function xk(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var Sk={workspaces:[],conversations:[],subagentRuns:[]},Ck=e=>e.nativeEvent.isComposing||e.keyCode===229,wk=(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},Tk=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)},Ek=6e4,Dk=60*Ek,Ok=24*Dk,kk=7*Ok,Ak=30*Ok,jk=365*Ok,Mk=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<Dk?`${Math.max(1,Math.floor(r/Ek))}m ago`:r<Ok?`${Math.floor(r/Dk)}h ago`:r<kk?`${Math.floor(r/Ok)}d ago`:r<Ak?`${Math.floor(r/kk)}w ago`:r<jk?`${Math.floor(r/Ak)}mo ago`:`${Math.floor(r/jk)}y ago`},Nk=(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},Pk=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`)}`},Fk=1e3,Ik=3e4,Lk=async e=>{try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0;pointer-events:none`,document.body.appendChild(t);try{return t.select(),t.setSelectionRange(0,t.value.length),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}};function Rk({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,V.useRef)(null),[o,s]=(0,V.useState)({left:t,top:n});(0,V.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,V.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 Lk(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,H.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,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,H.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function zk({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a,sendCommand:o,orchestrated:s,childCount:c}){let l=(0,V.useRef)(null),[u,d]=(0,V.useState)({left:t,top:n});(0,V.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let r=e.getBoundingClientRect();d({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,V.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 f=async e=>{try{let t=await fetch(`/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(`停止失败:${tp(e)}`,`error`)}},p=async e=>{try{let t=await fetch(`/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(`停止子树失败:${tp(e)}`,`error`)}},m=async()=>{let t=await Lk(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,H.jsxs)(`div`,{ref:l,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:u.left,top:u.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void m(),children:`复制会话 ID`}),(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),(0,H.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,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-queue":e.id,onClick:()=>{a(),f(e.id)},children:`停止会话(含排队消息)`}),c>0&&(0,H.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-tree":e.id,onClick:()=>{a(),p(e.id)},children:[`停止整棵子树(`,c,` 个下属)`]}),(0,H.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var Bk={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},Vk=`请从刚才被截断的地方接着写完,不要重复已经写过的内容。`,Hk={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},Uk={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},Wk=`图文`,Gk=e=>e.imageInput?Wk:void 0,Kk=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),qk=(e,t)=>{let n=Kk(t.trim());return n?e.filter(e=>Kk(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function Jk({workspaceId:e,value:t,onChange:n}){let[r,i]=(0,V.useState)([]),[a,o]=(0,V.useState)(``);(0,V.useEffect)(()=>{i([]),o(``)},[e]),(0,V.useEffect)(()=>{let n=!0;return o(``),fetch(`/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,H.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,H.jsx)(`label`,{htmlFor:`empty-session-cwd`,children:`工作目录:`}),(0,H.jsxs)(`select`,{id:`empty-session-cwd`,"data-session-cwd-select":`1`,"aria-label":`会话工作目录(可选)`,value:t,onChange:e=>n(e.target.value),children:[(0,H.jsx)(`option`,{value:``,children:`工作区根目录`}),s.map(e=>(0,H.jsx)(`option`,{value:e,children:e},e))]}),a&&(0,H.jsx)(`span`,{role:`status`,children:a})]})}function Yk({workspace:e,onClose:t,onCreate:n}){let[r,i]=(0,V.useState)(``),a=(0,V.useRef)(null);return(0,V.useEffect)(()=>{i(``)},[e.id]),(0,V.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,H.jsx)(`div`,{className:`overlay session-create-overlay`,onClick:t,children:(0,H.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,H.jsx)(`h2`,{id:`session-create-title`,children:`新建会话`}),(0,H.jsxs)(`p`,{className:`session-create-workspace`,children:[`工作区:`,e.name,(0,H.jsx)(`small`,{children:e.path})]}),(0,H.jsx)(Jk,{workspaceId:e.id,value:r,onChange:i}),(0,H.jsxs)(`div`,{className:`session-create-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`session-create-cancel`,onClick:t,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`session-create-confirm picker-ok`,onClick:()=>n(r),children:`创建会话`})]})]})})}function Xk({onClose:e,onCreate:t}){let[n,r]=(0,V.useState)(),[i,a]=(0,V.useState)(!0),[o,s]=(0,V.useState)(),[c,l]=(0,V.useState)(``),[u,d]=(0,V.useState)(``),f=async e=>{a(!0),s(void 0);try{let t=await fetch(`/api/fs/dirs${e?`?path=${encodeURIComponent(e)}`:``}`),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let i=n;r(i),d(i.path),l(i.suggestedName)}catch(e){s(e instanceof Error?e.message:`目录加载失败`)}finally{a(!1)}};(0,V.useEffect)(()=>{f()},[]),(0,V.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let p=e=>{e?.preventDefault();let t=u.trim();t&&f(t)};return(0,H.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,H.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`h2`,{children:`选择工作区目录`}),(0,H.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:p,children:[(0,H.jsx)(`input`,{className:`picker-path-input`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(Ck(e)?e.preventDefault():(e.preventDefault(),p()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,H.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!u.trim()||i,children:`跳转`}),(0,H.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!n?.parent||i,onClick:()=>n?.parent&&void f(n.parent),title:`返回上一级目录`,children:`上一级`})]}),n?.drives?.length||n?.homeDir?(0,H.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,H.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),n?.homeDir&&(0,H.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(`~`),title:n.homeDir,children:`🏠 主目录`}),n?.drives?.map(e=>(0,H.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(e),children:e},e))]}):null,(0,H.jsxs)(`div`,{className:`picker-list`,children:[i&&(0,H.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!i&&o&&(0,H.jsxs)(`div`,{className:`picker-error`,children:[o,(0,H.jsx)(`button`,{onClick:()=>void f(n?.path||u),children:`重试`})]}),!i&&!o&&n?.entries.map(e=>(0,H.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void f(e.path),children:[`📁 `,e.name]},e.path)),!i&&!o&&n&&n.entries.length===0&&(0,H.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!i&&!o&&n?.truncated&&(0,H.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,H.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,H.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(Ck(e)?e.preventDefault():(e.preventDefault(),c.trim()&&n&&t(c.trim(),n.path)))},placeholder:`工作区名称`})]}),(0,H.jsxs)(`div`,{className:`picker-actions`,children:[(0,H.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,H.jsx)(`button`,{className:`picker-ok`,disabled:!c.trim()||i||!!o||!n,onClick:()=>n&&t(c.trim(),n.path),children:`使用这个目录`})]})]})})}var Zk={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},Qk=10;function $k(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(`
93
+ `).find(e=>e.trim().startsWith(`-`))?.trim()??`详情见设置`}`;if(e===`模型`&&n)return`此会话已包含图片,仅显示支持图文的模型`}function eA(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 tA=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function nA(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 rA={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function iA(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 aA({task:e,initialOutput:t,expanded:n}){let[r,i]=(0,V.useState)(t);(0,V.useEffect)(()=>{let n=t,r,a=t=>{let a=t.detail;a.sessionId===e.id&&(n=(n+a.data).slice(-512e3),r===void 0&&(r=requestAnimationFrame(()=>{r=void 0,i(n)})))};return window.addEventListener(`super-pi-exec-output`,a),()=>{window.removeEventListener(`super-pi-exec-output`,a),r!==void 0&&cancelAnimationFrame(r)}},[e.id]);let a=e.output??r;return(0,H.jsxs)(H.Fragment,{children:[!n&&a&&(0,H.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:iA(a)}),n&&(0,H.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:a||`等待输出…`})]})}function oA({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,H.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,H.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,H.jsxs)(`div`,{className:`call-head-row`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,H.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,H.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,H.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,H.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,H.jsx)(`span`,{className:`call-duration`,children:nA(e.durationMs)}),e.backgroundTask&&(0,H.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,e.backgroundTask.status===`running`?`运行中`:e.backgroundTask.status===`completed`?`已完成`:`失败`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,H.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,H.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,H.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:iA(e.live)}),n&&(0,H.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,H.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,H.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,H.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,H.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,H.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,H.jsxs)(`div`,{className:`call-result-head`,children:[(0,H.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,H.jsx)(sA,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,H.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,H.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,H.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function sA({index:e,text:t}){let[n,r]=(0,V.useState)(!1);return(0,H.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await Lk(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function cA({messageId:e,nestedCount:t,liveCall:n,liveAwaitingReader:r,liveExtra:i,preview:a,expanded:o,onToggle:s,children:c}){return(0,H.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":o?`true`:`false`,"data-thinking-calls":t,children:[(0,H.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":o,"aria-label":`${o?`折叠`:`展开`}这段思考`,title:o?`折叠这段思考`:`展开这段思考`,onClick:s}),(0,H.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":o,title:o?`折叠这段思考`:`展开这段思考`,onClick:s,children:[(0,H.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`}),(0,H.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,H.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!o&&n&&(0,H.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,H.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:r?`?`:`⚙`}),r?`等你回答`:`正在执行 ${n}`,i?` 等 ${i+1} 个`:``]}),!o&&a&&(0,H.jsx)(`span`,{className:`thinking-preview`,title:a,children:a})]}),o&&(0,H.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:c})]})}function lA({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`,u=e.output??``,d=e.dispatchedBy===`model`,[f,p]=(0,V.useState)(0);(0,V.useEffect)(()=>{if(!l)return;p(Date.now());let e=window.setInterval(()=>p(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let m=Date.parse(e.startedAt),h=l&&f>0&&Number.isFinite(m)?f-m:void 0,g=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,H.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${d?` 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":d?`model`:`human`,children:[(0,H.jsxs)(`div`,{className:`subagent-head`,children:[(0,H.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,H.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,H.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,H.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,H.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?h!==void 0&&(0,H.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":h,children:[`已运行 `,nA(h)]}):e.durationMs!==void 0&&(0,H.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,nA(e.durationMs)]}),l&&(0,H.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,H.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,H.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,H.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,H.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,H.jsx)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:u||(l?`…`:e.outputTruncated?`(已按 50 KB 上限截断,浏览器仍收到完整内容)`:`(没有输出)`)}),e.failure&&(0,H.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,H.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,H.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:rA[e.failure.stage]}),e.failure.stage===`tool`&&g&&(0,H.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,g]}),o.length>0&&(0,H.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,H.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,title:np(e.error),children:tp(e.error,`这条子任务没有完成。`)}),o.length>0&&(0,H.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,H.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,H.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,H.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,H.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,H.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,H.jsx)(`span`,{className:`subagent-tool-duration`,children:nA(e.durationMs)})]},`${t}:${e.label}`))]}),e.usage&&(0,H.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,H.jsxs)(`span`,{children:[e.usage.turns,` 轮`]}),(0,H.jsxs)(`span`,{title:`输入 token`,children:[`↑`,tA(e.usage.input)]}),(0,H.jsxs)(`span`,{title:`输出 token`,children:[`↓`,tA(e.usage.output)]}),e.usage.cacheRead>0&&(0,H.jsxs)(`span`,{title:`缓存读取`,children:[`缓存读 `,tA(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,H.jsxs)(`span`,{title:`缓存写入`,children:[`缓存写 `,tA(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,H.jsxs)(`span`,{title:`本轮花费`,children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,H.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function uA({messages:e,running:t,pendingInterrupts:n=[],onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:s}){let[c,l]=(0,V.useState)(!1);if(!e.length)return null;let u=e.filter(e=>e.delivery===`sending`).length;return(0,H.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-interrupt-pending":n.length,"data-queue-count":e.length,"data-queue-sending":u,"aria-label":`排队等待回答的消息`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!c,onClick:()=>l(e=>!e),children:[(0,H.jsx)(`span`,{className:`chevron`,children:c?`▸`:`▾`}),(0,H.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),u>0&&(0,H.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,u,` 条`]}),c&&(0,H.jsx)(`span`,{className:`queue-dock-preview`,children:dA(e[0])})]}),!c&&(0,H.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((c,l)=>(0,H.jsx)(pA,{message:c,order:l+1,total:e.length,interrupting:n.includes(c.id),running:t,onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:s},c.id))})]})}function dA(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function fA(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};if(!/<task id="[^"]+" state="[^"]+"/.test(e.content))return{label:(e.content.split(`
94
+ `).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 pA({message:e,order:t,total:n,running:r,interrupting:i=!1,onSteer:a,onInterrupt:o,onSend:s,onCancel:c,onEdit:l}){let[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(e.content),m=e.delivery===`sending`,h=e.role===`tool`,{label:g,state:_}=h?fA(e):{label:dA(e),state:`user`},v=()=>{let t=f.trim();t&&t!==e.content&&l(e.id,t),d(!1)};return(0,H.jsxs)(`li`,{className:`queue-row ${m?`queue-row-sending`:`queue-row-queued`} ${h?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":h?_:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[(0,H.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),h?(0,H.jsxs)(`span`,{className:`queue-bg-result`,title:g,children:[(0,H.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:_===`error`?`✕`:`↩`}),(0,H.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,H.jsx)(`span`,{className:`bg-result-summary`,children:g})]}):u?(0,H.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,H.jsx)(`textarea`,{value:f,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>p(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),p(e.content),d(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),v())}}),(0,H.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:v,children:`保存`}),(0,H.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{p(e.content),d(!1)},children:`取消`})]}):(0,H.jsx)(`span`,{className:`queue-text`,title:g,children:g}),(0,H.jsx)(`span`,{className:`queue-state`,"data-waiting-state":m?`sending`:`queued`,children:m?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),m?(0,H.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,H.jsxs)(H.Fragment,{children:[r?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,disabled:i,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${g}」`,onClick:()=>o(e.id),children:i?`◌ 打断中…`:`打断并回答`}),(0,H.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${g}」`:`让「${g}」插到最前`,onClick:()=>a(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,H.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${g}」`,onClick:()=>s(e.id),children:`现在就回答`}),!h&&(0,H.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${g}」`,onClick:()=>{p(e.content),d(!0)},children:`改字`}),(0,H.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${g}」`,onClick:()=>c(e.id),children:`撤回`})]})]})}function mA({question:e,index:t,expanded:n,onToggle:r,onAnswer:i}){return(0,H.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,H.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:r}),(0,H.jsxs)(`div`,{className:`call-head-row`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,H.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,H.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,H.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,H.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,H.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),n&&(0,H.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,H.jsx)(hA,{question:e,onAnswer:i})})]})}function hA({question:e,onAnswer:t}){let[n,r]=(0,V.useState)(()=>Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected]))),[i,a]=(0,V.useState)(()=>e.answers?.map(e=>e.note??``).join(`
95
+ `)??``),o=(e,t,n)=>{r(r=>{let i=r[e]??[];return n?{...r,[e]:i.includes(t)?i.filter(e=>e!==t):[...i,t]}:{...r,[e]:[t]}})},s=()=>{t(e.items.map(e=>({id:e.id,selected:n[e.id]??[],...e.extraNote&&i.trim()?{note:i.trim()}:{}})),!1)},c=e.items.some(e=>(n[e.id]??[]).length>0);return(0,H.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(t=>(0,H.jsxs)(`div`,{className:`question-item`,children:[(0,H.jsx)(`div`,{className:`question-text`,children:t.header?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{className:`question-header`,children:t.header}),(0,H.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,H.jsx)(Am,{source:t.question})]}):(0,H.jsx)(Am,{source:t.question})}),(0,H.jsx)(`div`,{className:`question-options`,"data-question-options":t.id,children:t.options.map(r=>{let i=(n[t.id]??[]).includes(r),a=e.status!==`pending`;return(0,H.jsxs)(`label`,{className:i?`is-chosen`:``,"data-chosen":a&&i?`1`:void 0,children:[(0,H.jsx)(`input`,{type:t.multiple?`checkbox`:`radio`,name:`q-${t.id}`,checked:i,disabled:a,onChange:()=>o(t.id,r,t.multiple)}),(0,H.jsx)(jm,{source:r}),a&&i?(0,H.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},r)})}),e.status===`pending`&&t.extraNote?(0,H.jsx)(`textarea`,{value:i,placeholder:`补充说明(可选)`,onChange:e=>a(e.target.value)}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,H.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,H.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},t.id)),e.status===`pending`&&(0,H.jsxs)(`div`,{className:`question-actions`,children:[(0,H.jsx)(`button`,{type:`button`,onClick:s,disabled:!c,children:`提交`}),(0,H.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>t([],!0),children:`跳过`})]})]})}function gA({request:e,onAnswer:t,pending:n}){let[r,i]=(0,V.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,H.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,H.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,H.jsxs)(`div`,{className:`extui-head`,children:[(0,H.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,H.jsxs)(`span`,{className:`extui-deadline`,children:[Math.round(e.timeoutMs/1e3),`s 超时`]})]}),n&&(0,H.jsx)(`p`,{className:`extui-pending`,role:`status`,children:`提交中…`}),(0,H.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,H.jsx)(`h3`,{className:`extui-title`,children:e.title||DA[e.method]}),e.method===`confirm`&&(0,H.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,H.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,H.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,H.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,H.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,H.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Ck(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,H.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Ck(e)&&e.preventDefault()}}),(0,H.jsxs)(`div`,{className:`extui-actions`,children:[(0,H.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,H.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,H.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,H.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function _A({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,V.useState)(e),o=(0,V.useRef)(null),s=(0,V.useRef)(!1);(0,V.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},u=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,H.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,H.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(Ck(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,H.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,H.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function vA({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c}){let[l,u]=(0,V.useState)(!1),[d,f]=(0,V.useState)(``),[p,m]=(0,V.useState)(0),h=(0,V.useRef)(null),g=(0,V.useRef)(null),_=(0,V.useRef)(null),v=(0,V.useRef)(null),y=(0,V.useRef)([]),b=i.find(e=>e.selected),x=qk(i,d),S=x.length===0?-1:Math.min(Math.max(p,0),x.length-1),C=S<0?void 0:x[S],w=(e=!1)=>{u(!1),e&&g.current?.focus()},T=()=>{f(``),m(Math.max(i.findIndex(e=>e.selected),0)),u(!0)},E=e=>m(t=>x.length?Math.min(Math.max(t+e,0),x.length-1):0);(0,V.useEffect)(()=>{if(!l)return;let e=e=>{h.current?.contains(e.target)||w()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[l]),(0,V.useEffect)(()=>{if(!l)return;let e=h.current,t=t=>{e?.contains(t.relatedTarget)||w()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[l]),(0,V.useEffect)(()=>{l&&v.current?.focus()},[l]),(0,V.useEffect)(()=>{l&&S>=0&&y.current[S]?.scrollIntoView({block:`nearest`})},[l,S]),(0,V.useLayoutEffect)(()=>{if(!l)return;let e=_.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`)},[l,x.length,i.length]);let D=e=>{if(l){if(e.key===`Escape`)e.preventDefault(),w(!0);else if(e.key===`ArrowDown`)e.preventDefault(),E(1);else if(e.key===`ArrowUp`)e.preventDefault(),E(-1);else if(e.key===`Home`)e.preventDefault(),m(0);else if(e.key===`End`)e.preventDefault(),m(Math.max(x.length-1,0));else if(e.key===`Enter`){if(Ck(e))return;e.preventDefault(),C&&(s(C.key),w(!0))}}},O=`picker-list-${c??e}`,k=t=>`picker-option-${c??e}-${t}`;return(0,H.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:h,onKeyDown:l?D:void 0,children:[(0,H.jsxs)(`button`,{ref:g,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":l,title:o??`${Bk[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>l?w():T(),children:[(0,H.jsx)(`span`,{className:`session-picker-kind`,children:Bk[e]}),(0,H.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,H.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,H.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),l&&(0,H.jsxs)(`div`,{className:`picker-menu`,ref:_,"data-picker-menu":e,"data-picker-highlight":S,children:[(0,H.jsxs)(`div`,{className:`picker-filter`,children:[(0,H.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,H.jsx)(`input`,{ref:v,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${Hk[e]}选项`,"aria-expanded":`true`,"aria-controls":O,"aria-autocomplete":`list`,"aria-activedescendant":C?k(S):void 0,value:d,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{f(e.target.value),m(0)}}),d&&(0,H.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{f(``),m(0),v.current?.focus()},children:`✕`})]}),b&&!x.some(e=>e.key===b.key)&&(0,H.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":b.key,children:[(0,H.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,H.jsx)(`span`,{className:`picker-current-value`,children:b.label})]}),(0,H.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:O,"aria-label":Uk[e],children:[x.map((e,t)=>(0,H.jsxs)(`button`,{id:k(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{y.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===S&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===S,onClick:()=>{s(e.key),w(!0)},children:[e.color&&(0,H.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,H.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,H.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,H.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,H.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),x.length===0&&(0,H.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:`没有匹配「${d.trim()}」的${Hk[e]}`})]})]})]})}var yA=`__pi_default__`;function bA({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onClose:a}){let[o,s]=(0,V.useState)(e.defaultAgentId),[c,l]=(0,V.useState)(e.defaultModel),[u,d]=(0,V.useState)(e.defaultThinkingLevel);(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let f=t?.source===`pi`,p=[{key:yA,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:c===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Gk(e),selected:c?.provider===e.provider&&c.modelId===e.modelId}))],m=[{key:yA,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:u===void 0},...(t?.levels??[]).map(e=>({key:e,label:e,selected:e===u}))],h=e=>{if(e===yA){l(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);n&&l({provider:n.provider,modelId:n.modelId,label:n.label})},g=e=>d(e===yA?void 0:e),_=[{key:yA,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:o===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:o===e.id}))];return(0,H.jsx)(`div`,{className:`overlay`,onClick:a,children:(0,H.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`h2`,{children:`工作区设置`}),(0,H.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,H.jsxs)(`div`,{className:`settings-row`,children:[(0,H.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,H.jsx)(vA,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===o)?.name??`跟随 Pi 默认`,value:o??yA,detail:o?`${n?.agents.find(e=>e.id===o)?.toolSummary??``}`:void 0,options:_,disabled:!n||n.source===`unavailable`,note:eA(n),onChoose:e=>s(e===yA?void 0:e)})]}),(0,H.jsxs)(`div`,{className:`settings-row`,children:[(0,H.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,H.jsx)(vA,{kind:`model`,scope:`settings-model`,label:c?.label??`跟随 Pi 默认`,value:c?`${c.provider}/${c.modelId}`:yA,detail:c?`${c.provider}/${c.modelId}`:void 0,options:p,disabled:!f,note:$k(`模型`,t),onChoose:h})]}),(0,H.jsxs)(`div`,{className:`settings-row`,children:[(0,H.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,H.jsx)(vA,{kind:`thinking`,scope:`settings-thinking`,label:u??`跟随 Pi 默认`,value:u??yA,options:m,disabled:!f,note:$k(`思考等级`,t),onChoose:g})]}),(0,H.jsxs)(`div`,{className:`picker-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,H.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:a,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(o,c,u),children:`保存`})]})]})})}var xA=[{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`}],SA={waiting:`⋯`,running:``,failed:``,question:`?`,completed:``,unread:`•`,idle:``,awaiting_background:`⚙`},CA={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,completed:`已完成`,unread:`有未读`,idle:`空闲`,awaiting_background:`等待后台任务`},wA={idle:`就绪`,waiting:`等待 LLM`,running:`正在生成`,completed:`已完成`,stopped:`已停止`,failed:`运行失败`,awaiting_background:`等待后台任务`},TA=e=>e?.status===`running`||e?.status===`waiting`,EA={running:`运行中`,completed:`已完成`,failed:`失败`,stopped:`已停止`,cancelled:`已取消`},DA={select:`请选择一项`,confirm:`请确认`,input:`请输入内容`,editor:`请输入内容`,notify:`扩展通知`,setStatus:`扩展状态`,setWidget:`扩展内容`,setTitle:`扩展标题`,set_editor_text:`扩展输入`};function OA(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 kA(e,t,n){if(t)return`question`;if(e.status===`failed`)return`failed`;if(e.status===`waiting`)return`waiting`;if(e.status===`running`)return`running`;if(e.status===`awaiting_background`)return`awaiting_background`;let r=n??``;return e.status===`completed`&&e.updatedAt>r?`completed`:e.updatedAt>r?`unread`:`idle`}function AA({state:e}){let t=SA[e];return e===`idle`?null:(0,H.jsx)(`i`,{className:`session-state session-state-${e}`,"data-session-state":e,title:CA[e],"aria-label":CA[e],...e===`awaiting_background`?{style:{color:`var(--accent)`}}:{},children:(0,H.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:t})})}function jA(e,t){return(0,H.jsxs)(H.Fragment,{children:[e.origin===`orchestrator`&&(0,H.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`orchestrator`,title:`编排会话:由上级智能体创建`,"aria-label":`编排会话:由上级智能体创建`,children:`编排`}),t&&(0,H.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`scheduled`,title:`定时任务会话:${t.name}`,"aria-label":`定时任务会话:${t.name}`,children:`定时`})]})}function MA(e,t){let n=[];return e.origin===`orchestrator`&&n.push(`编排会话`),t&&n.push(`定时任务会话:${t.name}`),n.length?`(${n.join(`;`)})`:``}var NA={pending:`未开始`,in_progress:`运行中`,completed:`已完成`},PA={pending:`○`,in_progress:`◐`,completed:`✓`},FA={high:`高`,medium:`中`,low:`低`};function IA(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function LA({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,H.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,title:`状态:${NA[e.status]}`,children:[(0,H.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:PA[e.status]}),(0,H.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,H.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:NA[e.status]}),e.priority&&(0,H.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:FA[e.priority]})]})}function RA(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 zA({tasks:e,messages:t,execOutputs:n,onStop:r}){return(0,H.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?EA[o]??(/[\u3400-\u9fff]/.test(o)?o:`未知状态`):`未知状态`;return(0,H.jsx)(BA,{task:e,status:s,messages:t,execOutputs:n,onStop:r},a)})})}function BA({task:e,status:t,messages:n,execOutputs:r,onStop:i}){let[a,o]=(0,V.useState)(!1),[s,c]=(0,V.useState)(()=>r.get(e.id)??``);(0,V.useEffect)(()=>{let t=r.get(e.id)??``;c(t);let n,i=r=>{let i=r.detail;i.sessionId===e.id&&(t=(t+i.data).slice(-512e3),n===void 0&&(n=requestAnimationFrame(()=>{n=void 0,c(t)})))};return window.addEventListener(`super-pi-exec-output`,i),()=>{window.removeEventListener(`super-pi-exec-output`,i),n!==void 0&&cancelAnimationFrame(n)}},[e.id,r]);let l=e.originMessageId!==void 0&&e.originCallRow!==void 0?n.find(t=>t.id===e.originMessageId)?.toolCalls?.[e.originCallRow]:void 0,u=(l?.backgroundTask?.id===e.id?l.backgroundTask.output:void 0)??s,d=e.status?.trim()??``,f=d===`running`?`运行中,暂无输出`:d in EA?`任务已结束,输出未保留`:`暂无可显示的输出`;return(0,H.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,H.jsxs)(`button`,{type:`button`,className:`bg-item-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,"aria-label":`展开后台任务详情`,children:[(0,H.jsxs)(`div`,{className:`bg-item-header`,children:[(0,H.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务`}),i&&(0,H.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:t=>{t.stopPropagation(),i(e.id)},children:`终止`})]}),(0,H.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,H.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,H.jsx)(`span`,{className:`bg-status`,children:t})]})]}),a&&(0,H.jsx)(`pre`,{className:`bg-output`,"data-bg-output":e.id,children:u||f})]})}function VA({todos:e,tasks:t,messages:n,execOutputs:r,scheduledTasks:i,scheduledCatalog:a,scheduledAgents:o,collapsed:s,onToggle:c,workspaceId:l,workspaceLabel:u,cwd:d=``,conversationId:f,connected:p,files:m,onOpenFile:h,onOpenChanged:g,activeTab:_,onSelectTab:v,sendCommand:y,registerTerminalSink:b,terminalShell:x,notify:S,serverTimeZone:C,onOpenSession:w}){let T=xA;return T.some(e=>e.id===_)||T[0].id,(0,H.jsx)(`div`,{className:`right-rail${s?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":`右侧栏`,"data-right-rail":`1`,"data-right-rail-collapsed":s,children:s?(0,H.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:c,children:`‹`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`right-rail-head`,children:[(0,H.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":T.length,children:T.map(e=>(0,H.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===_?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===_,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>v(e.id),children:e.label},e.id))}),(0,H.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":`收起右侧栏`,onClick:c,children:`›`})]}),xA.filter(e=>e.id===_).map(s=>(0,H.jsxs)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${s.id}`,"aria-labelledby":`right-tab-${s.id}`,"data-right-panel":s.id,children:[s.id===`main`&&(0,H.jsxs)(H.Fragment,{children:[(e.length>0||t.length>0)&&(0,H.jsxs)(`p`,{className:`rail-legend`,"data-rail-legend":`1`,children:[(0,H.jsx)(`span`,{className:`rail-legend-label`,children:`左侧竖条=状态`}),(0,H.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,H.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-pending`,"aria-hidden":`true`}),`未开始`]}),(0,H.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,H.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-running`,"aria-hidden":`true`}),`运行中`]}),(0,H.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,H.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-done`,"aria-hidden":`true`}),`已完成`]})]}),(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`待办任务`}),(0,H.jsx)(`span`,{className:`rail-section-count`,"data-todo-summary":`1`,children:IA(e)})]}),e.length>0?(0,H.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,H.jsx)(LA,{todo:e,index:t},e.id??`todo_${t}`))}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。Agent 开始处理多步骤任务时,会自己把待办写到这里。`}),(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`后台任务`}),(0,H.jsx)(`span`,{className:`rail-section-count`,"data-bg-summary":`1`,children:t.length?`${t.filter(e=>e.status===`running`).length} 个运行中 / 共 ${t.length} 个`:`0 个`})]}),t.length>0?(0,H.jsx)(zA,{tasks:t,messages:n,execOutputs:r,onStop:e=>y({type:`backgroundTask.stop`,taskId:e})}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`}),(0,H.jsx)(PD,{tasks:i,workspaceId:l,catalog:a,agents:o,sendCommand:y,notify:S,serverTimeZone:C})]}),s.id===`projects`&&(0,H.jsx)(uO,{workspaceId:l,notify:S,onOpenSession:w},l),s.id===`tools`&&(0,H.jsx)(HA,{workspaceId:l,onOpenSession:w},l),s.id===`files`&&(0,H.jsx)(z_,{workspaceId:l,files:m,onOpenFile:h,onOpenChanged:g}),s.id===`git`&&(0,H.jsx)(Ap,{workspaceId:l??null,conversationId:f,cwd:d,onOpenChanged:g},f||`global`),s.id===`terminal`&&(0,H.jsx)(xD,{workspaceId:l,workspaceLabel:u,cwd:d,conversationId:f,connected:p,sendCommand:y,registerSink:b,terminalShell:x},f||`global`)]},s.id))]})})}function HA({workspaceId:e,onOpenSession:t}){let{tools:n,mountedTools:r,openToolId:i,shortcuts:a}=ik(),[o,s]=(0,V.useState)(),c=async e=>{s(void 0);let t=await sk(e);t&&s(`移除工具失败:${tp(t)}`)},l=(e,t)=>t?`打开${e}(快捷键 ${NO(t)})`:`打开${e}`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(vO,{workspaceId:e,onOpenSession:t}),(0,H.jsxs)(`div`,{className:`rail-section-head`,children:[(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,H.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[n.length+r.length,` 个`]})]}),n.length+r.length>0?(0,H.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":n.length+r.length,children:[n.map(e=>(0,H.jsxs)(`li`,{className:`tool-slot`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":i===e.id?`open`:`idle`,title:l(e.name,a[e.id]),"aria-label":l(e.name,a[e.id]),"aria-current":i===e.id?`true`:void 0,onClick:()=>ak.toggleTool(e.id),children:[(0,H.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),a[e.id]&&(0,H.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${NO(a[e.id])}`,children:PO(a[e.id])}),e.kind===`link`&&(0,H.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>ak.removeTool(e.id),children:`✕`})]},e.id)),r.map(e=>(0,H.jsxs)(`li`,{className:`tool-slot`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,"data-tool-state":i===e.id?`open`:`idle`,title:l(e.name,a[e.id]),"aria-label":l(e.name,a[e.id]),onClick:()=>ak.toggleTool(e.id),children:[(0,H.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,H.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),a[e.id]&&(0,H.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${NO(a[e.id])}`,children:PO(a[e.id])}),(0,H.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void c(e.id),children:`✕`})]},e.id))]}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,H.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具、快捷键与说明`,"aria-label":`打开工具设置`,onClick:()=>ak.openSettings(),children:`⚙ 工具设置`}),o&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-error":`1`,children:o})]})}function UA({onClose:e}){let{tools:t,mountedTools:n,shortcuts:r}=ik(),[i,a]=(0,V.useState)(``),[o,s]=(0,V.useState)(``),[c,l]=(0,V.useState)(),[u,d]=(0,V.useState)(!1),[f,p]=(0,V.useState)(),[m,h]=(0,V.useState)(),[g,_]=(0,V.useState)(),[v,y]=(0,V.useState)(``),[b,x]=(0,V.useState)(),[S,C]=(0,V.useState)(),[w,T]=(0,V.useState)(!1),[E,D]=(0,V.useState)(),[O,k]=(0,V.useState)(),A=(0,V.useRef)(null),j=(0,V.useRef)(null),[M,N]=(0,V.useState)(),[P,F]=(0,V.useState)(),ee=(0,V.useRef)(null),[te,ne]=(0,V.useState)(()=>{let e=XO();return!e||typeof window>`u`?e:QO(e,window.innerWidth,window.innerHeight)}),re=async()=>{let e=await Lk(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
96
96
 
97
97
  工具不属于当前 workspace;通过内置 tool_register 一次性提交完整文件(index.html、JS/CSS,必要时 .py),Super Pi 会保存为全局工具并自动出现在每个 workspace 的工具 Tab。
98
98
 
99
- 如需本地计算,声明 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、访问地址、文件清单和验证结果。`);d(e),window.setTimeout(()=>d(!1),1800)};(0,V.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let I=(0,V.useMemo)(()=>[...t.map(e=>({id:e.id,name:e.name,glyph:e.glyph})),...n.map(e=>({id:e.id,name:e.name,glyph:`🧩`}))],[t,n]);(0,V.useEffect)(()=>{if(!M)return;let e=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),N(void 0);return}if(DO(e.key)||IO(e.target))return;e.preventDefault(),e.stopPropagation();let t=M;if(N(void 0),e.key===`Delete`||e.key===`Backspace`){nk.clearShortcut(t),F(void 0);return}let n=OO(e);if(!n){F(`没有认出这个按键,换一个试试。`);return}let i=PO(n);if(!i.ok){F(i.reason);return}let a=BO(r,n,t);if(a){let e=I.find(e=>e.id===a)?.name;F(e?`这个组合键已经被「${e}」占用了,换一个键。`:`这个组合键已经被另一个工具占用了,换一个键。`)}else nk.setShortcut(t,n),F(void 0)};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[M,r,I]);let ie=e=>{ne(YO(e,window.innerWidth,window.innerHeight))},ae=e=>{JO(e)},oe=()=>{ne(void 0),JO(void 0)},se=(0,V.useRef)(!1),ce=n.map(e=>e.slug).filter(e=>typeof e==`string`),le=e=>{p(void 0),h(void 0),k(void 0),D({tool:e,name:fk({slug:e.slug??`tool`})})},ue=async(e,t)=>{p(void 0),h(void 0),k(void 0);let n=pk(t);if(!n.ok)k(n.reason);else try{let t=await fetch(`/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),h(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){p(`导出失败:${tp(e)}`)}finally{D(void 0)}},de=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;p(void 0),h(void 0),x(void 0);let n=lk(await t.text(),t.name);n.ok?(_({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),y(ce.includes(n.bundle.slug)?dk(n.bundle.slug,ce):n.bundle.slug),C(n.bundle.files[0]?.path)):p(n.reason)},fe=()=>{_(void 0),y(``),x(void 0),C(void 0)},pe=async()=>{if(!g)return;x(void 0);let e=uk(v);if(!e.ok)x(e.reason);else if(ce.includes(e.slug))x(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{T(!0);try{let t=await fetch(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(vk(g.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await rk(),h(`已导入「${g.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),fe()}catch(e){p(`导入失败:${tp(e)}`)}finally{T(!1)}}};(0,V.useEffect)(()=>{E&&j.current?.scrollIntoView({block:`center`})},[E]);let L=()=>{let e=Cv(i);e.ok?t.length>=32?l(`工具最多 32 个,先删掉一个再加。`):(nk.setTools([...t,{id:Dv(`link`,t.map(e=>e.id)),kind:`link`,name:o.trim()||GA(e.url),glyph:`↗`,url:e.url}]),a(``),s(``),l(void 0)):l(e.reason)},me=te?{width:`${te.width}px`,height:`${te.height}px`,maxWidth:`calc(100vw - 32px)`,maxHeight:`calc(100vh - 32px)`}:void 0;return(0,sa.createPortal)((0,H.jsxs)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onPointerDown:()=>{se.current=!1},onClick:t=>{se.current?se.current=!1:t.target===t.currentTarget&&e()},children:[(0,H.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,ref:ee,style:me,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:e,children:`✕`})]}),(0,H.jsx)(`div`,{className:`tool-dialog-body`,children:g?(0,H.jsx)(WA,{pending:g,slugDraft:v,slugError:b,preview:S,busy:w,onSlugChange:e=>{y(e),x(void 0)},onPreviewChange:C,onCancel:fe,onConfirm:()=>void pe()}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,H.jsx)(`strong`,{children:`给 Agent 开发新工具`}),(0,H.jsx)(`p`,{className:`tool-hint`,children:`工具会挂载到 Super Pi 的统一 HTTP 服务,不需要再启动独立服务器。`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void re(),children:u?`已复制`:`复制工具开发 Prompt`})]}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,H.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":_v.length,children:_v.map(e=>{let n=t.some(t=>t.kind===e.kind);return(0,H.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":e.kind,children:[(0,H.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.jsx)(`small`,{children:e.blurb})]}),(0,H.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:()=>nk.setTools(Ov(t,e.kind)),children:n?`已添加`:`添加`})]},e.kind)})}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,H.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,H.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,H.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:o,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>s(e.target.value)}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!i.trim(),onClick:L,children:`添加网址工具`}),c&&(0,H.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:c}),(0,H.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,H.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`快捷键`})}),(0,H.jsxs)(`p`,{className:`tool-hint`,"data-tool-shortcut-hint":`1`,children:[`给每个工具绑一个组合键,按下就直接打开它,不用先找到右侧栏。`,(0,H.jsx)(`b`,{children:`弹窗打开时快捷键不生效`}),`——模态弹窗期间键盘归它自己,关掉之后再按。`]}),(0,H.jsx)(`div`,{className:`tool-shortcuts`,"data-tool-shortcut-count":I.length,children:I.map(e=>(0,H.jsxs)(`div`,{className:`tool-shortcut-row`,"data-tool-shortcut-row":e.id,children:[(0,H.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.jsx)(`small`,{children:r[e.id]?`按 ${AO(r[e.id])} 打开`:`还没有快捷键`})]}),(0,H.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:()=>{F(void 0),N(M===e.id?void 0:e.id)},children:M===e.id?`按下组合键…`:r[e.id]?AO(r[e.id]):`未设置`}),r[e.id]&&(0,H.jsx)(`button`,{type:`button`,className:`tool-shortcut-clear`,"data-tool-shortcut-clear":e.id,title:`清除${e.name}的快捷键`,"aria-label":`清除${e.name}的快捷键`,onClick:()=>{nk.clearShortcut(e.id),F(void 0),N(void 0)},children:`清除`})]},e.id))}),P&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-shortcut-error":`1`,children:P}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有通过 tool_register 注册的工具。上面复制那段 Prompt,让 Agent 写一个。`}):(0,H.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=gk(e.environmentState);return(0,H.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,H.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,H.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.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,H.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>le(e),children:`导出`})]},e.id)})}),E&&(0,H.jsxs)(`div`,{className:`tool-share-review`,ref:j,"data-tool-export-name":`1`,children:[(0,H.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,E.tool.name,`」`]}),(0,H.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,H.jsx)(`input`,{className:`tool-input`,value:E.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>D({...E,name:e.target.value})})]}),O&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:O}),(0,H.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{D(void 0),k(void 0)},children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void ue(E.tool,E.name),children:`导出`})]})]}),m&&(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:m}),f&&(0,H.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:f}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,H.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,H.jsx)(`code`,{children:ak}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,H.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>A.current?.click(),children:`选择文件…`}),(0,H.jsx)(`input`,{ref:A,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void de(e)})]})})]}),(0,H.jsx)(HA,{targetRef:ee,onResize:ie,onCommit:ae,onDragEnd:()=>{se.current=!0},onReset:oe})]}),document.body)}var VA=18;function HA({targetRef:e,onResize:t,onCommit:n,onDragEnd:r,onReset:i}){let[a,o]=(0,V.useState)(),s=(0,V.useRef)(void 0);return(0,V.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=t.getBoundingClientRect();o({left:e.right-VA,top:e.bottom-VA})};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,H.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=YO({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??HO.width,l=o?.height??HO.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=YO({width:c,height:l},window.innerWidth,window.innerHeight);s.current=u,t(u),n(u)},onClick:e=>e.stopPropagation()})}function UA(){let{tools:e,mountedTools:t,openToolId:n,settingsOpen:r,shortcuts:i}=tk(),a=e.find(e=>e.id===n),o=t.find(e=>e.id===n);return(0,V.useEffect)(()=>{let n=n=>{if(!r&&!document.querySelector(`[aria-modal="true"]`)&&!(n.isComposing||n.defaultPrevented)){for(let[r,a]of Object.entries(i))if(LO(a,n)&&(e.some(e=>e.id===r)||t.some(e=>e.id===r))){n.preventDefault(),nk.openTool(r);return}}};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[i,e,t,r]),(0,V.useEffect)(()=>{rk();let e=()=>{rk()};return window.addEventListener(`super-pi-tools-updated`,e),()=>window.removeEventListener(`super-pi-tools-updated`,e)},[]),(0,V.useEffect)(()=>{nk.persistTools()},[]),(0,H.jsxs)(H.Fragment,{children:[r&&(0,H.jsx)(BA,{onClose:()=>nk.closeSettings()}),a&&(0,H.jsx)(KA,{tool:a,onClose:()=>nk.closeTool()}),o&&(0,H.jsx)($A,{tool:o,onClose:()=>nk.closeTool()})]})}function WA({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=hk(l),f=mk(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,H.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,H.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,H.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,H.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,_k(u)]}),(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,H.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,H.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,H.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,H.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,H.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` · `,l.environment.fingerprint.platform||`未知平台`,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,H.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,H.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,H.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,H.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,H.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,H.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,H.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,H.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,H.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,H.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,H.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function GA(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 KA({tool:e,onClose:t}){return(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,sa.createPortal)((0,H.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,H.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,H.jsx)(`span`,{className:`tool-dialog-glyph`,"aria-hidden":`true`,children:e.glyph}),e.name]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,H.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,H.jsx)(JA,{}),e.kind===`timestamp`&&(0,H.jsx)(YA,{}),e.kind===`link`&&(0,H.jsx)(XA,{tool:e})]})]})}),document.body)}function qA({image:e,onClose:t}){return(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,sa.createPortal)((0,H.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,H.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,H.jsxs)(`div`,{className:`lightbox-head`,children:[(0,H.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,H.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,H.jsx)(`div`,{className:`lightbox-body`,children:(0,H.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function JA(){let[e,t]=(0,V.useState)(`12 * (3 + 4)`),n=Hv(e),r=e=>{t(t=>t+e)};return(0,H.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,H.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,H.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,H.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,H.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:Uv(n.value)}):(0,H.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function YA(){let[e,t]=(0,V.useState)(``),n=Wv(e),r=n.ok?Kv(n.ms):null;return(0,H.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,H.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,H.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`本地时间`}),(0,H.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`ISO(UTC)`}),(0,H.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`秒`}),(0,H.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`毫秒`}),(0,H.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,H.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function XA({tool:e}){let[t,n]=(0,V.useState)(!1),r=async()=>{let e=await Pk(`请为 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,H.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,H.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,H.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,H.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,H.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,H.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,H.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 ZA=`(max-width: 1100px)`,QA=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function $A({tool:e,onClose:t}){return(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,sa.createPortal)((0,H.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,H.jsxs)(`div`,{className:`tool-dialog`,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsxs)(`h2`,{className:`tool-dialog-title`,children:[`🧩 `,e.name]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,H.jsx)(`div`,{className:`tool-dialog-body`,children:(0,H.jsx)(`iframe`,{className:`tool-link-frame`,src:`/tools/${encodeURIComponent(e.id)}/`,title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function ej(e,t,n){let r=Math.max(0,Math.round(n)-480),i=QA(520,180,Math.max(180,r-240)),a=QA(Math.round(e),180,i),o=QA(640,240,Math.max(240,r-a));return{sidebar:a,rail:QA(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var tj=`super-pi.rail-widths.v1`,nj=`super-pi.reader-state.v1`,rj=`super-pi.folded-groups.v1`;function ij(){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 aj(e){try{typeof window<`u`&&window.localStorage.setItem(rj,JSON.stringify(e))}catch{}}var oj=32,sj=48,cj=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function lj(e,t,n=!1,r=!1){let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=n?!1:r?!0:t.followTail?i<=sj:i<=oj,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 uj(){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 dj(e){try{typeof window<`u`&&window.localStorage.setItem(nj,JSON.stringify(e))}catch{}}var fj=`super-pi.session-tabs.v1`;function pj(e,t){if(!t||e.has(t))return e;let n=new Set(e);return n.add(t),n}function mj(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 hj(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(window.sessionStorage.getItem(`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=typeof t.previewId==`string`&&n.includes(t.previewId)?t.previewId:void 0,i=Array.isArray(t.touched)?[...new Set(t.touched.filter(e=>typeof e==`string`))]:[];return{ids:n,activeId:typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0,previewId:r,touched:i}}catch{return{ids:[]}}}function gj(e,t,n,r){try{if(typeof window>`u`)return;window.sessionStorage.setItem(fj,JSON.stringify({ids:e,...t&&e.includes(t)?{activeId:t}:{},...n&&e.includes(n)?{previewId:n}:{},...r&&r.length>0?{touched:r}:{}}))}catch{}}function _j(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(tj);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 vj(e){try{if(typeof window>`u`)return;window.localStorage.setItem(tj,JSON.stringify(e))}catch{}}function yj({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,V.useState)(!1),c=e=>e.shiftKey?64:16;return(0,H.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(QA(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(QA(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(QA(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var bj=`super-pi.composer-height.v1`,xj=148,Sj=.55,Cj=()=>Math.max(xj,Math.round((typeof window>`u`?800:window.innerHeight)*Sj)),wj=e=>{let t=Number.isFinite(e)?e:xj;return Math.round(Math.min(Cj(),Math.max(xj,t)))},Tj=()=>{try{let e=window.localStorage.getItem(bj);return e===null?xj:wj(Number(e))}catch{return xj}};function Ej({height:e,onHeight:t}){let[n,r]=(0,V.useState)(!1),i=e=>e.shiftKey?64:16,a=Cj();return(0,H.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":xj,"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=wj(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(wj(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(wj(e-r))):n.key===`Home`?(n.preventDefault(),t(xj)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(wj(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(wj(e-96)))}})}function Dj(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 e[0]}function Oj(){let[e,t]=(0,V.useState)(yk),n=(0,V.useCallback)(e=>{t(t=>{let n=typeof e==`function`?e(t):e;return pe(n,t)})},[]),[r,i]=(0,V.useState)([]),a=(0,V.useRef)([]),o=(0,V.useRef)(null);o.current||=uj();let s=(0,V.useRef)(null);s.current||=hj();let c=s.current,l=r.reduce((e,t)=>t.apply(e),e),[u,d]=(0,V.useState)(s.current.activeId??o.current.activeId),[f,p]=(0,V.useState)(!1),[m,h]=(0,V.useState)(),[g,_]=(0,V.useState)(()=>ij().workspaces??{}),[v,y]=(0,V.useState)(o.current.workspaceId),[b,x]=(0,V.useState)(()=>({ids:c.ids,previewId:c.previewId,touched:new Set(c.touched??[]),emptied:!1})),S=b.ids,C=b.previewId,w=b.emptied===!0,[T,E]=(0,V.useState)(!1),[D,O]=(0,V.useState)(!1),[k,A]=(0,V.useState)(),j=(0,V.useRef)(null),M=(0,V.useRef)(void 0),N=(0,V.useRef)(o.current.conversations),P=(0,V.useRef)(S);P.current=S;let F=(0,V.useRef)(o.current.readAt??{}),[ee,te]=(0,V.useState)(0),ne=(0,V.useRef)(null),re=(0,V.useRef)(null),I=(0,V.useRef)(void 0),ie=(0,V.useRef)(!1),ae=(0,V.useRef)(!0),[oe,se]=(0,V.useState)({followTail:!0,scrollTop:0}),ce=(0,V.useRef)(!1),le=(0,V.useRef)(new Map),ue=(0,V.useRef)(void 0),de=(0,V.useRef)([]),fe=(0,V.useRef)(void 0),pe=(0,V.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,content:t.content,thinking:t.thinking,thinkingActive:t.thinkingActive,thinkingBlocks:t.thinkingBlocks}:e})}})}},[]),L=(0,V.useCallback)(()=>{if(fe.current!==void 0&&(cancelAnimationFrame(fe.current),fe.current=void 0),!de.current.length)return;let e=de.current;de.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)}n(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=[...i.thinkingBlocks??[]],r=n.at(-1);r&&r.at===t&&(e.blockIndex===void 0||e.blockIndex===n.length-1)?n[n.length-1]={...r,text:r.text+e.delta}:n.push({at:t,text:e.delta}),i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return n.every((t,n)=>t===e.messages[n])?e:{...e,messages:n}})}))},[]),me=(0,V.useCallback)(e=>{let t=de.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),fe.current===void 0&&(fe.current=requestAnimationFrame(L))},[L]),he=(0,V.useCallback)(e=>{ue.current=e},[]),[ge,_e]=(0,V.useState)(()=>ij().archived??{});(0,V.useEffect)(()=>{aj({workspaces:g,archived:ge})},[g,ge]);let[ve,ye]=(0,V.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),be=e=>{let t=e.slice(0,24);ye(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},xe=ve.trim()||`你`,[Se,Ce]=(0,V.useState)(),[we,Te]=(0,V.useState)([]),[Ee,De]=(0,V.useState)([]),[Oe,ke]=(0,V.useState)(new Map),[Ae,je]=(0,V.useState)(new Map),[Me,Ne]=(0,V.useState)(),[Pe,Fe]=(0,V.useState)(),[Ie,Le]=(0,V.useState)(),[Re,ze]=(0,V.useState)([]),[Be,Ve]=(0,V.useState)([]),[He,Ue]=(0,V.useState)(),[We,Ge]=(0,V.useState)(),[Ke,qe]=(0,V.useState)(),[Je,Ye]=(0,V.useState)(`idle`),[Xe,Ze]=(0,V.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Qe,$e]=(0,V.useState)(`chat`),[et,tt]=(0,V.useState)(!1),[nt,rt]=(0,V.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,V.useEffect)(()=>{let e=()=>rt(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[it,at]=(0,V.useState)(_j),ot=ej(it.sidebar??270,it.rail??320,nt);(0,V.useEffect)(()=>{vj({sidebar:it.sidebar??270,rail:it.rail??320})},[it.sidebar,it.rail]);let st=e=>at(t=>({...t,sidebar:e})),ct=e=>at(t=>({...t,rail:e})),[lt,ut]=(0,V.useState)(null);(0,V.useEffect)(()=>{ut(Tj())},[]),(0,V.useEffect)(()=>{lt!==null&&document.documentElement.style.setProperty(`--composer-height`,`${lt}px`)},[lt]);let dt=e=>{let t=wj(e);ut(t);try{window.localStorage.setItem(bj,String(t))}catch{}};(0,V.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(ZA),t=e=>{e.matches&&Ze(!0)};return e.addEventListener(`change`,t),e.matches&&Ze(!0),()=>e.removeEventListener(`change`,t)},[]);let ft=nt<=1100;(0,V.useEffect)(()=>{if(!ft||Xe)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(),Ze(!0)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[ft,Xe]);let[pt,mt]=(0,V.useState)({}),[ht,gt]=(0,V.useState)({}),[_t,vt]=(0,V.useState)({}),[yt,bt]=(0,V.useState)(),[xt,St]=(0,V.useState)(()=>new Set),[Ct,wt]=(0,V.useState)(),[Tt,Et]=(0,V.useState)(),Dt=(0,V.useRef)(new Map),[Ot,kt]=(0,V.useState)({}),At=(0,V.useRef)(new Set),[jt,Mt]=(0,V.useState)([]),[Nt,Pt]=(0,V.useState)([]),[Ft,It]=(0,V.useState)(),[Lt,Rt]=(0,V.useState)(!1),zt=(0,V.useRef)(null),Bt=(0,V.useRef)(!1),Vt=(0,V.useRef)(0),Ht=(0,V.useRef)([]),Ut=(0,V.useRef)(void 0),Wt=(0,V.useRef)(!1),Gt=(0,V.useRef)(new Set),Kt=(0,V.useRef)(new Set),qt=(0,V.useRef)(new Map),Jt=(0,V.useRef)(new Map),[Yt,Xt]=(0,V.useState)(()=>Date.now());(0,V.useEffect)(()=>{let e=window.setInterval(()=>Xt(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let Zt=(0,V.useMemo)(()=>l.conversations.filter(e=>!e.archivedAt),[l.conversations]),Qt=(0,V.useMemo)(()=>e.conversations.filter(e=>!e.archivedAt),[e.conversations]),$t=(0,V.useMemo)(()=>new Set(l.collapsedConversationIds??[]),[l.collapsedConversationIds]),R=(0,V.useMemo)(()=>{let e=Zt.find(e=>e.id===u);if(e)return e;if(!w)return Dj(Zt,l.workspaces,v)},[w,u,Zt,v,l.workspaces]),en=ne.current;if(en){let e=en.dataset.messageScrollContainer;e&&R?.id&&e!==R?.id&&en.querySelector(`[data-transcript-key]`)&&(N.current[e]=lj(en,N.current[e]??{followTail:!0,scrollTop:0}))}ae.current=R?.messagesLoaded!==!1,(0,V.useEffect)(()=>{if(!T||w||u&&Qt.some(e=>e.id===u)||u&&a.current.some(e=>e.temporaryId===u))return;let e=Dj(Zt,l.workspaces,v);d(e?.id)},[w,u,Qt,Zt,T,v,l.workspaces]),(0,V.useEffect)(()=>{h(void 0)},[u,v]);let tn=(0,V.useMemo)(()=>l.workspaces.find(e=>e.id===v)??l.workspaces[0],[l.workspaces,v]),[nn,rn]=(0,V.useState)(``);(0,V.useEffect)(()=>{rn(``)},[tn?.id]);let an=(0,V.useRef)(v);an.current=v,(0,V.useEffect)(()=>{R&&y(R.workspaceId)},[R?.id]),(0,V.useEffect)(()=>{Ut.current=u},[u]),(0,V.useEffect)(()=>{I.current=R?.id},[R?.id]),(0,V.useEffect)(()=>{let e=R?.id;if(!e)return;let t=l.conversations.find(t=>t.id===e);if(!t)return;let n=F.current[e];F.current[e]=t.updatedAt,n!==t.updatedAt&&te(e=>e+1),dj({activeId:Ut.current,workspaceId:R?.workspaceId??v,conversations:N.current,readAt:F.current})},[R?.id,l.conversations]),(0,V.useEffect)(()=>{f&&u&&dj({activeId:u,workspaceId:R?.workspaceId??v,conversations:N.current,readAt:F.current})},[u,R?.workspaceId,f,v]),(0,V.useEffect)(()=>{let e=ne.current;if(!e||!R?.id||R.messagesLoaded===!1)return;let t=R.id;ce.current=!1;let n=N.current[t]??{followTail:!0,scrollTop:0};N.current[t]=n,se(n);let r=requestAnimationFrame(()=>{if(ne.current!==e)ie.current=!1;else{if(n.followTail)cj(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}ie.current=!1}});return()=>cancelAnimationFrame(r)},[R?.id,R?.messagesLoaded]),(0,V.useLayoutEffect)(()=>{ie.current=!0},[R?.id,R?.messagesLoaded]);let on=(0,V.useCallback)((e,t=!1,n=!1)=>{let r=I.current;if(!r||ie.current||!ae.current)return;let i=lj(e,N.current[r]??{followTail:!0,scrollTop:0},t,n);ce.current=!i.followTail,N.current[r]=i,se(i),dj({activeId:r,workspaceId:an.current,conversations:N.current,readAt:F.current})},[]),sn=Ot[R?.id??``]??{text:``,images:[],attachments:[],uploading:0},cn=sn.text,ln=sn.images,un=sn.attachments,dn=sn.uploading,fn=(e,t)=>kt(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),pn=e=>fn(R?.id??``,t=>({...t,text:e})),mn=e=>fn(R?.id??``,t=>({...t,attachments:t.attachments.some(t=>t.kind===e.kind&&t.id===e.id)?t.attachments:[...t.attachments,e]})),hn=(e,t)=>fn(R?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[gn,_n]=(0,V.useState)({visible:!1,query:``,rect:null}),vn=e=>fn(R?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),yn=S.length>0?S:w?[]:R?[R.id]:[],bn=(0,V.useMemo)(()=>yn.map(e=>Zt.find(t=>t.id===e)).filter(e=>e!==void 0),[yn,Zt]),xn=bn.length>0;(0,V.useEffect)(()=>{if(!T)return;let e=new Set(Zt.map(e=>e.id));x(t=>{let n=t.ids.filter(t=>e.has(t)),r=t.previewId&&e.has(t.previewId)?t.previewId:void 0;return n.length===t.ids.length&&r===t.previewId?t:{...t,ids:n,previewId:r}})},[T,Zt]),(0,V.useEffect)(()=>{gj(S,u,C,[...b.touched])},[u,S,C,b.touched]);let Sn=(0,V.useCallback)(e=>{e&&x(t=>{if(t.touched.has(e))return t;let n=t.previewId===e?void 0:t.previewId;return{...t,previewId:n,touched:pj(t.touched,e)}})},[]),Cn=(0,V.useCallback)(e=>{d(e);let t=Zt.find(t=>t.id===e)?.workspaceId;t&&y(t),Kn(`session`),x(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&&R?.id&&R.id!==e?[R.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}})},[R,Zt]),wn=(0,V.useCallback)(e=>{e&&(Sn(e),Cn(e))},[Sn,Cn]),Tn=R?.workspaceId??v,En=R?.cwd??``,z=P_(Tn,En),Dn=(0,V.useRef)(z.setChangedFor),On=(0,V.useRef)(z.setIndex),kn=(0,V.useRef)(Tn);kn.current=Tn;let An=(0,V.useRef)(En);An.current=En,(0,V.useEffect)(()=>{Dn.current=z.setChangedFor},[z.setChangedFor]),(0,V.useEffect)(()=>{On.current=z.setIndex},[z.setIndex]);let[jn,Mn]=(0,V.useState)(vA[0].id),[Nn,Pn]=(0,V.useState)({}),Fn=(R?.id?Nn[R.id]:void 0)??jn,In=(0,V.useCallback)(e=>{Mn(e),R?.id&&Pn(t=>({...t,[R.id]:e}))},[R?.id]),[Ln,Rn]=(0,V.useState)(!1),zn=(0,V.useRef)(void 0),Bn=(0,V.useRef)(``);(0,V.useEffect)(()=>{Rn(!1),M.current?.readyState===WebSocket.OPEN&&M.current.send(JSON.stringify({type:`files.index.subscribe`}))},[Tn,En]);let[Vn,Hn]=(0,V.useState)(!1),[Un,Wn]=(0,V.useState)(),[Gn,Kn]=(0,V.useState)(`session`),[qn,Jn]=(0,V.useState)(),[Yn,Xn]=(0,V.useState)([]);(0,V.useEffect)(()=>{Gn===`file`&&!z.active&&Kn(`session`)},[Gn,z.active]),(0,V.useEffect)(()=>{Gn===`diff`&&!qn&&Kn(`session`)},[Gn,qn]);let Zn=(0,V.useRef)(`${Tn??``}:${En}`);(0,V.useEffect)(()=>{let e=`${Tn??``}:${En}`;Zn.current!==e&&(Zn.current=e,Xn([]),Jn(void 0),Kn(`session`))},[Tn,En]),(0,V.useEffect)(()=>{z.restoredActive&&Kn(`file`)},[z.restoredActive]);let Qn=(0,V.useCallback)(e=>{Xn(t=>t.includes(e)?t:[...t,e]),Jn(e),Kn(`diff`),Mn(`files`)},[]),[$n,er]=(0,V.useState)({diff:null,loading:!1,error:``}),[tr,nr]=(0,V.useState)(`server`);(0,V.useEffect)(()=>{if(Gn!==`diff`||!qn||!Tn)return;let e=!0;return er({diff:null,loading:!0,error:``}),fetch(`/api/files/diff?workspaceId=${encodeURIComponent(Tn)}&path=${encodeURIComponent(qn)}${En?`&cwd=${encodeURIComponent(En)}`:``}`).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(t=>{e&&er({diff:t,loading:!1,error:``})}).catch(t=>{e&&er({diff:null,loading:!1,error:t instanceof Error?t.message:`读取差异失败`})}),()=>{e=!1}},[Gn,qn,Tn,En]);let rr=(0,V.useMemo)(()=>{if(!qn)return;let e=z.open.find(e=>e.path===qn);return e&&e.dirty?e.content:void 0},[qn,z.open]),ir=(0,V.useCallback)(e=>{z.setActivePath(e),Kn(`file`),Mn(`files`)},[z.setActivePath]),ar=(0,V.useCallback)(async(e,t)=>{Wn(t?{workspaceId:v,path:e.path,line:t,request:Date.now()}:void 0),await z.openFile(e),Kn(`file`)},[z.openFile,v]);(0,V.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key.toLowerCase()===`f`?(e.preventDefault(),Hn(!0)):(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&(e.preventDefault(),zn.current=Tn,Bn.current=En,Rn(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Tn,En]);let or=(0,V.useMemo)(()=>bn.map(e=>({id:`session:${e.id}`,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:!0,preview:C===e.id,badge:(0,H.jsx)(DA,{state:EA(e,TA(e,we),F.current[e.id])})})),[bn,we,l.conversations,ee,C]),sr=(0,V.useMemo)(()=>z.open.map(e=>({id:`file:${e.path}`,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,H.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[z.open]),cr=(0,V.useMemo)(()=>Yn.map(e=>({id:`diff:${e}`,rawId:e,kind:`diff`,label:e.split(/[\\/]/).pop()||e,title:`${e}(改动)`,closable:!0,icon:(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`±`})})),[Yn]),lr=(0,V.useMemo)(()=>[...or,...sr,...cr],[or,sr,cr]),ur=Gn===`file`&&z.activePath?`file:${z.activePath}`:Gn===`diff`&&qn?`diff:${qn}`:R?.id?`session:${R.id}`:void 0,dr=(0,V.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);ir(t)}else if(e.startsWith(`diff:`)){let t=e.slice(5);Jn(t),Kn(`diff`)}else if(e.startsWith(`session:`)){let t=e.slice(8);Cn(t)}},[ir,Cn]),fr=(0,V.useCallback)(e=>{e.startsWith(`session:`)&&wn(e.slice(8))},[wn]),pr=(0,V.useCallback)(e=>{let t=yn.indexOf(e);if(t<0)return;let n=yn.filter(t=>t!==e);if(x(t=>({...t,ids:t.ids.filter(t=>t!==e),previewId:t.previewId===e?void 0:t.previewId,emptied:n.length===0||t.emptied})),R?.id!==e)return;let r=n[Math.min(t,n.length-1)];if(r)d(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),Kn(`file`)}else Yn.length>0?(Jn(Yn[0]),Kn(`diff`)):d(void 0)},[yn,R,z,Yn]),mr=(0,V.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);z.closeFile(t),z.activePath===t&&z.open.length<=1&&Kn(`session`)}else if(e.startsWith(`diff:`)){let t=e.slice(5);Xn(e=>e.filter(e=>e!==t)),qn===t&&(Jn(void 0),Kn(`session`))}else if(e.startsWith(`session:`)){let t=e.slice(8);pr(t)}},[z,pr,qn]),hr=z.active,gr=R?.id;(0,V.useEffect)(()=>{gr&&!gr.startsWith(`pending:`)&&xr({type:`conversation.select`,conversationId:gr})},[gr]);let B=(e,t=`info`)=>{if(!e)return;let n=++Vt.current;De(r=>[...r,{key:n,text:e,kind:t}]),Ht.current.push(window.setTimeout(()=>De(e=>e.filter(e=>e.key!==n)),7e3))};(0,V.useEffect)(()=>{let e=R?.id,t=R?.agentNotice;e&&t&&!Gt.current.has(e)&&(Gt.current.add(e),B(t,`info`))},[R?.id,R?.agentNotice]);let _r=(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},vr=(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},yr=(e,t)=>{if(t.blocking)Te(n=>[...n.filter(n=>n.conversationId!==e||n.request.requestId!==t.requestId),{conversationId:e,request:t}]);else if(t.method===`notify`)B(t.message||t.title,t.notifyType??`info`);else if(t.method===`setStatus`){let e=t.statusKey??``;ke(n=>{let r=new Map(n);return t.statusText===void 0?r.delete(e):r.set(e,t.statusText),r})}else if(t.method===`setWidget`){let e=t.widgetKey??``;je(n=>{let r=new Map(n);return t.widgetLines===void 0?r.delete(e):r.set(e,{lines:t.widgetLines,placement:t.widgetPlacement??`aboveEditor`}),r})}else t.method===`setTitle`?Ne(t.title):t.method===`set_editor_text`&&e===Ut.current&&pn(t.text??``)},br=(e,t,n)=>{Te(n=>n.filter(n=>n.conversationId!==e||n.request.requestId!==t));let r=Jk[n];r&&B(r,`warning`)};(0,V.useEffect)(()=>{let e=!1,t=0,r,s=()=>{if(e)return;let c=location.protocol===`https:`?`wss`:`ws`,l=new WebSocket(`${c}://${location.host}/ws?state=focused${Ut.current?`&conversationId=${encodeURIComponent(Ut.current)}`:``}`);M.current=l,l.onopen=()=>{if(!e){t=0,p(!0),l.send(JSON.stringify({type:`stream.configure`,coalesce:!0})),l.send(JSON.stringify({type:`catalog.fetch`,conversationId:Ut.current})),an.current&&l.send(JSON.stringify({type:`prompt.catalog.fetch`,workspaceId:an.current})),l.send(JSON.stringify({type:`catalog.fetchAll`})),l.send(JSON.stringify({type:`agent.catalog.fetch`})),l.send(JSON.stringify({type:`subagent.catalog.fetch`}));for(let e of a.current)e.retry&&e.command&&l.send(JSON.stringify({...e.command,operationRequestId:e.id}))}},l.onclose=n=>{if(e)return;Wt.current=!1;let o=_O(a.current);for(let e of o.failed)e.onFailure?.();if(a.current=o.retry,i(o.retry),p(!1),t===0){let e=n.reason?.trim()?`${n.reason.trim()}(code ${n.code})`:`code ${n.code}`;console.error(`[Super Pi Error] websocket closed:`,n.code,n.reason),B(`与 Super Pi 服务的连接断开,正在重连。(${e})`,`error`)}r=window.setTimeout(s,Math.min(Nk,Mk*2**t++))},l.onmessage=({data:t})=>{if(e)return;let r=JSON.parse(t);if(r.type!==`message.delta`&&r.type!==`message.thinking`&&L(),r.type===`exec.output`){let e=le.current.get(r.sessionId)??``;le.current.set(r.sessionId,(e+r.data).slice(-512e3)),le.current.size>64&&le.current.delete(le.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:r}))}else if(r.type===`run.stopping`)St(e=>{let t=new Set(e);return t.add(r.conversationId),t});else if(r.type===`exec.exit`)(r.stdout||r.stderr)&&le.current.set(r.sessionId,`${r.stdout}${r.stderr}`);else if(r.type.startsWith(`terminal.`))ue.current?.(r);else if(r.type===`conversation.autoRename.result`){let e=Dt.current.get(r.conversationId);e&&(Dt.current.delete(r.conversationId),r.ok?e.resolve(r.title):e.reject(Error(r.error)))}else if(r.type===`message.thinking`)me(r);else if(r.type===`state`){L(),Wt.current=!1;let e=Ut.current,t=!!(e&&Kt.current.has(e)),s=!(!e||r.state.conversations.some(t=>t.id===e)),c=t&&s&&e&&qt.current.has(e)?{...r.state,conversations:[qt.current.get(e),...r.state.conversations]}:r.state;e&&!s&&(Kt.current.delete(e),qt.current.delete(e)),a.current=a.current.filter(e=>!e.accepted?.(c)),i(a.current),St(e=>{let t=new Set(e);for(let e of[...t]){let n=c.conversations.find(t=>t.id===e);(!n||n.status!==`running`&&n.status!==`waiting`)&&t.delete(e)}return t}),n(c),E(!0),p(!0),y(e=>{if(e&&(c.workspaces.some(t=>t.id===e)||a.current.some(t=>t.temporaryId===e)))return e;let t=o.current?.workspaceId;return t&&c.workspaces.some(e=>e.id===t)?t:c.workspaces[0]?.id})}else if(r.type===`message.delta`)me(r);else if(r.type===`message.revert.result`)Ji(void 0),bt(void 0),r.ok||(console.error(`[Super Pi Error] revert failed:`,r.message),h(r.message));else if(r.type===`operation.result`){let e=a.current.find(e=>e.id===r.requestId);if(a.current=a.current.filter(e=>e.id!==r.requestId),i(a.current),e?.temporaryId){let t=e.temporaryId;if(r.ok&&r.entityId){let e=r.entityId,i=Jt.current.get(t);if(i&&qt.current.set(e,{...i,id:e}),Kt.current.add(e),i){let t={...i,id:e};n(n=>n.conversations.some(t=>t.id===e)?n:{...n,conversations:[t,...n.conversations]})}kt(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.attachments.length?r.attachments:i.attachments,uploading:r.uploading+i.uploading}:r,delete a[t],a}),Jt.current.delete(t)}d(n=>n===t?r.ok?r.entityId:e.previousActiveId:n),x(e=>mj(e,t,r.ok&&r.entityId?r.entityId:void 0)),y(e=>e===t?r.ok?r.entityId:void 0:e)}if(!r.ok){console.error(`[Super Pi Error] operation failed:`,r.message),e?.onFailure?.(r.message);let t=r.message??`操作失败`;h(t),e?.onFailure||B(tp(t),`error`)}}else r.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):r.type===`files.changed`?Dn.current(r.workspaceId,r.changes,r.dropped):r.type===`files.index`?r.workspaceId===kn.current&&(r.cwd??``)===An.current&&On.current(r):r.type===`error`?(console.error(`[Super Pi Error]`,r.message),h(r.message),B(tp(r.message),`error`),Wt.current&&=!1):r.type===`extension.ui`?yr(r.conversationId,r.request):r.type===`extension.ui.closed`?br(r.conversationId,r.requestId,r.reason):r.type===`model.catalog`?(!r.conversationId||r.conversationId===Ut.current)&&Fe(r.catalog):r.type===`model.catalog.all`?Le(r.catalog):r.type===`providers.list`?(ze(r.providers),Ve(r.apis)):r.type===`agent.catalog`?Ue(r.catalog):r.type===`prompt.catalog`?Ce(r.catalog):r.type===`subagent.catalog`?Ge(r.catalog):r.type===`server.version`?(qe(r.version),r.version.needsRestart&&B(`检测到 Super Pi 代码已更新(v${r.version.runningVersion} → v${r.version.diskVersion}),请执行 /super_pi restart 重启服务生效`,`warning`)):r.type===`subagent.event`?n(e=>({...e,subagentRuns:_r(e.subagentRuns??[],r.run)})):r.type===`workflow.event`?n(e=>({...e,workflows:vr(e.workflows??[],r.workflow)})):r.type===`message.tools`?n(e=>({...e,conversations:e.conversations.map(e=>e.id===r.conversationId?{...e,messages:e.messages.map(e=>e.id===r.messageId?{...e,toolCalls:r.toolCalls}:e)}:e)})):r.type===`conversation.fork.result`&&(ta(e=>e===r.conversationId?void 0:e),B(r.ok?`已从「${r.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${r.messagesCopied?`复制了 ${r.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${tp(r.message)}`,r.ok?`info`:`error`))}};return s(),()=>{e=!0,L(),window.clearTimeout(r);for(let e of Ht.current)window.clearTimeout(e);M.current?.close()}},[me,L]);let xr=(0,V.useCallback)(e=>M.current?.readyState===WebSocket.OPEN&&(M.current.send(JSON.stringify(e)),!0),[]);(0,V.useEffect)(()=>{if(!f)return;let e=R?.id;e?.startsWith(`pending:`)||xr({type:`state.subscribe`,...e?{conversationId:e}:{}})},[R?.id,f,xr]),(0,V.useEffect)(()=>{if(f&&Ln&&Tn&&zn.current===Tn&&Bn.current===En)return xr({type:`files.index.subscribe`,workspaceId:Tn,...En?{cwd:En}:{}}),z.requestIndex(!0),()=>{xr({type:`files.index.subscribe`}),z.cancelIndexRequest()}},[f,Ln,Tn,En,xr,z.requestIndex,z.cancelIndexRequest]);let Sr=(e,t,n,r,o,s,c)=>{let l=M.current?.readyState===WebSocket.OPEN,u=gO(e);if(a.current.some(e=>e.key===t)||!l&&!u)return!1;let d=Ev(),f={id:d,key:t,apply:n,temporaryId:r,previousActiveId:Ut.current,onFailure:o,accepted:s,...c?{expiresAt:Date.now()+c}:{},...u?{retry:!0,command:e}:{}};return a.current=[...a.current,f],i(a.current),l&&M.current.send(JSON.stringify({...e,operationRequestId:d})),!0},Cr=e=>{if(!e)return;let t=`message_${Ev()}`;Sr({type:`message.send`,conversationId:e,content:Rk,clientId:t},`continue-truncated:${e}`,e=>e,void 0,void 0,void 0)};(0,V.useEffect)(()=>{let e=r.flatMap(e=>e.expiresAt?[e.expiresAt]:[]);if(!e.length)return;let t=window.setTimeout(()=>{let e=a.current.filter(e=>e.expiresAt&&e.expiresAt<=Date.now());if(e.length){a.current=a.current.filter(t=>!e.includes(t)),i(a.current);for(let t of e)t.onFailure?.(`打断请求超时,尚未确认是否开始回答;请检查会话状态后重试`)}},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[r]);let wr=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Tr=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Er=R?.id.startsWith(`pending:`)===!0,Dr=!!(R&&SA(R)&&(xt.has(R.id)||r.some(e=>e.key===`stop:${R.id}`))),Or=R?.messagesLoaded===!1||r.some(e=>e.key.startsWith(`send:${R?.id}:`)||e.key===`configuration:${R?.id}`||e.temporaryId===R?.id||e.key===`archive:${R?.id}`),kr=(e,t,n,r,i)=>{e&&M.current?.send(JSON.stringify({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i}))},Ar=(e,t,n)=>(Sn(e),Sr({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e)),jr=R?.model??Pe?.defaultModel,Mr=R?.thinkingLevel??Pe?.defaultThinkingLevel,Nr=Pe?.source===`pi`,Pr=!!Pe?.models.find(e=>e.provider===jr?.provider&&e.modelId===jr?.modelId)?.imageInput,Fr=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(l.modelFilterRules??[]).every(n=>{try{return!new RegExp(n.workspacePattern,`i`).test(t.name)||new RegExp(n.modelPattern,`i`).test(e.label)||new RegExp(n.modelPattern,`i`).test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},Ir=!!R?.messages?.some(e=>e.images&&e.images.length>0),Lr=Fr(Pe,l.workspaces.find(e=>e.id===R?.workspaceId))?.models??[],Rr=(Ir?Lr.filter(e=>e.imageInput):Lr).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Hk(e),selected:jr?.provider===e.provider&&jr.modelId===e.modelId})),zr=(Pe?.levels??[]).map(e=>({key:e,label:e,selected:e===Mr})),Br=e=>{if(!R)return;let[t,n]=e.split(`/`);t&&n&&(Sn(R.id),Sr({type:`conversation.model`,conversationId:R.id,provider:t,modelId:n},`configuration:${R.id}`,wr(R.id,{model:Pe?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}})))},Vr=e=>{R&&(Sn(R.id),Sr({type:`conversation.thinking`,conversationId:R.id,level:e},`configuration:${R.id}`,wr(R.id,{thinkingLevel:e})))},Hr=He?.agents.find(e=>e.id===R?.agentId),Ur=[{key:gA,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!R?.agentId},...(He?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:R?.agentId===e.id}))],Wr=Hr?.model,Gr=!!(Wr&&R?.model&&R.model.provider===Wr.provider&&R.model.modelId===Wr.modelId);Hr?.thinkingLevel&&(R?.thinkingLevel,Hr.thinkingLevel);let Kr=e=>{if(R){let t=He?.agents.find(t=>t.id===e);Sr({type:`conversation.agent`,conversationId:R.id,agentId:e===gA?null:e},`configuration:${R.id}`,wr(R.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},qr=we.filter(e=>e.conversationId===R?.id),Jr=(0,V.useMemo)(()=>(l.subagentRuns??[]).filter(e=>e.conversationId===R?.id),[l.subagentRuns,R?.id]),Yr=(0,V.useMemo)(()=>(l.workflows??[]).filter(e=>e.conversationId===R?.id),[l.workflows,R?.id]),Xr=(0,V.useMemo)(()=>new Map(Yr.map(e=>[e.id,e])),[Yr]),Zr=(0,V.useMemo)(()=>new Map((We?.agents??[]).map(e=>[e.id,e.name])),[We]),Qr=(0,V.useMemo)(()=>new Map((R?.messages??[]).map(e=>[e.id,e])),[R?.messages]),$r=(0,V.useMemo)(()=>new Map(Jr.map(e=>[e.id,e])),[Jr]),ei=(0,V.useMemo)(()=>{let e=new Map;for(let t of Jr)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[Jr]),ti=(0,V.useMemo)(()=>{if(!R||!xn)return[];let e=yt?.conversationId===R.id?(()=>{let e=R.messages.find(e=>e.id===yt.messageId);if(e)return{index:R.messages.indexOf(e),at:Date.parse(e.createdAt)||0,...yt.kind===`withdraw`?{inclusive:!0}:{inclusive:!1}}})():void 0,t=[];return R.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}`})}),Jr.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&R?.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}`})}),Yr.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}`})}),t.sort((e,t)=>e.at-t.at||e.seq-t.seq).map(e=>e.key)},[R,Jr,Yr,yt]),ni=(0,V.useMemo)(()=>{for(let e=ti.length-1;e>=0;--e){let t=ti[e];if(t.startsWith(`m:`)&&Qr.get(t.slice(2))?.role===`user`)return t.slice(2)}},[ti,Qr]);(0,V.useEffect)(()=>{let e=ne.current;if(!e||!R?.id)return;let t=()=>{!ce.current&&N.current[R.id]?.followTail&&(cj(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()},[R?.id,R?.messages,Jr,Yr,xn,ti]);let ri=e=>mt(t=>({...t,[e]:!t[e]})),ii=(e,t)=>gt(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),ai=(e,t)=>vt(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[oi,si]=(0,V.useState)({}),ci=e=>si(t=>({...t,[e]:t[e]!==!0})),li=e=>{Sr({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||B(`连接断开,无法停止子智能体,请重试`,`error`)},ui=e=>{Sr({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||B(`连接断开,无法停止编排,请重试`,`error`)},di=e=>[...Ae].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,H.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,Yk).map((e,t)=>(0,H.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>Yk&&(0,H.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),fi=(e,t)=>{let n=`pending:${Ev()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};Sr({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(y(n),d(void 0),O(!1))},[pi,mi]=(0,V.useState)(),hi=(e,t)=>mi(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),gi=()=>mi(void 0),_i=(e,t)=>pi?.kind===e&&pi.id===t,vi=(e,t,n)=>!t.startsWith(`pending:`)&&(e===`conversation`&&Sn(t),Sr(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Tr(t,{name:n}):wr(t,{title:n}))?(Wt.current=!0,gi(),!0):(B(`连接断开,改名未保存,请重试`,`error`),!1)),yi=async e=>{if(e.startsWith(`pending:`)){B(`这个会话还在创建中,稍后再试`,`warning`);return}if(Dt.current.has(e))return;B(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{Dt.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{Dt.current.delete(e)&&n(Error(`模型在 30 秒内没有返回标题`))},32e3)});if(!xr({type:`conversation.autoRename`,conversationId:e}))Dt.current.delete(e),B(`连接断开,无法生成标题`,`error`);else try{let n=await t;vi(`conversation`,e,n),B(`已重命名为「${n}」`,`info`)}catch(e){B(`重命名失败:${tp(e)}`,`error`)}},bi=e=>{if(e.id.startsWith(`pending:`))return;let t=l.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`从列表移除工作区「${e.name}」?${t?`其中的 ${t} 条会话会保留,`:``}重新添加同一个目录即可恢复,不会删除任何会话。`)&&Sr({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)}))},[xi,Si]=(0,V.useState)(),Ci=xi?l.workspaces.find(e=>e.id===xi):void 0,{theme:wi,setTheme:Ti}=ey(),[Ei,Di]=(0,V.useState)(!1),[Oi,ki]=(0,V.useState)(!1),Ai=(e,t,n,r)=>{e.startsWith(`pending:`)||(Sr({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Tr(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Si(void 0):B(`连接断开,设置未保存,请重试`,`error`))},ji=(e,t=``)=>{if(e.startsWith(`pending:`))return;if(a.current.some(t=>t.key===`defaults:${e}`)){B(`工作区设置正在保存,请稍后再新建会话`,`warning`);return}let n=`pending:${Ev()}`,r={id:n,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[],...t?{cwd:t}:{}};Jt.current.set(n,r),Sr({type:`conversation.create`,workspaceId:e,...t?{cwd:t}:{}},`create-session:${e}:${n}`,e=>({...e,conversations:[r,...e.conversations]}),n)?(y(e),d(n),Kn(`session`),x(e=>({...e,ids:[...e.ids.filter(e=>e!==n),n],touched:pj(e.touched,n)}))):(Jt.current.delete(n),B(`连接断开,会话未创建,请重试`,`error`))},Mi=e=>{if(e.startsWith(`pending:`))return;let t=l.conversations.find(t=>t.id===e);if(!t||t.archivedAt||t.parentConversationId&&l.conversations.some(e=>e.id===t.parentConversationId))return;let n=Ak(l.conversations,e),r=n.filter(e=>!e.archivedAt),i=r.length-1,a=n.length-r.length;if(i>0&&!window.confirm(`归档整棵会话树「${t.title}」?本次将归档 ${r.length} 个会话(1 个根会话和 ${i} 个活跃子孙)${a?`,跳过 ${a} 个已归档子孙`:``};恢复根会话时,整棵树会一起恢复。`))return;let o=new Date().toISOString(),s=new Set(r.map(e=>e.id));Sr({type:`conversation.archive`,conversationId:e},`archive:${e}`,e=>({...e,conversations:e.conversations.map(e=>s.has(e.id)&&!e.archivedAt?{...e,archivedAt:o}:e)}))},Ni=(e,t)=>Sr({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}),Pi=e=>{let t=l.conversations.find(t=>t.id===e);if(!t?.archivedAt||(t.parentConversationId?l.conversations.find(e=>e.id===t.parentConversationId):void 0)?.archivedAt)return;let n=new Set(Ak(l.conversations,e).filter(e=>e.archivedAt).map(e=>e.id));Sr({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})}))},Fi=async e=>{if(!R){B(`请先选择或创建会话`,`error`);return}if(!Pr){B(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(B(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(B(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=R.id;fn(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:Ev(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));Pt(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 fetch(`/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`)){B(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(At.current.has(n.id))continue;Pt(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),fn(r,t=>({...t,images:[...t.images,{id:e.id,name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));B(tp(e.error,`上传失败(HTTP ${i.status})`),`error`)}}catch(e){B(`上传失败:${tp(e,`网络或服务暂时不可用`)}`,`error`)}finally{Pt(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),fn(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Ii=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(!Pr){B(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),Fi(n)}},Li=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),Rt(!0))},Ri=e=>{e.currentTarget.contains(e.relatedTarget)||Rt(!1)},zi=e=>{Rt(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!Pr){B(`当前模型不支持图片输入`,`error`);return}Fi(t)}},Bi=e=>{if(e.preventDefault(),!R)return;if(Or){B(Er?`会话正在创建,请稍候再发送`:R.messagesLoaded===!1?`正在加载会话,请稍候再发送`:`正在保存配置,请稍候再发送`,`info`);return}if(!cn.trim()&&ln.length===0)return;if(ln.length>0&&!Pr){B(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(dn>0){B(`图片正在上传中,请稍候…`,`info`);return}let t=`message_${Ev()}`,n=R.id,r=cn,i=ln,a=un;Sn(n),Sr({type:`message.send`,conversationId:n,content:cn,clientId:t,...ln.length>0?{images:ln}:{},...un.length>0?{attachments:un}:{}},`send:${n}:${t}`,e=>{let a=e.conversations.find(e=>e.id===n);if(!a||a.messages.some(e=>e.id===t))return e;let o=a.status===`running`||a.status===`waiting`,s=new Date().toISOString();return{...e,conversations:e.conversations.map(e=>e.id===n?{...e,...o?{}:{status:`waiting`,updatedAt:s},messages:[...e.messages,{id:t,role:`user`,content:r,...i.length>0?{images:i}:{},...un.length>0?{attachments:un}:{},...o?{delivery:`waiting`}:{},createdAt:s}]}:e)}},t,e=>{Mt(o=>[...o,{id:t,conversationId:n,content:r,images:i,attachments:a,reason:e}]),fn(n,e=>e.text||e.images.length||e.attachments.length?e:{...e,text:r,images:i,attachments:a})},e=>!!e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t))?fn(R.id,e=>({...e,text:``,images:[]})):B(`这条消息已经在发送队列中,请稍候`,`info`)},Vi=(0,V.useMemo)(()=>(R?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[R?.messages]),Hi=e=>{Sr({type:`message.cancel`,conversationId:R?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===R?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||B(`连接断开,撤回没有生效,请重试`,`error`)},Ui=e=>{Sr({type:`message.steer`,conversationId:R?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===R?.id?{...t,messages:xk(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===R?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||B(`连接断开,插到最前没有生效,请重试`,`error`)},Wi=e=>{let t=R?.id;t&&(M.current?.readyState===WebSocket.OPEN?Sr({type:`message.interrupt`,conversationId:t,messageId:e},`interrupt:${t}:${e}`,e=>e,void 0,e=>B(e??`打断失败,请重试`,`error`),n=>{let r=n.conversations.find(e=>e.id===t)?.messages.find(t=>t.id===e);return!(!r||r.delivery)},3e4)||B(`正在打断,请稍候`,`info`):B(`连接断开,打断没有生效,请重试`,`error`))},Gi=e=>{Sr({type:`message.sendQueued`,conversationId:R?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===R?.id)?.messages.find(t=>t.id===e)?.delivery)||B(`连接断开,发送没有生效,请重试`,`error`)},Ki=(e,t)=>{Sr({type:`message.edit`,conversationId:R?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===R?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||B(`连接断开,修改没有生效,请重试`,`error`)},[qi,Ji]=(0,V.useState)(),Yi=(e,t=!1)=>{if(!R||R.messagesLoaded===!1||qi)return;let n=R.messages.find(t=>t.id===e);n&&(n&&kt(e=>{let t=e[R.id]??{text:``,images:[],attachments:[],uploading:0};return t.text.trim()||t.images.length||t.attachments.length?e:{...e,[R.id]:{...t,text:n.content,images:n.images??[]}}}),bt({conversationId:R.id,messageId:e,kind:t?`withdraw`:`revert`})),xr({type:`message.revert`,conversationId:R.id,messageId:e,withdraw:t})?Ji(e):(bt(void 0),B(`连接断开,回退未执行,请重试`,`error`))},[Xi,Zi]=(0,V.useState)(),Qi=(0,V.useRef)(void 0),$i=async(e,t)=>{Qi.current&&clearTimeout(Qi.current);let n=await Pk(t);Zi({id:e,kind:n?`copied`:`error`}),n||B(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),Qi.current=setTimeout(()=>Zi(void 0),2e3)};(0,V.useEffect)(()=>()=>{Qi.current&&clearTimeout(Qi.current)},[]);let[ea,ta]=(0,V.useState)(),na=e=>{ea||e.startsWith(`pending:`)||(Sn(e),xr({type:`conversation.fork`,conversationId:e})?ta(e):B(`连接断开,分叉没有执行,请重试`,`error`))},ra=new Map;for(let e of l.scheduledTasks??[])e.conversationId&&!ra.has(e.conversationId)&&ra.set(e.conversationId,e);return(0,H.jsxs)(`main`,{className:`shell${Xe?` shell-rail-collapsed`:``} mobile-panel-${Qe}${et?` mobile-drawer-open`:``}`,"data-rail-collapsed":Xe,"data-selected-workspace":v??``,style:{"--sidebar-width":`${ot.sidebar}px`,"--rail-col":Xe?void 0:`${ot.rail}px`},children:[(0,H.jsxs)(`aside`,{children:[(0,H.jsxs)(`div`,{className:`brand`,children:[(0,H.jsx)(`span`,{children:`π`}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:`SUPER PI`}),(0,H.jsx)(`small`,{children:`agent workspace`})]})]}),(0,H.jsx)(`div`,{className:`sidebar-actions`,children:(0,H.jsx)(`button`,{className:`workspace-new`,onClick:()=>O(!0),children:`+ 工作区`})}),(0,H.jsx)(`div`,{className:`label label-desktop`,children:`工作区`}),(0,H.jsx)(`div`,{className:`label label-phone`,children:`会话`}),(0,H.jsx)(`nav`,{children:l.workspaces.map(e=>{let t=l.conversations.filter(t=>t.workspaceId===e.id),n=t.filter(e=>!e.archivedAt),r=yO(n,$t),i=t.filter(e=>e.archivedAt),a=yO(i,new Set),o=g[e.id]??!1,s=ge[e.id]??!0;return(0,H.jsxs)(`section`,{className:`workspace-group`,children:[(0,H.jsx)(`div`,{className:`workspace-header`,children:_i(`workspace`,e.id)?(0,H.jsx)(mA,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>vi(`workspace`,e.id,t),onClose:gi}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{className:`workspace-toggle`,"aria-expanded":!o,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();wt({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{let t=Zt.find(t=>t.workspaceId===e.id)?.id;y(e.id),d(t),_(t=>({...t,[e.id]:!o}))},children:[(0,H.jsx)(`span`,{className:`chevron chevron-folder`,"aria-hidden":`true`,children:o?`📁`:`📂`}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{onDoubleClick:()=>hi(`workspace`,e.id),children:e.name}),(0,H.jsx)(`small`,{children:e.path})]})]}),(0,H.jsx)(`button`,{className:`workspace-add`,title:`在此工作区新建会话`,onClick:t=>{j.current=t.currentTarget,A({workspaceId:e.id})},children:`+`}),(0,H.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Si(e.id),children:`⚙`}),(0,H.jsx)(`button`,{className:`workspace-delete`,title:`从列表移除工作区(会话保留,重新添加同一目录即可恢复)`,onClick:()=>bi(e),children:`×`})]})}),!o&&(r.length?r.map(({conversation:t,depth:r,childCount:i,isLastSibling:a})=>(0,H.jsxs)(`div`,{className:`conversation-row`,style:{"--tree-depth":r},children:[i>0?(0,H.jsxs)(`button`,{type:`button`,className:`conversation-tree-toggle`,"data-tree-toggle":t.id,"aria-expanded":!$t.has(t.id),title:$t.has(t.id)?`展开 ${i} 个子会话`:`折叠 ${i} 个子会话`,"aria-label":$t.has(t.id)?`展开会话 ${t.title} 的 ${i} 个子会话`:`折叠会话 ${t.title} 的 ${i} 个子会话`,onClick:()=>Ni(t.id,!$t.has(t.id)),children:[(0,H.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:$t.has(t.id)?`▸`:`▾`}),(0,H.jsx)(`small`,{children:i})]}):(0,H.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),_i(`conversation`,t.id)?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(mA,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>vi(`conversation`,t.id,e),onClose:gi}),(0,H.jsx)(`small`,{className:`conversation-time`,children:kk(t.updatedAt,Yt)})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{className:`conversation ${R?.id===t.id?`selected`:``}`,"data-conversation":t.id,"data-tree-child":r>0?`true`:void 0,"data-tree-last":r>0&&a?`true`:void 0,title:r>0?`${t.title}(由「${n.find(e=>e.id===t.parentConversationId)?.title??`已不存在的会话`}」创建)`:t.title,"aria-label":`打开会话 ${t.title}${kA(t,ra.get(t.id))}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();Et({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{Cn(t.id),y(e.id),tt(!1)},onDoubleClick:()=>{wn(t.id)},children:[(0,H.jsx)(`i`,{className:`conversation-mark`,children:(0,H.jsx)(DA,{state:EA(t,TA(t,we),F.current[t.id])})}),(0,H.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:e=>{e.stopPropagation(),hi(`conversation`,t.id)},style:{flex:`0 1 auto`},children:t.title}),(0,H.jsx)(`span`,{className:`conversation-title-gap`,"aria-hidden":`true`,style:{marginLeft:`-8px`}}),OA(t,ra.get(t.id)),(0,H.jsx)(`small`,{children:kk(t.updatedAt,Yt)})]}),(0,H.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":ea===t.id?`pending`:`idle`,disabled:!!ea,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>na(t.id),children:`⑂`}),!(t.parentConversationId&&l.conversations.some(e=>e.id===t.parentConversationId))&&(0,H.jsx)(`button`,{className:`conversation-archive`,"data-archive-conversation":t.id,title:`归档整棵会话树`,"aria-label":`归档会话 ${t.title}`,onClick:()=>Mi(t.id),children:`×`})]})]},t.id)):(0,H.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!o&&i.length>0&&(0,H.jsxs)(`div`,{className:`archived-group`,"data-archived-count":i.length,children:[(0,H.jsxs)(`button`,{className:`archived-toggle`,title:s?`展开已归档会话`:`收起已归档会话`,"aria-expanded":!s,onClick:()=>_e(t=>({...t,[e.id]:!s})),children:[(0,H.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:s?`▸`:`▾`}),(0,H.jsxs)(`span`,{className:`archived-label`,children:[`已归档 (`,i.length,`)`]})]}),!s&&a.map(({conversation:e,depth:t,isLastSibling:n})=>{let r=Ak(i,e.id).length-1,a=!!(e.parentConversationId&&l.conversations.some(t=>t.id===e.parentConversationId&&t.archivedAt));return(0,H.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,H.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{"data-archived-title":e.id,children:e.title}),OA(e,ra.get(e.id)),(0,H.jsx)(`small`,{children:jk(e.archivedAt)}),!a&&(0,H.jsx)(`button`,{className:`conversation-restore`,"data-restore-conversation":e.id,title:r?`恢复这个会话和它的 ${r} 个子孙会话`:`恢复为正常会话`,"aria-label":r?`恢复会话 ${e.title} 及其 ${r} 个子孙会话`:`恢复会话 ${e.title}`,onClick:()=>Pi(e.id),children:`↑`})]},e.id)})]})]},e.id)})}),(0,H.jsxs)(`footer`,{children:[(0,H.jsxs)(`div`,{className:`footer-status`,children:[(0,H.jsx)(`i`,{className:f?`online`:`offline`}),f?`已连接`:`正在连接`,(0,H.jsx)(`span`,{children:`本地持久化`})]}),(0,H.jsxs)(`div`,{className:`footer-version`,"data-super-pi-version":Ke?.runningVersion??``,children:[`Super Pi v`,Ke?.runningVersion??`…`]}),(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Ei,onClick:()=>{Di(!0),xr({type:`catalog.fetchAll`}),xr({type:`providers.fetch`})},children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),`设置`]}),(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Oi,onClick:()=>ki(!0),children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`📖`}),`使用指南`]}),(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`检查 Super Pi 更新`,onClick:async()=>{Ye(`updating`);try{let e=await fetch(`/api/update-check`);if(!e.ok)throw Error(`check failed`);let t=await e.json();if(t.needsRestart)B(`当前代码已更新,正在重启服务…`,`info`);else if(t.updateAvailable){if(!window.confirm(`发现新版本 v${t.latestVersion??``},是否立即更新并重启 Super Pi?`))B(`已取消更新`,`info`);else{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);B(`正在更新到 v${t.latestVersion} 并重启…`,`info`)}}else B(`当前已是最新版本`,`info`)}catch{B(`检查更新失败,请检查网络或服务日志`,`error`)}finally{Ye(`idle`)}},children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:Je===`updating`?`⟳`:`↻`}),Je===`updating`?`正在检查更新…`:`检查更新`]}),Ke?.needsRestart&&(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`代码已更新:当前运行 v${Ke.runningVersion},磁盘版本 v${Ke.diskVersion}。点击复制重启命令 /super_pi restart`,onClick:async()=>{Ye(`updating`);try{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);B(`正在更新 Super Pi,服务即将重启…`,`info`)}catch{Ye(`idle`),B(`更新启动失败,请检查服务日志`,`error`)}},children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:Je===`updating`?`⟳`:`⚠️`}),Je===`updating`?`正在更新并重启…`:`更新并重启服务`]})]})]}),(0,H.jsx)(yj,{side:`left`,width:ot.sidebar,min:ot.sidebarMin,max:ot.sidebarMax,label:`调整左侧栏宽度`,onWidth:st}),(0,H.jsxs)(`section`,{className:`chat`,"data-main-view":Gn,"data-main-view-kind":Gn,children:[lr.length>0&&(0,H.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":bn.length,"data-file-count":z.open.length,children:(0,H.jsx)(G_,{tabs:lr,prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:ur,onSelect:dr,onClose:mr,onActivate:fr,minWidth:120,maxWidth:320})}),(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`button`,{type:`button`,className:`mobile-drawer-toggle`,"data-mobile-drawer-toggle":`1`,"aria-label":`打开会话列表`,title:`会话列表`,"aria-expanded":et,onClick:()=>tt(!0),children:`☰`}),(0,H.jsxs)(`div`,{className:`chat-head`,children:[(0,H.jsx)(`h1`,{children:R?.title??`准备开始`}),Oe.size>0?[...Oe].map(([e,t])=>(0,H.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):(0,H.jsx)(`p`,{"data-role":`run-status`,children:R?.status===`running`?`Agent 正在工作`:R?.status===`awaiting_background`?`后台任务运行中`:`Pi runtime · Web 控制台`})]}),(0,H.jsxs)(`span`,{className:`chat-view chat-view-${Gn}`,"data-main-view-indicator":Gn,"data-main-view-kind":Gn,title:Gn===`file`?`中间主画面正在显示文件 ${z.active?.path??``}`:Gn===`diff`?`中间主画面正在显示 ${qn??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,H.jsx)(`span`,{className:`chat-view-label`,children:`主区显示`}),(0,H.jsx)(`span`,{className:`chat-view-kind`,children:Gn===`file`?`文件`:Gn===`diff`?`改动`:`会话`}),Gn===`file`&&z.active&&(0,H.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":z.active.name,children:z.active.name}),Gn===`diff`&&qn&&(0,H.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":qn,children:qn})]}),(0,H.jsx)(`div`,{className:`badge`,"data-conversation-status":R?.status??`idle`,children:xA[R?.status??`idle`]})]}),m&&(0,H.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,H.jsx)(`span`,{title:np(m),children:tp(m)}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>h(void 0),children:`×`})]}),R?.error&&(0,H.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,title:np(R.error),children:tp(R.error)}),R?.warning&&(0,H.jsxs)(`div`,{className:`warning`,role:`status`,"data-role":`conversation-warning`,title:np(R.warning),children:[(0,H.jsx)(`span`,{children:R.warning}),(0,H.jsx)(`button`,{type:`button`,"data-role":`conversation-warning-continue`,title:`让模型接着把被截断的部分写完`,onClick:()=>Cr(R?.id??``),children:`继续写完`})]}),R?.modelNotice&&(0,H.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-model-notice`,children:R.modelNotice}),R?.agentNotice&&(0,H.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-agent-notice`,children:R.agentNotice}),Me&&(0,H.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,Me]}),Ee.length>0&&(0,H.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Ee.length,children:Ee.map(e=>(0,H.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),Gn===`file`?(0,H.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":hr?.path,"data-file-view-kind":`editor`,children:hr?(0,H.jsx)(A_,{file:hr,state:z.saves[hr.path]?.state??`idle`,message:z.saves[hr.path]?.message??``,external:z.external[hr.path]===!0,jumpToLine:Un&&Un.workspaceId===v&&Un.path===hr.path?Un:void 0,onChange:e=>z.updateBuffer(hr.path,e),onSave:()=>void z.save(hr.path,!1),onReload:()=>void z.reload(hr.path),onOverwrite:()=>void z.save(hr.path,!0),workspaceId:v,cwd:En}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})}):Gn===`diff`?(0,H.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":qn??``,"data-file-view-kind":`diff`,children:(0,H.jsx)(M_,{diff:$n.diff,loading:$n.loading,error:$n.error,bufferContent:rr,mode:tr,onMode:nr})}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`messages`,ref:ne,"data-message-scroll-container":R?.id??``,onWheel:e=>{e.deltaY<0&&N.current[R?.id??``]?.followTail&&(ce.current=!0,on(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:on(t)},children:[(!R||!xn)&&(0,H.jsxs)(`div`,{className:`empty`,children:[(0,H.jsx)(`div`,{className:`orb`,children:`π`}),(0,H.jsx)(`h2`,{children:`开始一个新会话`}),l.workspaces.length===0?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,H.jsx)(`button`,{onClick:()=>O(!0),children:`+ 新建工作区`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{children:l.workspaces.length===1&&tn?`在「${tn.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),l.workspaces.length>1&&(0,H.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,H.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,H.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:tn?.id,onChange:e=>{e.target.value===`__new__`?O(!0):y(e.target.value)},children:[l.workspaces.map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.name},e.id)),(0,H.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),tn&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Gk,{workspaceId:tn.id,value:nn,onChange:rn}),(0,H.jsx)(`button`,{onClick:()=>ji(tn.id,nn),children:`新建会话`})]}),(0,H.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>O(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O(!0))},children:`+ 新建工作区`})]})]}),R?.messagesLoaded===!1&&(0,H.jsx)(`p`,{role:`status`,"data-conversation-loading":`1`,children:`正在加载会话…`}),ti.map(e=>{if(e.startsWith(`m:`)){let t=Qr.get(e.slice(2));if(!t)return null;let n=t.id===ni,i=t.role===`user`&&R?.status!==`running`&&R?.status!==`waiting`&&qi!==t.id,a=i&&n&&!t.id.startsWith(`pending:`),o=i&&!n&&!!t.piEntryId,s=t.content?(0,H.jsx)(Am,{source:t.content}):(0,H.jsx)(`span`,{className:`typing`,children:`正在思考`}),c=t.toolCalls??[];if(t.role===`user`){let n=Xi?.id===t.id?Xi.kind:void 0,r=t.content||(t.images?.length?`[图片]`:``);return(0,H.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,H.jsxs)(`div`,{className:`message-body`,children:[(0,H.jsxs)(`div`,{className:`bubble`,children:[(0,H.jsxs)(`div`,{className:`meta`,children:[xe,(0,H.jsx)(`time`,{children:Sk(t.createdAt)})]}),t.images&&t.images.length>0&&(0,H.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,H.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>It({url:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,H.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,H.jsx)(`div`,{className:`content`,children:s})]}),t.attachments&&t.attachments.length>0&&(0,H.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:t.attachments.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=ht[n]??!1;return(0,H.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,H.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>gt(e=>({...e,[n]:!r})),children:[(0,H.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,H.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,H.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,H.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,H.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,H.jsxs)(`div`,{className:`message-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":n,"aria-label":`复制这条消息:${r}`,onClick:()=>$i(t.id,r),children:n===`copied`?`已复制`:n===`error`?`复制失败`:`复制`}),a&&(0,H.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>Yi(t.id,!0),children:`撤回`}),o&&(0,H.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退到这里:删除后续全部内容(Pi 的记录和这里的历史一起清掉,不会新建会话,也不动任何代码文件)`,onClick:()=>Yi(t.id),children:`回退`})]})]}),(0,H.jsx)(`div`,{className:`avatar`,title:xe,children:xe})]},e)}if(t.role===`tool`){let n=/<task id="[^"]+" state="[^"]+"/.test(t.content),r=(()=>{let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():n?`后台回传`:(t.content.split(`
99
+ 如需本地计算,声明 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、访问地址、文件清单和验证结果。`);d(e),window.setTimeout(()=>d(!1),1800)};(0,V.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let I=(0,V.useMemo)(()=>[...t.map(e=>({id:e.id,name:e.name,glyph:e.glyph})),...n.map(e=>({id:e.id,name:e.name,glyph:`🧩`}))],[t,n]);(0,V.useEffect)(()=>{if(!M)return;let e=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),N(void 0);return}if(AO(e.key)||zO(e.target))return;e.preventDefault(),e.stopPropagation();let t=M;if(N(void 0),e.key===`Delete`||e.key===`Backspace`){ak.clearShortcut(t),F(void 0);return}let n=jO(e);if(!n){F(`没有认出这个按键,换一个试试。`);return}let i=LO(n);if(!i.ok){F(i.reason);return}let a=UO(r,n,t);if(a){let e=I.find(e=>e.id===a)?.name;F(e?`这个组合键已经被「${e}」占用了,换一个键。`:`这个组合键已经被另一个工具占用了,换一个键。`)}else ak.setShortcut(t,n),F(void 0)};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[M,r,I]);let ie=e=>{ne(QO(e,window.innerWidth,window.innerHeight))},ae=e=>{ZO(e)},oe=()=>{ne(void 0),ZO(void 0)},se=(0,V.useRef)(!1),ce=n.map(e=>e.slug).filter(e=>typeof e==`string`),le=e=>{p(void 0),h(void 0),k(void 0),D({tool:e,name:hk({slug:e.slug??`tool`})})},ue=async(e,t)=>{p(void 0),h(void 0),k(void 0);let n=gk(t);if(!n.ok)k(n.reason);else try{let t=await fetch(`/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),h(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){p(`导出失败:${tp(e)}`)}finally{D(void 0)}},de=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;p(void 0),h(void 0),x(void 0);let n=fk(await t.text(),t.name);n.ok?(_({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),y(ce.includes(n.bundle.slug)?mk(n.bundle.slug,ce):n.bundle.slug),C(n.bundle.files[0]?.path)):p(n.reason)},fe=()=>{_(void 0),y(``),x(void 0),C(void 0)},pe=async()=>{if(!g)return;x(void 0);let e=pk(v);if(!e.ok)x(e.reason);else if(ce.includes(e.slug))x(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{T(!0);try{let t=await fetch(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(xk(g.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await ok(),h(`已导入「${g.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),fe()}catch(e){p(`导入失败:${tp(e)}`)}finally{T(!1)}}};(0,V.useEffect)(()=>{E&&j.current?.scrollIntoView({block:`center`})},[E]);let L=()=>{let e=Cv(i);e.ok?t.length>=32?l(`工具最多 32 个,先删掉一个再加。`):(ak.setTools([...t,{id:Dv(`link`,t.map(e=>e.id)),kind:`link`,name:o.trim()||JA(e.url),glyph:`↗`,url:e.url}]),a(``),s(``),l(void 0)):l(e.reason)},me=te?{width:`${te.width}px`,height:`${te.height}px`,maxWidth:`calc(100vw - 32px)`,maxHeight:`calc(100vh - 32px)`}:void 0;return(0,sa.createPortal)((0,H.jsxs)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onPointerDown:()=>{se.current=!1},onClick:t=>{se.current?se.current=!1:t.target===t.currentTarget&&e()},children:[(0,H.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,ref:ee,style:me,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:e,children:`✕`})]}),(0,H.jsx)(`div`,{className:`tool-dialog-body`,children:g?(0,H.jsx)(qA,{pending:g,slugDraft:v,slugError:b,preview:S,busy:w,onSlugChange:e=>{y(e),x(void 0)},onPreviewChange:C,onCancel:fe,onConfirm:()=>void pe()}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,H.jsx)(`strong`,{children:`给 Agent 开发新工具`}),(0,H.jsx)(`p`,{className:`tool-hint`,children:`工具会挂载到 Super Pi 的统一 HTTP 服务,不需要再启动独立服务器。`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void re(),children:u?`已复制`:`复制工具开发 Prompt`})]}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,H.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":_v.length,children:_v.map(e=>{let n=t.some(t=>t.kind===e.kind);return(0,H.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":e.kind,children:[(0,H.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.jsx)(`small`,{children:e.blurb})]}),(0,H.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:()=>ak.setTools(Ov(t,e.kind)),children:n?`已添加`:`添加`})]},e.kind)})}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,H.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,H.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,H.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:o,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>s(e.target.value)}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!i.trim(),onClick:L,children:`添加网址工具`}),c&&(0,H.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:c}),(0,H.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,H.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`快捷键`})}),(0,H.jsxs)(`p`,{className:`tool-hint`,"data-tool-shortcut-hint":`1`,children:[`给每个工具绑一个组合键,按下就直接打开它,不用先找到右侧栏。`,(0,H.jsx)(`b`,{children:`弹窗打开时快捷键不生效`}),`——模态弹窗期间键盘归它自己,关掉之后再按。`]}),(0,H.jsx)(`div`,{className:`tool-shortcuts`,"data-tool-shortcut-count":I.length,children:I.map(e=>(0,H.jsxs)(`div`,{className:`tool-shortcut-row`,"data-tool-shortcut-row":e.id,children:[(0,H.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,H.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.jsx)(`small`,{children:r[e.id]?`按 ${NO(r[e.id])} 打开`:`还没有快捷键`})]}),(0,H.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:()=>{F(void 0),N(M===e.id?void 0:e.id)},children:M===e.id?`按下组合键…`:r[e.id]?NO(r[e.id]):`未设置`}),r[e.id]&&(0,H.jsx)(`button`,{type:`button`,className:`tool-shortcut-clear`,"data-tool-shortcut-clear":e.id,title:`清除${e.name}的快捷键`,"aria-label":`清除${e.name}的快捷键`,onClick:()=>{ak.clearShortcut(e.id),F(void 0),N(void 0)},children:`清除`})]},e.id))}),P&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-shortcut-error":`1`,children:P}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有通过 tool_register 注册的工具。上面复制那段 Prompt,让 Agent 写一个。`}):(0,H.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=yk(e.environmentState);return(0,H.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,H.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,H.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,H.jsx)(`strong`,{children:e.name}),(0,H.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,H.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>le(e),children:`导出`})]},e.id)})}),E&&(0,H.jsxs)(`div`,{className:`tool-share-review`,ref:j,"data-tool-export-name":`1`,children:[(0,H.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,E.tool.name,`」`]}),(0,H.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,H.jsx)(`input`,{className:`tool-input`,value:E.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>D({...E,name:e.target.value})})]}),O&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:O}),(0,H.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{D(void 0),k(void 0)},children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void ue(E.tool,E.name),children:`导出`})]})]}),m&&(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:m}),f&&(0,H.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:f}),(0,H.jsx)(`div`,{className:`rail-section-head`,children:(0,H.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,H.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,H.jsx)(`code`,{children:ck}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,H.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>A.current?.click(),children:`选择文件…`}),(0,H.jsx)(`input`,{ref:A,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void de(e)})]})})]}),(0,H.jsx)(GA,{targetRef:ee,onResize:ie,onCommit:ae,onDragEnd:()=>{se.current=!0},onReset:oe})]}),document.body)}var WA=18;function GA({targetRef:e,onResize:t,onCommit:n,onDragEnd:r,onReset:i}){let[a,o]=(0,V.useState)(),s=(0,V.useRef)(void 0);return(0,V.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=t.getBoundingClientRect();o({left:e.right-WA,top:e.bottom-WA})};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,H.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=QO({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??GO.width,l=o?.height??GO.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=QO({width:c,height:l},window.innerWidth,window.innerHeight);s.current=u,t(u),n(u)},onClick:e=>e.stopPropagation()})}function KA(){let{tools:e,mountedTools:t,openToolId:n,settingsOpen:r,shortcuts:i}=ik(),a=e.find(e=>e.id===n),o=t.find(e=>e.id===n);return(0,V.useEffect)(()=>{let n=n=>{if(!r&&!document.querySelector(`[aria-modal="true"]`)&&!(n.isComposing||n.defaultPrevented)){for(let[r,a]of Object.entries(i))if(BO(a,n)&&(e.some(e=>e.id===r)||t.some(e=>e.id===r))){n.preventDefault(),ak.openTool(r);return}}};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[i,e,t,r]),(0,V.useEffect)(()=>{ok();let e=()=>{ok()};return window.addEventListener(`super-pi-tools-updated`,e),()=>window.removeEventListener(`super-pi-tools-updated`,e)},[]),(0,V.useEffect)(()=>{ak.persistTools()},[]),(0,H.jsxs)(H.Fragment,{children:[r&&(0,H.jsx)(UA,{onClose:()=>ak.closeSettings()}),a&&(0,H.jsx)(YA,{tool:a,onClose:()=>ak.closeTool()}),o&&(0,H.jsx)(nj,{tool:o,onClose:()=>ak.closeTool()})]})}function qA({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=vk(l),f=_k(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,H.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,H.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,H.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,H.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,bk(u)]}),(0,H.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,H.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,H.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,H.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,H.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,H.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` · `,l.environment.fingerprint.platform||`未知平台`,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,H.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,H.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,H.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,H.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,H.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,H.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,H.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,H.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,H.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,H.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,H.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,H.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,H.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function JA(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 YA({tool:e,onClose:t}){return(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,sa.createPortal)((0,H.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,H.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,H.jsx)(`span`,{className:`tool-dialog-glyph`,"aria-hidden":`true`,children:e.glyph}),e.name]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,H.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,H.jsx)(ZA,{}),e.kind===`timestamp`&&(0,H.jsx)(QA,{}),e.kind===`link`&&(0,H.jsx)($A,{tool:e})]})]})}),document.body)}function XA({image:e,onClose:t}){return(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,sa.createPortal)((0,H.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,H.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,H.jsxs)(`div`,{className:`lightbox-head`,children:[(0,H.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,H.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,H.jsx)(`div`,{className:`lightbox-body`,children:(0,H.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function ZA(){let[e,t]=(0,V.useState)(`12 * (3 + 4)`),n=Hv(e),r=e=>{t(t=>t+e)};return(0,H.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,H.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,H.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,H.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,H.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:Uv(n.value)}):(0,H.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function QA(){let[e,t]=(0,V.useState)(``),n=Wv(e),r=n.ok?Kv(n.ms):null;return(0,H.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,H.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,H.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`本地时间`}),(0,H.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`ISO(UTC)`}),(0,H.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`秒`}),(0,H.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`dt`,{children:`毫秒`}),(0,H.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,H.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function $A({tool:e}){let[t,n]=(0,V.useState)(!1),r=async()=>{let e=await Lk(`请为 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,H.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,H.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,H.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,H.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,H.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,H.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,H.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 ej=`(max-width: 1100px)`,tj=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function nj({tool:e,onClose:t}){return(0,V.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,sa.createPortal)((0,H.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,H.jsxs)(`div`,{className:`tool-dialog`,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,H.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,H.jsxs)(`h2`,{className:`tool-dialog-title`,children:[`🧩 `,e.name]}),(0,H.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,H.jsx)(`div`,{className:`tool-dialog-body`,children:(0,H.jsx)(`iframe`,{className:`tool-link-frame`,src:`/tools/${encodeURIComponent(e.id)}/`,title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function rj(e,t,n){let r=Math.max(0,Math.round(n)-480),i=tj(520,180,Math.max(180,r-240)),a=tj(Math.round(e),180,i),o=tj(640,240,Math.max(240,r-a));return{sidebar:a,rail:tj(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var ij=`super-pi.rail-widths.v1`,aj=`super-pi.reader-state.v1`,oj=`super-pi.folded-groups.v1`;function sj(){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 cj(e){try{typeof window<`u`&&window.localStorage.setItem(oj,JSON.stringify(e))}catch{}}var lj=32,uj=48,dj=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function fj(e,t,n=!1,r=!1){let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=n?!1:r?!0:t.followTail?i<=uj:i<=lj,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 pj(){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 mj(e){try{typeof window<`u`&&window.localStorage.setItem(aj,JSON.stringify(e))}catch{}}var hj=`super-pi.session-tabs.v1`;function gj(e,t){if(!t||e.has(t))return e;let n=new Set(e);return n.add(t),n}function _j(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 vj(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(window.sessionStorage.getItem(`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=typeof t.previewId==`string`&&n.includes(t.previewId)?t.previewId:void 0,i=Array.isArray(t.touched)?[...new Set(t.touched.filter(e=>typeof e==`string`))]:[];return{ids:n,activeId:typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0,previewId:r,touched:i}}catch{return{ids:[]}}}function yj(e,t,n,r){try{if(typeof window>`u`)return;window.sessionStorage.setItem(hj,JSON.stringify({ids:e,...t&&e.includes(t)?{activeId:t}:{},...n&&e.includes(n)?{previewId:n}:{},...r&&r.length>0?{touched:r}:{}}))}catch{}}function bj(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(ij);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 xj(e){try{if(typeof window>`u`)return;window.localStorage.setItem(ij,JSON.stringify(e))}catch{}}function Sj({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,V.useState)(!1),c=e=>e.shiftKey?64:16;return(0,H.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(tj(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(tj(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(tj(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var Cj=`super-pi.composer-height.v1`,wj=148,Tj=.55,Ej=()=>Math.max(wj,Math.round((typeof window>`u`?800:window.innerHeight)*Tj)),Dj=e=>{let t=Number.isFinite(e)?e:wj;return Math.round(Math.min(Ej(),Math.max(wj,t)))},Oj=()=>{try{let e=window.localStorage.getItem(Cj);return e===null?wj:Dj(Number(e))}catch{return wj}};function kj({height:e,onHeight:t}){let[n,r]=(0,V.useState)(!1),i=e=>e.shiftKey?64:16,a=Ej();return(0,H.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":wj,"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=Dj(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(Dj(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(Dj(e-r))):n.key===`Home`?(n.preventDefault(),t(wj)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(Dj(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(Dj(e-96)))}})}function Aj(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 e[0]}function jj(){let[e,t]=(0,V.useState)(Sk),n=(0,V.useCallback)(e=>{t(t=>{let n=typeof e==`function`?e(t):e;return pe(n,t)})},[]),[r,i]=(0,V.useState)([]),a=(0,V.useRef)([]),o=(0,V.useRef)(null);o.current||=pj();let s=(0,V.useRef)(null);s.current||=vj();let c=s.current,l=r.reduce((e,t)=>t.apply(e),e),[u,d]=(0,V.useState)(s.current.activeId??o.current.activeId),[f,p]=(0,V.useState)(!1),[m,h]=(0,V.useState)(),[g,_]=(0,V.useState)(()=>sj().workspaces??{}),[v,y]=(0,V.useState)(o.current.workspaceId),[b,x]=(0,V.useState)(()=>({ids:c.ids,previewId:c.previewId,touched:new Set(c.touched??[]),emptied:!1})),S=b.ids,C=b.previewId,w=b.emptied===!0,[T,E]=(0,V.useState)(!1),[D,O]=(0,V.useState)(!1),[k,A]=(0,V.useState)(),j=(0,V.useRef)(null),M=(0,V.useRef)(void 0),N=(0,V.useRef)(o.current.conversations),P=(0,V.useRef)(S);P.current=S;let F=(0,V.useRef)(o.current.readAt??{}),[ee,te]=(0,V.useState)(0),ne=(0,V.useRef)(null),re=(0,V.useRef)(null),I=(0,V.useRef)(void 0),ie=(0,V.useRef)(!1),ae=(0,V.useRef)(!0),[oe,se]=(0,V.useState)({followTail:!0,scrollTop:0}),ce=(0,V.useRef)(!1),le=(0,V.useRef)(new Map),ue=(0,V.useRef)(void 0),de=(0,V.useRef)([]),fe=(0,V.useRef)(void 0),pe=(0,V.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,content:t.content,thinking:t.thinking,thinkingActive:t.thinkingActive,thinkingBlocks:t.thinkingBlocks}:e})}})}},[]),L=(0,V.useCallback)(()=>{if(fe.current!==void 0&&(cancelAnimationFrame(fe.current),fe.current=void 0),!de.current.length)return;let e=de.current;de.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)}n(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=[...i.thinkingBlocks??[]],r=n.at(-1);r&&r.at===t&&(e.blockIndex===void 0||e.blockIndex===n.length-1)?n[n.length-1]={...r,text:r.text+e.delta}:n.push({at:t,text:e.delta}),i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return n.every((t,n)=>t===e.messages[n])?e:{...e,messages:n}})}))},[]),me=(0,V.useCallback)(e=>{let t=de.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),fe.current===void 0&&(fe.current=requestAnimationFrame(L))},[L]),he=(0,V.useCallback)(e=>{ue.current=e},[]),[ge,_e]=(0,V.useState)(()=>sj().archived??{});(0,V.useEffect)(()=>{cj({workspaces:g,archived:ge})},[g,ge]);let[ve,ye]=(0,V.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),be=e=>{let t=e.slice(0,24);ye(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},xe=ve.trim()||`你`,[Se,Ce]=(0,V.useState)(),[we,Te]=(0,V.useState)([]),[Ee,De]=(0,V.useState)([]),[Oe,ke]=(0,V.useState)(new Map),[Ae,je]=(0,V.useState)(new Map),[Me,Ne]=(0,V.useState)(),[Pe,Fe]=(0,V.useState)(),[Ie,Le]=(0,V.useState)(),[Re,ze]=(0,V.useState)([]),[Be,Ve]=(0,V.useState)([]),[He,Ue]=(0,V.useState)(),[We,Ge]=(0,V.useState)(),[Ke,qe]=(0,V.useState)(),[Je,Ye]=(0,V.useState)(`idle`),[Xe,Ze]=(0,V.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Qe,$e]=(0,V.useState)(`chat`),[et,tt]=(0,V.useState)(!1),[nt,rt]=(0,V.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,V.useEffect)(()=>{let e=()=>rt(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[it,at]=(0,V.useState)(bj),ot=rj(it.sidebar??270,it.rail??320,nt);(0,V.useEffect)(()=>{xj({sidebar:it.sidebar??270,rail:it.rail??320})},[it.sidebar,it.rail]);let st=e=>at(t=>({...t,sidebar:e})),ct=e=>at(t=>({...t,rail:e})),[lt,ut]=(0,V.useState)(null);(0,V.useEffect)(()=>{ut(Oj())},[]),(0,V.useEffect)(()=>{lt!==null&&document.documentElement.style.setProperty(`--composer-height`,`${lt}px`)},[lt]);let dt=e=>{let t=Dj(e);ut(t);try{window.localStorage.setItem(Cj,String(t))}catch{}};(0,V.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(ej),t=e=>{e.matches&&Ze(!0)};return e.addEventListener(`change`,t),e.matches&&Ze(!0),()=>e.removeEventListener(`change`,t)},[]);let ft=nt<=1100;(0,V.useEffect)(()=>{if(!ft||Xe)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(),Ze(!0)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[ft,Xe]);let[pt,mt]=(0,V.useState)({}),[ht,gt]=(0,V.useState)({}),[_t,vt]=(0,V.useState)({}),[yt,bt]=(0,V.useState)(),[xt,St]=(0,V.useState)(()=>new Set),[Ct,wt]=(0,V.useState)(),[Tt,Et]=(0,V.useState)(),Dt=(0,V.useRef)(new Map),[Ot,kt]=(0,V.useState)({}),At=(0,V.useRef)(new Set),[jt,Mt]=(0,V.useState)([]),[Nt,Pt]=(0,V.useState)([]),[Ft,It]=(0,V.useState)(),[Lt,Rt]=(0,V.useState)(!1),zt=(0,V.useRef)(null),Bt=(0,V.useRef)(!1),Vt=(0,V.useRef)(0),Ht=(0,V.useRef)([]),Ut=(0,V.useRef)(void 0),Wt=(0,V.useRef)(!1),Gt=(0,V.useRef)(new Set),Kt=(0,V.useRef)(new Set),qt=(0,V.useRef)(new Map),Jt=(0,V.useRef)(new Map),[Yt,Xt]=(0,V.useState)(()=>Date.now());(0,V.useEffect)(()=>{let e=window.setInterval(()=>Xt(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let Zt=(0,V.useMemo)(()=>l.conversations.filter(e=>!e.archivedAt),[l.conversations]),Qt=(0,V.useMemo)(()=>e.conversations.filter(e=>!e.archivedAt),[e.conversations]),$t=(0,V.useMemo)(()=>new Set(l.collapsedConversationIds??[]),[l.collapsedConversationIds]),R=(0,V.useMemo)(()=>{let e=Zt.find(e=>e.id===u);if(e)return e;if(!w)return Aj(Zt,l.workspaces,v)},[w,u,Zt,v,l.workspaces]),en=ne.current;if(en){let e=en.dataset.messageScrollContainer;e&&R?.id&&e!==R?.id&&en.querySelector(`[data-transcript-key]`)&&(N.current[e]=fj(en,N.current[e]??{followTail:!0,scrollTop:0}))}ae.current=R?.messagesLoaded!==!1,(0,V.useEffect)(()=>{if(!T||w||u&&Qt.some(e=>e.id===u)||u&&a.current.some(e=>e.temporaryId===u))return;let e=Aj(Zt,l.workspaces,v);d(e?.id)},[w,u,Qt,Zt,T,v,l.workspaces]),(0,V.useEffect)(()=>{h(void 0)},[u,v]);let tn=(0,V.useMemo)(()=>l.workspaces.find(e=>e.id===v)??l.workspaces[0],[l.workspaces,v]),[nn,rn]=(0,V.useState)(``);(0,V.useEffect)(()=>{rn(``)},[tn?.id]);let an=(0,V.useRef)(v);an.current=v,(0,V.useEffect)(()=>{R&&y(R.workspaceId)},[R?.id]),(0,V.useEffect)(()=>{Ut.current=u},[u]),(0,V.useEffect)(()=>{I.current=R?.id},[R?.id]),(0,V.useEffect)(()=>{let e=R?.id;if(!e)return;let t=l.conversations.find(t=>t.id===e);if(!t)return;let n=F.current[e];F.current[e]=t.updatedAt,n!==t.updatedAt&&te(e=>e+1),mj({activeId:Ut.current,workspaceId:R?.workspaceId??v,conversations:N.current,readAt:F.current})},[R?.id,l.conversations]),(0,V.useEffect)(()=>{f&&u&&mj({activeId:u,workspaceId:R?.workspaceId??v,conversations:N.current,readAt:F.current})},[u,R?.workspaceId,f,v]),(0,V.useEffect)(()=>{let e=ne.current;if(!e||!R?.id||R.messagesLoaded===!1)return;let t=R.id;ce.current=!1;let n=N.current[t]??{followTail:!0,scrollTop:0};N.current[t]=n,se(n);let r=requestAnimationFrame(()=>{if(ne.current!==e)ie.current=!1;else{if(n.followTail)dj(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}ie.current=!1}});return()=>cancelAnimationFrame(r)},[R?.id,R?.messagesLoaded]),(0,V.useLayoutEffect)(()=>{ie.current=!0},[R?.id,R?.messagesLoaded]);let on=(0,V.useCallback)((e,t=!1,n=!1)=>{let r=I.current;if(!r||ie.current||!ae.current)return;let i=fj(e,N.current[r]??{followTail:!0,scrollTop:0},t,n);ce.current=!i.followTail,N.current[r]=i,se(i),mj({activeId:r,workspaceId:an.current,conversations:N.current,readAt:F.current})},[]),sn=Ot[R?.id??``]??{text:``,images:[],attachments:[],uploading:0},cn=sn.text,ln=sn.images,un=sn.attachments,dn=sn.uploading,fn=(e,t)=>kt(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),pn=e=>fn(R?.id??``,t=>({...t,text:e})),mn=e=>fn(R?.id??``,t=>({...t,attachments:t.attachments.some(t=>t.kind===e.kind&&t.id===e.id)?t.attachments:[...t.attachments,e]})),hn=(e,t)=>fn(R?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[gn,_n]=(0,V.useState)({visible:!1,query:``,rect:null}),vn=e=>fn(R?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),yn=S.length>0?S:w?[]:R?[R.id]:[],bn=(0,V.useMemo)(()=>yn.map(e=>Zt.find(t=>t.id===e)).filter(e=>e!==void 0),[yn,Zt]),xn=bn.length>0;(0,V.useEffect)(()=>{if(!T)return;let e=new Set(Zt.map(e=>e.id));x(t=>{let n=t.ids.filter(t=>e.has(t)),r=t.previewId&&e.has(t.previewId)?t.previewId:void 0;return n.length===t.ids.length&&r===t.previewId?t:{...t,ids:n,previewId:r}})},[T,Zt]),(0,V.useEffect)(()=>{yj(S,u,C,[...b.touched])},[u,S,C,b.touched]);let Sn=(0,V.useCallback)(e=>{e&&x(t=>{if(t.touched.has(e))return t;let n=t.previewId===e?void 0:t.previewId;return{...t,previewId:n,touched:gj(t.touched,e)}})},[]),Cn=(0,V.useCallback)(e=>{d(e);let t=Zt.find(t=>t.id===e)?.workspaceId;t&&y(t),Kn(`session`),x(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&&R?.id&&R.id!==e?[R.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}})},[R,Zt]),wn=(0,V.useCallback)(e=>{e&&(Sn(e),Cn(e))},[Sn,Cn]),Tn=R?.workspaceId??v,En=R?.cwd??``,z=P_(Tn,En),Dn=(0,V.useRef)(z.setChangedFor),On=(0,V.useRef)(z.setIndex),kn=(0,V.useRef)(Tn);kn.current=Tn;let An=(0,V.useRef)(En);An.current=En,(0,V.useEffect)(()=>{Dn.current=z.setChangedFor},[z.setChangedFor]),(0,V.useEffect)(()=>{On.current=z.setIndex},[z.setIndex]);let[jn,Mn]=(0,V.useState)(xA[0].id),[Nn,Pn]=(0,V.useState)({}),Fn=(R?.id?Nn[R.id]:void 0)??jn,In=(0,V.useCallback)(e=>{Mn(e),R?.id&&Pn(t=>({...t,[R.id]:e}))},[R?.id]),[Ln,Rn]=(0,V.useState)(!1),zn=(0,V.useRef)(void 0),Bn=(0,V.useRef)(``);(0,V.useEffect)(()=>{Rn(!1),M.current?.readyState===WebSocket.OPEN&&M.current.send(JSON.stringify({type:`files.index.subscribe`}))},[Tn,En]);let[Vn,Hn]=(0,V.useState)(!1),[Un,Wn]=(0,V.useState)(),[Gn,Kn]=(0,V.useState)(`session`),[qn,Jn]=(0,V.useState)(),[Yn,Xn]=(0,V.useState)([]);(0,V.useEffect)(()=>{Gn===`file`&&!z.active&&Kn(`session`)},[Gn,z.active]),(0,V.useEffect)(()=>{Gn===`diff`&&!qn&&Kn(`session`)},[Gn,qn]);let Zn=(0,V.useRef)(`${Tn??``}:${En}`);(0,V.useEffect)(()=>{let e=`${Tn??``}:${En}`;Zn.current!==e&&(Zn.current=e,Xn([]),Jn(void 0),Kn(`session`))},[Tn,En]),(0,V.useEffect)(()=>{z.restoredActive&&Kn(`file`)},[z.restoredActive]);let Qn=(0,V.useCallback)(e=>{Xn(t=>t.includes(e)?t:[...t,e]),Jn(e),Kn(`diff`),Mn(`files`)},[]),[$n,er]=(0,V.useState)({diff:null,loading:!1,error:``}),[tr,nr]=(0,V.useState)(`server`);(0,V.useEffect)(()=>{if(Gn!==`diff`||!qn||!Tn)return;let e=!0;return er({diff:null,loading:!0,error:``}),fetch(`/api/files/diff?workspaceId=${encodeURIComponent(Tn)}&path=${encodeURIComponent(qn)}${En?`&cwd=${encodeURIComponent(En)}`:``}`).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(t=>{e&&er({diff:t,loading:!1,error:``})}).catch(t=>{e&&er({diff:null,loading:!1,error:t instanceof Error?t.message:`读取差异失败`})}),()=>{e=!1}},[Gn,qn,Tn,En]);let rr=(0,V.useMemo)(()=>{if(!qn)return;let e=z.open.find(e=>e.path===qn);return e&&e.dirty?e.content:void 0},[qn,z.open]),ir=(0,V.useCallback)(e=>{z.setActivePath(e),Kn(`file`),Mn(`files`)},[z.setActivePath]),ar=(0,V.useCallback)(async(e,t)=>{Wn(t?{workspaceId:v,path:e.path,line:t,request:Date.now()}:void 0),await z.openFile(e),Kn(`file`)},[z.openFile,v]);(0,V.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key.toLowerCase()===`f`?(e.preventDefault(),Hn(!0)):(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&(e.preventDefault(),zn.current=Tn,Bn.current=En,Rn(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Tn,En]);let or=(0,V.useMemo)(()=>bn.map(e=>({id:`session:${e.id}`,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:!0,preview:C===e.id,badge:(0,H.jsx)(AA,{state:kA(e,OA(e,we),F.current[e.id])})})),[bn,we,l.conversations,ee,C]),sr=(0,V.useMemo)(()=>z.open.map(e=>({id:`file:${e.path}`,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,H.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[z.open]),cr=(0,V.useMemo)(()=>Yn.map(e=>({id:`diff:${e}`,rawId:e,kind:`diff`,label:e.split(/[\\/]/).pop()||e,title:`${e}(改动)`,closable:!0,icon:(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`±`})})),[Yn]),lr=(0,V.useMemo)(()=>[...or,...sr,...cr],[or,sr,cr]),ur=Gn===`file`&&z.activePath?`file:${z.activePath}`:Gn===`diff`&&qn?`diff:${qn}`:R?.id?`session:${R.id}`:void 0,dr=(0,V.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);ir(t)}else if(e.startsWith(`diff:`)){let t=e.slice(5);Jn(t),Kn(`diff`)}else if(e.startsWith(`session:`)){let t=e.slice(8);Cn(t)}},[ir,Cn]),fr=(0,V.useCallback)(e=>{e.startsWith(`session:`)&&wn(e.slice(8))},[wn]),pr=(0,V.useCallback)(e=>{let t=yn.indexOf(e);if(t<0)return;let n=yn.filter(t=>t!==e);if(x(t=>({...t,ids:t.ids.filter(t=>t!==e),previewId:t.previewId===e?void 0:t.previewId,emptied:n.length===0||t.emptied})),R?.id!==e)return;let r=n[Math.min(t,n.length-1)];if(r)d(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),Kn(`file`)}else Yn.length>0?(Jn(Yn[0]),Kn(`diff`)):d(void 0)},[yn,R,z,Yn]),mr=(0,V.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);z.closeFile(t),z.activePath===t&&z.open.length<=1&&Kn(`session`)}else if(e.startsWith(`diff:`)){let t=e.slice(5);Xn(e=>e.filter(e=>e!==t)),qn===t&&(Jn(void 0),Kn(`session`))}else if(e.startsWith(`session:`)){let t=e.slice(8);pr(t)}},[z,pr,qn]),hr=z.active,gr=R?.id;(0,V.useEffect)(()=>{gr&&!gr.startsWith(`pending:`)&&xr({type:`conversation.select`,conversationId:gr})},[gr]);let B=(e,t=`info`)=>{if(!e)return;let n=++Vt.current;De(r=>[...r,{key:n,text:e,kind:t}]),Ht.current.push(window.setTimeout(()=>De(e=>e.filter(e=>e.key!==n)),7e3))};(0,V.useEffect)(()=>{let e=R?.id,t=R?.agentNotice;e&&t&&!Gt.current.has(e)&&(Gt.current.add(e),B(t,`info`))},[R?.id,R?.agentNotice]);let _r=(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},vr=(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},yr=(e,t)=>{if(t.blocking)Te(n=>[...n.filter(n=>n.conversationId!==e||n.request.requestId!==t.requestId),{conversationId:e,request:t}]);else if(t.method===`notify`)B(t.message||t.title,t.notifyType??`info`);else if(t.method===`setStatus`){let e=t.statusKey??``;ke(n=>{let r=new Map(n);return t.statusText===void 0?r.delete(e):r.set(e,t.statusText),r})}else if(t.method===`setWidget`){let e=t.widgetKey??``;je(n=>{let r=new Map(n);return t.widgetLines===void 0?r.delete(e):r.set(e,{lines:t.widgetLines,placement:t.widgetPlacement??`aboveEditor`}),r})}else t.method===`setTitle`?Ne(t.title):t.method===`set_editor_text`&&e===Ut.current&&pn(t.text??``)},br=(e,t,n)=>{Te(n=>n.filter(n=>n.conversationId!==e||n.request.requestId!==t));let r=Zk[n];r&&B(r,`warning`)};(0,V.useEffect)(()=>{let e=!1,t=0,r,s=()=>{if(e)return;let c=location.protocol===`https:`?`wss`:`ws`,l=new WebSocket(`${c}://${location.host}/ws?state=focused${Ut.current?`&conversationId=${encodeURIComponent(Ut.current)}`:``}`);M.current=l,l.onopen=()=>{if(!e){t=0,p(!0),l.send(JSON.stringify({type:`stream.configure`,coalesce:!0})),l.send(JSON.stringify({type:`catalog.fetch`,conversationId:Ut.current})),an.current&&l.send(JSON.stringify({type:`prompt.catalog.fetch`,workspaceId:an.current})),l.send(JSON.stringify({type:`catalog.fetchAll`})),l.send(JSON.stringify({type:`agent.catalog.fetch`})),l.send(JSON.stringify({type:`subagent.catalog.fetch`}));for(let e of a.current)e.retry&&e.command&&l.send(JSON.stringify({...e.command,operationRequestId:e.id}))}},l.onclose=n=>{if(e)return;Wt.current=!1;let o=bO(a.current);for(let e of o.failed)e.onFailure?.();if(a.current=o.retry,i(o.retry),p(!1),t===0){let e=n.reason?.trim()?`${n.reason.trim()}(code ${n.code})`:`code ${n.code}`;console.error(`[Super Pi Error] websocket closed:`,n.code,n.reason),B(`与 Super Pi 服务的连接断开,正在重连。(${e})`,`error`)}r=window.setTimeout(s,Math.min(Ik,Fk*2**t++))},l.onmessage=({data:t})=>{if(e)return;let r=JSON.parse(t);if(r.type!==`message.delta`&&r.type!==`message.thinking`&&L(),r.type===`exec.output`){let e=le.current.get(r.sessionId)??``;le.current.set(r.sessionId,(e+r.data).slice(-512e3)),le.current.size>64&&le.current.delete(le.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:r}))}else if(r.type===`run.stopping`)St(e=>{let t=new Set(e);return t.add(r.conversationId),t});else if(r.type===`exec.exit`)(r.stdout||r.stderr)&&le.current.set(r.sessionId,`${r.stdout}${r.stderr}`);else if(r.type.startsWith(`terminal.`))ue.current?.(r);else if(r.type===`conversation.autoRename.result`){let e=Dt.current.get(r.conversationId);e&&(Dt.current.delete(r.conversationId),r.ok?e.resolve(r.title):e.reject(Error(r.error)))}else if(r.type===`message.thinking`)me(r);else if(r.type===`state`){L(),Wt.current=!1;let e=Ut.current,t=!!(e&&Kt.current.has(e)),s=!(!e||r.state.conversations.some(t=>t.id===e)),c=t&&s&&e&&qt.current.has(e)?{...r.state,conversations:[qt.current.get(e),...r.state.conversations]}:r.state;e&&!s&&(Kt.current.delete(e),qt.current.delete(e)),a.current=a.current.filter(e=>!e.accepted?.(c)),i(a.current),St(e=>{let t=new Set(e);for(let e of[...t]){let n=c.conversations.find(t=>t.id===e);(!n||n.status!==`running`&&n.status!==`waiting`)&&t.delete(e)}return t}),n(c),E(!0),p(!0),y(e=>{if(e&&(c.workspaces.some(t=>t.id===e)||a.current.some(t=>t.temporaryId===e)))return e;let t=o.current?.workspaceId;return t&&c.workspaces.some(e=>e.id===t)?t:c.workspaces[0]?.id})}else if(r.type===`message.delta`)me(r);else if(r.type===`message.revert.result`)Ji(void 0),bt(void 0),r.ok||(console.error(`[Super Pi Error] revert failed:`,r.message),h(r.message));else if(r.type===`operation.result`){let e=a.current.find(e=>e.id===r.requestId);if(a.current=a.current.filter(e=>e.id!==r.requestId),i(a.current),e?.temporaryId){let t=e.temporaryId;if(r.ok&&r.entityId){let e=r.entityId,i=Jt.current.get(t);if(i&&qt.current.set(e,{...i,id:e}),Kt.current.add(e),i){let t={...i,id:e};n(n=>n.conversations.some(t=>t.id===e)?n:{...n,conversations:[t,...n.conversations]})}kt(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.attachments.length?r.attachments:i.attachments,uploading:r.uploading+i.uploading}:r,delete a[t],a}),Jt.current.delete(t)}d(n=>n===t?r.ok?r.entityId:e.previousActiveId:n),x(e=>_j(e,t,r.ok&&r.entityId?r.entityId:void 0)),y(e=>e===t?r.ok?r.entityId:void 0:e)}if(!r.ok){console.error(`[Super Pi Error] operation failed:`,r.message),e?.onFailure?.(r.message);let t=r.message??`操作失败`;h(t),e?.onFailure||B(tp(t),`error`)}}else r.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):r.type===`files.changed`?Dn.current(r.workspaceId,r.changes,r.dropped):r.type===`files.index`?r.workspaceId===kn.current&&(r.cwd??``)===An.current&&On.current(r):r.type===`error`?(console.error(`[Super Pi Error]`,r.message),h(r.message),B(tp(r.message),`error`),Wt.current&&=!1):r.type===`extension.ui`?yr(r.conversationId,r.request):r.type===`extension.ui.closed`?br(r.conversationId,r.requestId,r.reason):r.type===`model.catalog`?(!r.conversationId||r.conversationId===Ut.current)&&Fe(r.catalog):r.type===`model.catalog.all`?Le(r.catalog):r.type===`providers.list`?(ze(r.providers),Ve(r.apis)):r.type===`agent.catalog`?Ue(r.catalog):r.type===`prompt.catalog`?Ce(r.catalog):r.type===`subagent.catalog`?Ge(r.catalog):r.type===`server.version`?(qe(r.version),r.version.needsRestart&&B(`检测到 Super Pi 代码已更新(v${r.version.runningVersion} → v${r.version.diskVersion}),请执行 /super_pi restart 重启服务生效`,`warning`)):r.type===`subagent.event`?n(e=>({...e,subagentRuns:_r(e.subagentRuns??[],r.run)})):r.type===`workflow.event`?n(e=>({...e,workflows:vr(e.workflows??[],r.workflow)})):r.type===`message.tools`?n(e=>({...e,conversations:e.conversations.map(e=>e.id===r.conversationId?{...e,messages:e.messages.map(e=>e.id===r.messageId?{...e,toolCalls:r.toolCalls}:e)}:e)})):r.type===`conversation.fork.result`&&(ta(e=>e===r.conversationId?void 0:e),B(r.ok?`已从「${r.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${r.messagesCopied?`复制了 ${r.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${tp(r.message)}`,r.ok?`info`:`error`))}};return s(),()=>{e=!0,L(),window.clearTimeout(r);for(let e of Ht.current)window.clearTimeout(e);M.current?.close()}},[me,L]);let xr=(0,V.useCallback)(e=>M.current?.readyState===WebSocket.OPEN&&(M.current.send(JSON.stringify(e)),!0),[]);(0,V.useEffect)(()=>{if(!f)return;let e=R?.id;e?.startsWith(`pending:`)||xr({type:`state.subscribe`,...e?{conversationId:e}:{}})},[R?.id,f,xr]),(0,V.useEffect)(()=>{if(f&&Ln&&Tn&&zn.current===Tn&&Bn.current===En)return xr({type:`files.index.subscribe`,workspaceId:Tn,...En?{cwd:En}:{}}),z.requestIndex(!0),()=>{xr({type:`files.index.subscribe`}),z.cancelIndexRequest()}},[f,Ln,Tn,En,xr,z.requestIndex,z.cancelIndexRequest]);let Sr=(e,t,n,r,o,s,c)=>{let l=M.current?.readyState===WebSocket.OPEN,u=yO(e);if(a.current.some(e=>e.key===t)||!l&&!u)return!1;let d=Ev(),f={id:d,key:t,apply:n,temporaryId:r,previousActiveId:Ut.current,onFailure:o,accepted:s,...c?{expiresAt:Date.now()+c}:{},...u?{retry:!0,command:e}:{}};return a.current=[...a.current,f],i(a.current),l&&M.current.send(JSON.stringify({...e,operationRequestId:d})),!0},Cr=e=>{if(!e)return;let t=`message_${Ev()}`;Sr({type:`message.send`,conversationId:e,content:Vk,clientId:t},`continue-truncated:${e}`,e=>e,void 0,void 0,void 0)};(0,V.useEffect)(()=>{let e=r.flatMap(e=>e.expiresAt?[e.expiresAt]:[]);if(!e.length)return;let t=window.setTimeout(()=>{let e=a.current.filter(e=>e.expiresAt&&e.expiresAt<=Date.now());if(e.length){a.current=a.current.filter(t=>!e.includes(t)),i(a.current);for(let t of e)t.onFailure?.(`打断请求超时,尚未确认是否开始回答;请检查会话状态后重试`)}},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[r]);let wr=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Tr=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Er=R?.id.startsWith(`pending:`)===!0,Dr=!!(R&&TA(R)&&(xt.has(R.id)||r.some(e=>e.key===`stop:${R.id}`))),Or=R?.messagesLoaded===!1||r.some(e=>e.key.startsWith(`send:${R?.id}:`)||e.key===`configuration:${R?.id}`||e.temporaryId===R?.id||e.key===`archive:${R?.id}`),kr=(e,t,n,r,i)=>{e&&M.current?.send(JSON.stringify({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i}))},Ar=(e,t,n)=>(Sn(e),Sr({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e)),jr=R?.model??Pe?.defaultModel,Mr=R?.thinkingLevel??Pe?.defaultThinkingLevel,Nr=Pe?.source===`pi`,Pr=!!Pe?.models.find(e=>e.provider===jr?.provider&&e.modelId===jr?.modelId)?.imageInput,Fr=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(l.modelFilterRules??[]).every(n=>{try{return!new RegExp(n.workspacePattern,`i`).test(t.name)||new RegExp(n.modelPattern,`i`).test(e.label)||new RegExp(n.modelPattern,`i`).test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},Ir=!!R?.messages?.some(e=>e.images&&e.images.length>0),Lr=Fr(Pe,l.workspaces.find(e=>e.id===R?.workspaceId))?.models??[],Rr=(Ir?Lr.filter(e=>e.imageInput):Lr).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Gk(e),selected:jr?.provider===e.provider&&jr.modelId===e.modelId})),zr=(Pe?.levels??[]).map(e=>({key:e,label:e,selected:e===Mr})),Br=e=>{if(!R)return;let[t,n]=e.split(`/`);t&&n&&(Sn(R.id),Sr({type:`conversation.model`,conversationId:R.id,provider:t,modelId:n},`configuration:${R.id}`,wr(R.id,{model:Pe?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}})))},Vr=e=>{R&&(Sn(R.id),Sr({type:`conversation.thinking`,conversationId:R.id,level:e},`configuration:${R.id}`,wr(R.id,{thinkingLevel:e})))},Hr=He?.agents.find(e=>e.id===R?.agentId),Ur=[{key:yA,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!R?.agentId},...(He?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:R?.agentId===e.id}))],Wr=Hr?.model,Gr=!!(Wr&&R?.model&&R.model.provider===Wr.provider&&R.model.modelId===Wr.modelId);Hr?.thinkingLevel&&(R?.thinkingLevel,Hr.thinkingLevel);let Kr=e=>{if(R){let t=He?.agents.find(t=>t.id===e);Sr({type:`conversation.agent`,conversationId:R.id,agentId:e===yA?null:e},`configuration:${R.id}`,wr(R.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},qr=we.filter(e=>e.conversationId===R?.id),Jr=(0,V.useMemo)(()=>(l.subagentRuns??[]).filter(e=>e.conversationId===R?.id),[l.subagentRuns,R?.id]),Yr=(0,V.useMemo)(()=>(l.workflows??[]).filter(e=>e.conversationId===R?.id),[l.workflows,R?.id]),Xr=(0,V.useMemo)(()=>new Map(Yr.map(e=>[e.id,e])),[Yr]),Zr=(0,V.useMemo)(()=>new Map((We?.agents??[]).map(e=>[e.id,e.name])),[We]),Qr=(0,V.useMemo)(()=>new Map((R?.messages??[]).map(e=>[e.id,e])),[R?.messages]),$r=(0,V.useMemo)(()=>new Map(Jr.map(e=>[e.id,e])),[Jr]),ei=(0,V.useMemo)(()=>{let e=new Map;for(let t of Jr)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[Jr]),ti=(0,V.useMemo)(()=>{if(!R||!xn)return[];let e=yt?.conversationId===R.id?(()=>{let e=R.messages.find(e=>e.id===yt.messageId);if(e)return{index:R.messages.indexOf(e),at:Date.parse(e.createdAt)||0,...yt.kind===`withdraw`?{inclusive:!0}:{inclusive:!1}}})():void 0,t=[];return R.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}`})}),Jr.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&R?.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}`})}),Yr.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}`})}),t.sort((e,t)=>e.at-t.at||e.seq-t.seq).map(e=>e.key)},[R,Jr,Yr,yt]),ni=(0,V.useMemo)(()=>{for(let e=ti.length-1;e>=0;--e){let t=ti[e];if(t.startsWith(`m:`)&&Qr.get(t.slice(2))?.role===`user`)return t.slice(2)}},[ti,Qr]);(0,V.useEffect)(()=>{let e=ne.current;if(!e||!R?.id)return;let t=()=>{!ce.current&&N.current[R.id]?.followTail&&(dj(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()},[R?.id,R?.messages,Jr,Yr,xn,ti]);let ri=e=>mt(t=>({...t,[e]:!t[e]})),ii=(e,t)=>gt(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),ai=(e,t)=>vt(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[oi,si]=(0,V.useState)({}),ci=e=>si(t=>({...t,[e]:t[e]!==!0})),li=e=>{Sr({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||B(`连接断开,无法停止子智能体,请重试`,`error`)},ui=e=>{Sr({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||B(`连接断开,无法停止编排,请重试`,`error`)},di=e=>[...Ae].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,H.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,Qk).map((e,t)=>(0,H.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>Qk&&(0,H.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),fi=(e,t)=>{let n=`pending:${Ev()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};Sr({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(y(n),d(void 0),O(!1))},[pi,mi]=(0,V.useState)(),hi=(e,t)=>mi(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),gi=()=>mi(void 0),_i=(e,t)=>pi?.kind===e&&pi.id===t,vi=(e,t,n)=>!t.startsWith(`pending:`)&&(e===`conversation`&&Sn(t),Sr(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Tr(t,{name:n}):wr(t,{title:n}))?(Wt.current=!0,gi(),!0):(B(`连接断开,改名未保存,请重试`,`error`),!1)),yi=async e=>{if(e.startsWith(`pending:`)){B(`这个会话还在创建中,稍后再试`,`warning`);return}if(Dt.current.has(e))return;B(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{Dt.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{Dt.current.delete(e)&&n(Error(`模型在 30 秒内没有返回标题`))},32e3)});if(!xr({type:`conversation.autoRename`,conversationId:e}))Dt.current.delete(e),B(`连接断开,无法生成标题`,`error`);else try{let n=await t;vi(`conversation`,e,n),B(`已重命名为「${n}」`,`info`)}catch(e){B(`重命名失败:${tp(e)}`,`error`)}},bi=e=>{if(e.id.startsWith(`pending:`))return;let t=l.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`从列表移除工作区「${e.name}」?${t?`其中的 ${t} 条会话会保留,`:``}重新添加同一个目录即可恢复,不会删除任何会话。`)&&Sr({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)}))},[xi,Si]=(0,V.useState)(),Ci=xi?l.workspaces.find(e=>e.id===xi):void 0,{theme:wi,setTheme:Ti}=ey(),[Ei,Di]=(0,V.useState)(!1),[Oi,ki]=(0,V.useState)(!1),Ai=(e,t,n,r)=>{e.startsWith(`pending:`)||(Sr({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Tr(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Si(void 0):B(`连接断开,设置未保存,请重试`,`error`))},ji=(e,t=``)=>{if(e.startsWith(`pending:`))return;if(a.current.some(t=>t.key===`defaults:${e}`)){B(`工作区设置正在保存,请稍后再新建会话`,`warning`);return}let n=`pending:${Ev()}`,r={id:n,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[],...t?{cwd:t}:{}};Jt.current.set(n,r),Sr({type:`conversation.create`,workspaceId:e,...t?{cwd:t}:{}},`create-session:${e}:${n}`,e=>({...e,conversations:[r,...e.conversations]}),n)?(y(e),d(n),Kn(`session`),x(e=>({...e,ids:[...e.ids.filter(e=>e!==n),n],touched:gj(e.touched,n)}))):(Jt.current.delete(n),B(`连接断开,会话未创建,请重试`,`error`))},Mi=e=>{if(e.startsWith(`pending:`))return;let t=l.conversations.find(t=>t.id===e);if(!t||t.archivedAt||t.parentConversationId&&l.conversations.some(e=>e.id===t.parentConversationId))return;let n=Nk(l.conversations,e),r=n.filter(e=>!e.archivedAt),i=r.length-1,a=n.length-r.length;if(i>0&&!window.confirm(`归档整棵会话树「${t.title}」?本次将归档 ${r.length} 个会话(1 个根会话和 ${i} 个活跃子孙)${a?`,跳过 ${a} 个已归档子孙`:``};恢复根会话时,整棵树会一起恢复。`))return;let o=new Date().toISOString(),s=new Set(r.map(e=>e.id));Sr({type:`conversation.archive`,conversationId:e},`archive:${e}`,e=>({...e,conversations:e.conversations.map(e=>s.has(e.id)&&!e.archivedAt?{...e,archivedAt:o}:e)}))},Ni=(e,t)=>Sr({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}),Pi=e=>{let t=l.conversations.find(t=>t.id===e);if(!t?.archivedAt||(t.parentConversationId?l.conversations.find(e=>e.id===t.parentConversationId):void 0)?.archivedAt)return;let n=new Set(Nk(l.conversations,e).filter(e=>e.archivedAt).map(e=>e.id));Sr({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})}))},Fi=async e=>{if(!R){B(`请先选择或创建会话`,`error`);return}if(!Pr){B(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(B(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(B(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=R.id;fn(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:Ev(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));Pt(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 fetch(`/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`)){B(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(At.current.has(n.id))continue;Pt(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),fn(r,t=>({...t,images:[...t.images,{id:e.id,name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));B(tp(e.error,`上传失败(HTTP ${i.status})`),`error`)}}catch(e){B(`上传失败:${tp(e,`网络或服务暂时不可用`)}`,`error`)}finally{Pt(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),fn(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Ii=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(!Pr){B(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),Fi(n)}},Li=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),Rt(!0))},Ri=e=>{e.currentTarget.contains(e.relatedTarget)||Rt(!1)},zi=e=>{Rt(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!Pr){B(`当前模型不支持图片输入`,`error`);return}Fi(t)}},Bi=e=>{if(e.preventDefault(),!R)return;if(Or){B(Er?`会话正在创建,请稍候再发送`:R.messagesLoaded===!1?`正在加载会话,请稍候再发送`:`正在保存配置,请稍候再发送`,`info`);return}if(!cn.trim()&&ln.length===0)return;if(ln.length>0&&!Pr){B(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(dn>0){B(`图片正在上传中,请稍候…`,`info`);return}let t=`message_${Ev()}`,n=R.id,r=cn,i=ln,a=un;Sn(n),Sr({type:`message.send`,conversationId:n,content:cn,clientId:t,...ln.length>0?{images:ln}:{},...un.length>0?{attachments:un}:{}},`send:${n}:${t}`,e=>{let a=e.conversations.find(e=>e.id===n);if(!a||a.messages.some(e=>e.id===t))return e;let o=a.status===`running`||a.status===`waiting`,s=new Date().toISOString();return{...e,conversations:e.conversations.map(e=>e.id===n?{...e,...o?{}:{status:`waiting`,updatedAt:s},messages:[...e.messages,{id:t,role:`user`,content:r,...i.length>0?{images:i}:{},...un.length>0?{attachments:un}:{},...o?{delivery:`waiting`}:{},createdAt:s}]}:e)}},t,e=>{Mt(o=>[...o,{id:t,conversationId:n,content:r,images:i,attachments:a,reason:e}]),fn(n,e=>e.text||e.images.length||e.attachments.length?e:{...e,text:r,images:i,attachments:a})},e=>!!e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t))?fn(R.id,e=>({...e,text:``,images:[]})):B(`这条消息已经在发送队列中,请稍候`,`info`)},Vi=(0,V.useMemo)(()=>(R?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[R?.messages]),Hi=e=>{Sr({type:`message.cancel`,conversationId:R?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===R?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||B(`连接断开,撤回没有生效,请重试`,`error`)},Ui=e=>{Sr({type:`message.steer`,conversationId:R?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===R?.id?{...t,messages:wk(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===R?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||B(`连接断开,插到最前没有生效,请重试`,`error`)},Wi=e=>{let t=R?.id;t&&(M.current?.readyState===WebSocket.OPEN?Sr({type:`message.interrupt`,conversationId:t,messageId:e},`interrupt:${t}:${e}`,e=>e,void 0,e=>B(e??`打断失败,请重试`,`error`),n=>{let r=n.conversations.find(e=>e.id===t)?.messages.find(t=>t.id===e);return!(!r||r.delivery)},3e4)||B(`正在打断,请稍候`,`info`):B(`连接断开,打断没有生效,请重试`,`error`))},Gi=e=>{Sr({type:`message.sendQueued`,conversationId:R?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===R?.id)?.messages.find(t=>t.id===e)?.delivery)||B(`连接断开,发送没有生效,请重试`,`error`)},Ki=(e,t)=>{Sr({type:`message.edit`,conversationId:R?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===R?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||B(`连接断开,修改没有生效,请重试`,`error`)},[qi,Ji]=(0,V.useState)(),Yi=(e,t=!1)=>{if(!R||R.messagesLoaded===!1||qi)return;let n=R.messages.find(t=>t.id===e);n&&(n&&kt(e=>{let t=e[R.id]??{text:``,images:[],attachments:[],uploading:0};return t.text.trim()||t.images.length||t.attachments.length?e:{...e,[R.id]:{...t,text:n.content,images:n.images??[]}}}),bt({conversationId:R.id,messageId:e,kind:t?`withdraw`:`revert`})),xr({type:`message.revert`,conversationId:R.id,messageId:e,withdraw:t})?Ji(e):(bt(void 0),B(`连接断开,回退未执行,请重试`,`error`))},[Xi,Zi]=(0,V.useState)(),Qi=(0,V.useRef)(void 0),$i=async(e,t)=>{Qi.current&&clearTimeout(Qi.current);let n=await Lk(t);Zi({id:e,kind:n?`copied`:`error`}),n||B(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),Qi.current=setTimeout(()=>Zi(void 0),2e3)};(0,V.useEffect)(()=>()=>{Qi.current&&clearTimeout(Qi.current)},[]);let[ea,ta]=(0,V.useState)(),na=e=>{ea||e.startsWith(`pending:`)||(Sn(e),xr({type:`conversation.fork`,conversationId:e})?ta(e):B(`连接断开,分叉没有执行,请重试`,`error`))},ra=new Map;for(let e of l.scheduledTasks??[])e.conversationId&&!ra.has(e.conversationId)&&ra.set(e.conversationId,e);return(0,H.jsxs)(`main`,{className:`shell${Xe?` shell-rail-collapsed`:``} mobile-panel-${Qe}${et?` mobile-drawer-open`:``}`,"data-rail-collapsed":Xe,"data-selected-workspace":v??``,style:{"--sidebar-width":`${ot.sidebar}px`,"--rail-col":Xe?void 0:`${ot.rail}px`},children:[(0,H.jsxs)(`aside`,{children:[(0,H.jsxs)(`div`,{className:`brand`,children:[(0,H.jsx)(`span`,{children:`π`}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`strong`,{children:`SUPER PI`}),(0,H.jsx)(`small`,{children:`agent workspace`})]})]}),(0,H.jsx)(`div`,{className:`sidebar-actions`,children:(0,H.jsx)(`button`,{className:`workspace-new`,onClick:()=>O(!0),children:`+ 工作区`})}),(0,H.jsx)(`div`,{className:`label label-desktop`,children:`工作区`}),(0,H.jsx)(`div`,{className:`label label-phone`,children:`会话`}),(0,H.jsx)(`nav`,{children:l.workspaces.map(e=>{let t=l.conversations.filter(t=>t.workspaceId===e.id),n=t.filter(e=>!e.archivedAt),r=SO(n,$t),i=t.filter(e=>e.archivedAt),a=SO(i,new Set),o=g[e.id]??!1,s=ge[e.id]??!0;return(0,H.jsxs)(`section`,{className:`workspace-group`,children:[(0,H.jsx)(`div`,{className:`workspace-header`,children:_i(`workspace`,e.id)?(0,H.jsx)(_A,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>vi(`workspace`,e.id,t),onClose:gi}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{className:`workspace-toggle`,"aria-expanded":!o,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();wt({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{let t=Zt.find(t=>t.workspaceId===e.id)?.id;y(e.id),d(t),_(t=>({...t,[e.id]:!o}))},children:[(0,H.jsx)(`span`,{className:`chevron chevron-folder`,"aria-hidden":`true`,children:o?`📁`:`📂`}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{onDoubleClick:()=>hi(`workspace`,e.id),children:e.name}),(0,H.jsx)(`small`,{children:e.path})]})]}),(0,H.jsx)(`button`,{className:`workspace-add`,title:`在此工作区新建会话`,onClick:t=>{j.current=t.currentTarget,A({workspaceId:e.id})},children:`+`}),(0,H.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Si(e.id),children:`⚙`}),(0,H.jsx)(`button`,{className:`workspace-delete`,title:`从列表移除工作区(会话保留,重新添加同一目录即可恢复)`,onClick:()=>bi(e),children:`×`})]})}),!o&&(r.length?r.map(({conversation:t,depth:r,childCount:i,isLastSibling:a})=>(0,H.jsxs)(`div`,{className:`conversation-row`,style:{"--tree-depth":r},children:[i>0?(0,H.jsxs)(`button`,{type:`button`,className:`conversation-tree-toggle`,"data-tree-toggle":t.id,"aria-expanded":!$t.has(t.id),title:$t.has(t.id)?`展开 ${i} 个子会话`:`折叠 ${i} 个子会话`,"aria-label":$t.has(t.id)?`展开会话 ${t.title} 的 ${i} 个子会话`:`折叠会话 ${t.title} 的 ${i} 个子会话`,onClick:()=>Ni(t.id,!$t.has(t.id)),children:[(0,H.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:$t.has(t.id)?`▸`:`▾`}),(0,H.jsx)(`small`,{children:i})]}):(0,H.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),_i(`conversation`,t.id)?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(_A,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>vi(`conversation`,t.id,e),onClose:gi}),(0,H.jsx)(`small`,{className:`conversation-time`,children:Mk(t.updatedAt,Yt)})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{className:`conversation ${R?.id===t.id?`selected`:``}`,"data-conversation":t.id,"data-tree-child":r>0?`true`:void 0,"data-tree-last":r>0&&a?`true`:void 0,title:r>0?`${t.title}(由「${n.find(e=>e.id===t.parentConversationId)?.title??`已不存在的会话`}」创建)`:t.title,"aria-label":`打开会话 ${t.title}${MA(t,ra.get(t.id))}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();Et({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{Cn(t.id),y(e.id),tt(!1)},onDoubleClick:()=>{wn(t.id)},children:[(0,H.jsx)(`i`,{className:`conversation-mark`,children:(0,H.jsx)(AA,{state:kA(t,OA(t,we),F.current[t.id])})}),(0,H.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:e=>{e.stopPropagation(),hi(`conversation`,t.id)},style:{flex:`0 1 auto`},children:t.title}),(0,H.jsx)(`span`,{className:`conversation-title-gap`,"aria-hidden":`true`,style:{marginLeft:`-8px`}}),jA(t,ra.get(t.id)),(0,H.jsx)(`small`,{children:Mk(t.updatedAt,Yt)})]}),(0,H.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":ea===t.id?`pending`:`idle`,disabled:!!ea,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>na(t.id),children:`⑂`}),!(t.parentConversationId&&l.conversations.some(e=>e.id===t.parentConversationId))&&(0,H.jsx)(`button`,{className:`conversation-archive`,"data-archive-conversation":t.id,title:`归档整棵会话树`,"aria-label":`归档会话 ${t.title}`,onClick:()=>Mi(t.id),children:`×`})]})]},t.id)):(0,H.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!o&&i.length>0&&(0,H.jsxs)(`div`,{className:`archived-group`,"data-archived-count":i.length,children:[(0,H.jsxs)(`button`,{className:`archived-toggle`,title:s?`展开已归档会话`:`收起已归档会话`,"aria-expanded":!s,onClick:()=>_e(t=>({...t,[e.id]:!s})),children:[(0,H.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:s?`▸`:`▾`}),(0,H.jsxs)(`span`,{className:`archived-label`,children:[`已归档 (`,i.length,`)`]})]}),!s&&a.map(({conversation:e,depth:t,isLastSibling:n})=>{let r=Nk(i,e.id).length-1,a=!!(e.parentConversationId&&l.conversations.some(t=>t.id===e.parentConversationId&&t.archivedAt));return(0,H.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,H.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,H.jsx)(`span`,{"data-archived-title":e.id,children:e.title}),jA(e,ra.get(e.id)),(0,H.jsx)(`small`,{children:Pk(e.archivedAt)}),!a&&(0,H.jsx)(`button`,{className:`conversation-restore`,"data-restore-conversation":e.id,title:r?`恢复这个会话和它的 ${r} 个子孙会话`:`恢复为正常会话`,"aria-label":r?`恢复会话 ${e.title} 及其 ${r} 个子孙会话`:`恢复会话 ${e.title}`,onClick:()=>Pi(e.id),children:`↑`})]},e.id)})]})]},e.id)})}),(0,H.jsxs)(`footer`,{children:[(0,H.jsxs)(`div`,{className:`footer-status`,children:[(0,H.jsx)(`i`,{className:f?`online`:`offline`}),f?`已连接`:`正在连接`,(0,H.jsx)(`span`,{children:`本地持久化`})]}),(0,H.jsxs)(`div`,{className:`footer-version`,"data-super-pi-version":Ke?.runningVersion??``,children:[`Super Pi v`,Ke?.runningVersion??`…`]}),(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Ei,onClick:()=>{Di(!0),xr({type:`catalog.fetchAll`}),xr({type:`providers.fetch`})},children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),`设置`]}),(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Oi,onClick:()=>ki(!0),children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`📖`}),`使用指南`]}),(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,title:`检查 Super Pi 更新`,onClick:async()=>{Ye(`updating`);try{let e=await fetch(`/api/update-check`);if(!e.ok)throw Error(`check failed`);let t=await e.json();if(t.needsRestart)B(`当前代码已更新,正在重启服务…`,`info`);else if(t.updateAvailable){if(!window.confirm(`发现新版本 v${t.latestVersion??``},是否立即更新并重启 Super Pi?`))B(`已取消更新`,`info`);else{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);B(`正在更新到 v${t.latestVersion} 并重启…`,`info`)}}else B(`当前已是最新版本`,`info`)}catch{B(`检查更新失败,请检查网络或服务日志`,`error`)}finally{Ye(`idle`)}},children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:Je===`updating`?`⟳`:`↻`}),Je===`updating`?`正在检查更新…`:`检查更新`]}),Ke?.needsRestart&&(0,H.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`代码已更新:当前运行 v${Ke.runningVersion},磁盘版本 v${Ke.diskVersion}。点击复制重启命令 /super_pi restart`,onClick:async()=>{Ye(`updating`);try{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);B(`正在更新 Super Pi,服务即将重启…`,`info`)}catch{Ye(`idle`),B(`更新启动失败,请检查服务日志`,`error`)}},children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:Je===`updating`?`⟳`:`⚠️`}),Je===`updating`?`正在更新并重启…`:`更新并重启服务`]})]})]}),(0,H.jsx)(Sj,{side:`left`,width:ot.sidebar,min:ot.sidebarMin,max:ot.sidebarMax,label:`调整左侧栏宽度`,onWidth:st}),(0,H.jsxs)(`section`,{className:`chat`,"data-main-view":Gn,"data-main-view-kind":Gn,children:[lr.length>0&&(0,H.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":bn.length,"data-file-count":z.open.length,children:(0,H.jsx)(G_,{tabs:lr,prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:ur,onSelect:dr,onClose:mr,onActivate:fr,minWidth:120,maxWidth:320})}),(0,H.jsxs)(`header`,{children:[(0,H.jsx)(`button`,{type:`button`,className:`mobile-drawer-toggle`,"data-mobile-drawer-toggle":`1`,"aria-label":`打开会话列表`,title:`会话列表`,"aria-expanded":et,onClick:()=>tt(!0),children:`☰`}),(0,H.jsxs)(`div`,{className:`chat-head`,children:[(0,H.jsx)(`h1`,{children:R?.title??`准备开始`}),Oe.size>0?[...Oe].map(([e,t])=>(0,H.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):(0,H.jsx)(`p`,{"data-role":`run-status`,children:R?.status===`running`?`Agent 正在工作`:R?.status===`awaiting_background`?`后台任务运行中`:`Pi runtime · Web 控制台`})]}),(0,H.jsxs)(`span`,{className:`chat-view chat-view-${Gn}`,"data-main-view-indicator":Gn,"data-main-view-kind":Gn,title:Gn===`file`?`中间主画面正在显示文件 ${z.active?.path??``}`:Gn===`diff`?`中间主画面正在显示 ${qn??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,H.jsx)(`span`,{className:`chat-view-label`,children:`主区显示`}),(0,H.jsx)(`span`,{className:`chat-view-kind`,children:Gn===`file`?`文件`:Gn===`diff`?`改动`:`会话`}),Gn===`file`&&z.active&&(0,H.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":z.active.name,children:z.active.name}),Gn===`diff`&&qn&&(0,H.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":qn,children:qn})]}),(0,H.jsx)(`div`,{className:`badge`,"data-conversation-status":R?.status??`idle`,children:wA[R?.status??`idle`]})]}),m&&(0,H.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,H.jsx)(`span`,{title:np(m),children:tp(m)}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>h(void 0),children:`×`})]}),R?.error&&(0,H.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,title:np(R.error),children:tp(R.error)}),R?.warning&&(0,H.jsxs)(`div`,{className:`warning`,role:`status`,"data-role":`conversation-warning`,title:np(R.warning),children:[(0,H.jsx)(`span`,{children:R.warning}),(0,H.jsx)(`button`,{type:`button`,"data-role":`conversation-warning-continue`,title:`让模型接着把被截断的部分写完`,onClick:()=>Cr(R?.id??``),children:`继续写完`})]}),R?.modelNotice&&(0,H.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-model-notice`,children:R.modelNotice}),R?.agentNotice&&(0,H.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-agent-notice`,children:R.agentNotice}),Me&&(0,H.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,Me]}),Ee.length>0&&(0,H.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Ee.length,children:Ee.map(e=>(0,H.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),Gn===`file`?(0,H.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":hr?.path,"data-file-view-kind":`editor`,children:hr?(0,H.jsx)(A_,{file:hr,state:z.saves[hr.path]?.state??`idle`,message:z.saves[hr.path]?.message??``,external:z.external[hr.path]===!0,jumpToLine:Un&&Un.workspaceId===v&&Un.path===hr.path?Un:void 0,onChange:e=>z.updateBuffer(hr.path,e),onSave:()=>void z.save(hr.path,!1),onReload:()=>void z.reload(hr.path),onOverwrite:()=>void z.save(hr.path,!0),workspaceId:v,cwd:En}):(0,H.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})}):Gn===`diff`?(0,H.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":qn??``,"data-file-view-kind":`diff`,children:(0,H.jsx)(M_,{diff:$n.diff,loading:$n.loading,error:$n.error,bufferContent:rr,mode:tr,onMode:nr})}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`messages`,ref:ne,"data-message-scroll-container":R?.id??``,onWheel:e=>{e.deltaY<0&&N.current[R?.id??``]?.followTail&&(ce.current=!0,on(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:on(t)},children:[(!R||!xn)&&(0,H.jsxs)(`div`,{className:`empty`,children:[(0,H.jsx)(`div`,{className:`orb`,children:`π`}),(0,H.jsx)(`h2`,{children:`开始一个新会话`}),l.workspaces.length===0?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,H.jsx)(`button`,{onClick:()=>O(!0),children:`+ 新建工作区`})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`p`,{children:l.workspaces.length===1&&tn?`在「${tn.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),l.workspaces.length>1&&(0,H.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,H.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,H.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:tn?.id,onChange:e=>{e.target.value===`__new__`?O(!0):y(e.target.value)},children:[l.workspaces.map(e=>(0,H.jsx)(`option`,{value:e.id,children:e.name},e.id)),(0,H.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),tn&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Jk,{workspaceId:tn.id,value:nn,onChange:rn}),(0,H.jsx)(`button`,{onClick:()=>ji(tn.id,nn),children:`新建会话`})]}),(0,H.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>O(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O(!0))},children:`+ 新建工作区`})]})]}),R?.messagesLoaded===!1&&(0,H.jsx)(`p`,{role:`status`,"data-conversation-loading":`1`,children:`正在加载会话…`}),ti.map(e=>{if(e.startsWith(`m:`)){let t=Qr.get(e.slice(2));if(!t)return null;let n=t.id===ni,i=t.role===`user`&&R?.status!==`running`&&R?.status!==`waiting`&&qi!==t.id,a=i&&n&&!t.id.startsWith(`pending:`),o=i&&!n&&!!t.piEntryId,s=t.content?(0,H.jsx)(Am,{source:t.content}):(0,H.jsx)(`span`,{className:`typing`,children:`正在思考`}),c=t.toolCalls??[];if(t.role===`user`){let n=Xi?.id===t.id?Xi.kind:void 0,r=t.content||(t.images?.length?`[图片]`:``);return(0,H.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,H.jsxs)(`div`,{className:`message-body`,children:[(0,H.jsxs)(`div`,{className:`bubble`,children:[(0,H.jsxs)(`div`,{className:`meta`,children:[xe,(0,H.jsx)(`time`,{children:Tk(t.createdAt)})]}),t.images&&t.images.length>0&&(0,H.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,H.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>It({url:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,H.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,H.jsx)(`div`,{className:`content`,children:s})]}),t.attachments&&t.attachments.length>0&&(0,H.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:t.attachments.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=ht[n]??!1;return(0,H.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,H.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>gt(e=>({...e,[n]:!r})),children:[(0,H.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,H.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,H.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,H.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,H.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,H.jsxs)(`div`,{className:`message-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":n,"aria-label":`复制这条消息:${r}`,onClick:()=>$i(t.id,r),children:n===`copied`?`已复制`:n===`error`?`复制失败`:`复制`}),a&&(0,H.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>Yi(t.id,!0),children:`撤回`}),o&&(0,H.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退到这里:删除后续全部内容(Pi 的记录和这里的历史一起清掉,不会新建会话,也不动任何代码文件)`,onClick:()=>Yi(t.id),children:`回退`})]})]}),(0,H.jsx)(`div`,{className:`avatar`,title:xe,children:xe})]},e)}if(t.role===`tool`){let n=/<task id="[^"]+" state="[^"]+"/.test(t.content),r=(()=>{let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():n?`后台回传`:(t.content.split(`
100
100
  `).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`})(),i=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),a=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:t.content})(),o=(()=>{let e=/<result_file>([\s\S]*?)<\/result_file>/.exec(t.content);return e&&e[1].trim()?e[1].trim():void 0})(),s=(()=>{let e=/<task id="([^"]+)"/.exec(t.content);return e?e[1]:void 0})(),c=!!(s&&Zt.some(e=>e.id===s)),l=`tool:${t.id}`,u=ht[l]??!1,d=n?`后台回传`:`智能体下发`;return(0,H.jsx)(`article`,{className:`message tool${n?``:` tool-order`}`,"data-transcript-key":e,"data-tool-state":i,"data-tool-kind":n?`delivery`:`order`,children:(0,H.jsxs)(`div`,{className:`message-body`,children:[(0,H.jsxs)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:[(0,H.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":u,title:u?`折叠${d}`:`展开${d}`,onClick:()=>gt(e=>({...e,[l]:!u})),children:[(0,H.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:i===`error`?`✕`:n?`↩`:`↓`}),(0,H.jsx)(`span`,{className:`bg-result-label`,children:d}),(0,H.jsx)(`span`,{className:`bg-result-summary`,title:r,children:r}),!u&&(0,H.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看完整输出`,children:a.split(`
101
- `).slice(-1)[0]}),(0,H.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:u?`▾`:`▸`})]}),(o||c&&s)&&(0,H.jsxs)(`div`,{className:`bg-result-actions`,"data-bg-result-actions":t.id,children:[o&&(0,H.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-file-link":o,title:`在主区域打开产物文件:${o}`,onClick:e=>{e.stopPropagation();let t=o.split(/[/\\]/).pop()||o;ar({path:o,name:t,text:!0}).catch(e=>{console.warn(`打开产物文件失败:`,e)})},children:[(0,H.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`📄`}),(0,H.jsx)(`span`,{children:`查看产物文件`})]}),c&&s&&(0,H.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-session-link":s,title:`跳转到子会话:${s}`,onClick:e=>{e.stopPropagation(),Cn(s)},children:[(0,H.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`↗`}),(0,H.jsx)(`span`,{children:`跳转到子会话`})]})]})]}),u&&(0,H.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,H.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:a})})]})},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))},f=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,p=e=>c.map((e,t)=>({call:e,index:t})).filter(({call:t})=>f(t)===e),m=[],h=[...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}})),...c.map((e,t)=>({at:d(e,t),order:(e.thinkingAt??0)*2,segment:{call:e,index:t}})).filter(({segment:e})=>`call`in e&&f(e.call)<0)].sort((e,t)=>e.at-t.at||e.order-t.order),g=0;for(let e of h){let n=Math.max(g,Math.min(e.at,t.content.length));n>g&&m.push({text:t.content.slice(g,n)}),m.push(e.segment),g=n}g<t.content.length&&m.push({text:t.content.slice(g)});let _=e=>{let t=ei.get(e);if(t)return(0,H.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,H.jsx)(oA,{run:t,name:Zr.get(t.agentId)??``,expanded:!!pt[t.id],onToggle:()=>ri(t.id),onStop:()=>li(t.id),stopping:r.some(e=>e.key===`stop:${t.id}`)})})},v=e=>e.call.question?(0,H.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,H.jsx)(dA,{question:e.call.question,index:e.index,expanded:`${t.id}:${e.index}`in _t?!!_t[`${t.id}:${e.index}`]:!0,onToggle:()=>ai(t.id,e.index),onAnswer:(n,r)=>kr(R?.id??``,t.id,e.index,n,r)})},`c${e.index}`):(0,H.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,H.jsx)(rA,{call:e.call,index:e.index,expanded:`${t.id}:${e.index}`in ht&&!!ht[`${t.id}:${e.index}`],onToggle:()=>ii(t.id,e.index),backgroundOutput:e.call.backgroundTask&&(0,H.jsx)(nA,{task:e.call.backgroundTask,initialOutput:le.current.get(e.call.backgroundTask.id)??``,expanded:`${t.id}:${e.index}`in ht&&!!ht[`${t.id}:${e.index}`]}),runCard:_(`${t.id}:${e.index}`)})},`c${e.index}`),y=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 p(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,H.jsx)(`div`,{className:`content thinking-text`,children:(0,H.jsx)(Am,{source:n.text.slice(i,e)})},`t${o}`)),a.push(v({call:t,index:o})),i=e}i<n.text.length&&a.push((0,H.jsx)(`div`,{className:`content thinking-text`,children:(0,H.jsx)(Am,{source:n.text.slice(i)})},`tail`));let o=p(e).filter(e=>e.call.status===void 0),s=o.find(e=>e.call.question?.status===`pending`);return(0,H.jsx)(aA,{liveCall:s?`question`:o.at(-1)?.call.label,liveAwaitingReader:!!s,liveExtra:o.length>1?o.length-1:void 0,messageId:`${t.id}:${e}`,nestedCount:p(e).length,preview:n.text.split(`
102
- `).map(e=>e.trim()).find(Boolean)??``,expanded:oi[`${t.id}:${e}`]===!0,onToggle:()=>ci(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,H.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,H.jsx)(`div`,{className:`avatar`,children:`π`}),(0,H.jsxs)(`div`,{className:`message-body`,children:[(0,H.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,H.jsx)(`time`,{children:Sk(t.createdAt)})]}),m.length===0&&(R?.status===`running`||R?.status===`waiting`)?(0,H.jsx)(`div`,{className:`content`,children:(0,H.jsx)(`span`,{className:`typing`,children:`正在思考`})}):m.map((e,t)=>`blockIndex`in e?y(e.blockIndex):`text`in e?e.text?(0,H.jsx)(`div`,{className:`content`,children:(0,H.jsx)(Am,{source:e.text})},`t${t}`):null:v(e))]})]},e)}if(e.startsWith(`w:`)){let t=Xr.get(e.slice(2));return t?(0,H.jsxs)(`div`,{"data-transcript-key":e,children:[r.some(e=>e.key===`stop:${t.id}`)&&(0,H.jsx)(`span`,{children:`停止中…`}),(0,H.jsx)(ev,{workflow:t,names:Zr,stopping:r.some(e=>e.key===`stop:${t.id}`),onStop:()=>ui(t.id)},e)]},e):null}let t=$r.get(e.slice(2));return t?(0,H.jsxs)(`div`,{"data-transcript-key":e,children:[r.some(e=>e.key===`stop:${t.id}`)&&(0,H.jsx)(`span`,{children:`停止中…`}),(0,H.jsx)(oA,{run:t,stopping:r.some(e=>e.key===`stop:${t.id}`),name:Zr.get(t.agentId)??``,expanded:!!pt[t.id],onToggle:()=>ri(t.id),onStop:()=>li(t.id)},e)]},e):null})]}),(0,H.jsx)(sA,{messages:Vi,pendingInterrupts:r.filter(e=>e.key.startsWith(`interrupt:${R?.id}:`)).map(e=>e.key.slice(`interrupt:${R?.id}:`.length)),running:R?.status===`running`,onSteer:Ui,onInterrupt:Wi,onSend:Gi,onCancel:Hi,onEdit:Ki}),(0,H.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":oe.followTail?`true`:`false`,children:[lt!==null&&(0,H.jsx)(Ej,{height:lt,onHeight:dt}),(0,H.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":R?.status??`idle`,"data-stream-state":f?Dr?`stopping`:R&&TA(R,we)?`question`:R?.status===`waiting`?`waiting`:R?.status===`running`?`streaming`:R?.status===`awaiting_background`||Vi.length?`waiting`:R?.status===`failed`?`failed`:`ready`:`waiting`,children:f?Er?`正在创建会话…`:Dr?`正在停止…`:R&&TA(R,we)?`等你回答 · Agent 在等你的回复`:R?.messagesLoaded===!1?`正在加载会话…`:R?.status===`waiting`?`等待 LLM 返回`:R?.status===`running`?`Streaming · 正在生成`:R?.status===`awaiting_background`?`等待后台任务 · 任务在后台运行中`:Vi.length?`Waiting · 消息排队中`:R?.status===`failed`?`运行失败`:R?.status===`stopped`?`已停止`:`就绪`:`连接中 / 等待连接`}),!oe.followTail&&(0,H.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=ne.current;e&&(cj(e),e.scrollTop=e.scrollHeight,on(e,!1,!0))},children:`↓ 跳到底部`}),(0,H.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":oe.followTail?`true`:`false`,children:oe.followTail?`贴底`:`自由浏览`})]}),(qr.length>0||[...Ae.values()].some(e=>e.placement===`aboveEditor`))&&(0,H.jsxs)(`div`,{className:`extui`,"data-extui-count":qr.length,children:[qr.map(e=>(0,H.jsx)(pA,{request:e.request,pending:r.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>Ar(e.conversationId,e.request.requestId,t)},e.request.requestId)),di(`aboveEditor`)]}),(0,H.jsxs)(`form`,{onSubmit:Bi,onPaste:Ii,onDragOver:Li,onDragLeave:Ri,onDrop:zi,className:Lt?`composer-dropzone-active`:void 0,children:[(0,H.jsx)(`textarea`,{ref:re,value:cn,onCompositionStart:()=>{Bt.current=!0},onCompositionEnd:()=>{Bt.current=!1},onChange:e=>{pn(e.target.value),e.target.value.trim()&&Sn(R?.id??``);let t=e.target.value,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)?_n({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):_n({visible:!1,query:``,rect:null})},placeholder:R?Pr?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!R,onKeyDown:e=>{if(!(Bt.current||bk(e))){if(gn.visible){if(e.key===`Escape`){e.preventDefault(),_n({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())}}}),gn.visible&&gn.rect&&(0,H.jsx)(Um,{query:gn.query,anchorRect:gn.rect,workspaceId:R?.workspaceId,promptCatalog:Se,command:xr,onSelect:e=>{if(e.id.startsWith(`skill:`)){let t=e.id.slice(6),n=document.querySelector(`[data-selected-workspace]`)?.dataset.selectedWorkspace??R?.workspaceId,r=new URLSearchParams({name:t,...n?{workspaceId:n}:{}});fetch(`/api/skills/read?${r.toString()}`).then(async n=>{if(!n.ok){B(`读取技能失败`,`error`);return}let r=await n.json();typeof r.content==`string`&&mn({kind:`skill`,id:r.id??e.id,name:r.name??t,content:r.content})}).catch(()=>B(`读取技能失败`,`error`))}let t=re.current?.selectionStart??cn.length,n=cn.slice(0,t),r=n.lastIndexOf(`/`),i=Vm(e,gn.query),a=`${n.slice(0,r)}/${i} ${cn.slice(t)}`;pn(a),_n({visible:!1,query:``,rect:null})},onClose:()=>_n({visible:!1,query:``,rect:null})}),jt.filter(e=>e.conversationId===R?.id).map(e=>(0,H.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,H.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,H.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,H.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,title:np(e.reason),children:e.reason?.trim()?tp(e.reason):`服务端没有接受这条消息。`}),(0,H.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,H.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(cn||ln.length||un.length),title:cn||ln.length||un.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{fn(e.conversationId,t=>({...t,text:e.content,images:e.images,attachments:e.attachments})),Mt(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,H.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>Mt(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),Nt.filter(e=>e.conversationId===R?.id).map(e=>(0,H.jsxs)(`div`,{className:`composer-upload-preview${e.failed?` composer-upload-preview-failed`:``}`,"data-upload-preview":e.id,children:[(0,H.jsx)(`img`,{src:e.url,alt:e.name,width:44,height:44,className:`composer-upload-thumb`}),(0,H.jsx)(`span`,{className:`composer-upload-state`,"data-upload-preview-state":e.failed?`failed`:`uploading`,children:e.failed?`上传失败`:`上传中…`}),(0,H.jsx)(`button`,{type:`button`,className:`composer-upload-remove`,"aria-label":`移除 ${e.name}`,title:`移除这张图片`,onClick:()=>{At.current.add(e.id),URL.revokeObjectURL(e.url),Pt(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(ln.length>0||dn>0)&&(0,H.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[ln.map((e,t)=>(0,H.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,H.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>It({url:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,H.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,H.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>vn(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),dn>0&&(0,H.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,H.jsxs)(`span`,{children:[`图片上传中 (`,dn,`)…`]})}),un.map(e=>(0,H.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,H.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,H.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,H.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>hn(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),(0,H.jsxs)(`div`,{className:`composer`,children:[(0,H.jsxs)(`div`,{className:`session-picker`,"data-session-picker":`1`,children:[(0,H.jsx)(hA,{kind:`agent`,label:Hr?.name??`跟随 Pi 默认`,value:R?.agentId??gA,options:Ur,disabled:!He||He.source===`unavailable`||Or,note:Zk(He),onChoose:Kr}),(0,H.jsx)(hA,{kind:`model`,label:jr?.label??(Pe?`Pi 默认`:`读取中…`),value:jr?`${jr.provider}/${jr.modelId}`:void 0,detail:Gr?`来自 ${Hr?.name}`:jr&&Pe?.source===`pi`&&!R?.model?`Pi 默认模型`:jr?`${jr.provider}/${jr.modelId}`:void 0,options:Rr,disabled:!Nr||Or,note:Xk(`模型`,Pe,Ir),onChoose:Br}),(0,H.jsx)(hA,{kind:`thinking`,label:Mr??(Pe?`Pi 默认`:`读取中…`),value:Mr,options:zr,disabled:!Nr||Or,note:Xk(`思考等级`,Pe),onChoose:Vr})]}),(0,H.jsxs)(`div`,{className:`composer-hints`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>zt.current?.click(),disabled:!R||!Pr||dn>0,title:R?Pr?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` 图片`]}),(0,H.jsx)(`input`,{ref:zt,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(Fi(Array.from(e.target.files)),e.target.value=``)}}),Ir&&(0,H.jsx)(`span`,{"data-image-session-hint":`1`,title:`此会话历史已包含图片,仅显示支持图文的模型`,children:`图文会话`}),(0,H.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,H.jsxs)(`div`,{className:`composer-actions`,children:[R&&(SA(R)||R.status===`awaiting_background`)&&(0,H.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":R.id,disabled:r.some(e=>e.key===`stop:${R.id}`)||xt.has(R.id),onClick:()=>Sr({type:`run.stop`,conversationId:R.id},`stop:${R.id}`,e=>e),children:r.some(e=>e.key===`stop:${R.id}`)||xt.has(R.id)?`停止中…`:`停止`}),(0,H.jsx)(`button`,{className:`send ${SA(R)?`send-queued`:``}`,"data-send-mode":SA(R)?`queued`:`direct`,disabled:!cn.trim()&&ln.length===0||!R||dn>0||!!qi||Or,title:R?Er?`正在创建会话,请稍候再发送`:R.messagesLoaded===!1?`正在加载会话,请稍候再发送`:qi?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!cn.trim()&&ln.length===0?`请输入消息或添加图片后发送`:dn>0?`图片上传中…`:SA(R)?`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:qi?`撤回中…`:SA(R)?`排队发送 ↑`:`发送 ↑`})]})]})]}),di(`belowEditor`)]})]}),(0,H.jsx)(yj,{side:`right`,width:Xe?30:ot.rail,min:ot.railMin,max:ot.railMax,label:`调整右侧栏宽度`,onWidth:ct}),Ln&&(0,H.jsx)(V_,{entries:z.index,complete:z.indexComplete,skipped:z.indexSkipped,onOpen:e=>{ar(e)},onClose:()=>Rn(!1)}),Vn&&(0,H.jsx)(B_,{workspaceId:v,cwd:En,onOpen:e=>{ar({path:e.path,name:e.name,text:!0},e.line)},onClose:()=>Hn(!1)},`${v}:${En}`),(0,H.jsx)(UA,{}),et&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,className:`mobile-drawer-backdrop`,"data-mobile-drawer-backdrop":`1`,"aria-label":`关闭会话列表`,onClick:()=>tt(!1)}),(0,H.jsx)(`button`,{type:`button`,className:`mobile-drawer-close`,"data-mobile-drawer-close":`1`,"aria-label":`关闭会话列表`,title:`关闭`,onClick:()=>tt(!1),children:`×`})]}),(0,H.jsxs)(`nav`,{className:`mobile-nav`,"aria-label":`移动端主导航`,children:[(0,H.jsxs)(`button`,{type:`button`,"data-mobile-nav":`workspaces`,className:Qe===`workspaces`?`active`:``,onClick:()=>$e(`workspaces`),children:[`☰`,(0,H.jsx)(`span`,{children:`工作区`})]}),(0,H.jsxs)(`button`,{type:`button`,"data-mobile-nav":`chat`,className:Qe===`chat`?`active`:``,onClick:()=>$e(`chat`),children:[`◉`,(0,H.jsx)(`span`,{children:`对话`})]}),(0,H.jsxs)(`button`,{type:`button`,"data-mobile-nav":`rail`,className:Qe===`rail`?`active`:``,onClick:()=>{$e(`rail`),Ze(!1)},children:[`▣`,(0,H.jsx)(`span`,{children:`工具`})]})]}),` `,Ct&&(0,H.jsx)(Fk,{workspace:Ct.workspace,x:Ct.x,y:Ct.y,notify:B,onClose:()=>wt(void 0)}),Tt&&(0,H.jsx)(Ik,{conversation:Tt.conversation,x:Tt.x,y:Tt.y,notify:B,onRename:()=>void yi(Tt.conversation.id),onClose:()=>Et(void 0),sendCommand:xr,orchestrated:Tt.conversation.origin===`orchestrator`,childCount:Zt.filter(e=>e.parentConversationId===Tt.conversation.id).length}),D&&(0,H.jsx)(qk,{onClose:()=>O(!1),onCreate:fi}),k&&(()=>{let e=l.workspaces.find(e=>e.id===k.workspaceId);return e?(0,H.jsx)(Kk,{workspace:e,onClose:()=>{A(void 0),j.current?.focus()},onCreate:e=>{ji(k.workspaceId,e),A(void 0),j.current?.focus()}}):null})(),Ei&&(0,H.jsx)(py,{workspaceId:v,theme:wi,onChooseTheme:e=>Ti(e),onClose:()=>Di(!1),agentCatalog:He,subagentCatalog:We,modelFilterRules:l.modelFilterRules??[],pendingSettings:r.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Sr({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:l.defaultModel,modelCatalog:Ie,onSetDefaultModel:e=>Sr({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:Re,providerApis:Be,onSetProvider:e=>{xr({type:`providers.set`,provider:e})},onRemoveProvider:e=>{xr({type:`providers.remove`,providerId:e})},onRepairProviders:()=>{xr({type:`providers.repair`}),B(`正在清理 Pi 不接受的空字段并重新读取模型清单`,`info`)},onToggleProvider:(e,t)=>{xr(t?{type:`providers.enable`,providerId:e}:{type:`providers.disable`,providerId:e}),B(t?`已启用供应商「${e}」,它的模型重新出现在选择器里`:`已停用供应商「${e}」:配置已从 Pi 的文件里拿掉并保存在这里,模型不再出现在选择器里`,`info`)},onRemoveProviderModel:(e,t)=>{xr({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:l.customAgentDirs??[],onSetCustomAgentDirs:e=>Sr({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>xr({type:`agents.rescan`}),userNickname:ve,onSetUserNickname:be,terminalShell:l.terminalShell,onSetTerminalShell:e=>{xr({type:`terminal.shell.set`,command:e})}}),Oi&&(0,H.jsx)(nv,{onClose:()=>ki(!1)}),Ci&&(0,H.jsx)(_A,{workspace:Ci,catalog:Fr(Pe,Ci),agents:He,onClose:()=>Si(void 0),onRename:()=>{let e=Ci.id;Si(void 0),hi(`workspace`,e)},onSave:(e,t,n)=>Ai(Ci.id,e,t,n)}),Ft&&(0,H.jsx)(qA,{image:Ft,onClose:()=>It(void 0)}),ft&&!Xe&&(0,H.jsx)(`div`,{className:`rail-backdrop`,role:`presentation`,"aria-hidden":`true`,onClick:()=>Ze(!0)}),(0,H.jsx)(RA,{onOpenSession:Cn,todos:l.todosByConversation?.[R?.id??``]??[],tasks:FA(R,l.backgroundTasks??[]),messages:R?.messages??[],execOutputs:le.current,scheduledTasks:(l.scheduledTasks??[]).filter(e=>e.workspaceId===v),scheduledCatalog:Fr(Pe,l.workspaces.find(e=>e.id===v)),scheduledAgents:He,notify:B,serverTimeZone:l.serverTimeZone,collapsed:Xe,onToggle:()=>Ze(e=>!e),workspaceId:Tn,workspaceLabel:l.workspaces.find(e=>e.id===Tn)?.path,conversationId:R?.id,cwd:En,connected:f,files:z,onOpenFile:e=>void ar(e),onOpenChanged:Qn,activeTab:Fn,onSelectTab:In,sendCommand:xr,registerTerminalSink:he,terminalShell:l.terminalShell})]})}$v(Qv()),(0,ca.createRoot)(document.getElementById(`root`)).render((0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(Oj,{})}));export{d as a,y as i,d_ as n,s as o,Rg as r,l as s,c_ as t};
101
+ `).slice(-1)[0]}),(0,H.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:u?`▾`:`▸`})]}),(o||c&&s)&&(0,H.jsxs)(`div`,{className:`bg-result-actions`,"data-bg-result-actions":t.id,children:[o&&(0,H.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-file-link":o,title:`在主区域打开产物文件:${o}`,onClick:e=>{e.stopPropagation();let t=o.split(/[/\\]/).pop()||o;ar({path:o,name:t,text:!0}).catch(e=>{console.warn(`打开产物文件失败:`,e)})},children:[(0,H.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`📄`}),(0,H.jsx)(`span`,{children:`查看产物文件`})]}),c&&s&&(0,H.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-session-link":s,title:`跳转到子会话:${s}`,onClick:e=>{e.stopPropagation(),Cn(s)},children:[(0,H.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`↗`}),(0,H.jsx)(`span`,{children:`跳转到子会话`})]})]})]}),u&&(0,H.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,H.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:a})})]})},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))},f=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,p=e=>c.map((e,t)=>({call:e,index:t})).filter(({call:t})=>f(t)===e),m=[],h=[...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}})),...c.map((e,t)=>({at:d(e,t),order:(e.thinkingAt??0)*2,segment:{call:e,index:t}})).filter(({segment:e})=>`call`in e&&f(e.call)<0)].sort((e,t)=>e.at-t.at||e.order-t.order),g=0;for(let e of h){let n=Math.max(g,Math.min(e.at,t.content.length));n>g&&m.push({text:t.content.slice(g,n)}),m.push(e.segment),g=n}g<t.content.length&&m.push({text:t.content.slice(g)});let _=e=>{let t=ei.get(e);if(t)return(0,H.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,H.jsx)(lA,{run:t,name:Zr.get(t.agentId)??``,expanded:!!pt[t.id],onToggle:()=>ri(t.id),onStop:()=>li(t.id),stopping:r.some(e=>e.key===`stop:${t.id}`)})})},v=e=>e.call.question?(0,H.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,H.jsx)(mA,{question:e.call.question,index:e.index,expanded:`${t.id}:${e.index}`in _t?!!_t[`${t.id}:${e.index}`]:!0,onToggle:()=>ai(t.id,e.index),onAnswer:(n,r)=>kr(R?.id??``,t.id,e.index,n,r)})},`c${e.index}`):(0,H.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,H.jsx)(oA,{call:e.call,index:e.index,expanded:`${t.id}:${e.index}`in ht&&!!ht[`${t.id}:${e.index}`],onToggle:()=>ii(t.id,e.index),backgroundOutput:e.call.backgroundTask&&(0,H.jsx)(aA,{task:e.call.backgroundTask,initialOutput:le.current.get(e.call.backgroundTask.id)??``,expanded:`${t.id}:${e.index}`in ht&&!!ht[`${t.id}:${e.index}`]}),runCard:_(`${t.id}:${e.index}`)})},`c${e.index}`),y=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 p(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,H.jsx)(`div`,{className:`content thinking-text`,children:(0,H.jsx)(Am,{source:n.text.slice(i,e)})},`t${o}`)),a.push(v({call:t,index:o})),i=e}i<n.text.length&&a.push((0,H.jsx)(`div`,{className:`content thinking-text`,children:(0,H.jsx)(Am,{source:n.text.slice(i)})},`tail`));let o=p(e).filter(e=>e.call.status===void 0),s=o.find(e=>e.call.question?.status===`pending`);return(0,H.jsx)(cA,{liveCall:s?`question`:o.at(-1)?.call.label,liveAwaitingReader:!!s,liveExtra:o.length>1?o.length-1:void 0,messageId:`${t.id}:${e}`,nestedCount:p(e).length,preview:n.text.split(`
102
+ `).map(e=>e.trim()).find(Boolean)??``,expanded:oi[`${t.id}:${e}`]===!0,onToggle:()=>ci(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,H.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,H.jsx)(`div`,{className:`avatar`,children:`π`}),(0,H.jsxs)(`div`,{className:`message-body`,children:[(0,H.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,H.jsx)(`time`,{children:Tk(t.createdAt)})]}),m.length===0&&(R?.status===`running`||R?.status===`waiting`)?(0,H.jsx)(`div`,{className:`content`,children:(0,H.jsx)(`span`,{className:`typing`,children:`正在思考`})}):m.map((e,t)=>`blockIndex`in e?y(e.blockIndex):`text`in e?e.text?(0,H.jsx)(`div`,{className:`content`,children:(0,H.jsx)(Am,{source:e.text})},`t${t}`):null:v(e))]})]},e)}if(e.startsWith(`w:`)){let t=Xr.get(e.slice(2));return t?(0,H.jsxs)(`div`,{"data-transcript-key":e,children:[r.some(e=>e.key===`stop:${t.id}`)&&(0,H.jsx)(`span`,{children:`停止中…`}),(0,H.jsx)(ev,{workflow:t,names:Zr,stopping:r.some(e=>e.key===`stop:${t.id}`),onStop:()=>ui(t.id)},e)]},e):null}let t=$r.get(e.slice(2));return t?(0,H.jsxs)(`div`,{"data-transcript-key":e,children:[r.some(e=>e.key===`stop:${t.id}`)&&(0,H.jsx)(`span`,{children:`停止中…`}),(0,H.jsx)(lA,{run:t,stopping:r.some(e=>e.key===`stop:${t.id}`),name:Zr.get(t.agentId)??``,expanded:!!pt[t.id],onToggle:()=>ri(t.id),onStop:()=>li(t.id)},e)]},e):null})]}),(0,H.jsx)(uA,{messages:Vi,pendingInterrupts:r.filter(e=>e.key.startsWith(`interrupt:${R?.id}:`)).map(e=>e.key.slice(`interrupt:${R?.id}:`.length)),running:R?.status===`running`,onSteer:Ui,onInterrupt:Wi,onSend:Gi,onCancel:Hi,onEdit:Ki}),(0,H.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":oe.followTail?`true`:`false`,children:[lt!==null&&(0,H.jsx)(kj,{height:lt,onHeight:dt}),(0,H.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":R?.status??`idle`,"data-stream-state":f?Dr?`stopping`:R&&OA(R,we)?`question`:R?.status===`waiting`?`waiting`:R?.status===`running`?`streaming`:R?.status===`awaiting_background`||Vi.length?`waiting`:R?.status===`failed`?`failed`:`ready`:`waiting`,children:f?Er?`正在创建会话…`:Dr?`正在停止…`:R&&OA(R,we)?`等你回答 · Agent 在等你的回复`:R?.messagesLoaded===!1?`正在加载会话…`:R?.status===`waiting`?`等待 LLM 返回`:R?.status===`running`?`Streaming · 正在生成`:R?.status===`awaiting_background`?`等待后台任务 · 任务在后台运行中`:Vi.length?`Waiting · 消息排队中`:R?.status===`failed`?`运行失败`:R?.status===`stopped`?`已停止`:`就绪`:`连接中 / 等待连接`}),!oe.followTail&&(0,H.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=ne.current;e&&(dj(e),e.scrollTop=e.scrollHeight,on(e,!1,!0))},children:`↓ 跳到底部`}),(0,H.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":oe.followTail?`true`:`false`,children:oe.followTail?`贴底`:`自由浏览`})]}),(qr.length>0||[...Ae.values()].some(e=>e.placement===`aboveEditor`))&&(0,H.jsxs)(`div`,{className:`extui`,"data-extui-count":qr.length,children:[qr.map(e=>(0,H.jsx)(gA,{request:e.request,pending:r.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>Ar(e.conversationId,e.request.requestId,t)},e.request.requestId)),di(`aboveEditor`)]}),(0,H.jsxs)(`form`,{onSubmit:Bi,onPaste:Ii,onDragOver:Li,onDragLeave:Ri,onDrop:zi,className:Lt?`composer-dropzone-active`:void 0,children:[(0,H.jsx)(`textarea`,{ref:re,value:cn,onCompositionStart:()=>{Bt.current=!0},onCompositionEnd:()=>{Bt.current=!1},onChange:e=>{pn(e.target.value),e.target.value.trim()&&Sn(R?.id??``);let t=e.target.value,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)?_n({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):_n({visible:!1,query:``,rect:null})},placeholder:R?Pr?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!R,onKeyDown:e=>{if(!(Bt.current||Ck(e))){if(gn.visible){if(e.key===`Escape`){e.preventDefault(),_n({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())}}}),gn.visible&&gn.rect&&(0,H.jsx)(Um,{query:gn.query,anchorRect:gn.rect,workspaceId:R?.workspaceId,promptCatalog:Se,command:xr,onSelect:e=>{if(e.id.startsWith(`skill:`)){let t=e.id.slice(6),n=document.querySelector(`[data-selected-workspace]`)?.dataset.selectedWorkspace??R?.workspaceId,r=new URLSearchParams({name:t,...n?{workspaceId:n}:{}});fetch(`/api/skills/read?${r.toString()}`).then(async n=>{if(!n.ok){B(`读取技能失败`,`error`);return}let r=await n.json();typeof r.content==`string`&&mn({kind:`skill`,id:r.id??e.id,name:r.name??t,content:r.content})}).catch(()=>B(`读取技能失败`,`error`))}let t=re.current?.selectionStart??cn.length,n=cn.slice(0,t),r=n.lastIndexOf(`/`),i=Vm(e,gn.query),a=`${n.slice(0,r)}/${i} ${cn.slice(t)}`;pn(a),_n({visible:!1,query:``,rect:null})},onClose:()=>_n({visible:!1,query:``,rect:null})}),jt.filter(e=>e.conversationId===R?.id).map(e=>(0,H.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,H.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,H.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,H.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,title:np(e.reason),children:e.reason?.trim()?tp(e.reason):`服务端没有接受这条消息。`}),(0,H.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,H.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,H.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(cn||ln.length||un.length),title:cn||ln.length||un.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{fn(e.conversationId,t=>({...t,text:e.content,images:e.images,attachments:e.attachments})),Mt(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,H.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>Mt(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),Nt.filter(e=>e.conversationId===R?.id).map(e=>(0,H.jsxs)(`div`,{className:`composer-upload-preview${e.failed?` composer-upload-preview-failed`:``}`,"data-upload-preview":e.id,children:[(0,H.jsx)(`img`,{src:e.url,alt:e.name,width:44,height:44,className:`composer-upload-thumb`}),(0,H.jsx)(`span`,{className:`composer-upload-state`,"data-upload-preview-state":e.failed?`failed`:`uploading`,children:e.failed?`上传失败`:`上传中…`}),(0,H.jsx)(`button`,{type:`button`,className:`composer-upload-remove`,"aria-label":`移除 ${e.name}`,title:`移除这张图片`,onClick:()=>{At.current.add(e.id),URL.revokeObjectURL(e.url),Pt(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(ln.length>0||dn>0)&&(0,H.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[ln.map((e,t)=>(0,H.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,H.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>It({url:`/api/upload/${encodeURIComponent(R?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,H.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,H.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>vn(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),dn>0&&(0,H.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,H.jsxs)(`span`,{children:[`图片上传中 (`,dn,`)…`]})}),un.map(e=>(0,H.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,H.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,H.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,H.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>hn(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),(0,H.jsxs)(`div`,{className:`composer`,children:[(0,H.jsxs)(`div`,{className:`session-picker`,"data-session-picker":`1`,children:[(0,H.jsx)(vA,{kind:`agent`,label:Hr?.name??`跟随 Pi 默认`,value:R?.agentId??yA,options:Ur,disabled:!He||He.source===`unavailable`||Or,note:eA(He),onChoose:Kr}),(0,H.jsx)(vA,{kind:`model`,label:jr?.label??(Pe?`Pi 默认`:`读取中…`),value:jr?`${jr.provider}/${jr.modelId}`:void 0,detail:Gr?`来自 ${Hr?.name}`:jr&&Pe?.source===`pi`&&!R?.model?`Pi 默认模型`:jr?`${jr.provider}/${jr.modelId}`:void 0,options:Rr,disabled:!Nr||Or,note:$k(`模型`,Pe,Ir),onChoose:Br}),(0,H.jsx)(vA,{kind:`thinking`,label:Mr??(Pe?`Pi 默认`:`读取中…`),value:Mr,options:zr,disabled:!Nr||Or,note:$k(`思考等级`,Pe),onChoose:Vr})]}),(0,H.jsxs)(`div`,{className:`composer-hints`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>zt.current?.click(),disabled:!R||!Pr||dn>0,title:R?Pr?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,H.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` 图片`]}),(0,H.jsx)(`input`,{ref:zt,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(Fi(Array.from(e.target.files)),e.target.value=``)}}),Ir&&(0,H.jsx)(`span`,{"data-image-session-hint":`1`,title:`此会话历史已包含图片,仅显示支持图文的模型`,children:`图文会话`}),(0,H.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,H.jsxs)(`div`,{className:`composer-actions`,children:[R&&(TA(R)||R.status===`awaiting_background`)&&(0,H.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":R.id,disabled:r.some(e=>e.key===`stop:${R.id}`)||xt.has(R.id),onClick:()=>Sr({type:`run.stop`,conversationId:R.id},`stop:${R.id}`,e=>e),children:r.some(e=>e.key===`stop:${R.id}`)||xt.has(R.id)?`停止中…`:`停止`}),(0,H.jsx)(`button`,{className:`send ${TA(R)?`send-queued`:``}`,"data-send-mode":TA(R)?`queued`:`direct`,disabled:!cn.trim()&&ln.length===0||!R||dn>0||!!qi||Or,title:R?Er?`正在创建会话,请稍候再发送`:R.messagesLoaded===!1?`正在加载会话,请稍候再发送`:qi?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!cn.trim()&&ln.length===0?`请输入消息或添加图片后发送`:dn>0?`图片上传中…`:TA(R)?`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:qi?`撤回中…`:TA(R)?`排队发送 ↑`:`发送 ↑`})]})]})]}),di(`belowEditor`)]})]}),(0,H.jsx)(Sj,{side:`right`,width:Xe?30:ot.rail,min:ot.railMin,max:ot.railMax,label:`调整右侧栏宽度`,onWidth:ct}),Ln&&(0,H.jsx)(V_,{entries:z.index,complete:z.indexComplete,skipped:z.indexSkipped,onOpen:e=>{ar(e)},onClose:()=>Rn(!1)}),Vn&&(0,H.jsx)(B_,{workspaceId:v,cwd:En,onOpen:e=>{ar({path:e.path,name:e.name,text:!0},e.line)},onClose:()=>Hn(!1)},`${v}:${En}`),(0,H.jsx)(KA,{}),et&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,className:`mobile-drawer-backdrop`,"data-mobile-drawer-backdrop":`1`,"aria-label":`关闭会话列表`,onClick:()=>tt(!1)}),(0,H.jsx)(`button`,{type:`button`,className:`mobile-drawer-close`,"data-mobile-drawer-close":`1`,"aria-label":`关闭会话列表`,title:`关闭`,onClick:()=>tt(!1),children:`×`})]}),(0,H.jsxs)(`nav`,{className:`mobile-nav`,"aria-label":`移动端主导航`,children:[(0,H.jsxs)(`button`,{type:`button`,"data-mobile-nav":`workspaces`,className:Qe===`workspaces`?`active`:``,onClick:()=>$e(`workspaces`),children:[`☰`,(0,H.jsx)(`span`,{children:`工作区`})]}),(0,H.jsxs)(`button`,{type:`button`,"data-mobile-nav":`chat`,className:Qe===`chat`?`active`:``,onClick:()=>$e(`chat`),children:[`◉`,(0,H.jsx)(`span`,{children:`对话`})]}),(0,H.jsxs)(`button`,{type:`button`,"data-mobile-nav":`rail`,className:Qe===`rail`?`active`:``,onClick:()=>{$e(`rail`),Ze(!1)},children:[`▣`,(0,H.jsx)(`span`,{children:`工具`})]})]}),` `,Ct&&(0,H.jsx)(Rk,{workspace:Ct.workspace,x:Ct.x,y:Ct.y,notify:B,onClose:()=>wt(void 0)}),Tt&&(0,H.jsx)(zk,{conversation:Tt.conversation,x:Tt.x,y:Tt.y,notify:B,onRename:()=>void yi(Tt.conversation.id),onClose:()=>Et(void 0),sendCommand:xr,orchestrated:Tt.conversation.origin===`orchestrator`,childCount:Zt.filter(e=>e.parentConversationId===Tt.conversation.id).length}),D&&(0,H.jsx)(Xk,{onClose:()=>O(!1),onCreate:fi}),k&&(()=>{let e=l.workspaces.find(e=>e.id===k.workspaceId);return e?(0,H.jsx)(Yk,{workspace:e,onClose:()=>{A(void 0),j.current?.focus()},onCreate:e=>{ji(k.workspaceId,e),A(void 0),j.current?.focus()}}):null})(),Ei&&(0,H.jsx)(py,{workspaceId:v,theme:wi,onChooseTheme:e=>Ti(e),onClose:()=>Di(!1),agentCatalog:He,subagentCatalog:We,modelFilterRules:l.modelFilterRules??[],pendingSettings:r.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Sr({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:l.defaultModel,modelCatalog:Ie,onSetDefaultModel:e=>Sr({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:Re,providerApis:Be,onSetProvider:e=>{xr({type:`providers.set`,provider:e})},onRemoveProvider:e=>{xr({type:`providers.remove`,providerId:e})},onRepairProviders:()=>{xr({type:`providers.repair`}),B(`正在清理 Pi 不接受的空字段并重新读取模型清单`,`info`)},onToggleProvider:(e,t)=>{xr(t?{type:`providers.enable`,providerId:e}:{type:`providers.disable`,providerId:e}),B(t?`已启用供应商「${e}」,它的模型重新出现在选择器里`:`已停用供应商「${e}」:配置已从 Pi 的文件里拿掉并保存在这里,模型不再出现在选择器里`,`info`)},onRemoveProviderModel:(e,t)=>{xr({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:l.customAgentDirs??[],onSetCustomAgentDirs:e=>Sr({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>xr({type:`agents.rescan`}),userNickname:ve,onSetUserNickname:be,terminalShell:l.terminalShell,onSetTerminalShell:e=>{xr({type:`terminal.shell.set`,command:e})}}),Oi&&(0,H.jsx)(nv,{onClose:()=>ki(!1)}),Ci&&(0,H.jsx)(bA,{workspace:Ci,catalog:Fr(Pe,Ci),agents:He,onClose:()=>Si(void 0),onRename:()=>{let e=Ci.id;Si(void 0),hi(`workspace`,e)},onSave:(e,t,n)=>Ai(Ci.id,e,t,n)}),Ft&&(0,H.jsx)(XA,{image:Ft,onClose:()=>It(void 0)}),ft&&!Xe&&(0,H.jsx)(`div`,{className:`rail-backdrop`,role:`presentation`,"aria-hidden":`true`,onClick:()=>Ze(!0)}),(0,H.jsx)(VA,{onOpenSession:Cn,todos:l.todosByConversation?.[R?.id??``]??[],tasks:RA(R,l.backgroundTasks??[]),messages:R?.messages??[],execOutputs:le.current,scheduledTasks:(l.scheduledTasks??[]).filter(e=>e.workspaceId===v),scheduledCatalog:Fr(Pe,l.workspaces.find(e=>e.id===v)),scheduledAgents:He,notify:B,serverTimeZone:l.serverTimeZone,collapsed:Xe,onToggle:()=>Ze(e=>!e),workspaceId:Tn,workspaceLabel:l.workspaces.find(e=>e.id===Tn)?.path,conversationId:R?.id,cwd:En,connected:f,files:z,onOpenFile:e=>void ar(e),onOpenChanged:Qn,activeTab:Fn,onSelectTab:In,sendCommand:xr,registerTerminalSink:he,terminalShell:l.terminalShell})]})}$v(Qv()),(0,ca.createRoot)(document.getElementById(`root`)).render((0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(jj,{})}));export{d as a,y as i,d_ as n,s as o,Rg as r,l as s,c_ as t};