@evandu/super-pi 0.1.94 → 0.1.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agents/super-pi-task/core.ts +6 -5
- package/agents/super-pi-task/index.ts +2 -1
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +3 -3
- package/dist/client/assets/{index-zbxFjL-O.js → index-gjLqMWYT.js} +2 -2
- package/dist/client/index.html +1 -1
- package/dist/extension.js +13 -3
- package/dist/server/agents.d.ts +18 -0
- package/dist/server/agents.js +39 -0
- package/dist/server/application/run-service.d.ts +47 -3
- package/dist/server/application/run-service.js +158 -88
- package/dist/server/capability.d.ts +28 -12
- package/dist/server/capability.js +54 -20
- package/dist/server/http-server.js +14 -6
- package/dist/server/index.js +10 -1
- package/dist/server/pi-command.d.ts +29 -1
- package/dist/server/pi-command.js +82 -5
- package/dist/server/pi-session-events.d.ts +111 -0
- package/dist/server/pi-session-events.js +291 -0
- package/dist/server/pi-session-pool.d.ts +166 -0
- package/dist/server/pi-session-pool.js +262 -0
- package/dist/server/pi-session.d.ts +204 -0
- package/dist/server/pi-session.js +226 -0
- package/dist/server/runtime.d.ts +262 -29
- package/dist/server/runtime.js +664 -60
- package/dist/server/store.js +4 -4
- package/dist/server/ws-server.js +5 -4
- package/package.json +7 -3
- package/scripts/patch-brace-expansion.mjs +179 -0
|
@@ -62,13 +62,13 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
|
|
|
62
62
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),$s&&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=Sc(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=Ls(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,-Cc),Cc),t/=Cc,t/Math.abs(t)+Math.round(t*(wc-1)))}shouldForceSelection(e){return Ys?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(),Tc)}_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&&!(Ys&&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<Ec&&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=cc(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=Sc(n,this._bufferService.cols)}};Oc=Qn([F(3,Tr),F(4,Dr),F(5,zr),F(6,jr),F(7,Br),F(8,Rr)],Oc);var kc=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={}}},Ac=class{constructor(){this._color=new kc,this._css=new kc}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()}},jc=Object.freeze((()=>{let e=[W.toColor(`#2e3436`),W.toColor(`#cc0000`),W.toColor(`#4e9a06`),W.toColor(`#c4a000`),W.toColor(`#3465a4`),W.toColor(`#75507b`),W.toColor(`#06989a`),W.toColor(`#d3d7cf`),W.toColor(`#555753`),W.toColor(`#ef2929`),W.toColor(`#8ae234`),W.toColor(`#fce94f`),W.toColor(`#729fcf`),W.toColor(`#ad7fa8`),W.toColor(`#34e2e2`),W.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:as.toCss(r,i,a),rgba:as.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:as.toCss(n,n,n),rgba:as.toRgba(n,n,n)})}return e})()),Mc=W.toColor(`#ffffff`),Nc=W.toColor(`#000000`),Pc=W.toColor(`#ffffff`),Fc=Nc,Ic={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},Lc=Mc,Rc=class extends I{constructor(e){super(),this._optionsService=e,this._contrastCache=new Ac,this._halfContrastCache=new Ac,this._onChangeColors=this._register(new L),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Mc,background:Nc,cursor:Pc,cursorAccent:Fc,selectionForeground:void 0,selectionBackgroundTransparent:Ic,selectionBackgroundOpaque:U.blend(Nc,Ic),selectionInactiveBackgroundTransparent:Ic,selectionInactiveBackgroundOpaque:U.blend(Nc,Ic),scrollbarSliderBackground:U.opacity(Mc,.2),scrollbarSliderHoverBackground:U.opacity(Mc,.4),scrollbarSliderActiveBackground:U.opacity(Mc,.5),overviewRulerBorder:Mc,ansi:jc.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=G(e.foreground,Mc),t.background=G(e.background,Nc),t.cursor=U.blend(t.background,G(e.cursor,Pc)),t.cursorAccent=U.blend(t.background,G(e.cursorAccent,Fc)),t.selectionBackgroundTransparent=G(e.selectionBackground,Ic),t.selectionBackgroundOpaque=U.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=G(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=U.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?G(e.selectionForeground,is):void 0,t.selectionForeground===is&&(t.selectionForeground=void 0),U.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=U.opacity(t.selectionBackgroundTransparent,.3)),U.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=U.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=G(e.scrollbarSliderBackground,U.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=G(e.scrollbarSliderHoverBackground,U.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=G(e.scrollbarSliderActiveBackground,U.opacity(t.foreground,.5)),t.overviewRulerBorder=G(e.overviewRulerBorder,Lc),t.ansi=jc.slice(),t.ansi[0]=G(e.black,jc[0]),t.ansi[1]=G(e.red,jc[1]),t.ansi[2]=G(e.green,jc[2]),t.ansi[3]=G(e.yellow,jc[3]),t.ansi[4]=G(e.blue,jc[4]),t.ansi[5]=G(e.magenta,jc[5]),t.ansi[6]=G(e.cyan,jc[6]),t.ansi[7]=G(e.white,jc[7]),t.ansi[8]=G(e.brightBlack,jc[8]),t.ansi[9]=G(e.brightRed,jc[9]),t.ansi[10]=G(e.brightGreen,jc[10]),t.ansi[11]=G(e.brightYellow,jc[11]),t.ansi[12]=G(e.brightBlue,jc[12]),t.ansi[13]=G(e.brightMagenta,jc[13]),t.ansi[14]=G(e.brightCyan,jc[14]),t.ansi[15]=G(e.brightWhite,jc[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]=G(e.extendedAnsi[r],jc[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()}}};Rc=Qn([F(0,jr)],Rc);function G(e,t){if(e!==void 0)try{return W.toColor(e)}catch{}return t}var zc=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)}},Bc=class{constructor(){this._services=new zc,this._services.set(kr,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Sr(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)}},Vc={trace:0,debug:1,info:2,warn:3,error:4,off:5},Hc=`xterm.js: `,Uc=class extends I{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),Wc=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Vc[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?``:Hc)+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)}};Uc=Qn([F(0,jr)],Uc);var Wc,Gc=class extends I{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new L),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new L),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new L),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}},K=3,Kc=Object.freeze(new gr),qc=0,Jc=2,Yc=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*K);let r=t||vr.fromCharData([0,mr,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*K+0],n=t&2097151;return[this._data[e*K+1],t&2097152?this._combined[e]:n?ur(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*K+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*K+0]=e|2097152|t[2]<<22):this._data[e*K+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*K+0]>>22}hasWidth(e){return this._data[e*K+0]&12582912}getFg(e){return this._data[e*K+1]}getBg(e){return this._data[e*K+2]}hasContent(e){return this._data[e*K+0]&4194303}getCodePoint(e){let t=this._data[e*K+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*K+0]&2097152}getString(e){let t=this._data[e*K+0];return t&2097152?this._combined[e]:t&2097151?ur(t&2097151):``}isProtected(e){return this._data[e*K+2]&536870912}loadCell(e,t){return qc=e*K,t.content=this._data[qc+0],t.fg=this._data[qc+1],t.bg=this._data[qc+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*K+0]=t.content,this._data[e*K+1]=t.fg,this._data[e*K+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*K+0]=t|n<<22,this._data[e*K+1]=r.fg,this._data[e*K+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*K+0];r&2097152?this._combined[e]+=ur(t):r&2097151?(this._combined[e]=ur(r&2097151)+ur(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*K+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 vr;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 vr;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*Jc<this._data.buffer.byteLength;let n=e*K;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*Jc<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*Jc<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*K+0]&4194303)return e+(this._data[e*K+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*K+0]&4194303||this._data[e*K+2]&50331648)return e+(this._data[e*K+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<K;e++)this._data[(n+i)*K+e]=a[(t+i)*K+e];a[(t+i)*K+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<K;e++)this._data[(n+i)*K+e]=a[(t+i)*K+e];a[(t+i)*K+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*K+0],n=e&2097151,a=e&2097152?this._combined[t]:n?ur(n):hr;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 Xc(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=el(u,d,t),p=1,m=0;for(;p<u.length;){let e=el(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 Zc(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 Qc(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 $c(e,t,n){let r=[],i=e.map((n,r)=>el(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=el(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 el(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 tl=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new L),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),li(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};tl._nextId=1;var nl=tl,rl={},il=rl.B;rl[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:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},rl.A={"#":`£`},rl.B=void 0,rl[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},rl.C=rl[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},rl.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},rl.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},rl.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},rl.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},rl.E=rl[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},rl.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},rl.H=rl[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},rl[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var al=4294967295,ol=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=Kc.clone(),this.savedCharset=il,this.markers=[],this._nullCell=vr.fromCharData([0,mr,1,0]),this._whitespaceCell=vr.fromCharData([0,hr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new ic,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Gc(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 _r),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 _r),this._whitespaceCell}getBlankLine(e,t){return new Yc(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>al?al:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Kc);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 Gc(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(Kc),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 Yc(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 Yc(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=Xc(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Kc),n);if(r.length>0){let n=Zc(this.lines,r);Qc(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(Kc),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new Yc(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(Kc),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=$c(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(Kc,!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--,_=el(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 nl(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)}},sl=class extends I{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new L),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 ol(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new ol(!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)}},cl=2,ll=1,ul=class extends I{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new L),this.onResize=this._onResize.event,this._onScroll=this._register(new L),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,cl),this.rows=Math.max(e.rawOptions.rows||0,ll),this.buffers=this._register(new sl(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))}};ul=Qn([F(0,jr)],ul);var dl={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:Ys,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},fl=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],pl=class extends I{constructor(e){super(),this._onOptionChange=this._register(new L),this.onOptionChange=this._onOptionChange.event;let t={...dl};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(di(()=>{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 dl))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in dl))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||=dl[e],!ml(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=dl[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=fl.includes(t)?t:dl[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 ml(e){return e===`block`||e===`underline`||e===`bar`}function q(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]&&q(e[r],t-1);return n}var hl=Object.freeze({insertMode:!1}),gl=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_l=class extends I{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new L),this.onData=this._onData.event,this._onUserInput=this._register(new L),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new L),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new L),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=q(hl),this.decPrivateModes=q(gl)}reset(){this.modes=q(hl),this.decPrivateModes=q(gl)}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))}};_l=Qn([F(0,Tr),F(1,Ar),F(2,jr)],_l);var vl={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 yl(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 bl=String.fromCharCode,xl={DEFAULT:e=>{let t=[yl(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${bl(t[0])}${bl(t[1])}${bl(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${yl(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${yl(e,!0)};${e.x};${e.y}${t}`}},Sl=class extends I{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new L),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(vl))this.addProtocol(e,vl[e]);for(let e of Object.keys(xl))this.addEncoding(e,xl[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}};Sl=Qn([F(0,Tr),F(1,Dr),F(2,jr)],Sl);var Cl=[[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]],wl=[[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]],Tl;function El(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 Dl=class{constructor(){if(this.version=`6`,!Tl){Tl=new Uint8Array(65536),Tl.fill(1),Tl[0]=0,Tl.fill(0,1,32),Tl.fill(0,127,160),Tl.fill(2,4352,4448),Tl[9001]=2,Tl[9002]=2,Tl.fill(2,11904,42192),Tl[12351]=1,Tl.fill(2,44032,55204),Tl.fill(2,63744,64256),Tl.fill(2,65040,65050),Tl.fill(2,65072,65136),Tl.fill(2,65280,65377),Tl.fill(2,65504,65511);for(let e=0;e<Cl.length;++e)Tl.fill(0,Cl[e][0],Cl[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Tl[e]:El(e,wl)?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=Ol.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Ol.createPropertyValue(0,n,r)}},Ol=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new L,this.onChange=this._onChange.event;let e=new Dl;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)}},kl=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 Al(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 jl=2147483647,Ml=256,Nl=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>Ml)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>jl?jl: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>jl?jl: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,jl):e}},Pl=[],Fl=class{constructor(){this._state=0,this._active=Pl,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=Pl}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=Pl,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Pl,!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`,dr(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=Pl,this._id=-1,this._state=0}}},Il=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+=dr(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}},Ll=[],Rl=class{constructor(){this._handlers=Object.create(null),this._active=Ll,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Ll}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=Ll,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Ll,!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`,dr(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=Ll,this._ident=0}},zl=new Nl;zl.addParam(0);var Bl=class{constructor(e){this._handler=e,this._data=``,this._params=zl,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():zl,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=dr(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=zl,this._data=``,this._hitLimit=!1,e));return this._params=zl,this._data=``,this._hitLimit=!1,t}},Vl=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}},Hl=160,Ul=function(){let e=new Vl(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(Hl,0,2,0),e.add(Hl,8,5,8),e.add(Hl,6,0,6),e.add(Hl,11,0,11),e.add(Hl,13,13,13),e}(),Wl=class extends I{constructor(e=Ul){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 Nl,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(di(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Fl),this._dcsParser=this._register(new Rl),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:Hl)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<Hl||++i>=t||(r=e[i])<32||r>126&&r<Hl||++i>=t||(r=e[i])<32||r>126&&r<Hl||++i>=t||(r=e[i])<32||r>126&&r<Hl){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<Hl){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<Hl){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}}},Gl=/^([\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})$/,Kl=/^[\da-f]+$/;function ql(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=Gl.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),Kl.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 Jl(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 Yl(e,t=16){let[n,r,i]=e;return`rgb:${Jl(n,t)}/${Jl(r,t)}/${Jl(i,t)}`}var Xl={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Zl=131072,Ql=10;function $l(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 eu=5e3,tu=0,J=class extends I{constructor(e,t,n,r,i,a,o,s,c=new Wl){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 fr,this._utf8Decoder=new pr,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Kc.clone(),this._eraseAttrDataInternal=Kc.clone(),this._onRequestBell=this._register(new L),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new L),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new L),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new L),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new L),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new L),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new L),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new L),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new L),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new L),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new L),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new L),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new L),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 nu(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(H.BEL,()=>this.bell()),this._parser.setExecuteHandler(H.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(H.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(H.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(H.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(H.BS,()=>this.backspace()),this._parser.setExecuteHandler(H.HT,()=>this.tab()),this._parser.setExecuteHandler(H.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(H.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Zo.IND,()=>this.index()),this._parser.setExecuteHandler(Zo.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Zo.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Il(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new Il(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new Il(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new Il(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new Il(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new Il(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new Il(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new Il(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new Il(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new Il(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new Il(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new Il(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 rl)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 Bl((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`),eu))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${eu} 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>Zl&&(a=this._parseStack.position+Zl)}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<Zl&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Zl))),o||this._dirtyRowTracker.clearRange(),e.length>Zl)for(let t=a;t<e.length;t+=Zl){let a=t+Zl<e.length?t+Zl: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=Ol.extractWidth(t);let n=Ol.extractShouldJoin(t),m=n?Ol.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(ur(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 Yc&&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=>!$l(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Bl(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Il(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(Kc));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=Ol.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(H.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(H.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(H.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(H.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(H.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,il),this._charsetService.setgCharset(1,il),this._charsetService.setgCharset(2,il),this._charsetService.setgCharset(3,il);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(`${H.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|=gr.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=Kc.fg,e.bg=Kc.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|=Kc.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=Kc.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|=Kc.fg&16777215,r.bg&=-67108864,r.bg|=Kc.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${H.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${H.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(`${H.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=Kc.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(!$l(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(`${H.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Ql&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Ql&&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(ru(n)){if(r===`?`)t.push({type:0,index:n});else{let e=ql(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=ql(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]);ru(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,il),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(Xl[e[0]],rl[e[1]]||il),!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=Kc.clone(),this._eraseAttrDataInternal=Kc.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 vr;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(`${H.ESC}${e}${H.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)}},nu=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&&(tu=e,e=t,t=tu),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};nu=Qn([F(0,Tr)],nu);function ru(e){return 0<=e&&e<256}var iu=5e7,au=12,ou=50,su=class extends I{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new L),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>iu)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>=au?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>=au)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>ou&&(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()}},cu=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)))}};cu=Qn([F(0,Tr)],cu);var lu=!1,uu=class extends I{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new mi),this._onBinary=this._register(new L),this.onBinary=this._onBinary.event,this._onData=this._register(new L),this.onData=this._onData.event,this._onLineFeed=this._register(new L),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new L),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new L),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new L),this._instantiationService=new Bc,this.optionsService=this._register(new pl(e)),this._instantiationService.setService(jr,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(ul)),this._instantiationService.setService(Tr,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Uc)),this._instantiationService.setService(Ar,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_l)),this._instantiationService.setService(Dr,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Sl)),this._instantiationService.setService(Er,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Ol)),this._instantiationService.setService(Nr,this.unicodeService),this._charsetService=this._instantiationService.createInstance(kl),this._instantiationService.setService(Or,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(cu),this._instantiationService.setService(Mr,this._oscLinkService),this._inputHandler=this._register(new J(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(xi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(xi.forward(this._bufferService.onResize,this._onResize)),this._register(xi.forward(this.coreService.onData,this._onData)),this._register(xi.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 su((e,t)=>this._inputHandler.parse(e,t))),this._register(xi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new L),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&&!lu&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),lu=!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,cl),t=Math.max(t,ll),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(Al.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Al(this._bufferService),!1))),this._windowsWrappingHeuristics.value=di(()=>{for(let t of e)t.dispose()})}}},du={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 fu(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?H.ESC+`OA`:H.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?H.ESC+`OD`:H.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?H.ESC+`OC`:H.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?H.ESC+`OB`:H.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:H.DEL,e.altKey&&(i.key=H.ESC+i.key);break;case 9:if(e.shiftKey){i.key=H.ESC+`[Z`;break}i.key=H.HT,i.cancel=!0;break;case 13:i.key=e.altKey?H.ESC+H.CR:H.CR,i.cancel=!0;break;case 27:i.key=H.ESC,e.altKey&&(i.key=H.ESC+H.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?H.ESC+`[1;`+(a+1)+`D`:t?H.ESC+`OD`:H.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?H.ESC+`[1;`+(a+1)+`C`:t?H.ESC+`OC`:H.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?H.ESC+`[1;`+(a+1)+`A`:t?H.ESC+`OA`:H.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?H.ESC+`[1;`+(a+1)+`B`:t?H.ESC+`OB`:H.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=H.ESC+`[2~`);break;case 46:i.key=a?H.ESC+`[3;`+(a+1)+`~`:H.ESC+`[3~`;break;case 36:i.key=a?H.ESC+`[1;`+(a+1)+`H`:t?H.ESC+`OH`:H.ESC+`[H`;break;case 35:i.key=a?H.ESC+`[1;`+(a+1)+`F`:t?H.ESC+`OF`:H.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?H.ESC+`[5;`+(a+1)+`~`:H.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?H.ESC+`[6;`+(a+1)+`~`:H.ESC+`[6~`;break;case 112:i.key=a?H.ESC+`[1;`+(a+1)+`P`:H.ESC+`OP`;break;case 113:i.key=a?H.ESC+`[1;`+(a+1)+`Q`:H.ESC+`OQ`;break;case 114:i.key=a?H.ESC+`[1;`+(a+1)+`R`:H.ESC+`OR`;break;case 115:i.key=a?H.ESC+`[1;`+(a+1)+`S`:H.ESC+`OS`;break;case 116:i.key=a?H.ESC+`[15;`+(a+1)+`~`:H.ESC+`[15~`;break;case 117:i.key=a?H.ESC+`[17;`+(a+1)+`~`:H.ESC+`[17~`;break;case 118:i.key=a?H.ESC+`[18;`+(a+1)+`~`:H.ESC+`[18~`;break;case 119:i.key=a?H.ESC+`[19;`+(a+1)+`~`:H.ESC+`[19~`;break;case 120:i.key=a?H.ESC+`[20;`+(a+1)+`~`:H.ESC+`[20~`;break;case 121:i.key=a?H.ESC+`[21;`+(a+1)+`~`:H.ESC+`[21~`;break;case 122:i.key=a?H.ESC+`[23;`+(a+1)+`~`:H.ESC+`[23~`;break;case 123:i.key=a?H.ESC+`[24;`+(a+1)+`~`:H.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=H.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=H.DEL:e.keyCode===219?i.key=H.ESC:e.keyCode===220?i.key=H.FS:e.keyCode===221&&(i.key=H.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=du[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=H.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=H.ESC+n}else if(e.keyCode===32)i.key=H.ESC+(e.ctrlKey?H.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=H.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=H.US),e.key===`@`&&(i.key=H.NUL))}return i}var pu=0,mu=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new ic,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new ic,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||(pu=this._search(t),pu===-1)||this._getKey(this._array[pu])!==t)return!1;do if(this._array[pu]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pu),!0;while(++pu<this._array.length&&this._getKey(this._array[pu])===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&&(pu=this._search(e),!(pu<0||pu>=this._array.length)&&this._getKey(this._array[pu])===e))do yield this._array[pu];while(++pu<this._array.length&&this._getKey(this._array[pu])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pu=this._search(e),!(pu<0||pu>=this._array.length)&&this._getKey(this._array[pu])===e))do t(this._array[pu]);while(++pu<this._array.length&&this._getKey(this._array[pu])===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}},hu=0,gu=0,_u=class extends I{constructor(){super(),this._decorations=new mu(e=>e?.marker.line),this._onDecorationRegistered=this._register(new L),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new L),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(di(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new vu(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=>{hu=t.options.x??0,gu=hu+(t.options.width??1),e>=hu&&e<gu&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},vu=class extends pi{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new L),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new L),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?W.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?W.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},yu=1e3,bu=class{constructor(e,t=yu){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)}},xu=20,Su=class extends I{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new bu(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(`
|
|
63
63
|
`))),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(B(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(di(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<xu+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
64
64
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===xu+1&&(this._liveRegion.textContent+=nr.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})`}};Su=Qn([F(1,kr),F(2,Rr),F(3,Br)],Su);var Cu=class extends I{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new L),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new L),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(di(()=>{li(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(B(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(B(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(B(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(B(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&&wu(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,li(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}}};Cu=Qn([F(1,zr),F(2,Br),F(3,Tr),F(4,Wr)],Cu);function wu(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 Tu=class extends uu{constructor(e={}){super(e),this._linkifier=this._register(new mi),this.browser=Vs,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new mi),this._onCursorMove=this._register(new L),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new L),this.onKey=this._onKey.event,this._onRender=this._register(new L),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new L),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new L),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new L),this.onBell=this._onBell.event,this._onFocus=this._register(new L),this._onBlur=this._register(new L),this._onA11yCharEmitter=this._register(new L),this._onA11yTabEmitter=this._register(new L),this._onWillOpen=this._register(new L),this._setup(),this._decorationService=this._instantiationService.createInstance(_u),this._instantiationService.setService(Pr,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Is),this._instantiationService.setService(Wr,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Fr)),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(xi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(xi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(xi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(xi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(di(()=>{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=U.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${H.ESC}]${n};${Yl(r)}${Qo.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=as.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=as.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(Su,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(H.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(H.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(B(this.element,`copy`,e=>{this.hasSelection()&&ar(e,this._selectionService)}));let e=e=>or(e,this.textarea,this.coreService,this.optionsService);this._register(B(this.textarea,`paste`,e)),this._register(B(this.element,`paste`,e)),Gs?this._register(B(this.element,`mousedown`,e=>{e.button===2&&lr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(B(this.element,`contextmenu`,e=>{lr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),$s&&this._register(B(this.element,`auxclick`,e=>{e.button===1&&cr(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(B(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(B(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(B(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(B(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(B(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(B(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(B(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(B(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`,er.get()),ec||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(Ps,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(Rr,this._coreBrowserService),this._register(B(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(B(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(As,this._document,this._helperContainer),this._instantiationService.setService(Lr,this._charSizeService),this._themeService=this._instantiationService.createInstance(Rc),this._instantiationService.setService(Ur,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ds),this._instantiationService.setService(Hr,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(oc,this.rows,this.screenElement)),this._instantiationService.setService(Br,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($o,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(zs),this._instantiationService.setService(zr,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Cu,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(Wo,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(Oc,this.element,this.screenElement,r)),this._instantiationService.setService(Vr,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(xi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Go,this.screenElement)),this._register(B(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(Su,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Xo,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Xo,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ks,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(B(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(B(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=H.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){sr(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=fu(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===H.ETX||n.key===H.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)&&(Eu(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(Kc));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(H.ESC+`[I`):this.coreService.triggerDataEvent(H.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(`${H.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(`${H.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function Eu(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Du=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)}},Ou=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 vr)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},ku=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 Ou(t)}getNullCell(){return new vr}},Au=class extends I{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new L),this.onBufferChange=this._onBufferChange.event,this._normal=new ku(this._core.buffers.normal,`normal`),this._alternate=new ku(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)}},ju=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)}},Mu=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}},Nu=[`cols`,`rows`],Pu=0,Fu=class extends I{constructor(e){super(),this._core=this._register(new Tu(e)),this._addonManager=this._register(new Du),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(Nu.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 ju(this._core),this._parser}get unicode(){return this._checkProposedApi(),new Mu(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 Au(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
|
|
65
|
-
`,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 er.get()},set promptLabel(e){er.set(e)},get tooMuchOutput(){return nr.get()},set tooMuchOutput(e){nr.set(e)}}}_verifyIntegers(...e){for(Pu of e)if(Pu===1/0||isNaN(Pu)||Pu%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(Pu of e)if(Pu&&(Pu===1/0||isNaN(Pu)||Pu%1!=0||Pu<0))throw Error(`This API only accepts positive integers`)}},Iu=2,Lu=1,Ru=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(Iu,Math.floor(u/e.css.cell.width)),rows:Math.max(Lu,Math.floor(l/e.css.cell.height))}}},zu=`terminal-right-rail`,Bu=5,Vu=20,Hu=5,Uu=240,Wu=120,Gu={checking:`检查中`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`},Ku=e=>`${zu}-${e}`,qu=e=>({id:Ku(e),title:String(e),phase:`checking`});function Ju({workspaceId:e,workspaceLabel:t,connected:n,sendCommand:r,registerSink:i}){let[a,o]=(0,p.useState)(()=>[qu(1)]),[s,c]=(0,p.useState)(()=>Ku(1)),l=(0,p.useRef)(s);l.current=s;let u=(0,p.useRef)(a);u.current=a;let d=(0,p.useRef)(e);d.current=e;let f=(0,p.useRef)(r);f.current=r;let h=(0,p.useRef)(new Set),g=(0,p.useRef)(!1),_=(0,p.useRef)(new Map),v=(0,p.useRef)(new Map),y=(0,p.useRef)(new Map),[b,x]=(0,p.useState)(0),S=(0,p.useRef)(n),C=(0,p.useCallback)(e=>{_.current.get(e)?.dispose(),_.current.delete(e),v.current.delete(e),y.current.delete(e)},[]),w=(0,p.useCallback)(e=>{let t=_.current.get(e),n=v.current.get(e);if(!t||!n)return;let r=y.current.get(e);if(!(!r||r.clientWidth<2||r.clientHeight<2)){try{n.fit()}catch{return}t.cols<Vu||t.rows<Hu||t.cols>Uu||t.rows>Wu||h.current.has(e)&&f.current({type:`terminal.resize`,sessionId:e,cols:t.cols,rows:t.rows})}},[]),T=(0,p.useCallback)((e,t)=>{if(!t){y.current.delete(e);return}if(y.current.set(e,t),_.current.has(e))return;let n=getComputedStyle(t),r=(e,t)=>n.getPropertyValue(e).trim()||t,i=new Fu({cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:r(`--term-fg`,`#dbe4f0`),cursor:r(`--term-fg`,`#dbe4f0`),selectionBackground:r(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),a=new Ru;i.loadAddon(a),i.open(t),i.onData(t=>{h.current.has(e)&&f.current({type:`terminal.input`,sessionId:e,data:t})}),i.onResize(({cols:t,rows:n})=>{h.current.has(e)&&f.current({type:`terminal.resize`,sessionId:e,cols:t,rows:n})}),_.current.set(e,i),v.current.set(e,a),requestAnimationFrame(()=>w(e)),x(e=>e+1)},[w]),ee=(0,p.useCallback)(e=>{_.current.get(e)?.reset()},[]),E=(0,p.useCallback)(e=>{let t=d.current,n=_.current.get(e);if(!t||!n||h.current.has(e))return;n.reset(),w(e),o(t=>t.map(t=>t.id===e?{...t,phase:`starting`,exitCode:void 0,reason:``}:t));let r=Math.max(Vu,Math.min(Uu,n.cols||80)),i=Math.max(Hu,Math.min(Wu,n.rows||24));f.current({type:`terminal.open`,sessionId:e,workspaceId:t,cols:r,rows:i})?(h.current.add(e),o(t=>t.map(t=>t.id===e?{...t,phase:`running`}:t))):o(t=>t.map(t=>t.id===e?{...t,phase:`exited`,reason:`Super Pi 服务的连接尚未就绪`}:t))},[w]);(0,p.useEffect)(()=>{let e=!1;return fetch(`/api/terminal`).then(e=>e.json()).then(t=>{e||(t.enabled?(g.current=!0,o(e=>e.map(e=>e.phase===`checking`?{...e,phase:`starting`}:e))):o(e=>e.map(e=>({...e,phase:`unavailable`,reason:t.reason??`终端未启用`}))))}).catch(()=>{e||o(e=>e.map(e=>({...e,phase:`unavailable`,reason:`无法读取终端状态`})))}),()=>{e=!0}},[]),(0,p.useEffect)(()=>{if(g.current)for(let e of a)(e.phase===`checking`||e.phase===`starting`)&&!h.current.has(e.id)&&E(e.id)},[a,E,b]);let te=(0,p.useCallback)(e=>{e.type===`terminal.output`?_.current.get(e.sessionId)?.write(e.data):e.type===`terminal.exit`?(h.current.delete(e.sessionId),ee(e.sessionId),o(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t))):e.type===`terminal.error`?(h.current.delete(e.sessionId),ee(e.sessionId),o(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t))):e.type===`terminal.status`&&!e.enabled&&o(t=>t.map(t=>({...t,phase:`unavailable`,reason:e.reason??`终端未启用`})))},[ee]);(0,p.useEffect)(()=>(i(te),()=>i(void 0)),[te,i]),(0,p.useEffect)(()=>()=>{for(let e of h.current)f.current({type:`terminal.close`,sessionId:e});h.current.clear();for(let e of _.current.keys())C(e)},[C]),(0,p.useEffect)(()=>{let e=n&&!S.current;S.current=n,e&&o(e=>e.map(e=>e.phase===`exited`&&!e.deliberate?{...e,phase:`starting`,reason:``}:e))},[n]),(0,p.useLayoutEffect)(()=>{let e=new ResizeObserver(()=>w(l.current));for(let t of y.current.values())e.observe(t);return w(l.current),()=>e.disconnect()},[w,a,b]);let D=(0,p.useCallback)(e=>{c(e),requestAnimationFrame(()=>w(e))},[w]),ne=(0,p.useCallback)(()=>{let e=new Set(u.current.map(e=>e.title)),t=1;for(;e.has(String(t));)t+=1;let n=qu(t);o(e=>e.length>=Bu?e:[...e,n]),c(n.id)},[]),re=(0,p.useCallback)(e=>{f.current({type:`terminal.close`,sessionId:e}),h.current.delete(e),C(e),o(t=>{if(t.length<=1)return t;let n=t.findIndex(t=>t.id===e),r=t.filter(t=>t.id!==e);return l.current===e&&c(r[Math.min(n,r.length-1)].id),r})},[C]),ie=(0,p.useCallback)(()=>{let e=l.current;f.current({type:`terminal.close`,sessionId:e}),h.current.delete(e),o(t=>t.map(t=>t.id===e?{...t,phase:`exited`,deliberate:!0}:t))},[]),O=a.find(e=>e.id===s)??a[0];return O?O.phase===`checking`?(0,m.jsx)(`p`,{className:`rail-empty`,"data-terminal-phase":`checking`,children:`正在检查终端状态…`}):O.phase===`unavailable`?(0,m.jsxs)(`div`,{className:`terminal-unavailable`,"data-terminal-phase":`unavailable`,children:[(0,m.jsx)(`p`,{className:`terminal-unavailable-reason`,children:O.reason}),(0,m.jsx)(`p`,{className:`rail-empty`,children:`终端仅接受本机与局域网连接。`})]}):(0,m.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":O.phase,children:[(0,m.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[a.map(e=>(0,m.jsxs)(`div`,{className:`terminal-tab${e.id===s?` is-active`:``}`,children:[(0,m.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===s,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>D(e.id),title:Gu[e.phase],children:[(0,m.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.phase}`,"aria-hidden":`true`}),e.title]}),(0,m.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)),a.length<Bu&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,"data-terminal-add":`1`,onClick:ne,title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,m.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,m.jsxs)(`span`,{className:`terminal-status terminal-status-${O.phase}`,"data-terminal-status":O.phase,children:[(0,m.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),Gu[O.phase]]}),(0,m.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[t&&(0,m.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),O.phase===`running`?(0,m.jsx)(`button`,{type:`button`,className:`terminal-close-btn`,"data-terminal-close":`1`,onClick:ie,children:`结束会话`}):(0,m.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,onClick:()=>E(O.id),children:`重新打开`})]})]}),O.reason&&(0,m.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,children:O.reason}),O.phase===`exited`&&O.exitCode!==void 0&&O.exitCode!==0&&(0,m.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,O.exitCode,`。`]}),(0,m.jsx)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:a.map(e=>(0,m.jsx)(`div`,{ref:t=>T(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===s?`block`:`none`}},e.id))})]}):null}var Yu=`.super-pi-tool.json`,Xu=512e3,Y=/^[a-z0-9][a-z0-9-]{0,63}$/,Zu=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function X(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${Yu})。`}}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:`工具文件合计超过 ${rd(Xu)} 的上限。`};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`||!Zu.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 Z(e){let t=e.trim().toLowerCase();return t?Y.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function Q(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 Qu(e){return`${e.slug}${Yu}`}function $u(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}${Yu}`}:{ok:!1,reason:`请填写文件名。`}}function ed(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function td(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 nd(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 rd(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function id(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var ad={workspaces:[],conversations:[],subagentRuns:[]},od=e=>e.nativeEvent.isComposing||e.keyCode===229,sd=(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)return e;let a=Math.max(0,Math.min(n,r.length-1));if(a===i)return e;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s);let c=[...e],l=0;for(let e=0;e<c.length;e+=1)c[e].role===`user`&&c[e].delivery&&(c[e]=o[l++]);return c},cd=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)},ld=6e4,ud=60*ld,dd=24*ud,fd=7*dd,pd=30*dd,md=365*dd,hd=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<ud?`${Math.max(1,Math.floor(r/ld))}m ago`:r<dd?`${Math.floor(r/ud)}h ago`:r<fd?`${Math.floor(r/dd)}d ago`:r<pd?`${Math.floor(r/fd)}w ago`:r<md?`${Math.floor(r/pd)}mo ago`:`${Math.floor(r/md)}y ago`},gd=(e,t)=>e.updatedAt<t.updatedAt?1:e.updatedAt>t.updatedAt?-1:0,_d=(e,t)=>{let n=e.archivedAt??``,r=t.archivedAt??``;return n<r?1:n>r?-1:0},vd=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`)}`},yd=1e3,bd=3e4,xd=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 Sd({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,p.useRef)(null),[o,s]=(0,p.useState)({left:t,top:n});(0,p.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,p.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`,i,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await xd(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,m.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,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function Cd({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a}){let o=(0,p.useRef)(null),[s,c]=(0,p.useState)({left:t,top:n});(0,p.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let r=e.getBoundingClientRect();c({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,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{o.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`,a,!0),window.removeEventListener(`resize`,i)}},[a]);let l=async()=>{let t=await xd(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,m.jsxs)(`div`,{ref:o,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:s.left,top:s.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void l(),children:`复制会话 ID`}),(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var wd={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},Td={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},Ed={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},Dd=`图文`,Od=e=>e.imageInput?Dd:void 0,kd=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),Ad=(e,t)=>{let n=kd(t.trim());return n?e.filter(e=>kd(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function jd({onClose:e,onCreate:t}){let[n,r]=(0,p.useState)(),[i,a]=(0,p.useState)(!0),[o,s]=(0,p.useState)(),[c,l]=(0,p.useState)(``),[u,d]=(0,p.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,p.useEffect)(()=>{f()},[]),(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let h=e=>{e?.preventDefault();let t=u.trim();t&&f(t)};return(0,m.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,m.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`选择工作区目录`}),(0,m.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:h,children:[(0,m.jsx)(`input`,{className:`picker-path-input`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(od(e)?e.preventDefault():(e.preventDefault(),h()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,m.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!u.trim()||i,children:`跳转`}),(0,m.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,m.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,m.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),n?.homeDir&&(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(`~`),title:n.homeDir,children:`🏠 主目录`}),n?.drives?.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(e),children:e},e))]}):null,(0,m.jsxs)(`div`,{className:`picker-list`,children:[i&&(0,m.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!i&&o&&(0,m.jsxs)(`div`,{className:`picker-error`,children:[o,(0,m.jsx)(`button`,{onClick:()=>void f(n?.path||u),children:`重试`})]}),!i&&!o&&n?.entries.map(e=>(0,m.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void f(e.path),children:[`📁 `,e.name]},e.path)),!i&&!o&&n&&n.entries.length===0&&(0,m.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!i&&!o&&n?.truncated&&(0,m.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,m.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,m.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(od(e)?e.preventDefault():(e.preventDefault(),c.trim()&&n&&t(c.trim(),n.path)))},placeholder:`工作区名称`})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,m.jsx)(`button`,{className:`picker-ok`,disabled:!c.trim()||i||!!o||!n,onClick:()=>n&&t(c.trim(),n.path),children:`使用这个目录`})]})]})})}var Md={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},Nd=10;function Pd(e,t){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`}function Fd(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 Id=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function Ld(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 Rd={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function zd({task:e,initialOutput:t,expanded:n}){let[r,i]=(0,p.useState)(t);(0,p.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,m.jsxs)(m.Fragment,{children:[!n&&a&&(0,m.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:a.split(`
|
|
65
|
+
`,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 er.get()},set promptLabel(e){er.set(e)},get tooMuchOutput(){return nr.get()},set tooMuchOutput(e){nr.set(e)}}}_verifyIntegers(...e){for(Pu of e)if(Pu===1/0||isNaN(Pu)||Pu%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(Pu of e)if(Pu&&(Pu===1/0||isNaN(Pu)||Pu%1!=0||Pu<0))throw Error(`This API only accepts positive integers`)}},Iu=2,Lu=1,Ru=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(Iu,Math.floor(u/e.css.cell.width)),rows:Math.max(Lu,Math.floor(l/e.css.cell.height))}}},zu=`terminal-right-rail`,Bu=5,Vu=20,Hu=5,Uu=240,Wu=120,Gu={checking:`检查中`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`},Ku=e=>`${zu}-${e}`,qu=e=>({id:Ku(e),title:String(e),phase:`checking`});function Ju({workspaceId:e,workspaceLabel:t,connected:n,sendCommand:r,registerSink:i}){let[a,o]=(0,p.useState)(()=>[qu(1)]),[s,c]=(0,p.useState)(()=>Ku(1)),l=(0,p.useRef)(s);l.current=s;let u=(0,p.useRef)(a);u.current=a;let d=(0,p.useRef)(e);d.current=e;let f=(0,p.useRef)(r);f.current=r;let h=(0,p.useRef)(new Set),g=(0,p.useRef)(!1),_=(0,p.useRef)(new Map),v=(0,p.useRef)(new Map),y=(0,p.useRef)(new Map),[b,x]=(0,p.useState)(0),S=(0,p.useRef)(n),C=(0,p.useCallback)(e=>{_.current.get(e)?.dispose(),_.current.delete(e),v.current.delete(e),y.current.delete(e)},[]),w=(0,p.useCallback)(e=>{let t=_.current.get(e),n=v.current.get(e);if(!t||!n)return;let r=y.current.get(e);if(!(!r||r.clientWidth<2||r.clientHeight<2)){try{n.fit()}catch{return}t.cols<Vu||t.rows<Hu||t.cols>Uu||t.rows>Wu||h.current.has(e)&&f.current({type:`terminal.resize`,sessionId:e,cols:t.cols,rows:t.rows})}},[]),T=(0,p.useCallback)((e,t)=>{if(!t){y.current.delete(e);return}if(y.current.set(e,t),_.current.has(e))return;let n=getComputedStyle(t),r=(e,t)=>n.getPropertyValue(e).trim()||t,i=new Fu({cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:r(`--term-fg`,`#dbe4f0`),cursor:r(`--term-fg`,`#dbe4f0`),selectionBackground:r(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),a=new Ru;i.loadAddon(a),i.open(t),i.onData(t=>{h.current.has(e)&&f.current({type:`terminal.input`,sessionId:e,data:t})}),i.onResize(({cols:t,rows:n})=>{h.current.has(e)&&f.current({type:`terminal.resize`,sessionId:e,cols:t,rows:n})}),_.current.set(e,i),v.current.set(e,a),requestAnimationFrame(()=>w(e)),x(e=>e+1)},[w]),ee=(0,p.useCallback)(e=>{_.current.get(e)?.reset()},[]),E=(0,p.useCallback)(e=>{let t=d.current,n=_.current.get(e);if(!t||!n||h.current.has(e))return;n.reset(),w(e),o(t=>t.map(t=>t.id===e?{...t,phase:`starting`,exitCode:void 0,reason:``}:t));let r=Math.max(Vu,Math.min(Uu,n.cols||80)),i=Math.max(Hu,Math.min(Wu,n.rows||24));f.current({type:`terminal.open`,sessionId:e,workspaceId:t,cols:r,rows:i})?(h.current.add(e),o(t=>t.map(t=>t.id===e?{...t,phase:`running`}:t))):o(t=>t.map(t=>t.id===e?{...t,phase:`exited`,reason:`Super Pi 服务的连接尚未就绪`}:t))},[w]);(0,p.useEffect)(()=>{let e=!1;return fetch(`/api/terminal`).then(e=>e.json()).then(t=>{e||(t.enabled?(g.current=!0,o(e=>e.map(e=>e.phase===`checking`?{...e,phase:`starting`}:e))):o(e=>e.map(e=>({...e,phase:`unavailable`,reason:t.reason??`终端未启用`}))))}).catch(()=>{e||o(e=>e.map(e=>({...e,phase:`unavailable`,reason:`无法读取终端状态`})))}),()=>{e=!0}},[]),(0,p.useEffect)(()=>{if(g.current)for(let e of a)(e.phase===`checking`||e.phase===`starting`)&&!h.current.has(e.id)&&E(e.id)},[a,E,b]);let te=(0,p.useCallback)(e=>{e.type===`terminal.output`?_.current.get(e.sessionId)?.write(e.data):e.type===`terminal.exit`?(h.current.delete(e.sessionId),ee(e.sessionId),o(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t))):e.type===`terminal.error`?(h.current.delete(e.sessionId),ee(e.sessionId),o(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t))):e.type===`terminal.status`&&!e.enabled&&o(t=>t.map(t=>({...t,phase:`unavailable`,reason:e.reason??`终端未启用`})))},[ee]);(0,p.useEffect)(()=>(i(te),()=>i(void 0)),[te,i]),(0,p.useEffect)(()=>()=>{for(let e of h.current)f.current({type:`terminal.close`,sessionId:e});h.current.clear();for(let e of _.current.keys())C(e)},[C]),(0,p.useEffect)(()=>{let e=n&&!S.current;S.current=n,e&&o(e=>e.map(e=>e.phase===`exited`&&!e.deliberate?{...e,phase:`starting`,reason:``}:e))},[n]),(0,p.useLayoutEffect)(()=>{let e=new ResizeObserver(()=>w(l.current));for(let t of y.current.values())e.observe(t);return w(l.current),()=>e.disconnect()},[w,a,b]);let D=(0,p.useCallback)(e=>{c(e),requestAnimationFrame(()=>w(e))},[w]),ne=(0,p.useCallback)(()=>{let e=new Set(u.current.map(e=>e.title)),t=1;for(;e.has(String(t));)t+=1;let n=qu(t);o(e=>e.length>=Bu?e:[...e,n]),c(n.id)},[]),re=(0,p.useCallback)(e=>{f.current({type:`terminal.close`,sessionId:e}),h.current.delete(e),C(e),o(t=>{if(t.length<=1)return t;let n=t.findIndex(t=>t.id===e),r=t.filter(t=>t.id!==e);return l.current===e&&c(r[Math.min(n,r.length-1)].id),r})},[C]),ie=(0,p.useCallback)(()=>{let e=l.current;f.current({type:`terminal.close`,sessionId:e}),h.current.delete(e),o(t=>t.map(t=>t.id===e?{...t,phase:`exited`,deliberate:!0}:t))},[]),O=a.find(e=>e.id===s)??a[0];return O?O.phase===`checking`?(0,m.jsx)(`p`,{className:`rail-empty`,"data-terminal-phase":`checking`,children:`正在检查终端状态…`}):O.phase===`unavailable`?(0,m.jsxs)(`div`,{className:`terminal-unavailable`,"data-terminal-phase":`unavailable`,children:[(0,m.jsx)(`p`,{className:`terminal-unavailable-reason`,children:O.reason}),(0,m.jsx)(`p`,{className:`rail-empty`,children:`终端仅接受本机与局域网连接。`})]}):(0,m.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":O.phase,children:[(0,m.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[a.map(e=>(0,m.jsxs)(`div`,{className:`terminal-tab${e.id===s?` is-active`:``}`,children:[(0,m.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===s,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>D(e.id),title:Gu[e.phase],children:[(0,m.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.phase}`,"aria-hidden":`true`}),e.title]}),(0,m.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)),a.length<Bu&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,"data-terminal-add":`1`,onClick:ne,title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,m.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,m.jsxs)(`span`,{className:`terminal-status terminal-status-${O.phase}`,"data-terminal-status":O.phase,children:[(0,m.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),Gu[O.phase]]}),(0,m.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[t&&(0,m.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),O.phase===`running`?(0,m.jsx)(`button`,{type:`button`,className:`terminal-close-btn`,"data-terminal-close":`1`,onClick:ie,children:`结束会话`}):(0,m.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,onClick:()=>E(O.id),children:`重新打开`})]})]}),O.reason&&(0,m.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,children:O.reason}),O.phase===`exited`&&O.exitCode!==void 0&&O.exitCode!==0&&(0,m.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,O.exitCode,`。`]}),(0,m.jsx)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:a.map(e=>(0,m.jsx)(`div`,{ref:t=>T(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===s?`block`:`none`}},e.id))})]}):null}var Yu=`.super-pi-tool.json`,Xu=512e3,Y=/^[a-z0-9][a-z0-9-]{0,63}$/,Zu=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function X(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${Yu})。`}}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:`工具文件合计超过 ${rd(Xu)} 的上限。`};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`||!Zu.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 Z(e){let t=e.trim().toLowerCase();return t?Y.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function Q(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 Qu(e){return`${e.slug}${Yu}`}function $u(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}${Yu}`}:{ok:!1,reason:`请填写文件名。`}}function ed(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function td(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 nd(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 rd(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function id(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var ad={workspaces:[],conversations:[],subagentRuns:[]},od=e=>e.nativeEvent.isComposing||e.keyCode===229,sd=(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},cd=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)},ld=6e4,ud=60*ld,dd=24*ud,fd=7*dd,pd=30*dd,md=365*dd,hd=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<ud?`${Math.max(1,Math.floor(r/ld))}m ago`:r<dd?`${Math.floor(r/ud)}h ago`:r<fd?`${Math.floor(r/dd)}d ago`:r<pd?`${Math.floor(r/fd)}w ago`:r<md?`${Math.floor(r/pd)}mo ago`:`${Math.floor(r/md)}y ago`},gd=(e,t)=>e.updatedAt<t.updatedAt?1:e.updatedAt>t.updatedAt?-1:0,_d=(e,t)=>{let n=e.archivedAt??``,r=t.archivedAt??``;return n<r?1:n>r?-1:0},vd=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`)}`},yd=1e3,bd=3e4,xd=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 Sd({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,p.useRef)(null),[o,s]=(0,p.useState)({left:t,top:n});(0,p.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,p.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`,i,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await xd(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,m.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,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function Cd({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a}){let o=(0,p.useRef)(null),[s,c]=(0,p.useState)({left:t,top:n});(0,p.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let r=e.getBoundingClientRect();c({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,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{o.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`,a,!0),window.removeEventListener(`resize`,i)}},[a]);let l=async()=>{let t=await xd(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,m.jsxs)(`div`,{ref:o,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:s.left,top:s.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void l(),children:`复制会话 ID`}),(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var wd={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},Td={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},Ed={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},Dd=`图文`,Od=e=>e.imageInput?Dd:void 0,kd=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),Ad=(e,t)=>{let n=kd(t.trim());return n?e.filter(e=>kd(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function jd({onClose:e,onCreate:t}){let[n,r]=(0,p.useState)(),[i,a]=(0,p.useState)(!0),[o,s]=(0,p.useState)(),[c,l]=(0,p.useState)(``),[u,d]=(0,p.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,p.useEffect)(()=>{f()},[]),(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let h=e=>{e?.preventDefault();let t=u.trim();t&&f(t)};return(0,m.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,m.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`选择工作区目录`}),(0,m.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:h,children:[(0,m.jsx)(`input`,{className:`picker-path-input`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(od(e)?e.preventDefault():(e.preventDefault(),h()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,m.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!u.trim()||i,children:`跳转`}),(0,m.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,m.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,m.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),n?.homeDir&&(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(`~`),title:n.homeDir,children:`🏠 主目录`}),n?.drives?.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(e),children:e},e))]}):null,(0,m.jsxs)(`div`,{className:`picker-list`,children:[i&&(0,m.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!i&&o&&(0,m.jsxs)(`div`,{className:`picker-error`,children:[o,(0,m.jsx)(`button`,{onClick:()=>void f(n?.path||u),children:`重试`})]}),!i&&!o&&n?.entries.map(e=>(0,m.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void f(e.path),children:[`📁 `,e.name]},e.path)),!i&&!o&&n&&n.entries.length===0&&(0,m.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!i&&!o&&n?.truncated&&(0,m.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,m.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,m.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(od(e)?e.preventDefault():(e.preventDefault(),c.trim()&&n&&t(c.trim(),n.path)))},placeholder:`工作区名称`})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,m.jsx)(`button`,{className:`picker-ok`,disabled:!c.trim()||i||!!o||!n,onClick:()=>n&&t(c.trim(),n.path),children:`使用这个目录`})]})]})})}var Md={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},Nd=10;function Pd(e,t){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`}function Fd(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 Id=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function Ld(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 Rd={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function zd({task:e,initialOutput:t,expanded:n}){let[r,i]=(0,p.useState)(t);(0,p.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,m.jsxs)(m.Fragment,{children:[!n&&a&&(0,m.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:a.split(`
|
|
66
66
|
`).slice(-1)[0]}),n&&(0,m.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:a||`等待输出…`})]})}function Bd({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,m.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,m.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,m.jsxs)(`div`,{className:`call-head-row`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,m.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,m.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,m.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,m.jsx)(`span`,{className:`call-duration`,children:Ld(e.durationMs)}),e.backgroundTask&&(0,m.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,m.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,m.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,m.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:e.live.split(`
|
|
67
67
|
`).slice(-1)[0]}),n&&(0,m.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,m.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,m.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,m.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,m.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,m.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,m.jsxs)(`div`,{className:`call-result-head`,children:[(0,m.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,m.jsx)(Vd,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,m.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,m.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,m.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function Vd({index:e,text:t}){let[n,r]=(0,p.useState)(!1);return(0,m.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await xd(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function Hd({messageId:e,nestedCount:t,liveCall:n,liveExtra:r,preview:i,expanded:a,onToggle:o,children:s}){return(0,m.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":a?`true`:`false`,"data-thinking-calls":t,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":a,"aria-label":`${a?`折叠`:`展开`}这段思考`,title:a?`折叠这段思考`:`展开这段思考`,onClick:o}),(0,m.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":a,title:a?`折叠这段思考`:`展开这段思考`,onClick:o,children:[(0,m.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,m.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!a&&n&&(0,m.jsxs)(`span`,{className:`thinking-live`,"data-thinking-live":n,"data-thinking-live-extra":r??0,children:[(0,m.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:`⚙`}),`正在执行 `,n,r?` 等 ${r+1} 个`:``]}),!a&&i&&(0,m.jsx)(`span`,{className:`thinking-preview`,title:i,children:i})]}),a&&(0,m.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:s})]})}function Ud({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,h]=(0,p.useState)(0);(0,p.useEffect)(()=>{if(!l)return;h(Date.now());let e=window.setInterval(()=>h(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let g=Date.parse(e.startedAt),_=l&&f>0&&Number.isFinite(g)?f-g:void 0,v=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,m.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,m.jsxs)(`div`,{className:`subagent-head`,children:[(0,m.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,m.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,m.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,m.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,m.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?_!==void 0&&(0,m.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":_,children:[`已运行 `,Ld(_)]}):e.durationMs!==void 0&&(0,m.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,Ld(e.durationMs)]}),l&&(0,m.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,m.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,m.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,m.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,m.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,m.jsx)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:u||(l?`…`:e.outputTruncated?`(已按 50 KB 上限截断,浏览器仍收到完整内容)`:`(没有输出)`)}),e.failure&&(0,m.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,m.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,m.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:Rd[e.failure.stage]}),e.failure.stage===`tool`&&v&&(0,m.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,v]}),o.length>0&&(0,m.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,m.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,children:e.error}),o.length>0&&(0,m.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,m.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,m.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,m.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,m.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,m.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,m.jsx)(`span`,{className:`subagent-tool-duration`,children:Ld(e.durationMs)})]},`${t}:${e.label}`))]}),e.usage&&(0,m.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,m.jsxs)(`span`,{children:[e.usage.turns,` turns`]}),(0,m.jsxs)(`span`,{children:[`↑`,Id(e.usage.input)]}),(0,m.jsxs)(`span`,{children:[`↓`,Id(e.usage.output)]}),e.usage.cacheRead>0&&(0,m.jsxs)(`span`,{children:[`cache↓`,Id(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,m.jsxs)(`span`,{children:[`cache↑`,Id(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,m.jsxs)(`span`,{children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,m.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function Wd({messages:e,running:t,onSteer:n,onInterrupt:r,onSend:i,onCancel:a,onEdit:o}){let[s,c]=(0,p.useState)(!1);if(!e.length)return null;let l=e.filter(e=>e.delivery===`sending`).length;return(0,m.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-queue-count":e.length,"data-queue-sending":l,"aria-label":`排队等待回答的消息`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!s,onClick:()=>c(e=>!e),children:[(0,m.jsx)(`span`,{className:`chevron`,children:s?`▸`:`▾`}),(0,m.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),l>0&&(0,m.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,l,` 条`]}),s&&(0,m.jsx)(`span`,{className:`queue-dock-preview`,children:Gd(e[0])})]}),!s&&(0,m.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((s,c)=>(0,m.jsx)(qd,{message:s,order:c+1,total:e.length,running:t,onSteer:n,onInterrupt:r,onSend:i,onCancel:a,onEdit:o},s.id))})]})}function Gd(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function Kd(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};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 qd({message:e,order:t,total:n,running:r,onSteer:i,onInterrupt:a,onSend:o,onCancel:s,onEdit:c}){let[l,u]=(0,p.useState)(!1),[d,f]=(0,p.useState)(e.content),h=e.delivery===`sending`,g=e.role===`tool`,{label:_,state:v}=g?Kd(e):{label:Gd(e),state:`user`},y=()=>{let t=d.trim();t&&t!==e.content&&c(e.id,t),u(!1)};return(0,m.jsxs)(`li`,{className:`queue-row ${h?`queue-row-sending`:`queue-row-queued`} ${g?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":g?v:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[(0,m.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),g?(0,m.jsxs)(`span`,{className:`queue-bg-result`,title:_,children:[(0,m.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:v===`error`?`✕`:`↩`}),(0,m.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,m.jsx)(`span`,{className:`bg-result-summary`,children:_})]}):l?(0,m.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,m.jsx)(`textarea`,{value:d,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>f(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),f(e.content),u(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),y())}}),(0,m.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:y,children:`保存`}),(0,m.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{f(e.content),u(!1)},children:`取消`})]}):(0,m.jsx)(`span`,{className:`queue-text`,title:_,children:_}),(0,m.jsx)(`span`,{className:`queue-state`,"data-waiting-state":h?`sending`:`queued`,children:h?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),h?(0,m.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,m.jsxs)(m.Fragment,{children:[r?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${_}」`,onClick:()=>a(e.id),children:`打断并回答`}),(0,m.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${_}」`:`让「${_}」插到最前`,onClick:()=>i(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,m.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${_}」`,onClick:()=>o(e.id),children:`现在就回答`}),!g&&(0,m.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${_}」`,onClick:()=>{f(e.content),u(!0)},children:`改字`}),(0,m.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${_}」`,onClick:()=>s(e.id),children:`撤回`})]})]})}function Jd({question:e,index:t,expanded:n,onToggle:r,onAnswer:i}){return(0,m.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,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:r}),(0,m.jsxs)(`div`,{className:`call-head-row`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,m.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,m.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,m.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,m.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),n&&(0,m.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,m.jsx)(Yd,{question:e,onAnswer:i})})]})}function Yd({question:e,onAnswer:t}){let[n,r]=(0,p.useState)(()=>Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected]))),[i,a]=(0,p.useState)(()=>e.answers?.map(e=>e.note??``).join(`
|
|
68
68
|
`)??``),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,m.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(t=>(0,m.jsxs)(`div`,{className:`question-item`,children:[(0,m.jsx)(`div`,{className:`question-text`,children:t.header?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:`question-header`,children:t.header}),(0,m.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,m.jsx)(Qe,{source:t.question})]}):(0,m.jsx)(Qe,{source:t.question})}),(0,m.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,m.jsxs)(`label`,{className:i?`is-chosen`:``,"data-chosen":a&&i?`1`:void 0,children:[(0,m.jsx)(`input`,{type:t.multiple?`checkbox`:`radio`,name:`q-${t.id}`,checked:i,disabled:a,onChange:()=>o(t.id,r,t.multiple)}),(0,m.jsx)($e,{source:r}),a&&i?(0,m.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},r)})}),e.status===`pending`&&t.extraNote?(0,m.jsx)(`textarea`,{value:i,placeholder:`补充说明(可选)`,onChange:e=>a(e.target.value)}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,m.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,m.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},t.id)),e.status===`pending`&&(0,m.jsxs)(`div`,{className:`question-actions`,children:[(0,m.jsx)(`button`,{type:`button`,onClick:s,disabled:!c,children:`提交`}),(0,m.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>t([],!0),children:`跳过`})]})]})}function Xd({request:e,onAnswer:t,pending:n}){let[r,i]=(0,p.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,m.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,m.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,m.jsxs)(`div`,{className:`extui-head`,children:[(0,m.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,m.jsxs)(`span`,{className:`extui-deadline`,children:[Math.round(e.timeoutMs/1e3),`s 超时`]})]}),n&&(0,m.jsx)(`p`,{role:`status`,children:`提交中…`}),(0,m.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,m.jsx)(`h3`,{className:`extui-title`,children:e.title||e.method}),e.method===`confirm`&&(0,m.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,m.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,m.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,m.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,m.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,m.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&od(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,m.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&od(e)&&e.preventDefault()}}),(0,m.jsxs)(`div`,{className:`extui-actions`,children:[(0,m.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,m.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,m.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,m.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function Zd({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,p.useState)(e),o=(0,p.useRef)(null),s=(0,p.useRef)(!1);(0,p.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,m.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,m.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(od(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,m.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,m.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function Qd({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c}){let[l,u]=(0,p.useState)(!1),[d,f]=(0,p.useState)(``),[h,g]=(0,p.useState)(0),_=(0,p.useRef)(null),v=(0,p.useRef)(null),y=(0,p.useRef)(null),b=(0,p.useRef)(null),x=(0,p.useRef)([]),S=i.find(e=>e.selected),C=Ad(i,d),w=C.length===0?-1:Math.min(Math.max(h,0),C.length-1),T=w<0?void 0:C[w],ee=(e=!1)=>{u(!1),e&&v.current?.focus()},E=()=>{f(``),g(Math.max(i.findIndex(e=>e.selected),0)),u(!0)},te=e=>g(t=>C.length?Math.min(Math.max(t+e,0),C.length-1):0);(0,p.useEffect)(()=>{if(!l)return;let e=e=>{_.current?.contains(e.target)||ee()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[l]),(0,p.useEffect)(()=>{if(!l)return;let e=_.current,t=t=>{e?.contains(t.relatedTarget)||ee()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[l]),(0,p.useEffect)(()=>{l&&b.current?.focus()},[l]),(0,p.useEffect)(()=>{l&&w>=0&&x.current[w]?.scrollIntoView({block:`nearest`})},[l,w]),(0,p.useLayoutEffect)(()=>{if(!l)return;let e=y.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,C.length,i.length]);let D=e=>{if(l){if(e.key===`Escape`)e.preventDefault(),ee(!0);else if(e.key===`ArrowDown`)e.preventDefault(),te(1);else if(e.key===`ArrowUp`)e.preventDefault(),te(-1);else if(e.key===`Home`)e.preventDefault(),g(0);else if(e.key===`End`)e.preventDefault(),g(Math.max(C.length-1,0));else if(e.key===`Enter`){if(od(e))return;e.preventDefault(),T&&(s(T.key),ee(!0))}}},ne=`picker-list-${c??e}`,re=t=>`picker-option-${c??e}-${t}`;return(0,m.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:_,onKeyDown:l?D:void 0,children:[(0,m.jsxs)(`button`,{ref:v,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":l,title:o??`${wd[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>l?ee():E(),children:[(0,m.jsx)(`span`,{className:`session-picker-kind`,children:wd[e]}),(0,m.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,m.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,m.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),l&&(0,m.jsxs)(`div`,{className:`picker-menu`,ref:y,"data-picker-menu":e,"data-picker-highlight":w,children:[(0,m.jsxs)(`div`,{className:`picker-filter`,children:[(0,m.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,m.jsx)(`input`,{ref:b,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${Td[e]}选项`,"aria-expanded":`true`,"aria-controls":ne,"aria-autocomplete":`list`,"aria-activedescendant":T?re(w):void 0,value:d,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{f(e.target.value),g(0)}}),d&&(0,m.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{f(``),g(0),b.current?.focus()},children:`✕`})]}),S&&!C.some(e=>e.key===S.key)&&(0,m.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":S.key,children:[(0,m.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,m.jsx)(`span`,{className:`picker-current-value`,children:S.label})]}),(0,m.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:ne,"aria-label":Ed[e],children:[C.map((e,t)=>(0,m.jsxs)(`button`,{id:re(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{x.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===w&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===w,onClick:()=>{s(e.key),ee(!0)},children:[e.color&&(0,m.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,m.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,m.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,m.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),C.length===0&&(0,m.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:`没有匹配「${d.trim()}」的${Td[e]}`})]})]})]})}var $d=`__pi_default__`;function ef({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onClose:a}){let[o,s]=(0,p.useState)(e.defaultAgentId),[c,l]=(0,p.useState)(e.defaultModel),[u,d]=(0,p.useState)(e.defaultThinkingLevel);(0,p.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`,h=[{key:$d,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:c===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Od(e),selected:c?.provider===e.provider&&c.modelId===e.modelId}))],g=[{key:$d,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:u===void 0},...(t?.levels??[]).map(e=>({key:e,label:e,selected:e===u}))],_=e=>{if(e===$d){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})},v=e=>d(e===$d?void 0:e),y=[{key:$d,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,m.jsx)(`div`,{className:`overlay`,onClick:a,children:(0,m.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`工作区设置`}),(0,m.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,m.jsx)(Qd,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===o)?.name??`跟随 Pi 默认`,value:o??$d,detail:o?`${n?.agents.find(e=>e.id===o)?.toolSummary??``}`:void 0,options:y,disabled:!n||n.source===`unavailable`,note:Fd(n),onChoose:e=>s(e===$d?void 0:e)})]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,m.jsx)(Qd,{kind:`model`,scope:`settings-model`,label:c?.label??`跟随 Pi 默认`,value:c?`${c.provider}/${c.modelId}`:$d,detail:c?`${c.provider}/${c.modelId}`:void 0,options:h,disabled:!f,note:Pd(`模型`,t),onChoose:_})]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,m.jsx)(Qd,{kind:`thinking`,scope:`settings-thinking`,label:u??`跟随 Pi 默认`,value:u??$d,options:g,disabled:!f,note:Pd(`思考等级`,t),onChoose:v})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:a,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(o,c,u),children:`保存`})]})]})})}var tf=[{id:`main`,label:`主`,name:`主 tab`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`terminal`,label:`终端`,name:`终端 tab`}],nf={waiting:`⋯`,running:``,failed:`!`,question:`?`,unread:`•`,idle:``},rf={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,unread:`有未读`,idle:`空闲`};function af(e,t,n){return t?`question`:e.status===`failed`?`failed`:e.status===`waiting`?`waiting`:e.status===`running`?`running`:e.updatedAt>(n??``)?`unread`:`idle`}function of({state:e}){let t=nf[e];return e===`idle`?null:(0,m.jsx)(`i`,{className:`session-state session-state-${e}`,"data-session-state":e,title:rf[e],"aria-label":rf[e],children:(0,m.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:t})})}var sf={pending:`未开始`,in_progress:`进行中`,completed:`已完成`},cf={pending:`○`,in_progress:`◐`,completed:`✓`},lf={high:`高`,medium:`中`,low:`低`};function uf(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function df({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,m.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,children:[(0,m.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:cf[e.status]}),(0,m.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,m.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:sf[e.status]}),e.priority&&(0,m.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:lf[e.priority]})]})}function ff({tasks:e}){return(0,m.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,t)=>{let n=e.id||`bg_${t}`,r=e.status?.trim()||`未知状态`;return(0,m.jsxs)(`li`,{className:`bg-item`,"data-bg-task":n,"data-bg-task-status":e.status??`unknown`,children:[(0,m.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务 ${t+1}`}),(0,m.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,m.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,m.jsx)(`span`,{className:`bg-status`,children:r})]})]},n)})})}function pf({todos:e,tasks:t,collapsed:n,onToggle:r,workspaceId:i,workspaceLabel:a,connected:o,files:s,onOpenFile:c,activeTab:l,onSelectTab:u,sendCommand:d,registerTerminalSink:f}){let p=tf;return p.some(e=>e.id===l)||p[0].id,(0,m.jsx)(`div`,{className:`right-rail${n?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":`右侧栏`,"data-right-rail":`1`,"data-right-rail-collapsed":n,children:n?(0,m.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:r,children:`‹`}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`right-rail-head`,children:[(0,m.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":p.length,children:p.map(e=>(0,m.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===l?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===l,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>u(e.id),children:e.label},e.id))}),(0,m.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":`收起右侧栏`,onClick:r,children:`›`})]}),tf.filter(e=>e.id===l).map(n=>(0,m.jsxs)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${n.id}`,"aria-labelledby":`right-tab-${n.id}`,"data-right-panel":n.id,children:[n.id===`main`&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`rail-section-head`,children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`待办任务`}),(0,m.jsx)(`span`,{className:`rail-section-count`,"data-todo-summary":`1`,children:uf(e)})]}),e.length>0?(0,m.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,m.jsx)(df,{todo:e,index:t},e.id??`todo_${t}`))}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。Agent 开始处理多步骤任务时,会自己把待办写到这里。`}),(0,m.jsxs)(`div`,{className:`rail-section-head`,children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`后台任务`}),(0,m.jsx)(`span`,{className:`rail-section-count`,"data-bg-summary":`1`,children:t.length?`${t.length} 个运行中`:`0 个`})]}),t.length>0?(0,m.jsx)(ff,{tasks:t}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`})]}),n.id===`tools`&&(0,m.jsx)(gf,{}),n.id===`files`&&(0,m.jsx)(Nt,{workspaceId:i,files:s,onOpenFile:c}),n.id===`git`&&(0,m.jsx)(D,{workspaceId:i??null}),n.id===`terminal`&&(0,m.jsx)(Ju,{workspaceId:i,workspaceLabel:a,connected:o,sendCommand:d,registerSink:f})]},n.id))]})})}function mf(){try{if(typeof window>`u`)return on.slice();let e=dn(window.localStorage.getItem(ln));return window.localStorage.getItem(`super-pi:tools:v1`)===null?on.slice():e}catch{return on.slice()}}function hf(e){try{if(typeof window>`u`)return;window.localStorage.setItem(ln,fn(e))}catch{}}function gf(){let[e,t]=(0,p.useState)(mf),[n,r]=(0,p.useState)([]),[i,a]=(0,p.useState)(),[o,s]=(0,p.useState)(!1),[c,l]=(0,p.useState)(),u=e.find(e=>e.id===i),d=(0,p.useCallback)(async()=>{try{let e=await fetch(`/api/tools`),t=await e.json();e.ok&&Array.isArray(t.tools)&&r(t.tools.filter(e=>e.enabled))}catch{}},[]),f=async e=>{l(void 0);try{let t=await fetch(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(t=>t===e?void 0:t),await d()}catch(e){l(`移除工具失败:${e instanceof Error?e.message:String(e)}`)}};return(0,p.useEffect)(()=>{hf(e)},[e]),(0,p.useEffect)(()=>{d();let e=()=>{d()};return window.addEventListener(`super-pi-tools-updated`,e),()=>window.removeEventListener(`super-pi-tools-updated`,e)},[d]),(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`rail-section-head`,children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,m.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[e.length+n.length,` 个`]})]}),e.length+n.length>0?(0,m.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":e.length+n.length,children:[e.map(e=>(0,m.jsxs)(`li`,{className:`tool-slot`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":e.id===i?`open`:`idle`,title:`打开${e.name}`,"aria-label":`打开${e.name}`,"aria-current":e.id===i?`true`:void 0,onClick:()=>a(t=>t===e.id?void 0:e.id),children:[(0,m.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,m.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),e.kind===`link`&&(0,m.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>{t(t=>gn(t,e.id)),i===e.id&&a(void 0)},children:`✕`})]},e.id)),n.map(e=>(0,m.jsxs)(`li`,{className:`tool-slot`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,title:`打开${e.name}`,"aria-label":`打开${e.name}`,onClick:()=>a(t=>t===e.id?void 0:e.id),children:[(0,m.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,m.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void f(e.id),children:`✕`})]},e.id))]}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,m.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具与说明`,"aria-label":`打开工具设置`,onClick:()=>{a(void 0),s(!0)},children:`⚙ 工具设置`}),c&&(0,m.jsx)(`p`,{role:`alert`,"data-tool-error":`1`,children:c}),o&&(0,m.jsx)(_f,{tools:e,onToolsChange:t,mountedTools:n,onRefreshMountedTools:d,onClose:()=>s(!1)}),u&&(0,m.jsx)(bf,{tool:u,onClose:()=>a(void 0)}),n.find(e=>e.id===i)&&(0,m.jsx)(Df,{tool:n.find(e=>e.id===i),onClose:()=>a(void 0)})]})}function _f({tools:e,onToolsChange:t,mountedTools:n,onRefreshMountedTools:r,onClose:i}){let[a,o]=(0,p.useState)(``),[s,c]=(0,p.useState)(``),[l,u]=(0,p.useState)(),[f,h]=(0,p.useState)(!1),[g,_]=(0,p.useState)(),[v,y]=(0,p.useState)(),[b,x]=(0,p.useState)(),[S,C]=(0,p.useState)(``),[w,T]=(0,p.useState)(),[ee,E]=(0,p.useState)(),[te,D]=(0,p.useState)(!1),[ne,re]=(0,p.useState)(),[ie,O]=(0,p.useState)(),ae=(0,p.useRef)(null),oe=(0,p.useRef)(null),se=async()=>{let e=await xd(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
|
|
69
69
|
|
|
70
70
|
工具不属于当前 workspace;通过内置 tool_register 一次性提交完整文件(index.html、JS/CSS,必要时 .py),Super Pi 会保存为全局工具并自动出现在每个 workspace 的工具 Tab。
|
|
71
71
|
|
|
72
|
-
如需本地计算,声明 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、访问地址、文件清单和验证结果。`);h(e),window.setTimeout(()=>h(!1),1800)};(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]);let ce=n.map(e=>e.slug).filter(e=>typeof e==`string`),le=e=>{_(void 0),y(void 0),O(void 0),re({tool:e,name:Qu({slug:e.slug??`tool`})})},ue=async(e,t)=>{_(void 0),y(void 0),O(void 0);let n=$u(t);if(!n.ok)O(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),y(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){_(`导出失败:${e instanceof Error?e.message:String(e)}`)}finally{re(void 0)}},de=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;_(void 0),y(void 0),T(void 0);let n=X(await t.text(),t.name);n.ok?(x({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),C(ce.includes(n.bundle.slug)?Q(n.bundle.slug,ce):n.bundle.slug),E(n.bundle.files[0]?.path)):_(n.reason)},fe=()=>{x(void 0),C(``),T(void 0),E(void 0)},pe=async()=>{if(!b)return;T(void 0);let e=Z(S);if(!e.ok)T(e.reason);else if(ce.includes(e.slug))T(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{D(!0);try{let t=await fetch(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(id(b.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await r(),y(`已导入「${b.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),fe()}catch(e){_(`导入失败:${e instanceof Error?e.message:String(e)}`)}finally{D(!1)}}};return(0,p.useEffect)(()=>{ne&&oe.current?.scrollIntoView({block:`center`})},[ne]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&i()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:i,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:b?(0,m.jsx)(vf,{pending:b,slugDraft:S,slugError:w,preview:ee,busy:te,onSlugChange:e=>{C(e),T(void 0)},onPreviewChange:E,onCancel:fe,onConfirm:()=>void pe()}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,m.jsx)(`strong`,{children:`给 Agent 开发新工具`}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`工具会挂载到 Super Pi 的统一 HTTP 服务,不需要再启动独立服务器。`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void se(),children:f?`已复制`:`复制工具开发 Prompt`})]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":an.length,children:an.map(n=>{let r=e.some(e=>e.kind===n.kind);return(0,m.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":n.kind,children:[(0,m.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:n.glyph}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:n.name}),(0,m.jsx)(`small`,{children:n.blurb})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":n.kind,disabled:r,title:r?`${n.name}已经在工具栏里了`:`添加${n.name}`,"aria-label":r?`${n.name}已添加`:`添加${n.name}`,onClick:()=>t(hn(e,n.kind)),children:r?`已添加`:`添加`})]},n.kind)})}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:a,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{o(e.target.value),u(void 0)}}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:s,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>c(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!a.trim(),onClick:()=>{let n=un(a);n.ok?e.length>=32?u(`工具最多 32 个,先删掉一个再加。`):(t([...e,{id:mn(`link`,e.map(e=>e.id)),kind:`link`,name:s.trim()||yf(n.url),glyph:`↗`,url:n.url}]),o(``),c(``),u(void 0)):u(n.reason)},children:`添加网址工具`}),l&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:l}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,m.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有通过 tool_register 注册的工具。上面复制那段 Prompt,让 Agent 写一个。`}):(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=nd(e.environmentState);return(0,m.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,m.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.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,m.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,m.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)})}),ne&&(0,m.jsxs)(`div`,{className:`tool-share-review`,ref:oe,"data-tool-export-name":`1`,children:[(0,m.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,ne.tool.name,`」`]}),(0,m.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,m.jsx)(`input`,{className:`tool-input`,value:ne.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>re({...ne,name:e.target.value})})]}),ie&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:ie}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{re(void 0),O(void 0)},children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void ue(ne.tool,ne.name),children:`导出`})]})]}),v&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:v}),g&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:g}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,m.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,m.jsx)(`code`,{children:Yu}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,m.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>ae.current?.click(),children:`选择文件…`}),(0,m.jsx)(`input`,{ref:ae,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void de(e)})]})})]})}),document.body)}function vf({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=td(l),f=ed(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,m.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,m.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,m.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,rd(u)]}),(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,m.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,m.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,m.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,m.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` / `,l.environment.fingerprint.platform,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,m.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,m.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,m.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,m.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,m.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,m.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,m.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,m.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,m.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function yf(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 bf({tool:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,m.jsx)(`span`,{className:`tool-dialog-glyph`,"aria-hidden":`true`,children:e.glyph}),e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,m.jsx)(Sf,{}),e.kind===`timestamp`&&(0,m.jsx)(Cf,{}),e.kind===`link`&&(0,m.jsx)(wf,{tool:e})]})]})}),document.body)}function xf({image:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,m.jsxs)(`div`,{className:`lightbox-head`,children:[(0,m.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,m.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`lightbox-body`,children:(0,m.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function Sf(){let[e,t]=(0,p.useState)(`12 * (3 + 4)`),n=On(e),r=e=>{t(t=>t+e)};return(0,m.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,m.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,m.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,m.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,m.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:kn(n.value)}):(0,m.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function Cf(){let[e,t]=(0,p.useState)(``),n=An(e),r=n.ok?Mn(n.ms):null;return(0,m.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,m.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,m.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`本地时间`}),(0,m.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`ISO(UTC)`}),(0,m.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`秒`}),(0,m.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`毫秒`}),(0,m.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,m.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function wf({tool:e}){let[t,n]=(0,p.useState)(!1),r=async()=>{let e=await xd(`请为 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,m.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,m.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,m.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,m.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,m.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,m.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,m.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 Tf=`(max-width: 1100px)`,Ef=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Df({tool:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,children:[`🧩 `,e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:(0,m.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 Of(e,t,n){let r=Math.max(0,Math.round(n)-480),i=Ef(520,180,Math.max(180,r-240)),a=Ef(Math.round(e),180,i),o=Ef(640,240,Math.max(240,r-a));return{sidebar:a,rail:Ef(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var kf=`super-pi.rail-widths.v1`,Af=`super-pi.reader-state.v1`,jf=32,Mf=48,Nf=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function Pf(){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 Ff(e){try{typeof window<`u`&&window.localStorage.setItem(Af,JSON.stringify(e))}catch{}}var If=`super-pi.session-tabs.v1`;function Lf(){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`))]:[];return{ids:n,activeId:typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0}}catch{return{ids:[]}}}function Rf(e,t){try{typeof window<`u`&&window.sessionStorage.setItem(If,JSON.stringify({ids:e,...t&&e.includes(t)?{activeId:t}:{}}))}catch{}}function zf(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(kf);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 Bf(e){try{if(typeof window>`u`)return;window.localStorage.setItem(kf,JSON.stringify(e))}catch{}}function $({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,p.useState)(!1),c=e=>e.shiftKey?64:16;return(0,m.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(Ef(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(Ef(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(Ef(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var Vf=`super-pi.composer-height.v1`,Hf=148,Uf=.55,Wf=()=>Math.max(Hf,Math.round((typeof window>`u`?800:window.innerHeight)*Uf)),Gf=e=>{let t=Number.isFinite(e)?e:Hf;return Math.round(Math.min(Wf(),Math.max(Hf,t)))},Kf=()=>{try{let e=window.localStorage.getItem(Vf);return e===null?Hf:Gf(Number(e))}catch{return Hf}};function qf({height:e,onHeight:t}){let[n,r]=(0,p.useState)(!1),i=e=>e.shiftKey?64:16,a=Wf();return(0,m.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":Hf,"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=Gf(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(Gf(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(Gf(e-r))):n.key===`Home`?(n.preventDefault(),t(Hf)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(Gf(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(Gf(e-96)))}})}function Jf(){let[e,t]=(0,p.useState)(ad),[n,r]=(0,p.useState)([]),i=(0,p.useRef)([]),a=(0,p.useRef)(null);a.current||=Pf();let o=(0,p.useRef)(null);o.current||=Lf();let s=n.reduce((e,t)=>t.apply(e),e),[c,l]=(0,p.useState)(o.current.activeId??a.current.activeId),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(),[g,_]=(0,p.useState)({}),[v,y]=(0,p.useState)(a.current.workspaceId),[b,x]=(0,p.useState)(o.current.ids),[S,C]=(0,p.useState)(!1),[w,T]=(0,p.useState)(!1),ee=(0,p.useRef)(void 0),E=(0,p.useRef)(a.current.conversations),te=(0,p.useRef)(b);te.current=b;let D=(0,p.useRef)(a.current.readAt??{}),[ne,re]=(0,p.useState)(0),ie=(0,p.useRef)(null),O=(0,p.useRef)(null),ae=(0,p.useRef)(void 0),oe=(0,p.useRef)(a.current.activeId),[se,ce]=(0,p.useState)({followTail:!0,scrollTop:0}),le=(0,p.useRef)(!1),ue=(0,p.useRef)(new Map),de=(0,p.useRef)(void 0),fe=(0,p.useRef)([]),pe=(0,p.useRef)(void 0),me=(0,p.useCallback)(()=>{if(pe.current!==void 0&&(cancelAnimationFrame(pe.current),pe.current=void 0),!fe.current.length)return;let e=fe.current;fe.current=[];let n=new Map;for(let t of e){let e=`${t.conversationId}\u0000${t.messageId}`,r=n.get(e)??[];r.push(t),n.set(e,r)}t(e=>({...e,conversations:e.conversations.map(e=>{let t=e.messages.map(t=>{let r=n.get(`${e.id}\u0000${t.id}`);if(!r)return t;let i={...t};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 t.every((t,n)=>t===e.messages[n])?e:{...e,messages:t}})}))},[]),he=(0,p.useCallback)(e=>{let t=fe.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),pe.current===void 0&&(pe.current=requestAnimationFrame(me))},[me]),ge=(0,p.useCallback)(e=>{de.current=e},[]),[_e,ve]=(0,p.useState)({}),[ye,be]=(0,p.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),xe=e=>{let t=e.slice(0,24);be(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},k=ye.trim()||`你`,[A,Se]=(0,p.useState)([]),[Ce,we]=(0,p.useState)([]),[Te,Ee]=(0,p.useState)(new Map),[De,Oe]=(0,p.useState)(new Map),[ke,Ae]=(0,p.useState)(),[je,Me]=(0,p.useState)(),[Ne,Pe]=(0,p.useState)(),[Fe,Ie]=(0,p.useState)(),[Le,Re]=(0,p.useState)(),[ze,Be]=(0,p.useState)(`idle`),[Ve,He]=(0,p.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Ue,We]=(0,p.useState)(`chat`),[Ge,Ke]=(0,p.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,p.useEffect)(()=>{let e=()=>Ke(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[qe,Je]=(0,p.useState)(zf),Ye=Of(qe.sidebar??270,qe.rail??320,Ge);(0,p.useEffect)(()=>{Bf({sidebar:Ye.sidebar,rail:Ye.rail})},[Ye.sidebar,Ye.rail]);let Xe=e=>Je(t=>({...t,sidebar:e})),Ze=e=>Je(t=>({...t,rail:e})),[$e,et]=(0,p.useState)(null);(0,p.useEffect)(()=>{et(Kf())},[]),(0,p.useEffect)(()=>{$e!==null&&document.documentElement.style.setProperty(`--composer-height`,`${$e}px`)},[$e]);let tt=e=>{let t=Gf(e);et(t);try{window.localStorage.setItem(Vf,String(t))}catch{}};(0,p.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(Tf),t=e=>{e.matches&&He(!0)};return e.addEventListener(`change`,t),e.matches&&He(!0),()=>e.removeEventListener(`change`,t)},[]);let[nt,rt]=(0,p.useState)({}),[it,at]=(0,p.useState)({}),[ot,st]=(0,p.useState)({}),[ct,ut]=(0,p.useState)(),[ft,pt]=(0,p.useState)(),[mt,ht]=(0,p.useState)(),gt=(0,p.useRef)(new Map),[_t,vt]=(0,p.useState)({}),yt=(0,p.useRef)(new Set),[bt,xt]=(0,p.useState)([]),[St,Ct]=(0,p.useState)([]),[wt,Tt]=(0,p.useState)(),[Et,Dt]=(0,p.useState)(!1),Ot=(0,p.useRef)(null),kt=(0,p.useRef)(!1),jt=(0,p.useRef)(0),Nt=(0,p.useRef)([]),Pt=(0,p.useRef)(void 0),Ft=(0,p.useRef)(!1),It=(0,p.useRef)(new Set),Rt=(0,p.useRef)(new Map),zt=(0,p.useRef)(new Map),[Bt,Vt]=(0,p.useState)(()=>Date.now());(0,p.useEffect)(()=>{let e=window.setInterval(()=>Vt(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let Ht=(0,p.useMemo)(()=>s.conversations.filter(e=>!e.archivedAt),[s.conversations]),j=(0,p.useMemo)(()=>Ht.find(e=>e.id===c)??Ht.find(e=>e.workspaceId===v)??(v&&s.workspaces.some(e=>e.id===v)?void 0:Ht[0]),[c,Ht,v,s.workspaces]);(0,p.useEffect)(()=>{h(void 0)},[c,v]);let Ut=(0,p.useMemo)(()=>s.workspaces.find(e=>e.id===v)??s.workspaces[0],[s.workspaces,v]),Gt=(0,p.useRef)(v);Gt.current=v,(0,p.useEffect)(()=>{j&&y(j.workspaceId)},[j?.id]),(0,p.useEffect)(()=>{Pt.current=c},[c]),(0,p.useEffect)(()=>{ae.current=j?.id},[j?.id]),(0,p.useEffect)(()=>{let e=j?.id;if(!e)return;let t=s.conversations.find(t=>t.id===e);if(!t)return;let n=D.current[e];D.current[e]=t.updatedAt,n!==t.updatedAt&&re(e=>e+1),Ff({activeId:Pt.current,workspaceId:j?.workspaceId??v,conversations:E.current,readAt:D.current})},[j?.id,s.conversations]),(0,p.useEffect)(()=>{u&&c&&Ff({activeId:c,workspaceId:j?.workspaceId??v,conversations:E.current})},[c,j?.workspaceId,u,v]),(0,p.useEffect)(()=>{let e=ie.current;if(!e||!j?.id)return;let t=j.id;le.current=!1;let n=E.current[t]??{followTail:!0,scrollTop:0};ce(n),requestAnimationFrame(()=>{if(ie.current===e){if(n.followTail)Nf(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}}}),oe.current=void 0},[j?.id]);let qt=(0,p.useCallback)((e,t=!1,n=!1)=>{let r=ae.current;if(!r)return;let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=E.current[r]??{followTail:!0,scrollTop:0},o=t?!1:n?!0:a.followTail?i<=Mf:i<=jf,s,c;if(!o){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);s=n?.dataset.transcriptKey,c=n?n.getBoundingClientRect().top-t:void 0}let l={followTail:o,scrollTop:e.scrollTop,...s?{anchorKey:s,anchorOffset:c}:{}};le.current=!o,E.current[r]=l,ce(l),Ff({activeId:r,workspaceId:Gt.current,conversations:E.current})},[]),Jt=_t[j?.id??``]??{text:``,images:[],attachments:[],uploading:0},Yt=Jt.text,Xt=Jt.images,Zt=Jt.attachments,Qt=Jt.uploading,M=(e,t)=>vt(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),$t=e=>M(j?.id??``,t=>({...t,text:e})),en=e=>M(j?.id??``,t=>({...t,attachments:t.attachments.some(t=>t.kind===e.kind&&t.id===e.id)?t.attachments:[...t.attachments,e]})),tn=(e,t)=>M(j?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[nn,rn]=(0,p.useState)({visible:!1,query:``,rect:null}),an=e=>M(j?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),on=b.length>0?b:j?[j.id]:[],sn=(0,p.useMemo)(()=>on.map(e=>Ht.find(t=>t.id===e)).filter(e=>e!==void 0),[on,Ht]);(0,p.useEffect)(()=>{if(!S)return;let e=new Set(Ht.map(e=>e.id));x(t=>{let n=t.filter(t=>e.has(t));return n.length===t.length?t:n})},[S,Ht]),(0,p.useEffect)(()=>{Rf(b,c)},[c,b]);let cn=(0,p.useCallback)(e=>{l(e);let t=Ht.find(t=>t.id===e)?.workspaceId;t&&y(t),mn(`session`),x(t=>t.includes(e)?t:t.length>0?[...t,e]:[...j?.id&&j.id!==e?[j.id]:[],e])},[j]),ln=(0,p.useCallback)(e=>{let t=b.indexOf(e);if(t<0)return;let n=b.filter(t=>t!==e);if(x(n),j?.id!==e)return;let r=n[Math.min(t,n.length-1)];r&&l(r)},[b,j]),N=Mt(v),[un,dn]=(0,p.useState)(tf[0].id),[fn,mn]=(0,p.useState)(`session`);(0,p.useEffect)(()=>{fn===`file`&&!N.active&&mn(`session`)},[fn,N.active]);let hn=(0,p.useCallback)(e=>{N.setActivePath(e),mn(`file`),dn(`files`)},[N.setActivePath]),gn=(0,p.useCallback)(async e=>{await N.openFile(e),mn(`file`)},[N.openFile]),_n=(0,p.useMemo)(()=>sn.map(e=>({id:`session:${e.id}`,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:sn.length>1||N.open.length>0,badge:(0,m.jsx)(of,{state:af(e,A.some(t=>t.conversationId===e.id),D.current[e.id])})})),[sn,N.open.length,A,s.conversations,ne]),vn=(0,p.useMemo)(()=>N.open.map(e=>({id:`file:${e.path}`,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,m.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[N.open]),yn=(0,p.useMemo)(()=>[..._n,...vn],[_n,vn]),bn=fn===`file`&&N.activePath?`file:${N.activePath}`:j?.id?`session:${j.id}`:void 0,xn=(0,p.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);hn(t)}else if(e.startsWith(`session:`)){let t=e.slice(8);cn(t)}},[hn,cn]),Sn=(0,p.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);N.closeFile(t),N.activePath===t&&N.open.length<=1&&mn(`session`)}else if(e.startsWith(`session:`)){let t=e.slice(8);ln(t)}},[N,ln]),Cn=N.active,wn=j?.id;(0,p.useEffect)(()=>{wn&&!wn.startsWith(`pending:`)&&kn({type:`conversation.select`,conversationId:wn})},[wn]);let P=(e,t=`info`)=>{if(!e)return;let n=++jt.current;we(r=>[...r,{key:n,text:e,kind:t}]),Nt.current.push(window.setTimeout(()=>we(e=>e.filter(e=>e.key!==n)),7e3))},Tn=(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},En=(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},Dn=(e,t)=>{if(t.blocking)Se(n=>[...n.filter(n=>n.conversationId!==e||n.request.requestId!==t.requestId),{conversationId:e,request:t}]);else if(t.method===`notify`)P(t.message||t.title,t.notifyType??`info`);else if(t.method===`setStatus`){let e=t.statusKey??``;Ee(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??``;Oe(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`?Ae(t.title):t.method===`set_editor_text`&&e===Pt.current&&$t(t.text??``)},On=(e,t,n)=>{Se(n=>n.filter(n=>n.conversationId!==e||n.request.requestId!==t));let r=Md[n];r&&P(r,`warning`)};(0,p.useEffect)(()=>{let e=!1,n=0,o,s=()=>{if(e)return;let c=location.protocol===`https:`?`wss`:`ws`,u=new WebSocket(`${c}://${location.host}/ws`);ee.current=u,u.onopen=()=>{e||(n=0,d(!0),u.send(JSON.stringify({type:`stream.configure`,coalesce:!0})),u.send(JSON.stringify({type:`catalog.fetch`,conversationId:Pt.current})),u.send(JSON.stringify({type:`agent.catalog.fetch`})),u.send(JSON.stringify({type:`subagent.catalog.fetch`})))},u.onclose=()=>{if(!e){Ft.current=!1;for(let e of i.current)e.onFailure?.();i.current=[],r([]),d(!1),o=window.setTimeout(s,Math.min(bd,yd*2**n++))}},u.onmessage=({data:n})=>{if(e)return;let o=JSON.parse(n);if(o.type!==`message.delta`&&o.type!==`message.thinking`&&me(),o.type===`exec.output`){let e=ue.current.get(o.sessionId)??``;ue.current.set(o.sessionId,(e+o.data).slice(-512e3)),ue.current.size>64&&ue.current.delete(ue.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:o}))}else if(o.type===`exec.exit`)ue.current.delete(o.sessionId);else if(o.type.startsWith(`terminal.`))de.current?.(o);else if(o.type===`conversation.autoRename.result`){let e=gt.current.get(o.conversationId);e&&(gt.current.delete(o.conversationId),o.ok?e.resolve(o.title):e.reject(Error(o.error)))}else if(o.type===`message.thinking`)he(o);else if(o.type===`state`){me(),Ft.current=!1;let e=Pt.current,n=!!(e&&It.current.has(e)),s=!(!e||o.state.conversations.some(t=>t.id===e)),c=n&&s&&e&&Rt.current.has(e)?{...o.state,conversations:[Rt.current.get(e),...o.state.conversations]}:o.state;e&&!s&&(It.current.delete(e),Rt.current.delete(e)),i.current=i.current.filter(e=>!e.accepted?.(c)),r(i.current),t(c),C(!0),d(!0),l(e=>{let t=c.conversations.filter(e=>!e.archivedAt),n=a.current?.activeId,r=!!(e&&t.some(t=>t.id===e)),o=!!(e&&i.current.some(t=>t.temporaryId===e));return r||o?e:n&&t.some(e=>e.id===n)?n:t.find(e=>e.workspaceId===Gt.current)?.id}),y(e=>{let t=a.current?.workspaceId;return t&&c.workspaces.some(e=>e.id===t)?t:e&&(c.workspaces.some(t=>t.id===e)||i.current.some(t=>t.temporaryId===e))?e:c.workspaces[0]?.id})}else if(o.type===`message.delta`)he(o);else if(o.type===`message.revert.result`)Xr(void 0),ut(void 0),o.ok||h(o.message);else if(o.type===`operation.result`){let e=i.current.find(e=>e.id===o.requestId);if(i.current=i.current.filter(e=>e.id!==o.requestId),r(i.current),e?.temporaryId){let t=e.temporaryId;if(o.ok&&o.entityId){let e=zt.current.get(t);e&&Rt.current.set(o.entityId,{...e,id:o.entityId}),It.current.add(o.entityId)}l(n=>n===t?o.ok?o.entityId:e.previousActiveId:n),x(e=>e.flatMap(e=>e===t?o.ok&&o.entityId?[o.entityId]:[]:[e])),y(e=>e===t?o.ok?o.entityId:void 0:e)}o.ok||(e?.onFailure?.(),h(o.message??`操作失败`))}else o.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):o.type===`error`?(h(o.message),Ft.current&&(Ft.current=!1,P(`重命名失败:${o.message}`,`error`))):o.type===`extension.ui`?Dn(o.conversationId,o.request):o.type===`extension.ui.closed`?On(o.conversationId,o.requestId,o.reason):o.type===`model.catalog`?(!o.conversationId||o.conversationId===Pt.current)&&Me(o.catalog):o.type===`agent.catalog`?Pe(o.catalog):o.type===`subagent.catalog`?Ie(o.catalog):o.type===`server.version`?(Re(o.version),o.version.needsRestart&&P(`检测到 Super Pi 代码已更新(v${o.version.runningVersion} → v${o.version.diskVersion}),请执行 /super_pi restart 重启服务生效`,`warning`)):o.type===`subagent.event`?t(e=>({...e,subagentRuns:Tn(e.subagentRuns??[],o.run)})):o.type===`workflow.event`?t(e=>({...e,workflows:En(e.workflows??[],o.workflow)})):o.type===`message.tools`?t(e=>({...e,conversations:e.conversations.map(e=>e.id===o.conversationId?{...e,messages:e.messages.map(e=>e.id===o.messageId?{...e,toolCalls:o.toolCalls}:e)}:e)})):o.type===`conversation.fork.result`&&(ri(e=>e===o.conversationId?void 0:e),P(o.ok?`已从「${o.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${o.messagesCopied?`复制了 ${o.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${o.message}`,o.ok?`info`:`error`))}};return s(),()=>{e=!0,me(),window.clearTimeout(o);for(let e of Nt.current)window.clearTimeout(e);ee.current?.close()}},[he,me]);let kn=(0,p.useCallback)(e=>ee.current?.readyState===WebSocket.OPEN&&(ee.current.send(JSON.stringify(e)),!0),[]),An=(e,t,n,a,o,s)=>{if(ee.current?.readyState!==WebSocket.OPEN||i.current.some(e=>e.key===t))return!1;let c=pn(),l={id:c,key:t,apply:n,temporaryId:a,previousActiveId:Pt.current,onFailure:o,accepted:s};return i.current=[...i.current,l],r(i.current),ee.current.send(JSON.stringify({...e,operationRequestId:c})),!0},jn=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Mn=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Nn=n.some(e=>e.key===`send:${j?.id}`||e.key===`configuration:${j?.id}`||e.temporaryId===j?.id||e.key===`archive:${j?.id}`),Pn=(e,t,n,r,i)=>{e&&ee.current?.send(JSON.stringify({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i}))},Fn=(e,t,n)=>An({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e),In=j?.model??je?.defaultModel,Ln=j?.thinkingLevel??je?.defaultThinkingLevel,Rn=je?.source===`pi`,zn=!!je?.models.find(e=>e.provider===In?.provider&&e.modelId===In?.modelId)?.imageInput,Vn=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(s.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}}))},Hn=(Vn(je,s.workspaces.find(e=>e.id===j?.workspaceId))?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Od(e),selected:In?.provider===e.provider&&In.modelId===e.modelId})),Un=(je?.levels??[]).map(e=>({key:e,label:e,selected:e===Ln})),Wn=e=>{if(!j)return;let[t,n]=e.split(`/`);t&&n&&An({type:`conversation.model`,conversationId:j.id,provider:t,modelId:n},`configuration:${j.id}`,jn(j.id,{model:je?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}}))},Gn=e=>{j&&An({type:`conversation.thinking`,conversationId:j.id,level:e},`configuration:${j.id}`,jn(j.id,{thinkingLevel:e}))},Kn=Ne?.agents.find(e=>e.id===j?.agentId),qn=[{key:$d,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!j?.agentId},...(Ne?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:j?.agentId===e.id}))],Yn=Kn?.model,Xn=!!(Yn&&j?.model&&j.model.provider===Yn.provider&&j.model.modelId===Yn.modelId);Kn?.thinkingLevel&&(j?.thinkingLevel,Kn.thinkingLevel);let Zn=e=>{if(j){let t=Ne?.agents.find(t=>t.id===e);An({type:`conversation.agent`,conversationId:j.id,agentId:e===$d?null:e},`configuration:${j.id}`,jn(j.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},Qn=A.filter(e=>e.conversationId===j?.id),F=(0,p.useMemo)(()=>(s.subagentRuns??[]).filter(e=>e.conversationId===j?.id),[s.subagentRuns,j?.id]),$n=(0,p.useMemo)(()=>(s.workflows??[]).filter(e=>e.conversationId===j?.id),[s.workflows,j?.id]),er=(0,p.useMemo)(()=>new Map($n.map(e=>[e.id,e])),[$n]),tr=(0,p.useMemo)(()=>new Map((Fe?.agents??[]).map(e=>[e.id,e.name])),[Fe]),nr=(0,p.useMemo)(()=>new Map((j?.messages??[]).map(e=>[e.id,e])),[j?.messages]),rr=(0,p.useMemo)(()=>new Map(F.map(e=>[e.id,e])),[F]),ir=(0,p.useMemo)(()=>{let e=new Map;for(let t of F)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[F]),ar=(0,p.useMemo)(()=>{if(!j)return[];let e=ct?.conversationId===j.id?(()=>{let e=j.messages.find(e=>e.id===ct.messageId);if(e)return{index:j.messages.indexOf(e),at:Date.parse(e.createdAt)||0,...ct.kind===`withdraw`?{inclusive:!0}:{inclusive:!1}}})():void 0,t=[];return j.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}`})}),F.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&j?.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}`})}),$n.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)},[j,F,$n,ct]);(0,p.useEffect)(()=>{let e=ie.current;if(!e||!j?.id)return;let t=()=>{!le.current&&E.current[j.id]?.followTail&&(Nf(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()},[j?.id,j?.messages,F,$n,ar]);let or=e=>rt(t=>({...t,[e]:!t[e]})),sr=(e,t)=>at(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),cr=(e,t)=>st(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[lr,ur]=(0,p.useState)({}),dr=e=>ur(t=>({...t,[e]:t[e]!==!0})),fr=e=>{An({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||P(`连接断开,无法停止子智能体,请重试`,`error`)},pr=e=>{An({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||P(`连接断开,无法停止编排,请重试`,`error`)},mr=e=>[...De].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,m.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,Nd).map((e,t)=>(0,m.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>Nd&&(0,m.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),hr=(e,t)=>{let n=`pending:${pn()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};An({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(y(n),l(void 0),T(!1))},[gr,_r]=(0,p.useState)(),vr=(e,t)=>_r(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),yr=()=>_r(void 0),br=(e,t)=>gr?.kind===e&&gr.id===t,xr=(e,t,n)=>t.startsWith(`pending:`)?!1:An(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Mn(t,{name:n}):jn(t,{title:n}))?(Ft.current=!0,yr(),!0):(P(`连接断开,改名未保存,请重试`,`error`),!1),Sr=async e=>{if(e.startsWith(`pending:`)){P(`这个会话还在创建中,稍后再试`,`warning`);return}if(gt.current.has(e))return;P(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{gt.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{gt.current.delete(e)&&n(Error(`模型在 30 秒内没有返回标题`))},32e3)});if(!kn({type:`conversation.autoRename`,conversationId:e}))gt.current.delete(e),P(`连接断开,无法生成标题`,`error`);else try{let n=await t;xr(`conversation`,e,n),P(`已重命名为「${n}」`,`info`)}catch(e){P(`重命名失败:${e instanceof Error?e.message:String(e)}`,`error`)}},Cr=e=>{if(e.id.startsWith(`pending:`))return;let t=s.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`删除工作区「${e.name}」?${t?`其中 ${t} 条会话将一并删除,`:``}此操作不可撤销。`)&&An({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)}))},[wr,Tr]=(0,p.useState)(),Er=wr?s.workspaces.find(e=>e.id===wr):void 0,{theme:Dr,setTheme:Or}=Bn(),[kr,Ar]=(0,p.useState)(!1),[jr,Mr]=(0,p.useState)(!1),Nr=(e,t,n,r)=>{e.startsWith(`pending:`)||(An({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Mn(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Tr(void 0):P(`连接断开,设置未保存,请重试`,`error`))},Pr=e=>{if(e.startsWith(`pending:`)||i.current.some(t=>t.key===`defaults:${e}`))return;let t=`pending:${pn()}`,n={id:t,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[]};zt.current.set(t,n),An({type:`conversation.create`,workspaceId:e},`create-session:${e}`,e=>({...e,conversations:[n,...e.conversations]}),t)&&(y(e),l(t),mn(`session`),x(e=>[...e.filter(e=>e!==t),t]))},Fr=e=>{e.startsWith(`pending:`)||An({type:`conversation.archive`,conversationId:e},`archive:${e}`,jn(e,{archivedAt:new Date().toISOString()}))},Ir=e=>An({type:`conversation.unarchive`,conversationId:e},`archive:${e}`,jn(e,{archivedAt:void 0})),Lr=async e=>{if(!j){P(`请先选择或创建会话`,`error`);return}if(!zn){P(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(P(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(P(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=j.id;M(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:pn(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));Ct(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`)){P(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(yt.current.has(n.id))continue;Ct(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),M(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:`上传失败`}));P(e.error||`上传失败: ${i.status}`,`error`)}}catch(e){P(`上传错误: ${e instanceof Error?e.message:`网络错误`}`,`error`)}finally{Ct(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),M(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Rr=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(!zn){P(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),Lr(n)}},zr=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),Dt(!0))},Br=e=>{e.currentTarget.contains(e.relatedTarget)||Dt(!1)},Vr=e=>{Dt(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!zn){P(`当前模型不支持图片输入`,`error`);return}Lr(t)}},Hr=e=>{if(e.preventDefault(),!j||Nn||!Yt.trim()&&Xt.length===0)return;if(Xt.length>0&&!zn){P(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(Qt>0){P(`图片正在上传中,请稍候…`,`info`);return}let t=`message_${pn()}`,n=j.id,r=Yt,i=Xt;An({type:`message.send`,conversationId:n,content:Yt,clientId:t,...Xt.length>0?{images:Xt}:{},...Zt.length>0?{attachments:Zt}:{}},`send:${n}`,e=>e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t)?e:{...e,conversations:e.conversations.map(e=>e.id===n?{...e,messages:[...e.messages,{id:t,role:`user`,content:r,...i.length>0?{images:i}:{},...Zt.length>0?{attachments:Zt}:{},...j?.status===`running`?{delivery:`waiting`}:{},createdAt:new Date().toISOString()}]}:e)},t,()=>{xt(e=>[...e,{id:t,conversationId:n,content:r,images:i}]),M(n,e=>e.text||e.images.length?e:{...e,text:r,images:i})},e=>!!e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t))?M(j.id,e=>({...e,text:``,images:[]})):P(`连接断开,消息未发送,草稿已保留,请重试`,`error`)},Ur=(0,p.useMemo)(()=>(j?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[j?.messages]),Wr=e=>{An({type:`message.cancel`,conversationId:j?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===j?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||P(`连接断开,撤回没有生效,请重试`,`error`)},Gr=e=>{An({type:`message.steer`,conversationId:j?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===j?.id?{...t,messages:sd(t.messages,e,0)}:t)}))||P(`连接断开,插到最前没有生效,请重试`,`error`)},Kr=e=>{An({type:`message.interrupt`,conversationId:j?.id??``,messageId:e},`interrupt:${j?.id}:${e}`,e=>e,void 0,void 0,t=>{let n=t.conversations.find(e=>e.id===j?.id);return n?.status===`running`&&!n.messages.find(t=>t.id===e)?.delivery})||P(`请求正在处理,请稍候`,`info`)},qr=e=>{An({type:`message.sendQueued`,conversationId:j?.id??``,messageId:e},`send-queued:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===j?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}),void 0,void 0,t=>!t.conversations.find(e=>e.id===j?.id)?.messages.some(t=>t.id===e))||P(`连接断开,发送没有生效,请重试`,`error`)},Jr=(e,t)=>{An({type:`message.edit`,conversationId:j?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===j?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||P(`连接断开,修改没有生效,请重试`,`error`)},[Yr,Xr]=(0,p.useState)(),Zr=(e,t=!1)=>{if(!j||Yr)return;let n=j.messages.find(t=>t.id===e);n&&(n&&vt(e=>{let t=e[j.id]??{text:``,images:[],uploading:0};return t.text.trim()||t.images.length?e:{...e,[j.id]:{...t,text:n.content,images:n.images??[]}}}),ut({conversationId:j.id,messageId:e,kind:t?`withdraw`:`revert`})),kn({type:`message.revert`,conversationId:j.id,messageId:e,withdraw:t})?Xr(e):(ut(void 0),P(`连接断开,回退未执行,请重试`,`error`))},[Qr,$r]=(0,p.useState)(),ei=(0,p.useRef)(void 0),ti=async(e,t)=>{ei.current&&clearTimeout(ei.current);let n=await xd(t);$r({id:e,kind:n?`copied`:`error`}),n||P(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),ei.current=setTimeout(()=>$r(void 0),2e3)};(0,p.useEffect)(()=>()=>{ei.current&&clearTimeout(ei.current)},[]);let[ni,ri]=(0,p.useState)(),ii=e=>{ni||e.startsWith(`pending:`)||(kn({type:`conversation.fork`,conversationId:e})?ri(e):P(`连接断开,分叉没有执行,请重试`,`error`))};return(0,m.jsxs)(`main`,{className:`shell${Ve?` shell-rail-collapsed`:``} mobile-panel-${Ue}`,"data-rail-collapsed":Ve,"data-selected-workspace":v??``,style:{"--sidebar-width":`${Ye.sidebar}px`,"--rail-col":Ve?void 0:`${Ye.rail}px`},children:[(0,m.jsxs)(`aside`,{children:[(0,m.jsxs)(`div`,{className:`brand`,children:[(0,m.jsx)(`span`,{children:`π`}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`strong`,{children:`SUPER PI`}),(0,m.jsx)(`small`,{children:`agent workspace`})]})]}),(0,m.jsx)(`div`,{className:`sidebar-actions`,children:(0,m.jsx)(`button`,{className:`workspace-new`,onClick:()=>T(!0),children:`+ 工作区`})}),(0,m.jsx)(`div`,{className:`label`,children:`工作区`}),(0,m.jsx)(`nav`,{children:s.workspaces.map(e=>{let t=s.conversations.filter(t=>t.workspaceId===e.id),n=t.filter(e=>!e.archivedAt).sort(gd),r=t.filter(e=>e.archivedAt).sort(_d),i=g[e.id]??!1,a=_e[e.id]??!0;return(0,m.jsxs)(`section`,{className:`workspace-group`,children:[(0,m.jsx)(`div`,{className:`workspace-header`,children:br(`workspace`,e.id)?(0,m.jsx)(Zd,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>xr(`workspace`,e.id,t),onClose:yr}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{className:`workspace-toggle`,"aria-expanded":!i,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();pt({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{y(e.id),l(Ht.find(t=>t.workspaceId===e.id)?.id),_(t=>({...t,[e.id]:!i}))},children:[(0,m.jsx)(`span`,{className:`chevron chevron-folder`,"aria-hidden":`true`,children:i?`📁`:`📂`}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`strong`,{onDoubleClick:()=>vr(`workspace`,e.id),children:e.name}),(0,m.jsx)(`small`,{children:e.path})]})]}),(0,m.jsx)(`button`,{className:`workspace-add`,title:`在此工作区新建会话`,onClick:()=>Pr(e.id),children:`+`}),(0,m.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Tr(e.id),children:`⚙`}),(0,m.jsx)(`button`,{className:`workspace-delete`,title:`删除工作区`,onClick:()=>Cr(e),children:`×`})]})}),!i&&(n.length?n.map(t=>(0,m.jsx)(`div`,{className:`conversation-row`,children:br(`conversation`,t.id)?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(Zd,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>xr(`conversation`,t.id,e),onClose:yr}),(0,m.jsx)(`small`,{className:`conversation-time`,children:hd(t.updatedAt,Bt)})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{className:`conversation ${j?.id===t.id?`selected`:``}`,"data-conversation":t.id,title:t.title,"aria-label":`打开会话 ${t.title}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();ht({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{cn(t.id),y(e.id)},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,children:(0,m.jsx)(of,{state:af(t,A.some(e=>e.conversationId===t.id),D.current[t.id])})}),(0,m.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:()=>vr(`conversation`,t.id),children:t.title}),(0,m.jsx)(`small`,{children:hd(t.updatedAt,Bt)})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":ni===t.id?`pending`:`idle`,disabled:!!ni,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>ii(t.id),children:`⑂`}),(0,m.jsx)(`button`,{className:`conversation-archive`,title:`归档会话`,"aria-label":`归档会话 ${t.title}`,onClick:()=>Fr(t.id),children:`×`})]})},t.id)):(0,m.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!i&&r.length>0&&(0,m.jsxs)(`div`,{className:`archived-group`,"data-archived-count":r.length,children:[(0,m.jsxs)(`button`,{className:`archived-toggle`,title:a?`展开已归档会话`:`收起已归档会话`,"aria-expanded":!a,onClick:()=>ve(t=>({...t,[e.id]:!a})),children:[(0,m.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:a?`▸`:`▾`}),(0,m.jsxs)(`span`,{className:`archived-label`,children:[`Archived (`,r.length,`)`]})]}),!a&&r.map(e=>(0,m.jsx)(`div`,{className:`conversation-archived`,"data-archived-at":e.archivedAt,children:br(`conversation`,e.id)?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(Zd,{initial:e.title,label:`重命名已归档会话 ${e.title}`,onCommit:t=>xr(`conversation`,e.id,t),onClose:yr}),(0,m.jsx)(`small`,{children:vd(e.archivedAt)})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,m.jsx)(`span`,{"data-archived-title":e.id,onDoubleClick:()=>vr(`conversation`,e.id),children:e.title}),(0,m.jsx)(`small`,{children:vd(e.archivedAt)}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":e.id,"data-fork-state":ni===e.id?`pending`:`idle`,disabled:!!ni,title:`从此会话分叉出一个新会话`,"aria-label":`从已归档会话 ${e.title} 分叉出一个新会话`,onClick:()=>ii(e.id),children:`⑂`}),(0,m.jsx)(`button`,{className:`conversation-restore`,title:`恢复为正常会话`,"aria-label":`恢复会话 ${e.title}`,onClick:()=>Ir(e.id),children:`↑`})]})},e.id))]})]},e.id)})}),(0,m.jsxs)(`footer`,{children:[(0,m.jsxs)(`div`,{className:`footer-status`,children:[(0,m.jsx)(`i`,{className:u?`online`:`offline`}),u?`已连接`:`正在连接`,(0,m.jsx)(`span`,{children:`本地持久化`})]}),(0,m.jsxs)(`div`,{className:`footer-version`,"data-super-pi-version":Le?.runningVersion??``,children:[`Super Pi v`,Le?.runningVersion??`…`]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":kr,onClick:()=>Ar(!0),children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),`设置`]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":jr,onClick:()=>Mr(!0),children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`📖`}),`使用指南`]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`检查 Super Pi 更新`,onClick:async()=>{Be(`updating`);try{let e=await fetch(`/api/update-check`);if(!e.ok)throw Error(`check failed`);let t=await e.json();if(t.needsRestart)P(`当前代码已更新,正在重启服务…`,`info`);else if(t.updateAvailable){if(!window.confirm(`发现新版本 v${t.latestVersion??``},是否立即更新并重启 Super Pi?`))P(`已取消更新`,`info`);else{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);P(`正在更新到 v${t.latestVersion} 并重启…`,`info`)}}else P(`当前已是最新版本`,`info`)}catch{P(`检查更新失败,请检查网络或服务日志`,`error`)}finally{Be(`idle`)}},children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`↻`}),ze===`updating`?`正在检查更新…`:`检查更新`]}),Le?.needsRestart&&(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`代码已更新:当前运行 v${Le.runningVersion},磁盘版本 v${Le.diskVersion}。点击复制重启命令 /super_pi restart`,onClick:async()=>{Be(`updating`);try{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);P(`正在更新 Super Pi,服务即将重启…`,`info`)}catch{Be(`idle`),P(`更新启动失败,请检查服务日志`,`error`)}},children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`⚠️`}),ze===`updating`?`正在更新并重启…`:`更新并重启服务`]})]})]}),(0,m.jsx)($,{side:`left`,width:Ye.sidebar,min:Ye.sidebarMin,max:Ye.sidebarMax,label:`调整左侧栏宽度`,onWidth:Xe}),(0,m.jsxs)(`section`,{className:`chat`,"data-main-view":fn,"data-main-view-kind":fn,children:[yn.length>0&&(0,m.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":sn.length,"data-file-count":N.open.length,children:(0,m.jsx)(Lt,{tabs:yn,prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:bn,onSelect:xn,onClose:Sn,minWidth:120,maxWidth:320})}),(0,m.jsxs)(`header`,{children:[(0,m.jsxs)(`div`,{className:`chat-head`,children:[(0,m.jsx)(`h1`,{children:j?.title??`准备开始`}),Te.size>0?[...Te].map(([e,t])=>(0,m.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):(0,m.jsx)(`p`,{"data-role":`run-status`,children:j?.status===`running`?`Agent 正在工作`:`Pi runtime · Web 控制台`})]}),(0,m.jsxs)(`span`,{className:`chat-view chat-view-${fn}`,"data-main-view-indicator":fn,"data-main-view-kind":fn,title:fn===`file`?`中间主画面正在显示文件 ${N.active?.path??``}`:`中间主画面正在显示这个会话的消息流`,children:[(0,m.jsx)(`span`,{className:`chat-view-label`,children:`主区显示`}),(0,m.jsx)(`span`,{className:`chat-view-kind`,children:fn===`file`?`文件`:`会话`}),fn===`file`&&N.active&&(0,m.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":N.active.name,children:N.active.name})]}),(0,m.jsx)(`div`,{className:`badge`,children:j?.status??`idle`})]}),f&&(0,m.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,m.jsx)(`span`,{children:f}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>h(void 0),children:`×`})]}),j?.error&&(0,m.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,children:j.error}),ke&&(0,m.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,ke]}),Ce.length>0&&(0,m.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Ce.length,children:Ce.map(e=>(0,m.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),fn===`file`?(0,m.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":Cn?.path,"data-file-view-kind":`editor`,children:Cn?(0,m.jsx)(At,{file:Cn,state:N.saves[Cn.path]?.state??`idle`,message:N.saves[Cn.path]?.message??``,external:N.external[Cn.path]===!0,onChange:e=>N.updateBuffer(Cn.path,e),onSave:()=>void N.save(Cn.path,!1),onReload:()=>void N.reload(Cn.path),onOverwrite:()=>void N.save(Cn.path,!0)}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`messages`,ref:ie,"data-message-scroll-container":j?.id??``,onWheel:e=>{e.deltaY<0&&E.current[j?.id??``]?.followTail&&(le.current=!0,qt(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:qt(t)},children:[!j&&(0,m.jsxs)(`div`,{className:`empty`,children:[(0,m.jsx)(`div`,{className:`orb`,children:`π`}),(0,m.jsx)(`h2`,{children:`开始一个新会话`}),s.workspaces.length===0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,m.jsx)(`button`,{onClick:()=>T(!0),children:`+ 新建工作区`})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:s.workspaces.length===1&&Ut?`在「${Ut.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),s.workspaces.length>1&&(0,m.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,m.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,m.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Ut?.id,onChange:e=>{e.target.value===`__new__`?T(!0):y(e.target.value)},children:[s.workspaces.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id)),(0,m.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Ut&&(0,m.jsx)(`button`,{onClick:()=>Pr(Ut.id),children:`新建会话`}),(0,m.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>T(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),T(!0))},children:`+ 新建工作区`})]})]}),ar.map(e=>{if(e.startsWith(`m:`)){let t=nr.get(e.slice(2));if(!t)return null;let r=!j?.messages.some(n=>n.id!==t.id&&n.role===`user`&&ar.indexOf(`m:${n.id}`)>ar.indexOf(e)),i=t.role===`user`&&j?.status!==`running`&&j?.status!==`waiting`&&Yr!==t.id,a=i&&r&&!t.id.startsWith(`pending:`),o=i&&!r&&!!t.piEntryId,s=t.content?(0,m.jsx)(Qe,{source:t.content}):(0,m.jsx)(`span`,{className:`typing`,children:`正在思考`}),c=t.toolCalls??[];if(t.role===`user`){let n=Qr?.id===t.id?Qr.kind:void 0,r=t.content||(t.images?.length?`[图片]`:``);return(0,m.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`bubble`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[k,(0,m.jsx)(`time`,{children:cd(t.createdAt)})]}),t.images&&t.images.length>0&&(0,m.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>Tt({url:`/api/upload/${encodeURIComponent(j?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,m.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(j?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,m.jsx)(`div`,{className:`content`,children:s})]}),t.attachments&&t.attachments.length>0&&(0,m.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:t.attachments.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=it[n]??!1;return(0,m.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,m.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>at(e=>({...e,[n]:!r})),children:[(0,m.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,m.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,m.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,m.jsxs)(`div`,{className:`message-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":n,"aria-label":`复制这条消息:${r}`,onClick:()=>ti(t.id,r),children:n===`copied`?`已复制`:n===`error`?`复制失败`:`复制`}),a&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>Zr(t.id,!0),children:`撤回`}),o&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退到这里:删除后续全部内容(Pi 的记录和这里的历史一起清掉,不会新建会话,也不动任何代码文件)`,onClick:()=>Zr(t.id),children:`回退`})]})]}),(0,m.jsx)(`div`,{className:`avatar`,title:k,children:k})]},e)}if(t.role===`tool`){let n=(()=>{let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():`后台回传`})(),r=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),i=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:t.content})(),a=`tool:${t.id}`,o=it[a]??!1;return(0,m.jsx)(`article`,{className:`message tool`,"data-transcript-key":e,"data-tool-state":r,children:(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsx)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:(0,m.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":o,title:o?`折叠后台回传`:`展开后台回传`,onClick:()=>at(e=>({...e,[a]:!o})),children:[(0,m.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:r===`error`?`✕`:`↩`}),(0,m.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,m.jsx)(`span`,{className:`bg-result-summary`,title:n,children:n}),!o&&(0,m.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看完整输出`,children:i.split(`
|
|
72
|
+
如需本地计算,声明 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、访问地址、文件清单和验证结果。`);h(e),window.setTimeout(()=>h(!1),1800)};(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]);let ce=n.map(e=>e.slug).filter(e=>typeof e==`string`),le=e=>{_(void 0),y(void 0),O(void 0),re({tool:e,name:Qu({slug:e.slug??`tool`})})},ue=async(e,t)=>{_(void 0),y(void 0),O(void 0);let n=$u(t);if(!n.ok)O(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),y(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){_(`导出失败:${e instanceof Error?e.message:String(e)}`)}finally{re(void 0)}},de=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;_(void 0),y(void 0),T(void 0);let n=X(await t.text(),t.name);n.ok?(x({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),C(ce.includes(n.bundle.slug)?Q(n.bundle.slug,ce):n.bundle.slug),E(n.bundle.files[0]?.path)):_(n.reason)},fe=()=>{x(void 0),C(``),T(void 0),E(void 0)},pe=async()=>{if(!b)return;T(void 0);let e=Z(S);if(!e.ok)T(e.reason);else if(ce.includes(e.slug))T(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{D(!0);try{let t=await fetch(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(id(b.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await r(),y(`已导入「${b.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),fe()}catch(e){_(`导入失败:${e instanceof Error?e.message:String(e)}`)}finally{D(!1)}}};return(0,p.useEffect)(()=>{ne&&oe.current?.scrollIntoView({block:`center`})},[ne]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&i()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:i,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:b?(0,m.jsx)(vf,{pending:b,slugDraft:S,slugError:w,preview:ee,busy:te,onSlugChange:e=>{C(e),T(void 0)},onPreviewChange:E,onCancel:fe,onConfirm:()=>void pe()}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,m.jsx)(`strong`,{children:`给 Agent 开发新工具`}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`工具会挂载到 Super Pi 的统一 HTTP 服务,不需要再启动独立服务器。`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void se(),children:f?`已复制`:`复制工具开发 Prompt`})]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":an.length,children:an.map(n=>{let r=e.some(e=>e.kind===n.kind);return(0,m.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":n.kind,children:[(0,m.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:n.glyph}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:n.name}),(0,m.jsx)(`small`,{children:n.blurb})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":n.kind,disabled:r,title:r?`${n.name}已经在工具栏里了`:`添加${n.name}`,"aria-label":r?`${n.name}已添加`:`添加${n.name}`,onClick:()=>t(hn(e,n.kind)),children:r?`已添加`:`添加`})]},n.kind)})}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:a,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{o(e.target.value),u(void 0)}}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:s,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>c(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!a.trim(),onClick:()=>{let n=un(a);n.ok?e.length>=32?u(`工具最多 32 个,先删掉一个再加。`):(t([...e,{id:mn(`link`,e.map(e=>e.id)),kind:`link`,name:s.trim()||yf(n.url),glyph:`↗`,url:n.url}]),o(``),c(``),u(void 0)):u(n.reason)},children:`添加网址工具`}),l&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:l}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,m.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有通过 tool_register 注册的工具。上面复制那段 Prompt,让 Agent 写一个。`}):(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=nd(e.environmentState);return(0,m.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,m.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.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,m.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,m.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)})}),ne&&(0,m.jsxs)(`div`,{className:`tool-share-review`,ref:oe,"data-tool-export-name":`1`,children:[(0,m.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,ne.tool.name,`」`]}),(0,m.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,m.jsx)(`input`,{className:`tool-input`,value:ne.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>re({...ne,name:e.target.value})})]}),ie&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:ie}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{re(void 0),O(void 0)},children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void ue(ne.tool,ne.name),children:`导出`})]})]}),v&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:v}),g&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:g}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,m.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,m.jsx)(`code`,{children:Yu}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,m.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>ae.current?.click(),children:`选择文件…`}),(0,m.jsx)(`input`,{ref:ae,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void de(e)})]})})]})}),document.body)}function vf({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=td(l),f=ed(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,m.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,m.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,m.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,rd(u)]}),(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,m.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,m.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,m.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,m.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` / `,l.environment.fingerprint.platform,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,m.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,m.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,m.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,m.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,m.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,m.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,m.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,m.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,m.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function yf(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 bf({tool:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,m.jsx)(`span`,{className:`tool-dialog-glyph`,"aria-hidden":`true`,children:e.glyph}),e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,m.jsx)(Sf,{}),e.kind===`timestamp`&&(0,m.jsx)(Cf,{}),e.kind===`link`&&(0,m.jsx)(wf,{tool:e})]})]})}),document.body)}function xf({image:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,m.jsxs)(`div`,{className:`lightbox-head`,children:[(0,m.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,m.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`lightbox-body`,children:(0,m.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function Sf(){let[e,t]=(0,p.useState)(`12 * (3 + 4)`),n=On(e),r=e=>{t(t=>t+e)};return(0,m.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,m.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,m.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,m.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,m.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:kn(n.value)}):(0,m.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function Cf(){let[e,t]=(0,p.useState)(``),n=An(e),r=n.ok?Mn(n.ms):null;return(0,m.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,m.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,m.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`本地时间`}),(0,m.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`ISO(UTC)`}),(0,m.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`秒`}),(0,m.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`毫秒`}),(0,m.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,m.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function wf({tool:e}){let[t,n]=(0,p.useState)(!1),r=async()=>{let e=await xd(`请为 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,m.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,m.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,m.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,m.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,m.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,m.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,m.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 Tf=`(max-width: 1100px)`,Ef=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Df({tool:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,d.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,children:[`🧩 `,e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:(0,m.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 Of(e,t,n){let r=Math.max(0,Math.round(n)-480),i=Ef(520,180,Math.max(180,r-240)),a=Ef(Math.round(e),180,i),o=Ef(640,240,Math.max(240,r-a));return{sidebar:a,rail:Ef(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var kf=`super-pi.rail-widths.v1`,Af=`super-pi.reader-state.v1`,jf=32,Mf=48,Nf=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function Pf(){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 Ff(e){try{typeof window<`u`&&window.localStorage.setItem(Af,JSON.stringify(e))}catch{}}var If=`super-pi.session-tabs.v1`;function Lf(){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`))]:[];return{ids:n,activeId:typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0}}catch{return{ids:[]}}}function Rf(e,t){try{typeof window<`u`&&window.sessionStorage.setItem(If,JSON.stringify({ids:e,...t&&e.includes(t)?{activeId:t}:{}}))}catch{}}function zf(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(kf);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 Bf(e){try{if(typeof window>`u`)return;window.localStorage.setItem(kf,JSON.stringify(e))}catch{}}function $({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,p.useState)(!1),c=e=>e.shiftKey?64:16;return(0,m.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(Ef(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(Ef(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(Ef(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var Vf=`super-pi.composer-height.v1`,Hf=148,Uf=.55,Wf=()=>Math.max(Hf,Math.round((typeof window>`u`?800:window.innerHeight)*Uf)),Gf=e=>{let t=Number.isFinite(e)?e:Hf;return Math.round(Math.min(Wf(),Math.max(Hf,t)))},Kf=()=>{try{let e=window.localStorage.getItem(Vf);return e===null?Hf:Gf(Number(e))}catch{return Hf}};function qf({height:e,onHeight:t}){let[n,r]=(0,p.useState)(!1),i=e=>e.shiftKey?64:16,a=Wf();return(0,m.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":Hf,"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=Gf(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(Gf(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(Gf(e-r))):n.key===`Home`?(n.preventDefault(),t(Hf)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(Gf(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(Gf(e-96)))}})}function Jf(){let[e,t]=(0,p.useState)(ad),[n,r]=(0,p.useState)([]),i=(0,p.useRef)([]),a=(0,p.useRef)(null);a.current||=Pf();let o=(0,p.useRef)(null);o.current||=Lf();let s=n.reduce((e,t)=>t.apply(e),e),[c,l]=(0,p.useState)(o.current.activeId??a.current.activeId),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(),[g,_]=(0,p.useState)({}),[v,y]=(0,p.useState)(a.current.workspaceId),[b,x]=(0,p.useState)(o.current.ids),[S,C]=(0,p.useState)(!1),[w,T]=(0,p.useState)(!1),ee=(0,p.useRef)(void 0),E=(0,p.useRef)(a.current.conversations),te=(0,p.useRef)(b);te.current=b;let D=(0,p.useRef)(a.current.readAt??{}),[ne,re]=(0,p.useState)(0),ie=(0,p.useRef)(null),O=(0,p.useRef)(null),ae=(0,p.useRef)(void 0),oe=(0,p.useRef)(a.current.activeId),[se,ce]=(0,p.useState)({followTail:!0,scrollTop:0}),le=(0,p.useRef)(!1),ue=(0,p.useRef)(new Map),de=(0,p.useRef)(void 0),fe=(0,p.useRef)([]),pe=(0,p.useRef)(void 0),me=(0,p.useCallback)(()=>{if(pe.current!==void 0&&(cancelAnimationFrame(pe.current),pe.current=void 0),!fe.current.length)return;let e=fe.current;fe.current=[];let n=new Map;for(let t of e){let e=`${t.conversationId}\u0000${t.messageId}`,r=n.get(e)??[];r.push(t),n.set(e,r)}t(e=>({...e,conversations:e.conversations.map(e=>{let t=e.messages.map(t=>{let r=n.get(`${e.id}\u0000${t.id}`);if(!r)return t;let i={...t};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 t.every((t,n)=>t===e.messages[n])?e:{...e,messages:t}})}))},[]),he=(0,p.useCallback)(e=>{let t=fe.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),pe.current===void 0&&(pe.current=requestAnimationFrame(me))},[me]),ge=(0,p.useCallback)(e=>{de.current=e},[]),[_e,ve]=(0,p.useState)({}),[ye,be]=(0,p.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),xe=e=>{let t=e.slice(0,24);be(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},k=ye.trim()||`你`,[A,Se]=(0,p.useState)([]),[Ce,we]=(0,p.useState)([]),[Te,Ee]=(0,p.useState)(new Map),[De,Oe]=(0,p.useState)(new Map),[ke,Ae]=(0,p.useState)(),[je,Me]=(0,p.useState)(),[Ne,Pe]=(0,p.useState)(),[Fe,Ie]=(0,p.useState)(),[Le,Re]=(0,p.useState)(),[ze,Be]=(0,p.useState)(`idle`),[Ve,He]=(0,p.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Ue,We]=(0,p.useState)(`chat`),[Ge,Ke]=(0,p.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,p.useEffect)(()=>{let e=()=>Ke(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[qe,Je]=(0,p.useState)(zf),Ye=Of(qe.sidebar??270,qe.rail??320,Ge);(0,p.useEffect)(()=>{Bf({sidebar:Ye.sidebar,rail:Ye.rail})},[Ye.sidebar,Ye.rail]);let Xe=e=>Je(t=>({...t,sidebar:e})),Ze=e=>Je(t=>({...t,rail:e})),[$e,et]=(0,p.useState)(null);(0,p.useEffect)(()=>{et(Kf())},[]),(0,p.useEffect)(()=>{$e!==null&&document.documentElement.style.setProperty(`--composer-height`,`${$e}px`)},[$e]);let tt=e=>{let t=Gf(e);et(t);try{window.localStorage.setItem(Vf,String(t))}catch{}};(0,p.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(Tf),t=e=>{e.matches&&He(!0)};return e.addEventListener(`change`,t),e.matches&&He(!0),()=>e.removeEventListener(`change`,t)},[]);let[nt,rt]=(0,p.useState)({}),[it,at]=(0,p.useState)({}),[ot,st]=(0,p.useState)({}),[ct,ut]=(0,p.useState)(),[ft,pt]=(0,p.useState)(),[mt,ht]=(0,p.useState)(),gt=(0,p.useRef)(new Map),[_t,vt]=(0,p.useState)({}),yt=(0,p.useRef)(new Set),[bt,xt]=(0,p.useState)([]),[St,Ct]=(0,p.useState)([]),[wt,Tt]=(0,p.useState)(),[Et,Dt]=(0,p.useState)(!1),Ot=(0,p.useRef)(null),kt=(0,p.useRef)(!1),jt=(0,p.useRef)(0),Nt=(0,p.useRef)([]),Pt=(0,p.useRef)(void 0),Ft=(0,p.useRef)(!1),It=(0,p.useRef)(new Set),Rt=(0,p.useRef)(new Map),zt=(0,p.useRef)(new Map),[Bt,Vt]=(0,p.useState)(()=>Date.now());(0,p.useEffect)(()=>{let e=window.setInterval(()=>Vt(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let Ht=(0,p.useMemo)(()=>s.conversations.filter(e=>!e.archivedAt),[s.conversations]),j=(0,p.useMemo)(()=>Ht.find(e=>e.id===c)??Ht.find(e=>e.workspaceId===v)??(v&&s.workspaces.some(e=>e.id===v)?void 0:Ht[0]),[c,Ht,v,s.workspaces]);(0,p.useEffect)(()=>{h(void 0)},[c,v]);let Ut=(0,p.useMemo)(()=>s.workspaces.find(e=>e.id===v)??s.workspaces[0],[s.workspaces,v]),Gt=(0,p.useRef)(v);Gt.current=v,(0,p.useEffect)(()=>{j&&y(j.workspaceId)},[j?.id]),(0,p.useEffect)(()=>{Pt.current=c},[c]),(0,p.useEffect)(()=>{ae.current=j?.id},[j?.id]),(0,p.useEffect)(()=>{let e=j?.id;if(!e)return;let t=s.conversations.find(t=>t.id===e);if(!t)return;let n=D.current[e];D.current[e]=t.updatedAt,n!==t.updatedAt&&re(e=>e+1),Ff({activeId:Pt.current,workspaceId:j?.workspaceId??v,conversations:E.current,readAt:D.current})},[j?.id,s.conversations]),(0,p.useEffect)(()=>{u&&c&&Ff({activeId:c,workspaceId:j?.workspaceId??v,conversations:E.current})},[c,j?.workspaceId,u,v]),(0,p.useEffect)(()=>{let e=ie.current;if(!e||!j?.id)return;let t=j.id;le.current=!1;let n=E.current[t]??{followTail:!0,scrollTop:0};ce(n),requestAnimationFrame(()=>{if(ie.current===e){if(n.followTail)Nf(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}}}),oe.current=void 0},[j?.id]);let qt=(0,p.useCallback)((e,t=!1,n=!1)=>{let r=ae.current;if(!r)return;let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=E.current[r]??{followTail:!0,scrollTop:0},o=t?!1:n?!0:a.followTail?i<=Mf:i<=jf,s,c;if(!o){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);s=n?.dataset.transcriptKey,c=n?n.getBoundingClientRect().top-t:void 0}let l={followTail:o,scrollTop:e.scrollTop,...s?{anchorKey:s,anchorOffset:c}:{}};le.current=!o,E.current[r]=l,ce(l),Ff({activeId:r,workspaceId:Gt.current,conversations:E.current})},[]),Jt=_t[j?.id??``]??{text:``,images:[],attachments:[],uploading:0},Yt=Jt.text,Xt=Jt.images,Zt=Jt.attachments,Qt=Jt.uploading,M=(e,t)=>vt(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),$t=e=>M(j?.id??``,t=>({...t,text:e})),en=e=>M(j?.id??``,t=>({...t,attachments:t.attachments.some(t=>t.kind===e.kind&&t.id===e.id)?t.attachments:[...t.attachments,e]})),tn=(e,t)=>M(j?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[nn,rn]=(0,p.useState)({visible:!1,query:``,rect:null}),an=e=>M(j?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),on=b.length>0?b:j?[j.id]:[],sn=(0,p.useMemo)(()=>on.map(e=>Ht.find(t=>t.id===e)).filter(e=>e!==void 0),[on,Ht]);(0,p.useEffect)(()=>{if(!S)return;let e=new Set(Ht.map(e=>e.id));x(t=>{let n=t.filter(t=>e.has(t));return n.length===t.length?t:n})},[S,Ht]),(0,p.useEffect)(()=>{Rf(b,c)},[c,b]);let cn=(0,p.useCallback)(e=>{l(e);let t=Ht.find(t=>t.id===e)?.workspaceId;t&&y(t),mn(`session`),x(t=>t.includes(e)?t:t.length>0?[...t,e]:[...j?.id&&j.id!==e?[j.id]:[],e])},[j]),ln=(0,p.useCallback)(e=>{let t=b.indexOf(e);if(t<0)return;let n=b.filter(t=>t!==e);if(x(n),j?.id!==e)return;let r=n[Math.min(t,n.length-1)];r&&l(r)},[b,j]),N=Mt(v),[un,dn]=(0,p.useState)(tf[0].id),[fn,mn]=(0,p.useState)(`session`);(0,p.useEffect)(()=>{fn===`file`&&!N.active&&mn(`session`)},[fn,N.active]);let hn=(0,p.useCallback)(e=>{N.setActivePath(e),mn(`file`),dn(`files`)},[N.setActivePath]),gn=(0,p.useCallback)(async e=>{await N.openFile(e),mn(`file`)},[N.openFile]),_n=(0,p.useMemo)(()=>sn.map(e=>({id:`session:${e.id}`,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:sn.length>1||N.open.length>0,badge:(0,m.jsx)(of,{state:af(e,A.some(t=>t.conversationId===e.id),D.current[e.id])})})),[sn,N.open.length,A,s.conversations,ne]),vn=(0,p.useMemo)(()=>N.open.map(e=>({id:`file:${e.path}`,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,m.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[N.open]),yn=(0,p.useMemo)(()=>[..._n,...vn],[_n,vn]),bn=fn===`file`&&N.activePath?`file:${N.activePath}`:j?.id?`session:${j.id}`:void 0,xn=(0,p.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);hn(t)}else if(e.startsWith(`session:`)){let t=e.slice(8);cn(t)}},[hn,cn]),Sn=(0,p.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);N.closeFile(t),N.activePath===t&&N.open.length<=1&&mn(`session`)}else if(e.startsWith(`session:`)){let t=e.slice(8);ln(t)}},[N,ln]),Cn=N.active,wn=j?.id;(0,p.useEffect)(()=>{wn&&!wn.startsWith(`pending:`)&&kn({type:`conversation.select`,conversationId:wn})},[wn]);let P=(e,t=`info`)=>{if(!e)return;let n=++jt.current;we(r=>[...r,{key:n,text:e,kind:t}]),Nt.current.push(window.setTimeout(()=>we(e=>e.filter(e=>e.key!==n)),7e3))},Tn=(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},En=(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},Dn=(e,t)=>{if(t.blocking)Se(n=>[...n.filter(n=>n.conversationId!==e||n.request.requestId!==t.requestId),{conversationId:e,request:t}]);else if(t.method===`notify`)P(t.message||t.title,t.notifyType??`info`);else if(t.method===`setStatus`){let e=t.statusKey??``;Ee(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??``;Oe(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`?Ae(t.title):t.method===`set_editor_text`&&e===Pt.current&&$t(t.text??``)},On=(e,t,n)=>{Se(n=>n.filter(n=>n.conversationId!==e||n.request.requestId!==t));let r=Md[n];r&&P(r,`warning`)};(0,p.useEffect)(()=>{let e=!1,n=0,o,s=()=>{if(e)return;let c=location.protocol===`https:`?`wss`:`ws`,u=new WebSocket(`${c}://${location.host}/ws`);ee.current=u,u.onopen=()=>{e||(n=0,d(!0),u.send(JSON.stringify({type:`stream.configure`,coalesce:!0})),u.send(JSON.stringify({type:`catalog.fetch`,conversationId:Pt.current})),u.send(JSON.stringify({type:`agent.catalog.fetch`})),u.send(JSON.stringify({type:`subagent.catalog.fetch`})))},u.onclose=()=>{if(!e){Ft.current=!1;for(let e of i.current)e.onFailure?.();i.current=[],r([]),d(!1),o=window.setTimeout(s,Math.min(bd,yd*2**n++))}},u.onmessage=({data:n})=>{if(e)return;let o=JSON.parse(n);if(o.type!==`message.delta`&&o.type!==`message.thinking`&&me(),o.type===`exec.output`){let e=ue.current.get(o.sessionId)??``;ue.current.set(o.sessionId,(e+o.data).slice(-512e3)),ue.current.size>64&&ue.current.delete(ue.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:o}))}else if(o.type===`exec.exit`)ue.current.delete(o.sessionId);else if(o.type.startsWith(`terminal.`))de.current?.(o);else if(o.type===`conversation.autoRename.result`){let e=gt.current.get(o.conversationId);e&&(gt.current.delete(o.conversationId),o.ok?e.resolve(o.title):e.reject(Error(o.error)))}else if(o.type===`message.thinking`)he(o);else if(o.type===`state`){me(),Ft.current=!1;let e=Pt.current,n=!!(e&&It.current.has(e)),s=!(!e||o.state.conversations.some(t=>t.id===e)),c=n&&s&&e&&Rt.current.has(e)?{...o.state,conversations:[Rt.current.get(e),...o.state.conversations]}:o.state;e&&!s&&(It.current.delete(e),Rt.current.delete(e)),i.current=i.current.filter(e=>!e.accepted?.(c)),r(i.current),t(c),C(!0),d(!0),l(e=>{let t=c.conversations.filter(e=>!e.archivedAt),n=a.current?.activeId,r=!!(e&&t.some(t=>t.id===e)),o=!!(e&&i.current.some(t=>t.temporaryId===e));return r||o?e:n&&t.some(e=>e.id===n)?n:t.find(e=>e.workspaceId===Gt.current)?.id}),y(e=>{let t=a.current?.workspaceId;return t&&c.workspaces.some(e=>e.id===t)?t:e&&(c.workspaces.some(t=>t.id===e)||i.current.some(t=>t.temporaryId===e))?e:c.workspaces[0]?.id})}else if(o.type===`message.delta`)he(o);else if(o.type===`message.revert.result`)Xr(void 0),ut(void 0),o.ok||h(o.message);else if(o.type===`operation.result`){let e=i.current.find(e=>e.id===o.requestId);if(i.current=i.current.filter(e=>e.id!==o.requestId),r(i.current),e?.temporaryId){let t=e.temporaryId;if(o.ok&&o.entityId){let e=zt.current.get(t);e&&Rt.current.set(o.entityId,{...e,id:o.entityId}),It.current.add(o.entityId)}l(n=>n===t?o.ok?o.entityId:e.previousActiveId:n),x(e=>e.flatMap(e=>e===t?o.ok&&o.entityId?[o.entityId]:[]:[e])),y(e=>e===t?o.ok?o.entityId:void 0:e)}o.ok||(e?.onFailure?.(),h(o.message??`操作失败`))}else o.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):o.type===`error`?(h(o.message),Ft.current&&(Ft.current=!1,P(`重命名失败:${o.message}`,`error`))):o.type===`extension.ui`?Dn(o.conversationId,o.request):o.type===`extension.ui.closed`?On(o.conversationId,o.requestId,o.reason):o.type===`model.catalog`?(!o.conversationId||o.conversationId===Pt.current)&&Me(o.catalog):o.type===`agent.catalog`?Pe(o.catalog):o.type===`subagent.catalog`?Ie(o.catalog):o.type===`server.version`?(Re(o.version),o.version.needsRestart&&P(`检测到 Super Pi 代码已更新(v${o.version.runningVersion} → v${o.version.diskVersion}),请执行 /super_pi restart 重启服务生效`,`warning`)):o.type===`subagent.event`?t(e=>({...e,subagentRuns:Tn(e.subagentRuns??[],o.run)})):o.type===`workflow.event`?t(e=>({...e,workflows:En(e.workflows??[],o.workflow)})):o.type===`message.tools`?t(e=>({...e,conversations:e.conversations.map(e=>e.id===o.conversationId?{...e,messages:e.messages.map(e=>e.id===o.messageId?{...e,toolCalls:o.toolCalls}:e)}:e)})):o.type===`conversation.fork.result`&&(ri(e=>e===o.conversationId?void 0:e),P(o.ok?`已从「${o.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${o.messagesCopied?`复制了 ${o.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${o.message}`,o.ok?`info`:`error`))}};return s(),()=>{e=!0,me(),window.clearTimeout(o);for(let e of Nt.current)window.clearTimeout(e);ee.current?.close()}},[he,me]);let kn=(0,p.useCallback)(e=>ee.current?.readyState===WebSocket.OPEN&&(ee.current.send(JSON.stringify(e)),!0),[]),An=(e,t,n,a,o,s)=>{if(ee.current?.readyState!==WebSocket.OPEN||i.current.some(e=>e.key===t))return!1;let c=pn(),l={id:c,key:t,apply:n,temporaryId:a,previousActiveId:Pt.current,onFailure:o,accepted:s};return i.current=[...i.current,l],r(i.current),ee.current.send(JSON.stringify({...e,operationRequestId:c})),!0},jn=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Mn=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Nn=n.some(e=>e.key===`send:${j?.id}`||e.key===`configuration:${j?.id}`||e.temporaryId===j?.id||e.key===`archive:${j?.id}`),Pn=(e,t,n,r,i)=>{e&&ee.current?.send(JSON.stringify({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i}))},Fn=(e,t,n)=>An({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e),In=j?.model??je?.defaultModel,Ln=j?.thinkingLevel??je?.defaultThinkingLevel,Rn=je?.source===`pi`,zn=!!je?.models.find(e=>e.provider===In?.provider&&e.modelId===In?.modelId)?.imageInput,Vn=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(s.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}}))},Hn=(Vn(je,s.workspaces.find(e=>e.id===j?.workspaceId))?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:Od(e),selected:In?.provider===e.provider&&In.modelId===e.modelId})),Un=(je?.levels??[]).map(e=>({key:e,label:e,selected:e===Ln})),Wn=e=>{if(!j)return;let[t,n]=e.split(`/`);t&&n&&An({type:`conversation.model`,conversationId:j.id,provider:t,modelId:n},`configuration:${j.id}`,jn(j.id,{model:je?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}}))},Gn=e=>{j&&An({type:`conversation.thinking`,conversationId:j.id,level:e},`configuration:${j.id}`,jn(j.id,{thinkingLevel:e}))},Kn=Ne?.agents.find(e=>e.id===j?.agentId),qn=[{key:$d,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!j?.agentId},...(Ne?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:j?.agentId===e.id}))],Yn=Kn?.model,Xn=!!(Yn&&j?.model&&j.model.provider===Yn.provider&&j.model.modelId===Yn.modelId);Kn?.thinkingLevel&&(j?.thinkingLevel,Kn.thinkingLevel);let Zn=e=>{if(j){let t=Ne?.agents.find(t=>t.id===e);An({type:`conversation.agent`,conversationId:j.id,agentId:e===$d?null:e},`configuration:${j.id}`,jn(j.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},Qn=A.filter(e=>e.conversationId===j?.id),F=(0,p.useMemo)(()=>(s.subagentRuns??[]).filter(e=>e.conversationId===j?.id),[s.subagentRuns,j?.id]),$n=(0,p.useMemo)(()=>(s.workflows??[]).filter(e=>e.conversationId===j?.id),[s.workflows,j?.id]),er=(0,p.useMemo)(()=>new Map($n.map(e=>[e.id,e])),[$n]),tr=(0,p.useMemo)(()=>new Map((Fe?.agents??[]).map(e=>[e.id,e.name])),[Fe]),nr=(0,p.useMemo)(()=>new Map((j?.messages??[]).map(e=>[e.id,e])),[j?.messages]),rr=(0,p.useMemo)(()=>new Map(F.map(e=>[e.id,e])),[F]),ir=(0,p.useMemo)(()=>{let e=new Map;for(let t of F)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[F]),ar=(0,p.useMemo)(()=>{if(!j)return[];let e=ct?.conversationId===j.id?(()=>{let e=j.messages.find(e=>e.id===ct.messageId);if(e)return{index:j.messages.indexOf(e),at:Date.parse(e.createdAt)||0,...ct.kind===`withdraw`?{inclusive:!0}:{inclusive:!1}}})():void 0,t=[];return j.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}`})}),F.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&j?.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}`})}),$n.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)},[j,F,$n,ct]);(0,p.useEffect)(()=>{let e=ie.current;if(!e||!j?.id)return;let t=()=>{!le.current&&E.current[j.id]?.followTail&&(Nf(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()},[j?.id,j?.messages,F,$n,ar]);let or=e=>rt(t=>({...t,[e]:!t[e]})),sr=(e,t)=>at(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),cr=(e,t)=>st(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[lr,ur]=(0,p.useState)({}),dr=e=>ur(t=>({...t,[e]:t[e]!==!0})),fr=e=>{An({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||P(`连接断开,无法停止子智能体,请重试`,`error`)},pr=e=>{An({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||P(`连接断开,无法停止编排,请重试`,`error`)},mr=e=>[...De].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,m.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,Nd).map((e,t)=>(0,m.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>Nd&&(0,m.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),hr=(e,t)=>{let n=`pending:${pn()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};An({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(y(n),l(void 0),T(!1))},[gr,_r]=(0,p.useState)(),vr=(e,t)=>_r(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),yr=()=>_r(void 0),br=(e,t)=>gr?.kind===e&&gr.id===t,xr=(e,t,n)=>t.startsWith(`pending:`)?!1:An(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Mn(t,{name:n}):jn(t,{title:n}))?(Ft.current=!0,yr(),!0):(P(`连接断开,改名未保存,请重试`,`error`),!1),Sr=async e=>{if(e.startsWith(`pending:`)){P(`这个会话还在创建中,稍后再试`,`warning`);return}if(gt.current.has(e))return;P(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{gt.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{gt.current.delete(e)&&n(Error(`模型在 30 秒内没有返回标题`))},32e3)});if(!kn({type:`conversation.autoRename`,conversationId:e}))gt.current.delete(e),P(`连接断开,无法生成标题`,`error`);else try{let n=await t;xr(`conversation`,e,n),P(`已重命名为「${n}」`,`info`)}catch(e){P(`重命名失败:${e instanceof Error?e.message:String(e)}`,`error`)}},Cr=e=>{if(e.id.startsWith(`pending:`))return;let t=s.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`删除工作区「${e.name}」?${t?`其中 ${t} 条会话将一并删除,`:``}此操作不可撤销。`)&&An({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)}))},[wr,Tr]=(0,p.useState)(),Er=wr?s.workspaces.find(e=>e.id===wr):void 0,{theme:Dr,setTheme:Or}=Bn(),[kr,Ar]=(0,p.useState)(!1),[jr,Mr]=(0,p.useState)(!1),Nr=(e,t,n,r)=>{e.startsWith(`pending:`)||(An({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Mn(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Tr(void 0):P(`连接断开,设置未保存,请重试`,`error`))},Pr=e=>{if(e.startsWith(`pending:`)||i.current.some(t=>t.key===`defaults:${e}`))return;let t=`pending:${pn()}`,n={id:t,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[]};zt.current.set(t,n),An({type:`conversation.create`,workspaceId:e},`create-session:${e}`,e=>({...e,conversations:[n,...e.conversations]}),t)&&(y(e),l(t),mn(`session`),x(e=>[...e.filter(e=>e!==t),t]))},Fr=e=>{e.startsWith(`pending:`)||An({type:`conversation.archive`,conversationId:e},`archive:${e}`,jn(e,{archivedAt:new Date().toISOString()}))},Ir=e=>An({type:`conversation.unarchive`,conversationId:e},`archive:${e}`,jn(e,{archivedAt:void 0})),Lr=async e=>{if(!j){P(`请先选择或创建会话`,`error`);return}if(!zn){P(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(P(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(P(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=j.id;M(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:pn(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));Ct(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`)){P(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(yt.current.has(n.id))continue;Ct(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),M(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:`上传失败`}));P(e.error||`上传失败: ${i.status}`,`error`)}}catch(e){P(`上传错误: ${e instanceof Error?e.message:`网络错误`}`,`error`)}finally{Ct(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),M(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Rr=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(!zn){P(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),Lr(n)}},zr=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),Dt(!0))},Br=e=>{e.currentTarget.contains(e.relatedTarget)||Dt(!1)},Vr=e=>{Dt(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!zn){P(`当前模型不支持图片输入`,`error`);return}Lr(t)}},Hr=e=>{if(e.preventDefault(),!j||Nn||!Yt.trim()&&Xt.length===0)return;if(Xt.length>0&&!zn){P(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(Qt>0){P(`图片正在上传中,请稍候…`,`info`);return}let t=`message_${pn()}`,n=j.id,r=Yt,i=Xt;An({type:`message.send`,conversationId:n,content:Yt,clientId:t,...Xt.length>0?{images:Xt}:{},...Zt.length>0?{attachments:Zt}:{}},`send:${n}`,e=>e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t)?e:{...e,conversations:e.conversations.map(e=>e.id===n?{...e,messages:[...e.messages,{id:t,role:`user`,content:r,...i.length>0?{images:i}:{},...Zt.length>0?{attachments:Zt}:{},...j?.status===`running`?{delivery:`waiting`}:{},createdAt:new Date().toISOString()}]}:e)},t,()=>{xt(e=>[...e,{id:t,conversationId:n,content:r,images:i}]),M(n,e=>e.text||e.images.length?e:{...e,text:r,images:i})},e=>!!e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t))?M(j.id,e=>({...e,text:``,images:[]})):P(`连接断开,消息未发送,草稿已保留,请重试`,`error`)},Ur=(0,p.useMemo)(()=>(j?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[j?.messages]),Wr=e=>{An({type:`message.cancel`,conversationId:j?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===j?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||P(`连接断开,撤回没有生效,请重试`,`error`)},Gr=e=>{An({type:`message.steer`,conversationId:j?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===j?.id?{...t,messages:sd(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===j?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||P(`连接断开,插到最前没有生效,请重试`,`error`)},Kr=e=>{An({type:`message.interrupt`,conversationId:j?.id??``,messageId:e},`interrupt:${j?.id}:${e}`,e=>e,void 0,void 0,t=>{let n=t.conversations.find(e=>e.id===j?.id);return n?.status===`running`&&!n.messages.find(t=>t.id===e)?.delivery})||P(`请求正在处理,请稍候`,`info`)},qr=e=>{An({type:`message.sendQueued`,conversationId:j?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===j?.id)?.messages.find(t=>t.id===e)?.delivery)||P(`连接断开,发送没有生效,请重试`,`error`)},Jr=(e,t)=>{An({type:`message.edit`,conversationId:j?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===j?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||P(`连接断开,修改没有生效,请重试`,`error`)},[Yr,Xr]=(0,p.useState)(),Zr=(e,t=!1)=>{if(!j||Yr)return;let n=j.messages.find(t=>t.id===e);n&&(n&&vt(e=>{let t=e[j.id]??{text:``,images:[],uploading:0};return t.text.trim()||t.images.length?e:{...e,[j.id]:{...t,text:n.content,images:n.images??[]}}}),ut({conversationId:j.id,messageId:e,kind:t?`withdraw`:`revert`})),kn({type:`message.revert`,conversationId:j.id,messageId:e,withdraw:t})?Xr(e):(ut(void 0),P(`连接断开,回退未执行,请重试`,`error`))},[Qr,$r]=(0,p.useState)(),ei=(0,p.useRef)(void 0),ti=async(e,t)=>{ei.current&&clearTimeout(ei.current);let n=await xd(t);$r({id:e,kind:n?`copied`:`error`}),n||P(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),ei.current=setTimeout(()=>$r(void 0),2e3)};(0,p.useEffect)(()=>()=>{ei.current&&clearTimeout(ei.current)},[]);let[ni,ri]=(0,p.useState)(),ii=e=>{ni||e.startsWith(`pending:`)||(kn({type:`conversation.fork`,conversationId:e})?ri(e):P(`连接断开,分叉没有执行,请重试`,`error`))};return(0,m.jsxs)(`main`,{className:`shell${Ve?` shell-rail-collapsed`:``} mobile-panel-${Ue}`,"data-rail-collapsed":Ve,"data-selected-workspace":v??``,style:{"--sidebar-width":`${Ye.sidebar}px`,"--rail-col":Ve?void 0:`${Ye.rail}px`},children:[(0,m.jsxs)(`aside`,{children:[(0,m.jsxs)(`div`,{className:`brand`,children:[(0,m.jsx)(`span`,{children:`π`}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`strong`,{children:`SUPER PI`}),(0,m.jsx)(`small`,{children:`agent workspace`})]})]}),(0,m.jsx)(`div`,{className:`sidebar-actions`,children:(0,m.jsx)(`button`,{className:`workspace-new`,onClick:()=>T(!0),children:`+ 工作区`})}),(0,m.jsx)(`div`,{className:`label`,children:`工作区`}),(0,m.jsx)(`nav`,{children:s.workspaces.map(e=>{let t=s.conversations.filter(t=>t.workspaceId===e.id),n=t.filter(e=>!e.archivedAt).sort(gd),r=t.filter(e=>e.archivedAt).sort(_d),i=g[e.id]??!1,a=_e[e.id]??!0;return(0,m.jsxs)(`section`,{className:`workspace-group`,children:[(0,m.jsx)(`div`,{className:`workspace-header`,children:br(`workspace`,e.id)?(0,m.jsx)(Zd,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>xr(`workspace`,e.id,t),onClose:yr}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{className:`workspace-toggle`,"aria-expanded":!i,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();pt({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{y(e.id),l(Ht.find(t=>t.workspaceId===e.id)?.id),_(t=>({...t,[e.id]:!i}))},children:[(0,m.jsx)(`span`,{className:`chevron chevron-folder`,"aria-hidden":`true`,children:i?`📁`:`📂`}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`strong`,{onDoubleClick:()=>vr(`workspace`,e.id),children:e.name}),(0,m.jsx)(`small`,{children:e.path})]})]}),(0,m.jsx)(`button`,{className:`workspace-add`,title:`在此工作区新建会话`,onClick:()=>Pr(e.id),children:`+`}),(0,m.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Tr(e.id),children:`⚙`}),(0,m.jsx)(`button`,{className:`workspace-delete`,title:`删除工作区`,onClick:()=>Cr(e),children:`×`})]})}),!i&&(n.length?n.map(t=>(0,m.jsx)(`div`,{className:`conversation-row`,children:br(`conversation`,t.id)?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(Zd,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>xr(`conversation`,t.id,e),onClose:yr}),(0,m.jsx)(`small`,{className:`conversation-time`,children:hd(t.updatedAt,Bt)})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{className:`conversation ${j?.id===t.id?`selected`:``}`,"data-conversation":t.id,title:t.title,"aria-label":`打开会话 ${t.title}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();ht({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{cn(t.id),y(e.id)},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,children:(0,m.jsx)(of,{state:af(t,A.some(e=>e.conversationId===t.id),D.current[t.id])})}),(0,m.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:()=>vr(`conversation`,t.id),children:t.title}),(0,m.jsx)(`small`,{children:hd(t.updatedAt,Bt)})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":ni===t.id?`pending`:`idle`,disabled:!!ni,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>ii(t.id),children:`⑂`}),(0,m.jsx)(`button`,{className:`conversation-archive`,title:`归档会话`,"aria-label":`归档会话 ${t.title}`,onClick:()=>Fr(t.id),children:`×`})]})},t.id)):(0,m.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!i&&r.length>0&&(0,m.jsxs)(`div`,{className:`archived-group`,"data-archived-count":r.length,children:[(0,m.jsxs)(`button`,{className:`archived-toggle`,title:a?`展开已归档会话`:`收起已归档会话`,"aria-expanded":!a,onClick:()=>ve(t=>({...t,[e.id]:!a})),children:[(0,m.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:a?`▸`:`▾`}),(0,m.jsxs)(`span`,{className:`archived-label`,children:[`Archived (`,r.length,`)`]})]}),!a&&r.map(e=>(0,m.jsx)(`div`,{className:`conversation-archived`,"data-archived-at":e.archivedAt,children:br(`conversation`,e.id)?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(Zd,{initial:e.title,label:`重命名已归档会话 ${e.title}`,onCommit:t=>xr(`conversation`,e.id,t),onClose:yr}),(0,m.jsx)(`small`,{children:vd(e.archivedAt)})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,m.jsx)(`span`,{"data-archived-title":e.id,onDoubleClick:()=>vr(`conversation`,e.id),children:e.title}),(0,m.jsx)(`small`,{children:vd(e.archivedAt)}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":e.id,"data-fork-state":ni===e.id?`pending`:`idle`,disabled:!!ni,title:`从此会话分叉出一个新会话`,"aria-label":`从已归档会话 ${e.title} 分叉出一个新会话`,onClick:()=>ii(e.id),children:`⑂`}),(0,m.jsx)(`button`,{className:`conversation-restore`,title:`恢复为正常会话`,"aria-label":`恢复会话 ${e.title}`,onClick:()=>Ir(e.id),children:`↑`})]})},e.id))]})]},e.id)})}),(0,m.jsxs)(`footer`,{children:[(0,m.jsxs)(`div`,{className:`footer-status`,children:[(0,m.jsx)(`i`,{className:u?`online`:`offline`}),u?`已连接`:`正在连接`,(0,m.jsx)(`span`,{children:`本地持久化`})]}),(0,m.jsxs)(`div`,{className:`footer-version`,"data-super-pi-version":Le?.runningVersion??``,children:[`Super Pi v`,Le?.runningVersion??`…`]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":kr,onClick:()=>Ar(!0),children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),`设置`]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":jr,onClick:()=>Mr(!0),children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`📖`}),`使用指南`]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`检查 Super Pi 更新`,onClick:async()=>{Be(`updating`);try{let e=await fetch(`/api/update-check`);if(!e.ok)throw Error(`check failed`);let t=await e.json();if(t.needsRestart)P(`当前代码已更新,正在重启服务…`,`info`);else if(t.updateAvailable){if(!window.confirm(`发现新版本 v${t.latestVersion??``},是否立即更新并重启 Super Pi?`))P(`已取消更新`,`info`);else{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);P(`正在更新到 v${t.latestVersion} 并重启…`,`info`)}}else P(`当前已是最新版本`,`info`)}catch{P(`检查更新失败,请检查网络或服务日志`,`error`)}finally{Be(`idle`)}},children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`↻`}),ze===`updating`?`正在检查更新…`:`检查更新`]}),Le?.needsRestart&&(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`代码已更新:当前运行 v${Le.runningVersion},磁盘版本 v${Le.diskVersion}。点击复制重启命令 /super_pi restart`,onClick:async()=>{Be(`updating`);try{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);P(`正在更新 Super Pi,服务即将重启…`,`info`)}catch{Be(`idle`),P(`更新启动失败,请检查服务日志`,`error`)}},children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`⚠️`}),ze===`updating`?`正在更新并重启…`:`更新并重启服务`]})]})]}),(0,m.jsx)($,{side:`left`,width:Ye.sidebar,min:Ye.sidebarMin,max:Ye.sidebarMax,label:`调整左侧栏宽度`,onWidth:Xe}),(0,m.jsxs)(`section`,{className:`chat`,"data-main-view":fn,"data-main-view-kind":fn,children:[yn.length>0&&(0,m.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":sn.length,"data-file-count":N.open.length,children:(0,m.jsx)(Lt,{tabs:yn,prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:bn,onSelect:xn,onClose:Sn,minWidth:120,maxWidth:320})}),(0,m.jsxs)(`header`,{children:[(0,m.jsxs)(`div`,{className:`chat-head`,children:[(0,m.jsx)(`h1`,{children:j?.title??`准备开始`}),Te.size>0?[...Te].map(([e,t])=>(0,m.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):(0,m.jsx)(`p`,{"data-role":`run-status`,children:j?.status===`running`?`Agent 正在工作`:`Pi runtime · Web 控制台`})]}),(0,m.jsxs)(`span`,{className:`chat-view chat-view-${fn}`,"data-main-view-indicator":fn,"data-main-view-kind":fn,title:fn===`file`?`中间主画面正在显示文件 ${N.active?.path??``}`:`中间主画面正在显示这个会话的消息流`,children:[(0,m.jsx)(`span`,{className:`chat-view-label`,children:`主区显示`}),(0,m.jsx)(`span`,{className:`chat-view-kind`,children:fn===`file`?`文件`:`会话`}),fn===`file`&&N.active&&(0,m.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":N.active.name,children:N.active.name})]}),(0,m.jsx)(`div`,{className:`badge`,children:j?.status??`idle`})]}),f&&(0,m.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,m.jsx)(`span`,{children:f}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>h(void 0),children:`×`})]}),j?.error&&(0,m.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,children:j.error}),ke&&(0,m.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,ke]}),Ce.length>0&&(0,m.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Ce.length,children:Ce.map(e=>(0,m.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),fn===`file`?(0,m.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":Cn?.path,"data-file-view-kind":`editor`,children:Cn?(0,m.jsx)(At,{file:Cn,state:N.saves[Cn.path]?.state??`idle`,message:N.saves[Cn.path]?.message??``,external:N.external[Cn.path]===!0,onChange:e=>N.updateBuffer(Cn.path,e),onSave:()=>void N.save(Cn.path,!1),onReload:()=>void N.reload(Cn.path),onOverwrite:()=>void N.save(Cn.path,!0)}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`messages`,ref:ie,"data-message-scroll-container":j?.id??``,onWheel:e=>{e.deltaY<0&&E.current[j?.id??``]?.followTail&&(le.current=!0,qt(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:qt(t)},children:[!j&&(0,m.jsxs)(`div`,{className:`empty`,children:[(0,m.jsx)(`div`,{className:`orb`,children:`π`}),(0,m.jsx)(`h2`,{children:`开始一个新会话`}),s.workspaces.length===0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,m.jsx)(`button`,{onClick:()=>T(!0),children:`+ 新建工作区`})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:s.workspaces.length===1&&Ut?`在「${Ut.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),s.workspaces.length>1&&(0,m.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,m.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,m.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Ut?.id,onChange:e=>{e.target.value===`__new__`?T(!0):y(e.target.value)},children:[s.workspaces.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id)),(0,m.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Ut&&(0,m.jsx)(`button`,{onClick:()=>Pr(Ut.id),children:`新建会话`}),(0,m.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>T(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),T(!0))},children:`+ 新建工作区`})]})]}),ar.map(e=>{if(e.startsWith(`m:`)){let t=nr.get(e.slice(2));if(!t)return null;let r=!j?.messages.some(n=>n.id!==t.id&&n.role===`user`&&ar.indexOf(`m:${n.id}`)>ar.indexOf(e)),i=t.role===`user`&&j?.status!==`running`&&j?.status!==`waiting`&&Yr!==t.id,a=i&&r&&!t.id.startsWith(`pending:`),o=i&&!r&&!!t.piEntryId,s=t.content?(0,m.jsx)(Qe,{source:t.content}):(0,m.jsx)(`span`,{className:`typing`,children:`正在思考`}),c=t.toolCalls??[];if(t.role===`user`){let n=Qr?.id===t.id?Qr.kind:void 0,r=t.content||(t.images?.length?`[图片]`:``);return(0,m.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`bubble`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[k,(0,m.jsx)(`time`,{children:cd(t.createdAt)})]}),t.images&&t.images.length>0&&(0,m.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>Tt({url:`/api/upload/${encodeURIComponent(j?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,m.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(j?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,m.jsx)(`div`,{className:`content`,children:s})]}),t.attachments&&t.attachments.length>0&&(0,m.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:t.attachments.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=it[n]??!1;return(0,m.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,m.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>at(e=>({...e,[n]:!r})),children:[(0,m.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,m.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,m.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,m.jsxs)(`div`,{className:`message-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":n,"aria-label":`复制这条消息:${r}`,onClick:()=>ti(t.id,r),children:n===`copied`?`已复制`:n===`error`?`复制失败`:`复制`}),a&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>Zr(t.id,!0),children:`撤回`}),o&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退到这里:删除后续全部内容(Pi 的记录和这里的历史一起清掉,不会新建会话,也不动任何代码文件)`,onClick:()=>Zr(t.id),children:`回退`})]})]}),(0,m.jsx)(`div`,{className:`avatar`,title:k,children:k})]},e)}if(t.role===`tool`){let n=(()=>{let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():`后台回传`})(),r=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),i=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:t.content})(),a=`tool:${t.id}`,o=it[a]??!1;return(0,m.jsx)(`article`,{className:`message tool`,"data-transcript-key":e,"data-tool-state":r,children:(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsx)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:(0,m.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":o,title:o?`折叠后台回传`:`展开后台回传`,onClick:()=>at(e=>({...e,[a]:!o})),children:[(0,m.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:r===`error`?`✕`:`↩`}),(0,m.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,m.jsx)(`span`,{className:`bg-result-summary`,title:n,children:n}),!o&&(0,m.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看完整输出`,children:i.split(`
|
|
73
73
|
`).slice(-1)[0]}),(0,m.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`})]})}),o&&(0,m.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,m.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:i})})]})},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),h=[],g=[...u.map((e,t)=>({at:e.at,order:u.slice(0,t).reduce((e,t)=>e+t.text.length,0)*2+1,segment:{blockIndex:t}})),...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),_=0;for(let e of g){let n=Math.max(_,Math.min(e.at,t.content.length));n>_&&h.push({text:t.content.slice(_,n)}),h.push(e.segment),_=n}_<t.content.length&&h.push({text:t.content.slice(_)});let v=e=>{let t=ir.get(e);if(t)return(0,m.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,m.jsx)(Ud,{run:t,name:tr.get(t.agentId)??``,expanded:!!nt[t.id],onToggle:()=>or(t.id),onStop:()=>fr(t.id),stopping:n.some(e=>e.key===`stop:${t.id}`)})})},y=e=>e.call.question?(0,m.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,m.jsx)(Jd,{question:e.call.question,index:e.index,expanded:`${t.id}:${e.index}`in ot?!!ot[`${t.id}:${e.index}`]:!0,onToggle:()=>cr(t.id,e.index),onAnswer:(n,r)=>Pn(j?.id??``,t.id,e.index,n,r)})},`c${e.index}`):(0,m.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,m.jsx)(Bd,{call:e.call,index:e.index,expanded:`${t.id}:${e.index}`in it&&!!it[`${t.id}:${e.index}`],onToggle:()=>sr(t.id,e.index),backgroundOutput:e.call.backgroundTask&&(0,m.jsx)(zd,{task:e.call.backgroundTask,initialOutput:ue.current.get(e.call.backgroundTask.id)??``,expanded:`${t.id}:${e.index}`in it&&!!it[`${t.id}:${e.index}`]}),runCard:v(`${t.id}:${e.index}`)})},`c${e.index}`),b=e=>{let n=u[e],r=u.slice(0,e).reduce((e,t)=>e+t.text.length,0),i=0,a=[];for(let{call:t,index:o}of 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,m.jsx)(`div`,{className:`content thinking-text`,children:(0,m.jsx)(Qe,{source:n.text.slice(i,e)})},`t${o}`)),a.push(y({call:t,index:o})),i=e}i<n.text.length&&a.push((0,m.jsx)(`div`,{className:`content thinking-text`,children:(0,m.jsx)(Qe,{source:n.text.slice(i)})},`tail`));let o=p(e).filter(e=>e.call.status===void 0);return(0,m.jsx)(Hd,{liveCall:o.at(-1)?.call.label,liveExtra:o.length>1?o.length-1:void 0,messageId:`${t.id}:${e}`,nestedCount:p(e).length,preview:n.text.split(`
|
|
74
74
|
`).map(e=>e.trim()).find(Boolean)??``,expanded:lr[`${t.id}:${e}`]===!0,onToggle:()=>dr(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,m.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,m.jsx)(`div`,{className:`avatar`,children:`π`}),(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,m.jsx)(`time`,{children:cd(t.createdAt)})]}),h.map((e,t)=>`blockIndex`in e?b(e.blockIndex):`text`in e?e.text?(0,m.jsx)(`div`,{className:`content`,children:(0,m.jsx)(Qe,{source:e.text})},`t${t}`):null:y(e))]})]},e)}if(e.startsWith(`w:`)){let t=er.get(e.slice(2));return t?(0,m.jsxs)(`div`,{"data-transcript-key":e,children:[n.some(e=>e.key===`stop:${t.id}`)&&(0,m.jsx)(`span`,{children:`停止中…`}),(0,m.jsx)(Wt,{workflow:t,names:tr,stopping:n.some(e=>e.key===`stop:${t.id}`),onStop:()=>pr(t.id)},e)]},e):null}let t=rr.get(e.slice(2));return t?(0,m.jsxs)(`div`,{"data-transcript-key":e,children:[n.some(e=>e.key===`stop:${t.id}`)&&(0,m.jsx)(`span`,{children:`停止中…`}),(0,m.jsx)(Ud,{run:t,stopping:n.some(e=>e.key===`stop:${t.id}`),name:tr.get(t.agentId)??``,expanded:!!nt[t.id],onToggle:()=>or(t.id),onStop:()=>fr(t.id)},e)]},e):null})]}),(0,m.jsx)(Wd,{messages:Ur,running:j?.status===`running`,onSteer:Gr,onInterrupt:Kr,onSend:qr,onCancel:Wr,onEdit:Jr}),(0,m.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":se.followTail?`true`:`false`,children:[$e!==null&&(0,m.jsx)(qf,{height:$e,onHeight:tt}),(0,m.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":j?.status??`idle`,"data-stream-state":u?j?.status===`waiting`?`waiting`:j?.status===`running`?`streaming`:Ur.length?`waiting`:j?.status===`failed`?`failed`:`ready`:`waiting`,children:u?j?.status===`waiting`?`等待 LLM 返回`:j?.status===`running`?`Streaming · 正在生成`:Ur.length?`Waiting · 消息排队中`:j?.status===`failed`?`运行失败`:j?.status===`stopped`?`已停止`:`就绪`:`连接中 / 等待连接`}),!se.followTail&&(0,m.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=ie.current;e&&(Nf(e),e.scrollTop=e.scrollHeight,qt(e,!1,!0))},children:`↓ 跳到底部`}),(0,m.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":se.followTail?`true`:`false`,children:se.followTail?`贴底`:`自由浏览`})]}),(Qn.length>0||[...De.values()].some(e=>e.placement===`aboveEditor`))&&(0,m.jsxs)(`div`,{className:`extui`,"data-extui-count":Qn.length,children:[Qn.map(e=>(0,m.jsx)(Xd,{request:e.request,pending:n.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>Fn(e.conversationId,e.request.requestId,t)},e.request.requestId)),mr(`aboveEditor`)]}),(0,m.jsxs)(`form`,{onSubmit:Hr,onPaste:Rr,onDragOver:zr,onDragLeave:Br,onDrop:Vr,className:Et?`composer-dropzone-active`:void 0,children:[(0,m.jsx)(`textarea`,{ref:O,value:Yt,onCompositionStart:()=>{kt.current=!0},onCompositionEnd:()=>{kt.current=!1},onChange:e=>{$t(e.target.value);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)?rn({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):rn({visible:!1,query:``,rect:null})},placeholder:j?zn?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!j,onKeyDown:e=>{if(!(kt.current||od(e))){if(nn.visible){if(e.key===`Escape`){e.preventDefault(),rn({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())}}}),nn.visible&&nn.rect&&(0,m.jsx)(dt,{query:nn.query,anchorRect:nn.rect,workspaceId:j?.workspaceId,command:kn,onSelect:e=>{if(e.id.startsWith(`skill:`)){let t=e.id.slice(6),n=document.querySelector(`[data-selected-workspace]`)?.dataset.selectedWorkspace;n&&fetch(`/api/memory/tool`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspaceId:n,conversationId:j?.id,kind:`skill.read`,skillId:t})}).then(async n=>{if(!n.ok){P(`读取技能失败`,`error`);return}let r=await n.json();typeof r.content==`string`&&en({kind:`skill`,id:r.id??t,name:r.name??e.label,content:r.content})}).catch(()=>P(`读取技能失败`,`error`))}let t=O.current?.selectionStart??Yt.length,n=Yt.slice(0,t),r=n.lastIndexOf(`/`),i=lt(e,nn.query),a=`${n.slice(0,r)}/${i} ${Yt.slice(t)}`;$t(a),rn({visible:!1,query:``,rect:null})},onClose:()=>rn({visible:!1,query:``,rect:null})}),bt.filter(e=>e.conversationId===j?.id).map(e=>(0,m.jsxs)(`div`,{"data-failed-send":e.id,children:[(0,m.jsxs)(`span`,{children:[`发送失败:`,e.content]}),(0,m.jsx)(`button`,{type:`button`,disabled:!!(Yt||Xt.length),onClick:()=>{M(e.conversationId,t=>({...t,text:e.content,images:e.images})),xt(t=>t.filter(t=>t.id!==e.id))},children:`恢复草稿`}),(0,m.jsx)(`button`,{type:`button`,onClick:()=>xt(t=>t.filter(t=>t.id!==e.id)),children:`移除`})]},e.id)),St.filter(e=>e.conversationId===j?.id).map(e=>(0,m.jsxs)(`div`,{"data-upload-preview":e.id,children:[(0,m.jsx)(`img`,{src:e.url,alt:e.name,width:48,height:48}),(0,m.jsx)(`span`,{children:e.failed?`上传失败`:`上传中…`}),(0,m.jsx)(`button`,{type:`button`,onClick:()=>{yt.current.add(e.id),URL.revokeObjectURL(e.url),Ct(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(Xt.length>0||Qt>0)&&(0,m.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[Xt.map((e,t)=>(0,m.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,m.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(j?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>Tt({url:`/api/upload/${encodeURIComponent(j?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,m.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>an(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),Qt>0&&(0,m.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,m.jsxs)(`span`,{children:[`图片上传中 (`,Qt,`)…`]})}),Zt.map(e=>(0,m.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,m.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>tn(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),(0,m.jsxs)(`div`,{className:`composer`,children:[(0,m.jsxs)(`div`,{className:`session-picker`,"data-session-picker":`1`,children:[(0,m.jsx)(Qd,{kind:`agent`,label:Kn?.name??`跟随 Pi 默认`,value:j?.agentId??$d,options:qn,disabled:!Ne||Ne.source===`unavailable`||Nn,note:Fd(Ne),onChoose:Zn}),(0,m.jsx)(Qd,{kind:`model`,label:In?.label??(je?`Pi 默认`:`读取中…`),value:In?`${In.provider}/${In.modelId}`:void 0,detail:Xn?`来自 ${Kn?.name}`:In&&je?.source===`pi`&&!j?.model?`Pi 默认模型`:In?`${In.provider}/${In.modelId}`:void 0,options:Hn,disabled:!Rn||Nn,note:Pd(`模型`,je),onChoose:Wn}),(0,m.jsx)(Qd,{kind:`thinking`,label:Ln??(je?`Pi 默认`:`读取中…`),value:Ln,options:Un,disabled:!Rn||Nn,note:Pd(`思考等级`,je),onChoose:Gn})]}),(0,m.jsxs)(`div`,{className:`composer-hints`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>Ot.current?.click(),disabled:!j||!zn||Qt>0,title:j?zn?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` 图片`]}),(0,m.jsx)(`input`,{ref:Ot,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(Lr(Array.from(e.target.files)),e.target.value=``)}}),(0,m.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,m.jsxs)(`div`,{className:`composer-actions`,children:[j?.status===`running`&&(0,m.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":j.id,disabled:n.some(e=>e.key===`stop:${j.id}`),onClick:()=>An({type:`run.stop`,conversationId:j.id},`stop:${j.id}`,e=>e),children:n.some(e=>e.key===`stop:${j.id}`)?`停止中…`:`停止`}),(0,m.jsx)(`button`,{className:`send ${j?.status===`running`?`send-queued`:``}`,"data-send-mode":j?.status===`running`?`queued`:`direct`,disabled:!Yt.trim()&&Xt.length===0||!j||Qt>0||!!Yr||Nn,title:j?Yr?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!Yt.trim()&&Xt.length===0?`请输入消息或添加图片后发送`:Qt>0?`图片上传中…`:j.status===`running`?`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:Yr?`撤回中…`:j?.status===`running`?`排队发送 ↑`:`发送 ↑`})]})]})]}),mr(`belowEditor`)]})]}),(0,m.jsx)($,{side:`right`,width:Ve?30:Ye.rail,min:Ye.railMin,max:Ye.railMax,label:`调整右侧栏宽度`,onWidth:Ze}),(0,m.jsxs)(`nav`,{className:`mobile-nav`,"aria-label":`移动端主导航`,children:[(0,m.jsxs)(`button`,{type:`button`,"data-mobile-nav":`workspaces`,className:Ue===`workspaces`?`active`:``,onClick:()=>We(`workspaces`),children:[`☰`,(0,m.jsx)(`span`,{children:`工作区`})]}),(0,m.jsxs)(`button`,{type:`button`,"data-mobile-nav":`chat`,className:Ue===`chat`?`active`:``,onClick:()=>We(`chat`),children:[`◉`,(0,m.jsx)(`span`,{children:`对话`})]}),(0,m.jsxs)(`button`,{type:`button`,"data-mobile-nav":`rail`,className:Ue===`rail`?`active`:``,onClick:()=>{We(`rail`),He(!1)},children:[`▣`,(0,m.jsx)(`span`,{children:`工具`})]})]}),` `,ft&&(0,m.jsx)(Sd,{workspace:ft.workspace,x:ft.x,y:ft.y,notify:P,onClose:()=>pt(void 0)}),mt&&(0,m.jsx)(Cd,{conversation:mt.conversation,x:mt.x,y:mt.y,notify:P,onRename:()=>void Sr(mt.conversation.id),onClose:()=>ht(void 0)}),w&&(0,m.jsx)(jd,{onClose:()=>T(!1),onCreate:hr}),kr&&(0,m.jsx)(Jn,{workspaceId:v,theme:Dr,onChooseTheme:e=>Or(e),onClose:()=>Ar(!1),agentCatalog:Ne,subagentCatalog:Fe,modelFilterRules:s.modelFilterRules??[],pendingSettings:n.some(e=>e.key===`model-rules`||e.key===`agent-directories`),onSetModelRules:e=>An({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),customAgentDirs:s.customAgentDirs??[],onSetCustomAgentDirs:e=>An({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>kn({type:`agents.rescan`}),userNickname:ye,onSetUserNickname:xe}),jr&&(0,m.jsx)(Kt,{onClose:()=>Mr(!1)}),Er&&(0,m.jsx)(ef,{workspace:Er,catalog:Vn(je,Er),agents:Ne,onClose:()=>Tr(void 0),onRename:()=>{let e=Er.id;Tr(void 0),vr(`workspace`,e)},onSave:(e,t,n)=>Nr(Er.id,e,t,n)}),wt&&(0,m.jsx)(xf,{image:wt,onClose:()=>Tt(void 0)}),(0,m.jsx)(pf,{todos:s.todosByConversation?.[j?.id??``]??[],tasks:s.backgroundTasks??[],collapsed:Ve,onToggle:()=>He(e=>!e),workspaceId:v,workspaceLabel:s.workspaces.find(e=>e.id===v)?.path,connected:u,files:N,onOpenFile:e=>void gn(e),activeTab:un,onSelectTab:dn,sendCommand:kn,registerTerminalSink:ge})]})}zn(Rn()),(0,f.createRoot)(document.getElementById(`root`)).render((0,m.jsx)(p.StrictMode,{children:(0,m.jsx)(Jf,{})}));
|