teapot-coding-agent 0.35.11 → 0.35.12

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.
@@ -17,14 +17,14 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
17
17
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),bs&&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=Us(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=is(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,-Ws),Ws),t/=Ws,t/Math.abs(t)+Math.round(t*(Gs-1)))}shouldForceSelection(e){return gs?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(),Ks)}_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&&!(gs&&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<qs&&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=ks(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=Us(n,this._bufferService.cols)}};Ys=_n([H(3,Wn),H(4,Kn),H(5,ir),H(6,Xn),H(7,ar),H(8,rr)],Ys);var Xs=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={}}},Zs=class{constructor(){this._color=new Xs,this._css=new Xs}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()}},Qs=Object.freeze((()=>{let e=[Eo.toColor(`#2e3436`),Eo.toColor(`#cc0000`),Eo.toColor(`#4e9a06`),Eo.toColor(`#c4a000`),Eo.toColor(`#3465a4`),Eo.toColor(`#75507b`),Eo.toColor(`#06989a`),Eo.toColor(`#d3d7cf`),Eo.toColor(`#555753`),Eo.toColor(`#ef2929`),Eo.toColor(`#8ae234`),Eo.toColor(`#fce94f`),Eo.toColor(`#729fcf`),Eo.toColor(`#ad7fa8`),Eo.toColor(`#34e2e2`),Eo.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:To.toCss(r,i,a),rgba:To.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:To.toCss(n,n,n),rgba:To.toRgba(n,n,n)})}return e})()),$s=Eo.toColor(`#ffffff`),ec=Eo.toColor(`#000000`),tc=Eo.toColor(`#ffffff`),nc=ec,rc={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},ic=$s,ac=class extends W{constructor(e){super(),this._optionsService=e,this._contrastCache=new Zs,this._halfContrastCache=new Zs,this._onChangeColors=this._register(new K),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:$s,background:ec,cursor:tc,cursorAccent:nc,selectionForeground:void 0,selectionBackgroundTransparent:rc,selectionBackgroundOpaque:Y.blend(ec,rc),selectionInactiveBackgroundTransparent:rc,selectionInactiveBackgroundOpaque:Y.blend(ec,rc),scrollbarSliderBackground:Y.opacity($s,.2),scrollbarSliderHoverBackground:Y.opacity($s,.4),scrollbarSliderActiveBackground:Y.opacity($s,.5),overviewRulerBorder:$s,ansi:Qs.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=X(e.foreground,$s),t.background=X(e.background,ec),t.cursor=Y.blend(t.background,X(e.cursor,tc)),t.cursorAccent=Y.blend(t.background,X(e.cursorAccent,nc)),t.selectionBackgroundTransparent=X(e.selectionBackground,rc),t.selectionBackgroundOpaque=Y.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=X(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Y.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?X(e.selectionForeground,wo):void 0,t.selectionForeground===wo&&(t.selectionForeground=void 0),Y.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Y.opacity(t.selectionBackgroundTransparent,.3)),Y.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Y.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=X(e.scrollbarSliderBackground,Y.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=X(e.scrollbarSliderHoverBackground,Y.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=X(e.scrollbarSliderActiveBackground,Y.opacity(t.foreground,.5)),t.overviewRulerBorder=X(e.overviewRulerBorder,ic),t.ansi=Qs.slice(),t.ansi[0]=X(e.black,Qs[0]),t.ansi[1]=X(e.red,Qs[1]),t.ansi[2]=X(e.green,Qs[2]),t.ansi[3]=X(e.yellow,Qs[3]),t.ansi[4]=X(e.blue,Qs[4]),t.ansi[5]=X(e.magenta,Qs[5]),t.ansi[6]=X(e.cyan,Qs[6]),t.ansi[7]=X(e.white,Qs[7]),t.ansi[8]=X(e.brightBlack,Qs[8]),t.ansi[9]=X(e.brightRed,Qs[9]),t.ansi[10]=X(e.brightGreen,Qs[10]),t.ansi[11]=X(e.brightYellow,Qs[11]),t.ansi[12]=X(e.brightBlue,Qs[12]),t.ansi[13]=X(e.brightMagenta,Qs[13]),t.ansi[14]=X(e.brightCyan,Qs[14]),t.ansi[15]=X(e.brightWhite,Qs[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]=X(e.extendedAnsi[r],Qs[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()}}};ac=_n([H(0,Xn)],ac);function X(e,t){if(e!==void 0)try{return Eo.toColor(e)}catch{}return t}var oc=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)}},sc=class{constructor(){this._services=new oc,this._services.set(Jn,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Vn(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)}},cc={trace:0,debug:1,info:2,warn:3,error:4,off:5},lc=`xterm.js: `,uc=class extends W{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),dc=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=cc[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?``:lc)+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=_n([H(0,Xn)],uc);var dc,fc=class extends W{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new K),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new K),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new K),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}},Z=3,pc=Object.freeze(new Fn),mc=0,hc=2,gc=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*Z);let r=t||Ln.fromCharData([0,Nn,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*Z+0],n=t&2097151;return[this._data[e*Z+1],t&2097152?this._combined[e]:n?kn(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*Z+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*Z+0]=e|2097152|t[2]<<22):this._data[e*Z+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*Z+0]>>22}hasWidth(e){return this._data[e*Z+0]&12582912}getFg(e){return this._data[e*Z+1]}getBg(e){return this._data[e*Z+2]}hasContent(e){return this._data[e*Z+0]&4194303}getCodePoint(e){let t=this._data[e*Z+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*Z+0]&2097152}getString(e){let t=this._data[e*Z+0];return t&2097152?this._combined[e]:t&2097151?kn(t&2097151):``}isProtected(e){return this._data[e*Z+2]&536870912}loadCell(e,t){return mc=e*Z,t.content=this._data[mc+0],t.fg=this._data[mc+1],t.bg=this._data[mc+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*Z+0]=t.content,this._data[e*Z+1]=t.fg,this._data[e*Z+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*Z+0]=t|n<<22,this._data[e*Z+1]=r.fg,this._data[e*Z+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*Z+0];r&2097152?this._combined[e]+=kn(t):r&2097151?(this._combined[e]=kn(r&2097151)+kn(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*Z+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 Ln;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 Ln;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*hc<this._data.buffer.byteLength;let n=e*Z;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*hc<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*hc<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*Z+0]&4194303)return e+(this._data[e*Z+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*Z+0]&4194303||this._data[e*Z+2]&50331648)return e+(this._data[e*Z+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<Z;e++)this._data[(n+i)*Z+e]=a[(t+i)*Z+e];a[(t+i)*Z+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<Z;e++)this._data[(n+i)*Z+e]=a[(t+i)*Z+e];a[(t+i)*Z+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*Z+0],n=e&2097151,a=e&2097152?this._combined[t]:n?kn(n):Pn;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 _c(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=xc(u,d,t),p=1,m=0;for(;p<u.length;){let e=xc(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 vc(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 yc(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 bc(e,t,n){let r=[],i=e.map((n,r)=>xc(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=xc(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 xc(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 Sc=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new K),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Or(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};Sc._nextId=1;var Cc=Sc,wc={},Tc=wc.B;wc[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:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},wc.A={"#":`£`},wc.B=void 0,wc[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},wc.C=wc[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},wc.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},wc.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},wc.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},wc.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},wc.E=wc[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},wc.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},wc.H=wc[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},wc[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Ec=4294967295,Dc=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=pc.clone(),this.savedCharset=Tc,this.markers=[],this._nullCell=Ln.fromCharData([0,Nn,1,0]),this._whitespaceCell=Ln.fromCharData([0,Pn,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ts,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new fc(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 In),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 In),this._whitespaceCell}getBlankLine(e,t){return new gc(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>Ec?Ec:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=pc);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 fc(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(pc),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 gc(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 gc(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=_c(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(pc),n);if(r.length>0){let n=vc(this.lines,r);yc(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(pc),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new gc(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(pc),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=bc(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(pc,!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--,_=xc(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 Cc(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)}},Oc=class extends W{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new K),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 Dc(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Dc(!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)}},kc=2,Ac=1,jc=class extends W{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new K),this.onResize=this._onResize.event,this._onScroll=this._register(new K),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,kc),this.rows=Math.max(e.rawOptions.rows||0,Ac),this.buffers=this._register(new Oc(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))}};jc=_n([H(0,Xn)],jc);var Mc={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:gs,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Nc=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Pc=class extends W{constructor(e){super(),this._onOptionChange=this._register(new K),this.onOptionChange=this._onOptionChange.event;let t={...Mc};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(U(()=>{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 Mc))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Mc))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||=Mc[e],!Fc(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Mc[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Nc.includes(t)?t:Mc[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 Fc(e){return e===`block`||e===`underline`||e===`bar`}function Ic(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]&&Ic(e[r],t-1);return n}var Lc=Object.freeze({insertMode:!1}),Rc=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),zc=class extends W{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 K),this.onData=this._onData.event,this._onUserInput=this._register(new K),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new K),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new K),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Ic(Lc),this.decPrivateModes=Ic(Rc)}reset(){this.modes=Ic(Lc),this.decPrivateModes=Ic(Rc)}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))}};zc=_n([H(0,Wn),H(1,Yn),H(2,Xn)],zc);var Bc={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 Vc(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 Hc=String.fromCharCode,Uc={DEFAULT:e=>{let t=[Vc(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Hc(t[0])}${Hc(t[1])}${Hc(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Vc(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Vc(e,!0)};${e.x};${e.y}${t}`}},Wc=class extends W{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 K),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Bc))this.addProtocol(e,Bc[e]);for(let e of Object.keys(Uc))this.addEncoding(e,Uc[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}};Wc=_n([H(0,Wn),H(1,Kn),H(2,Xn)],Wc);var Gc=[[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]],Kc=[[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]],qc;function Jc(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 Yc=class{constructor(){if(this.version=`6`,!qc){qc=new Uint8Array(65536),qc.fill(1),qc[0]=0,qc.fill(0,1,32),qc.fill(0,127,160),qc.fill(2,4352,4448),qc[9001]=2,qc[9002]=2,qc.fill(2,11904,42192),qc[12351]=1,qc.fill(2,44032,55204),qc.fill(2,63744,64256),qc.fill(2,65040,65050),qc.fill(2,65072,65136),qc.fill(2,65280,65377),qc.fill(2,65504,65511);for(let e=0;e<Gc.length;++e)qc.fill(0,Gc[e][0],Gc[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?qc[e]:Jc(e,Kc)?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=Xc.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Xc.createPropertyValue(0,n,r)}},Xc=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new K,this.onChange=this._onChange.event;let e=new Yc;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)}},Zc=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 Qc(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 $c=2147483647,el=256,tl=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>el)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>$c?$c: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>$c?$c: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,$c):e}},nl=[],rl=class{constructor(){this._state=0,this._active=nl,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=nl}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=nl,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||nl,!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`,An(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=nl,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+=An(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}},al=[],ol=class{constructor(){this._handlers=Object.create(null),this._active=al,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=al}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=al,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||al,!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`,An(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=al,this._ident=0}},sl=new tl;sl.addParam(0);var cl=class{constructor(e){this._handler=e,this._data=``,this._params=sl,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():sl,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=An(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=sl,this._data=``,this._hitLimit=!1,e));return this._params=sl,this._data=``,this._hitLimit=!1,t}},ll=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}},ul=160,dl=function(){let e=new ll(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(ul,0,2,0),e.add(ul,8,5,8),e.add(ul,6,0,6),e.add(ul,11,0,11),e.add(ul,13,13,13),e}(),fl=class extends W{constructor(e=dl){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 tl,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(U(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new rl),this._dcsParser=this._register(new ol),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:ul)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<ul||++i>=t||(r=e[i])<32||r>126&&r<ul||++i>=t||(r=e[i])<32||r>126&&r<ul||++i>=t||(r=e[i])<32||r>126&&r<ul){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<ul){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<ul){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}}},pl=/^([\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})$/,ml=/^[\da-f]+$/;function hl(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=pl.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),ml.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 gl(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 _l(e,t=16){let[n,r,i]=e;return`rgb:${gl(n,t)}/${gl(r,t)}/${gl(i,t)}`}var vl={"(":0,")":1,"*":2,"+":3,"-":1,".":2},yl=131072,bl=10;function xl(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 Sl=5e3,Cl=0,wl=class extends W{constructor(e,t,n,r,i,a,o,s,c=new fl){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 jn,this._utf8Decoder=new Mn,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=pc.clone(),this._eraseAttrDataInternal=pc.clone(),this._onRequestBell=this._register(new K),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new K),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new K),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new K),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new K),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new K),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new K),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new K),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new K),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new K),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new K),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new K),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new K),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 Tl(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(J.BEL,()=>this.bell()),this._parser.setExecuteHandler(J.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(J.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(J.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(J.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(J.BS,()=>this.backspace()),this._parser.setExecuteHandler(J.HT,()=>this.tab()),this._parser.setExecuteHandler(J.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(J.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(_o.IND,()=>this.index()),this._parser.setExecuteHandler(_o.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(_o.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 wc)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 cl((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`),Sl))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${Sl} 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>yl&&(a=this._parseStack.position+yl)}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<yl&&(this._parseBuffer=new Uint32Array(Math.min(e.length,yl))),o||this._dirtyRowTracker.clearRange(),e.length>yl)for(let t=a;t<e.length;t+=yl){let a=t+yl<e.length?t+yl: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=Xc.extractWidth(t);let n=Xc.extractShouldJoin(t),m=n?Xc.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(kn(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 gc&&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=>!xl(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new cl(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(pc));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=Xc.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(J.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(J.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(J.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(J.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(J.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,Tc),this._charsetService.setgCharset(1,Tc),this._charsetService.setgCharset(2,Tc),this._charsetService.setgCharset(3,Tc);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(`${J.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|=Fn.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=pc.fg,e.bg=pc.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|=pc.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=pc.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|=pc.fg&16777215,r.bg&=-67108864,r.bg|=pc.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${J.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${J.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(`${J.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=pc.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(!xl(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(`${J.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>bl&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>bl&&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(El(n)){if(r===`?`)t.push({type:0,index:n});else{let e=hl(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=hl(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]);El(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,Tc),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(vl[e[0]],wc[e[1]]||Tc),!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=pc.clone(),this._eraseAttrDataInternal=pc.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 Ln;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(`${J.ESC}${e}${J.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)}},Tl=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&&(Cl=e,e=t,t=Cl),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Tl=_n([H(0,Wn)],Tl);function El(e){return 0<=e&&e<256}var Dl=5e7,Ol=12,kl=50,Al=class extends W{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 K),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>Dl)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>=Ol?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>=Ol)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>kl&&(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()}},jl=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)))}};jl=_n([H(0,Wn)],jl);var Ml=!1,Nl=class extends W{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Mr),this._onBinary=this._register(new K),this.onBinary=this._onBinary.event,this._onData=this._register(new K),this.onData=this._onData.event,this._onLineFeed=this._register(new K),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new K),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new K),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new K),this._instantiationService=new sc,this.optionsService=this._register(new Pc(e)),this._instantiationService.setService(Xn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(jc)),this._instantiationService.setService(Wn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(uc)),this._instantiationService.setService(Yn,this._logService),this.coreService=this._register(this._instantiationService.createInstance(zc)),this._instantiationService.setService(Kn,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Wc)),this._instantiationService.setService(Gn,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Xc)),this._instantiationService.setService(Qn,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Zc),this._instantiationService.setService(qn,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(jl),this._instantiationService.setService(Zn,this._oscLinkService),this._inputHandler=this._register(new wl(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Rr.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Rr.forward(this._bufferService.onResize,this._onResize)),this._register(Rr.forward(this.coreService.onData,this._onData)),this._register(Rr.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 Al((e,t)=>this._inputHandler.parse(e,t))),this._register(Rr.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new K),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&&!Ml&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Ml=!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,kc),t=Math.max(t,Ac),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(Qc.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Qc(this._bufferService),!1))),this._windowsWrappingHeuristics.value=U(()=>{for(let t of e)t.dispose()})}}},Pl={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 Fl(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?J.ESC+`OA`:J.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?J.ESC+`OD`:J.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?J.ESC+`OC`:J.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?J.ESC+`OB`:J.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:J.DEL,e.altKey&&(i.key=J.ESC+i.key);break;case 9:if(e.shiftKey){i.key=J.ESC+`[Z`;break}i.key=J.HT,i.cancel=!0;break;case 13:i.key=e.altKey?J.ESC+J.CR:J.CR,i.cancel=!0;break;case 27:i.key=J.ESC,e.altKey&&(i.key=J.ESC+J.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?J.ESC+`[1;`+(a+1)+`D`:t?J.ESC+`OD`:J.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?J.ESC+`[1;`+(a+1)+`C`:t?J.ESC+`OC`:J.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?J.ESC+`[1;`+(a+1)+`A`:t?J.ESC+`OA`:J.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?J.ESC+`[1;`+(a+1)+`B`:t?J.ESC+`OB`:J.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=J.ESC+`[2~`);break;case 46:i.key=a?J.ESC+`[3;`+(a+1)+`~`:J.ESC+`[3~`;break;case 36:i.key=a?J.ESC+`[1;`+(a+1)+`H`:t?J.ESC+`OH`:J.ESC+`[H`;break;case 35:i.key=a?J.ESC+`[1;`+(a+1)+`F`:t?J.ESC+`OF`:J.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?J.ESC+`[5;`+(a+1)+`~`:J.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?J.ESC+`[6;`+(a+1)+`~`:J.ESC+`[6~`;break;case 112:i.key=a?J.ESC+`[1;`+(a+1)+`P`:J.ESC+`OP`;break;case 113:i.key=a?J.ESC+`[1;`+(a+1)+`Q`:J.ESC+`OQ`;break;case 114:i.key=a?J.ESC+`[1;`+(a+1)+`R`:J.ESC+`OR`;break;case 115:i.key=a?J.ESC+`[1;`+(a+1)+`S`:J.ESC+`OS`;break;case 116:i.key=a?J.ESC+`[15;`+(a+1)+`~`:J.ESC+`[15~`;break;case 117:i.key=a?J.ESC+`[17;`+(a+1)+`~`:J.ESC+`[17~`;break;case 118:i.key=a?J.ESC+`[18;`+(a+1)+`~`:J.ESC+`[18~`;break;case 119:i.key=a?J.ESC+`[19;`+(a+1)+`~`:J.ESC+`[19~`;break;case 120:i.key=a?J.ESC+`[20;`+(a+1)+`~`:J.ESC+`[20~`;break;case 121:i.key=a?J.ESC+`[21;`+(a+1)+`~`:J.ESC+`[21~`;break;case 122:i.key=a?J.ESC+`[23;`+(a+1)+`~`:J.ESC+`[23~`;break;case 123:i.key=a?J.ESC+`[24;`+(a+1)+`~`:J.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=J.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=J.DEL:e.keyCode===219?i.key=J.ESC:e.keyCode===220?i.key=J.FS:e.keyCode===221&&(i.key=J.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=Pl[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=J.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=J.ESC+n}else if(e.keyCode===32)i.key=J.ESC+(e.ctrlKey?J.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=J.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=J.US),e.key===`@`&&(i.key=J.NUL))}return i}var Il=0,Ll=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ts,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ts,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||(Il=this._search(t),Il===-1)||this._getKey(this._array[Il])!==t)return!1;do if(this._array[Il]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Il),!0;while(++Il<this._array.length&&this._getKey(this._array[Il])===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&&(Il=this._search(e),!(Il<0||Il>=this._array.length)&&this._getKey(this._array[Il])===e))do yield this._array[Il];while(++Il<this._array.length&&this._getKey(this._array[Il])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Il=this._search(e),!(Il<0||Il>=this._array.length)&&this._getKey(this._array[Il])===e))do t(this._array[Il]);while(++Il<this._array.length&&this._getKey(this._array[Il])===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}},Rl=0,zl=0,Bl=class extends W{constructor(){super(),this._decorations=new Ll(e=>e?.marker.line),this._onDecorationRegistered=this._register(new K),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new K),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(U(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Vl(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=>{Rl=t.options.x??0,zl=Rl+(t.options.width??1),e>=Rl&&e<zl&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},Vl=class extends jr{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new K),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new K),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?Eo.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?Eo.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Hl=1e3,Ul=class{constructor(e,t=Hl){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)}},Wl=20,Gl=class extends W{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 Ul(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(`
18
18
  `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(q(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(U(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Wl+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
19
19
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Wl+1&&(this._liveRegion.textContent+=xn.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})`}};Gl=_n([H(1,Jn),H(2,rr),H(3,ar)],Gl);var Kl=class extends W{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 K),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new K),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(U(()=>{Or(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(q(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(q(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(q(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(q(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&ql(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,Or(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}}};Kl=_n([H(1,ir),H(2,ar),H(3,Wn),H(4,lr)],Kl);function ql(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 Jl=class extends Nl{constructor(e={}){super(e),this._linkifier=this._register(new Mr),this.browser=cs,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Mr),this._onCursorMove=this._register(new K),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new K),this.onKey=this._onKey.event,this._onRender=this._register(new K),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new K),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new K),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new K),this.onBell=this._onBell.event,this._onFocus=this._register(new K),this._onBlur=this._register(new K),this._onA11yCharEmitter=this._register(new K),this._onA11yTabEmitter=this._register(new K),this._onWillOpen=this._register(new K),this._setup(),this._decorationService=this._instantiationService.createInstance(Bl),this._instantiationService.setService($n,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(rs),this._instantiationService.setService(lr,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(er)),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(Rr.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Rr.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Rr.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Rr.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(U(()=>{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=Y.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${J.ESC}]${n};${_l(r)}${vo.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=To.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=To.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(Gl,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(J.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(J.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(q(this.element,`copy`,e=>{this.hasSelection()&&wn(e,this._selectionService)}));let e=e=>Tn(e,this.textarea,this.coreService,this.optionsService);this._register(q(this.textarea,`paste`,e)),this._register(q(this.element,`paste`,e)),fs?this._register(q(this.element,`mousedown`,e=>{e.button===2&&On(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(q(this.element,`contextmenu`,e=>{On(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),bs&&this._register(q(this.element,`auxclick`,e=>{e.button===1&&Dn(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(q(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(q(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(q(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(q(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(q(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(q(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(q(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(q(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,yn.get()),xs||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(ts,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(rr,this._coreBrowserService),this._register(q(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(q(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Zo,this._document,this._helperContainer),this._instantiationService.setService(nr,this._charSizeService),this._themeService=this._instantiationService.createInstance(ac),this._instantiationService.setService(cr,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Mo),this._instantiationService.setService(sr,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ds,this.rows,this.screenElement)),this._instantiationService.setService(ar,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(yo,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(os),this._instantiationService.setService(ir,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Kl,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(lo,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(Ys,this.element,this.screenElement,r)),this._instantiationService.setService(or,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(Rr.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(uo,this.screenElement)),this._register(q(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Gl,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(go,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(go,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Xo,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(q(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(q(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=J.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){En(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=Fl(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===J.ETX||n.key===J.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)&&(Yl(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(pc));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(J.ESC+`[I`):this.coreService.triggerDataEvent(J.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(`${J.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(`${J.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function Yl(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Xl=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)}},Zl=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 Ln)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Ql=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 Zl(t)}getNullCell(){return new Ln}},$l=class extends W{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new K),this.onBufferChange=this._onBufferChange.event,this._normal=new Ql(this._core.buffers.normal,`normal`),this._alternate=new Ql(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)}},eu=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)}},tu=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`],ru=0,iu=class extends W{constructor(e){super(),this._core=this._register(new Jl(e)),this._addonManager=this._register(new Xl),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 eu(this._core),this._parser}get unicode(){return this._checkProposedApi(),new tu(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 $l(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
20
- `,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 yn.get()},set promptLabel(e){yn.set(e)},get tooMuchOutput(){return xn.get()},set tooMuchOutput(e){xn.set(e)}}}_verifyIntegers(...e){for(ru of e)if(ru===1/0||isNaN(ru)||ru%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(ru of e)if(ru&&(ru===1/0||isNaN(ru)||ru%1!=0||ru<0))throw Error(`This API only accepts positive integers`)}},au=2,ou=1,su=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(au,Math.floor(u/e.css.cell.width)),rows:Math.max(ou,Math.floor(l/e.css.cell.height))}}};function cu(e){return e.length}function lu(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function uu(e,t,n){return lu(e===t?t:e>t?e-1:e,n)}function du(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function fu(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}var pu=`modulepreload`,mu=function(e){return`/`+e},hu={},gu=function(e){return e.pathname.endsWith(`.css`)},_u=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},vu=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=mu(t,n);let r=s(t),i=gu(r);return _u(hu,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:pu,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},yu=L(`<div class=overlay><div class=modal style=max-width:360px><div class=modal-head><b>🔒 sign in</b><span></span></div><form style=display:flex;flex-direction:column;gap:10px><input id=pw-input type=password placeholder=password autofocus><button type=submit style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:7px 12px;cursor:pointer">unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),bu=L(`<i class=notifdot>`),xu=L(`<br>`),Su=L(`<span class="badge queued">⏳ <!> of yours queued`),Cu=L(`<span class="badge cron">⏰ `),wu=L(`<header class=chan-head><span class=hash>#</span><span class=title></span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),Tu=L(`<div class=divider-msg>── beginning of log ──`),Eu=L(`<div class=divider-msg>loading older events…`),Du=L(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),Ou=L(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),ku=L(`<div class=content>`),Au=L(`<div class="msg live"><div class=avatar style="background:#5865f233;border:1px solid #5865f266">🫖</div><div class=msg-body><div class=msg-head><span class=author style=color:var(--acc)>agent</span><span class=ts>streaming…`),ju=L(`<div class=feed>`),Mu=L(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),Nu=L(`<div class=termsplit>`),Pu=L(`<div class="termempty muted">no shell here — click a tab or + to add`),Fu=L(`<div class=termpane>`),Iu=L(`<div class=termdrawer><div class=termgrip title="drag to resize · double-click to reset"></div><div class=termbar><div class=termtabs></div><div style=display:flex;gap:4px;align-items:center><span class="muted mono"style=flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap></span></div></div><div class=termbody><div class=termpane>`),Lu=L(`<button class=jump>↓ `),Ru=L(`<div class=cmds>`),zu=L(`<div class=imgstage><span class=muted style=font-size:11px;align-self:center> image<!> attached`),Bu=L(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),Vu=L(`<span class=muted style=font-size:11.5px;white-space:nowrap>🖼 `),Hu=L(`<div class="hint flashhint">`),Uu=L(`<div><form><textarea rows=1></textarea><button type=button class="iconbtn maxbtn"></button><button type=submit>send</button><input id=composer-file type=file accept=image/* multiple style=display:none>`),Wu=L(`<div class=rightbarbackdrop>`),Gu=L(`<div><nav class=sidebar><div class=agent-list></div><div class=sidebar-footer><div class=footer-row style=justify-content:flex-end><button>🔔</button></div><div class=brand-row><div class=brand>🫖 teapot <span class=version>v</span><span></span></div></div><div class=metrics></div></div></nav><section class=channel></section><aside><div class=rightbarhead><span class=muted>details`),Ku=L(`<div class=notifbackdrop>`),qu=L(`<button class=editbtn>clear all`),Ju=L(`<div class=notiflist>`),Yu=L(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),Xu=L(`<span class=wscount>`),Zu=L(`<div class=wsheader><span class=wscaret>`),Qu=L(`<span class=notifbadge>🔔`),$u=L(`<span class=subtag>🧩`),ed=L(`<span class=mini-cron>⏰`),td=L(`<span class=goaldone title="goal done">✓`),nd=L(`<div><span></span><span>`),rd=L(`<span class=caret-spacer>`),id=L(`<span class=caret>`),ad=L(`<span class=ghosttag title="workspace missing">👻`),od=L(`<span>🧩 `),sd=L(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),cd=L(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),ld=L(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),ud=L(`<div class="content muted">thinking…`),dd=L(`<span>⌨ <button class=tabx title="close this shell">✕`),fd=L(`<div><b class=mono></b><span class=muted>`),pd=L(`<div class=cmdrow><b>@</b><span class=muted>`),md=L(`<span class=imgchip><img><button type=button class=imgx title=remove>✕`),hd=L(`<h3 title="switch provider/model live — applies from the agent's next turn; the list shows context window &amp; pricing from the provider">🧦 model`),gd=L(`<div style=display:flex;gap:6px;align-items:center;margin-top:6px><label class=muted style=font-size:11.5px;white-space:nowrap>effort</label><select style=flex:1;min-width:0><option value>provider default`),_d=L(`<div class=meta style=color:var(--fg)>`),vd=L(`<div class=modelbox><select title="provider (OpenAI-compatible endpoint)"></select><div style=display:flex;gap:4px><input type=text list=model-list style=flex:1;min-width:0><datalist id=model-list></datalist></div><div style=display:flex;gap:6px;align-items:center;margin-top:6px><button title="apply the provider, model and effort above to this session — takes effect from the agent's next turn"style=flex:1>apply</button></div><div class=meta>current: `),yd=L(`<div class=ctrlrow><label title="auto-continue fires after a round ONLY when all hold: ① this toggle is on ② a goal is set and its status is 'active' ③ the round ended cleanly (no error / not stopped). It stops when the goal is marked done, or if you press ■ stop. Sending any prompt also starts an idle agent regardless."><input type=checkbox>auto-continue`),bd=L(`<span>`),xd=L(`<h3 title="what the agent is working toward. Stored with the session; the agent reads it via get_goal(). Auto-continue keeps looping while the status is 'active' and stops when marked done.">🎯 goal`),Sd=L(`<div class=statrow style=margin-bottom:6px><span class=k>status`),Cd=L(`<div class=card><div class=content>`),wd=L(`<div class="card verifycard"title="verification contract — finish(goalComplete=true) is audited against these requirements by an independent reviewer before the goal counts as done"><div class=vtitle>🔍 verification contract</div><div class=content>`),Td=L(`<form style=display:flex;flex-direction:column;gap:6px;margin-top:8px;margin-bottom:6px><textarea id=goal-input rows=3 placeholder="set new goal…"style="background:var(--bg-darkest);border:none;border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;width:100%;resize:vertical"></textarea><textarea id=goal-verify-input rows=2 placeholder="verification contract (optional) — e.g. 'npm test passes; endpoint documented'. finish(goalComplete=true) is then audited against this."title="pi-goal-x-style verification contract — an independent reviewer checks the agent's finish against these requirements"style="background:var(--bg-darkest);border:1px solid var(--bg-light);border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;font-size:12.5px;width:100%;resize:vertical"></textarea><div style=display:flex;justify-content:flex-end;align-items:center;gap:10px><label class=muted title="queue a harness prompt telling the agent about the new goal at its next turn boundary"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=goal-notify type=checkbox> notify agent</label><button type=submit style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:4px 12px;cursor:pointer">✓ save goal`),Ed=L(`<span class=badge>/<!> done`),Dd=L(`<h3 title="todo.md — a shared checklist in the session dir. Write tasks like '- [ ] fix login'; the agent ticks them off via set_todo, you edit here. With notify on, it's told at its next turn boundary.">✅ tasks<span class=muted style=text-transform:none;letter-spacing:0>· shared checklist (you + agent)`),Od=L(`<div class=bartrack style=margin-bottom:6px><div>`),kd=L(`<div style=display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:4px><label class=muted title="queue a harness prompt telling the agent the task list changed"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=todo-notify type=checkbox checked> notify agent</label><button style="background:var(--ok);border:none;border-radius:6px;color:#fff;padding:4px 12px;cursor:pointer">✓ save tasks`),Ad=L(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),jd=L(`<h3 title="context is how much of the model's window the live conversation occupies. Past the threshold, the oldest turns are summarized into notes so work can continue.">📊 runtime`),Md=L(`<div class=rtcell><span>cost</span><b>$`),Nd=L(`<div class=rtcell><span>cached</span><b>%`),Pd=L(`<div class="card runcard"><div class=rtgrid><div class=rtcell title="prompt tokens billed this session"><span>tokens in</span><b></b></div><div class=rtcell title="completion tokens billed this session"><span>tokens out</span><b></b></div><div class=rtcell title="assistant turns this session"><span>turns</span><b></b></div><div class=rtcell title="tool calls this session"><span>tools</span><b></b></div><div class=rtcell><span>compacted</span><b>`),Fd=L(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),Id=L(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),Ld=L(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),Rd=L(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙ settings → scheduled tasks.">⏰ schedule`),zd=L(`<option>`),Bd=L(`<span class=badge title="no goal set yet">no goal`),Vd=L(`<button>`),Hd=L(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),Ud=L(`<div><div class=vtitle><span class="meta muted"style=margin-left:auto></span></div><div class=content>`),Wd=L(`<div class=muted>none yet — the harness asks for a report after real activity, and the agent can report_progress anytime`),Gd=L(`<div class=progrow><b>recent</b><span class="content inline-md">`),Kd=L(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),qd=L(`<div class=progrow><b>next</b><span class="content inline-md">`),Jd=L(`<div class=progrow><b>goal</b><span>`),Yd=L(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),Xd=L(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),Zd=L(`<span>% of `),Qd=L(`<div class=bartrack><div>`),$d=L(`<div class=statrow title="a compaction pass is running right now — the summarizer's output streams in the timeline"><span class=k>🗜</span><b>compacting…</b><span class=muted style=font-size:11px;color:var(--acc)>`),ef=L(`<div class=ctxblock title="estimated live context vs the model's real window. Past the window, old turns are summarized into notes (compaction); the compact line below shows where that starts."><div class=statrow><span class=k>context</span><b>~<!> tok</b></div><div class=statrow style=margin-top:4px><span class=k>compact at</span><b> tok</b><span class=muted style=color:var(--dim)></span></div><div class=ctrlrow style=margin-top:6px><label title="when on, older turns are automatically summarized when context exceeds the budget"><input type=checkbox>auto-compact`),tf=L(`<div><span></span><span> events`),nf=L(`<div class=muted>no scheduled tasks — add them in ⚙ settings ("scheduled tasks")`),rf=L(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),af=L(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),of=L(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),sf=L(`<div class=nbody>`),cf=L(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),lf=L(`<div><div style=font-size:12.5px;margin-bottom:4px> event(s) came after this prompt — what should happen to them on the new branch?</div><label style=display:flex;gap:6px;align-items:center;font-size:13px;color:var(--fg)><input type=radio name=tail>summarize them into a note the agent can still read</label><label style=display:flex;gap:6px;align-items:center;font-size:13px;color:var(--fg)><input type=radio name=tail>discard them entirely (clean timeline)`),uf=L(`<form style=display:flex;flex-direction:column;gap:10px><textarea id=edit-text class="mono w100"rows=6></textarea><div style=display:flex;justify-content:flex-end;gap:8px><button type=button>cancel</button><button type=submit style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:6px 12px;cursor:pointer">⑂ fork & resend`),df=L(`<span class=bashelapsed>running… `),ff=L(`<span class=bashelapsed> elapsed`),pf=L(`<span class=thinktimer>`),mf=L(`<pre class="mono toolbody">`),hf=L(`<div class=meta>`),gf=L(`<div class=meta>waiting for output…`),_f=L(`<div class=mono>`),vf=L(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),yf=L(`<b>action="kill"`),bf=L(`<div class="meta muted"> bytes — open it from 🗂 files for the full view`),xf=L(`<div class=meta>writing…`),Sf=L(`<pre class="mono toolbody del">`),Cf=L(`<pre class="mono toolbody add">`),wf=L(`<div class=meta> · `),Tf=L(`<div class=meta>applying…`),Ef=L(`<pre class="mono toolbody patch">`),Df=L(`<div>`),Of=L(`<div class="pline meta">… <!> more lines`),kf=L(`<div class=meta>validating…`),Af=L(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),jf=L(`<span class=muted>`),Mf=L(`<div class=meta>loading…`),Nf=L(`<div class=meta>bundled: `),Pf=L(`<div class=meta>saving…`),Ff=L(`<span class=actor>@`),If=L(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),Lf=L(`<div class=divider-msg>⑂ forked from <!> → `),Rf=L(`<div><div class=goalline-label>`),zf=L(`<div class=divider-msg>✅ tasks updated (<!>)`),Bf=L(`<div> → `),Vf=L(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),Hf=L(`<div class="embed warn-embed"title="a round-fatal API error occurred; auto-retry is waiting, then a fresh round starts (onError: retry)"><div class=mono>↻ API error — retrying (attempt <!>) in <!>s…`),Uf=L(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),Wf=L(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),Gf=L(`<span class=ts>`),Kf=L(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),qf=L(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),Jf=L(`<div class=msg-head><span class=author></span><span class=ts>`),Yf=L(`<div><div></div><div class=msg-body>`),Xf=L(`<span class=grouptime>`),Zf=L(`<div class=qfree><input type=text><button>reply`),Qf=L(`<div class=promptimgs>`),$f=L(`<img class=promptimg alt=attachment>`),ep=L(`<details class=reasoning><summary>💭 reasoning</summary><div class=mono>`),tp=L(`<div class=interrupted>⚠ interrupted — partial output kept`),np=L(`<div class=msgfoot><span>copy summary`),rp=L(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),ip=L(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),ap=L(`<div class="content muted">Rejected: `),op=L(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged</span></summary><div class=content>`),sp=L(`<div class=meta style=color:var(--ok)>✓ answered — continuing below`),cp=L(`<div class=qopts>`),lp=L(`<div><div>❓ <div class="content inline-md">`),up=L(`<button class=qopt>`),dp=L(`<div class=embed style=border-color:var(--ok)><div>📈 <div class="content inline-md">`),fp=L(`<div class="embed fail"><div class=mono>⚠ `),pp=L(`<div class=vtitle style=margin-top:6px>what the agent kept`),mp=L(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),hp=L(`<div class="content muted">`),gp=L(`<button type=button><span class=iconbtn-glyph>`),_p=L(`<button class=copybtn>`),vp=L(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`),yp=L(`<span style=color:var(--err);font-size:13px>`),bp=L(`<form style=display:flex;flex-direction:column;gap:10px><label>workspace directory<div style=display:flex;gap:6px><input type=text class="w100 mono"><button type=button>go</button><button type=button title="parent directory">↑</button></div></label><div class=dirlist></div><div style=display:flex;gap:10px><label style=flex:1>agent name <input type=text placeholder="(directory name)"></label><label style="flex:0 1 auto;min-width:0">provider<select></select></label><label style=flex:1>model <input type=text placeholder="(provider default)"></label></div><button type=submit style=align-self:flex-end>create`),xp=L(`<div class=direntry>📁 `),Sp=L(`<span class=tprev><span class=tprev-nav></span><span class=tprev-head></span><span class=tprev-panel></span><span class=tprev-line style=left:32%;top:38%;width:34%;opacity:0.85></span><span class=tprev-line style=left:32%;top:50%;width:22%></span><span class=tprev-line style=left:32%;top:62%;width:40%></span><span class=tprev-dot style=left:6%;top:20%></span><span class=tprev-dot style=left:6%;top:40%></span><span class=tprev-dot style=left:6%;top:60%></span><span class=tprev-dot style=left:70%;top:12%></span><span class=tprev-dot style=left:84%;top:12%>`),Cp=L(`<select title="which custom theme to edit — selecting one also applies it">`),wp=L(`<div class=themeeditor><h4 class=cfgsub>your themes</h4><div class=btnrow><button type=button title="copy the theme you are using into a new editable one — presets themselves are never modified">+ duplicate current`),Tp=L(`<div class=muted style="margin:6px 0">no custom themes yet — press <b>+ duplicate current</b> to start from the palette you are using.`),Ep=L(`<div class=cfggrid style=margin-top:8px><label class=trow>name<input class=w100></label><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),Dp=L(`<div class=paletterows>`),Op=L(`<div class=btnrow><button type=button title="put every colour back to the palette this theme was created from">↺ reset palette</button><button type=button title="delete this custom theme">🗑 delete`),kp=L(`<h4 class=cfgsub>background image`),Ap=L(`<div class=bgpreview><img alt="theme background preview"><span class=muted title="this image is stored inside the theme">✓ image set — <!> KB</span><div class=btnrow><label class=trow title="how much the image is dimmed so text stays readable">dim<input type=range min=0 max=0.9 step=0.05><span class="muted mono">%</span></label><button type=button>✕ remove`),jp=L(`<div class=cfggrid><button type=button class=trow title="PNG/JPG/WebP. Stored in this browser, applied behind the panels."></button><input type=file accept=image/* style=display:none>`),Mp=L(`<div class=muted style=margin-top:6px;font-size:var(--text-xs)>the image is uploaded to the server and sits behind the panels, dimmed so text stays readable. No size limit — it is a file now, not browser storage.`),Np=L(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),Pp=L(`<div class="content mdpreview todopane">`),Fp=L(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- task one
20
+ `,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 yn.get()},set promptLabel(e){yn.set(e)},get tooMuchOutput(){return xn.get()},set tooMuchOutput(e){xn.set(e)}}}_verifyIntegers(...e){for(ru of e)if(ru===1/0||isNaN(ru)||ru%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(ru of e)if(ru&&(ru===1/0||isNaN(ru)||ru%1!=0||ru<0))throw Error(`This API only accepts positive integers`)}},au=2,ou=1,su=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(au,Math.floor(u/e.css.cell.width)),rows:Math.max(ou,Math.floor(l/e.css.cell.height))}}};function cu(e){return e.length}function lu(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function uu(e,t,n){return lu(e===t?t:e>t?e-1:e,n)}function du(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function fu(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}var pu=`modulepreload`,mu=function(e){return`/`+e},hu={},gu=function(e){return e.pathname.endsWith(`.css`)},_u=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},vu=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=mu(t,n);let r=s(t),i=gu(r);return _u(hu,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:pu,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},yu=L(`<div class=overlay><div class=modal style=max-width:360px><div class=modal-head><b>🔒 sign in</b><span></span></div><form style=display:flex;flex-direction:column;gap:10px><input id=pw-input type=password placeholder=password autofocus><button type=submit style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:7px 12px;cursor:pointer">unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),bu=L(`<i class=notifdot>`),xu=L(`<br>`),Su=L(`<span class="badge queued">⏳ <!> of yours queued`),Cu=L(`<span class="badge cron">⏰ `),wu=L(`<header class=chan-head><span class=hash>#</span><span class=title></span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),Tu=L(`<div class=divider-msg>── beginning of log ──`),Eu=L(`<div class=divider-msg>loading older events…`),Du=L(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),Ou=L(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),ku=L(`<div class=content>`),Au=L(`<div class="msg live"><div class=avatar style="background:#5865f233;border:1px solid #5865f266">🫖</div><div class=msg-body><div class=msg-head><span class=author style=color:var(--acc)>agent</span><span class=ts>streaming…`),ju=L(`<div class=feed>`),Mu=L(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),Nu=L(`<div class=termsplit>`),Pu=L(`<div class="termempty muted">no shell here — click a tab or + to add`),Fu=L(`<div class=termpane>`),Iu=L(`<div class=termdrawer><div class=termgrip title="drag to resize · double-click to reset"></div><div class=termbar><div class=termtabs></div><div style=display:flex;gap:4px;align-items:center><span class="muted mono"style=flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap></span></div></div><div class=termbody><div class=termpane>`),Lu=L(`<button class=jump>↓ `),Ru=L(`<div class=cmds>`),zu=L(`<div class=imgstage><span class=muted style=font-size:11px;align-self:center> image<!> attached`),Bu=L(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),Vu=L(`<span class=muted style=font-size:11.5px;white-space:nowrap>🖼 `),Hu=L(`<div class="hint flashhint">`),Uu=L(`<div><form><textarea rows=1></textarea><button type=button class="iconbtn maxbtn"></button><button type=submit>send</button><input id=composer-file type=file accept=image/* multiple style=display:none>`),Wu=L(`<div class=rightbarbackdrop>`),Gu=L(`<div><nav class=sidebar><div class=agent-list></div><div class=sidebar-footer><div class=footer-row style=justify-content:flex-end><button>🔔</button></div><div class=brand-row><div class=brand>🫖 teapot <span class=version>v</span><span></span></div></div><div class=metrics></div></div></nav><section class=channel></section><aside><div class=rightbarhead><span class=muted>details`),Ku=L(`<div class=notifbackdrop>`),qu=L(`<button class=editbtn>clear all`),Ju=L(`<div class=notiflist>`),Yu=L(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),Xu=L(`<span class=wscount>`),Zu=L(`<div class=wsheader><span class=wscaret>`),Qu=L(`<span class=notifbadge>🔔`),$u=L(`<span class=subtag>🧩`),ed=L(`<span class=mini-cron>⏰`),td=L(`<span class=goaldone title="goal done">✓`),nd=L(`<div><span></span><span>`),rd=L(`<span class=caret-spacer>`),id=L(`<span class=caret>`),ad=L(`<span class=ghosttag title="workspace missing">👻`),od=L(`<span>🧩 `),sd=L(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),cd=L(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),ld=L(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),ud=L(`<div class="content muted">thinking…`),dd=L(`<span>⌨ <button class=tabx title="close this shell">✕`),fd=L(`<div><b class=mono></b><span class=muted>`),pd=L(`<div class=cmdrow><b>@</b><span class=muted>`),md=L(`<span class=imgchip><img><button type=button class=imgx title=remove>✕`),hd=L(`<h3 title="switch provider/model live — applies from the agent's next turn; the list shows context window &amp; pricing from the provider">🧦 model`),gd=L(`<div style=display:flex;gap:6px;align-items:center;margin-top:6px><label class=muted style=font-size:11.5px;white-space:nowrap>effort</label><select style=flex:1;min-width:0><option value>provider default`),_d=L(`<div class=meta style=color:var(--fg)>`),vd=L(`<div class=modelbox><select title="provider (OpenAI-compatible endpoint)"></select><div style=display:flex;gap:4px><input type=text list=model-list style=flex:1;min-width:0><datalist id=model-list></datalist></div><div style=display:flex;gap:6px;align-items:center;margin-top:6px><button title="apply the provider, model and effort above to this session — takes effect from the agent's next turn"style=flex:1>apply</button></div><div class=meta>current: `),yd=L(`<div class=ctrlrow><label title="auto-continue fires after a round ONLY when all hold: ① this toggle is on ② a goal is set and its status is 'active' ③ the round ended cleanly (no error / not stopped). It stops when the goal is marked done, or if you press ■ stop. Sending any prompt also starts an idle agent regardless."><input type=checkbox>auto-continue`),bd=L(`<span>`),xd=L(`<h3 title="what the agent is working toward. Stored with the session; the agent reads it via get_goal(). Auto-continue keeps looping while the status is 'active' and stops when marked done.">🎯 goal`),Sd=L(`<div class=statrow style=margin-bottom:6px><span class=k>status`),Cd=L(`<div class="card goalcard"><div class=content>`),wd=L(`<div class="card verifycard"title="verification contract — finish(goalComplete=true) is audited against these requirements by an independent reviewer before the goal counts as done"><div class=vtitle>🔍 verification contract</div><div class=content>`),Td=L(`<form style=display:flex;flex-direction:column;gap:6px;margin-top:8px;margin-bottom:6px><textarea id=goal-input rows=3 placeholder="set new goal…"style="background:var(--bg-darkest);border:none;border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;width:100%;resize:vertical"></textarea><textarea id=goal-verify-input rows=2 placeholder="verification contract (optional) — e.g. 'npm test passes; endpoint documented'. finish(goalComplete=true) is then audited against this."title="pi-goal-x-style verification contract — an independent reviewer checks the agent's finish against these requirements"style="background:var(--bg-darkest);border:1px solid var(--bg-light);border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;font-size:12.5px;width:100%;resize:vertical"></textarea><div style=display:flex;justify-content:flex-end;align-items:center;gap:10px><label class=muted title="queue a harness prompt telling the agent about the new goal at its next turn boundary"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=goal-notify type=checkbox> notify agent</label><button type=submit style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:4px 12px;cursor:pointer">✓ save goal`),Ed=L(`<span class=badge>/<!> done`),Dd=L(`<h3 title="todo.md — a shared checklist in the session dir. Write tasks like '- [ ] fix login'; the agent ticks them off via set_todo, you edit here. With notify on, it's told at its next turn boundary.">✅ tasks<span class=muted style=text-transform:none;letter-spacing:0>· shared checklist (you + agent)`),Od=L(`<div class=bartrack style=margin-bottom:6px><div>`),kd=L(`<div style=display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:4px><label class=muted title="queue a harness prompt telling the agent the task list changed"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=todo-notify type=checkbox checked> notify agent</label><button style="background:var(--ok);border:none;border-radius:6px;color:#fff;padding:4px 12px;cursor:pointer">✓ save tasks`),Ad=L(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),jd=L(`<h3 title="context is how much of the model's window the live conversation occupies. Past the threshold, the oldest turns are summarized into notes so work can continue.">📊 runtime`),Md=L(`<div class=rtcell><span>cost</span><b>$`),Nd=L(`<div class=rtcell><span>cached</span><b>%`),Pd=L(`<div class="card runcard"><div class=rtgrid><div class=rtcell title="prompt tokens billed this session"><span>tokens in</span><b></b></div><div class=rtcell title="completion tokens billed this session"><span>tokens out</span><b></b></div><div class=rtcell title="assistant turns this session"><span>turns</span><b></b></div><div class=rtcell title="tool calls this session"><span>tools</span><b></b></div><div class=rtcell><span>compacted</span><b>`),Fd=L(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),Id=L(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),Ld=L(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),Rd=L(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙ settings → scheduled tasks.">⏰ schedule`),zd=L(`<option>`),Bd=L(`<span class=badge title="no goal set yet">no goal`),Vd=L(`<button>`),Hd=L(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),Ud=L(`<div><div class=vtitle><span class="meta muted"style=margin-left:auto></span></div><div class=content>`),Wd=L(`<div class=muted>none yet — the harness asks for a report after real activity, and the agent can report_progress anytime`),Gd=L(`<div class=progrow><b>recent</b><span class="content inline-md">`),Kd=L(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),qd=L(`<div class=progrow><b>next</b><span class="content inline-md">`),Jd=L(`<div class=progrow><b>goal</b><span>`),Yd=L(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),Xd=L(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),Zd=L(`<span>% of `),Qd=L(`<div class=bartrack><div>`),$d=L(`<div class=statrow title="a compaction pass is running right now — the summarizer's output streams in the timeline"><span class=k>🗜</span><b>compacting…</b><span class=muted style=font-size:11px;color:var(--acc)>`),ef=L(`<div class=ctxblock title="estimated live context vs the model's real window. Past the window, old turns are summarized into notes (compaction); the compact line below shows where that starts."><div class=statrow><span class=k>context</span><b>~<!> tok</b></div><div class=statrow style=margin-top:4px><span class=k>compact at</span><b> tok</b><span class=muted style=color:var(--dim)></span></div><div class=ctrlrow style=margin-top:6px><label title="when on, older turns are automatically summarized when context exceeds the budget"><input type=checkbox>auto-compact`),tf=L(`<div><span></span><span> events`),nf=L(`<div class=muted>no scheduled tasks — add them in ⚙ settings ("scheduled tasks")`),rf=L(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),af=L(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),of=L(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),sf=L(`<div class=nbody>`),cf=L(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),lf=L(`<div><div style=font-size:12.5px;margin-bottom:4px> event(s) came after this prompt — what should happen to them on the new branch?</div><label style=display:flex;gap:6px;align-items:center;font-size:13px;color:var(--fg)><input type=radio name=tail>summarize them into a note the agent can still read</label><label style=display:flex;gap:6px;align-items:center;font-size:13px;color:var(--fg)><input type=radio name=tail>discard them entirely (clean timeline)`),uf=L(`<form style=display:flex;flex-direction:column;gap:10px><textarea id=edit-text class="mono w100"rows=6></textarea><div style=display:flex;justify-content:flex-end;gap:8px><button type=button>cancel</button><button type=submit style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:6px 12px;cursor:pointer">⑂ fork & resend`),df=L(`<span class=bashelapsed>running… `),ff=L(`<span class=bashelapsed> elapsed`),pf=L(`<span class=thinktimer>`),mf=L(`<pre class="mono toolbody">`),hf=L(`<div class=meta>`),gf=L(`<div class=meta>waiting for output…`),_f=L(`<div class=mono>`),vf=L(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),yf=L(`<b>action="kill"`),bf=L(`<div class="meta muted"> bytes — open it from 🗂 files for the full view`),xf=L(`<div class=meta>writing…`),Sf=L(`<pre class="mono toolbody del">`),Cf=L(`<pre class="mono toolbody add">`),wf=L(`<div class=meta> · `),Tf=L(`<div class=meta>applying…`),Ef=L(`<pre class="mono toolbody patch">`),Df=L(`<div>`),Of=L(`<div class="pline meta">… <!> more lines`),kf=L(`<div class=meta>validating…`),Af=L(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),jf=L(`<span class=muted>`),Mf=L(`<div class=meta>loading…`),Nf=L(`<div class=meta>bundled: `),Pf=L(`<div class=meta>saving…`),Ff=L(`<span class=actor>@`),If=L(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),Lf=L(`<div class=divider-msg>⑂ forked from <!> → `),Rf=L(`<div><div class=goalline-label>`),zf=L(`<div class=divider-msg>✅ tasks updated (<!>)`),Bf=L(`<div> → `),Vf=L(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),Hf=L(`<div class="embed warn-embed"title="a round-fatal API error occurred; auto-retry is waiting, then a fresh round starts (onError: retry)"><div class=mono>↻ API error — retrying (attempt <!>) in <!>s…`),Uf=L(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),Wf=L(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),Gf=L(`<span class=ts>`),Kf=L(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),qf=L(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),Jf=L(`<div class=msg-head><span class=author></span><span class=ts>`),Yf=L(`<div><div></div><div class=msg-body>`),Xf=L(`<span class=grouptime>`),Zf=L(`<div class=qfree><input type=text><button>reply`),Qf=L(`<div class=promptimgs>`),$f=L(`<img class=promptimg alt=attachment>`),ep=L(`<details class=reasoning><summary>💭 reasoning</summary><div class=mono>`),tp=L(`<div class=interrupted>⚠ interrupted — partial output kept`),np=L(`<div class=msgfoot><span>copy summary`),rp=L(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),ip=L(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),ap=L(`<div class="content muted">Rejected: `),op=L(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged</span></summary><div class=content>`),sp=L(`<div class=meta style=color:var(--ok)>✓ answered — continuing below`),cp=L(`<div class=qopts>`),lp=L(`<div><div>❓ <div class="content inline-md">`),up=L(`<button class=qopt>`),dp=L(`<div class=embed style=border-color:var(--ok)><div>📈 <div class="content inline-md">`),fp=L(`<div class="embed fail"><div class=mono>⚠ `),pp=L(`<div class=vtitle style=margin-top:6px>what the agent kept`),mp=L(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),hp=L(`<div class="content muted">`),gp=L(`<button type=button><span class=iconbtn-glyph>`),_p=L(`<button class=copybtn>`),vp=L(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`),yp=L(`<span style=color:var(--err);font-size:13px>`),bp=L(`<form style=display:flex;flex-direction:column;gap:10px><label>workspace directory<div style=display:flex;gap:6px><input type=text class="w100 mono"><button type=button>go</button><button type=button title="parent directory">↑</button></div></label><div class=dirlist></div><div style=display:flex;gap:10px><label style=flex:1>agent name <input type=text placeholder="(directory name)"></label><label style="flex:0 1 auto;min-width:0">provider<select></select></label><label style=flex:1>model <input type=text placeholder="(provider default)"></label></div><button type=submit style=align-self:flex-end>create`),xp=L(`<div class=direntry>📁 `),Sp=L(`<span class=tprev><span class=tprev-nav></span><span class=tprev-head></span><span class=tprev-panel></span><span class=tprev-line style=left:32%;top:38%;width:34%;opacity:0.85></span><span class=tprev-line style=left:32%;top:50%;width:22%></span><span class=tprev-line style=left:32%;top:62%;width:40%></span><span class=tprev-dot style=left:6%;top:20%></span><span class=tprev-dot style=left:6%;top:40%></span><span class=tprev-dot style=left:6%;top:60%></span><span class=tprev-dot style=left:70%;top:12%></span><span class=tprev-dot style=left:84%;top:12%>`),Cp=L(`<select title="which custom theme to edit — selecting one also applies it">`),wp=L(`<div class=themeeditor><h4 class=cfgsub>your themes</h4><div class=btnrow><button type=button title="copy the theme you are using into a new editable one — presets themselves are never modified">+ duplicate current`),Tp=L(`<div class=muted style="margin:6px 0">no custom themes yet — press <b>+ duplicate current</b> to start from the palette you are using.`),Ep=L(`<div class=cfggrid style=margin-top:8px><label class=trow>name<input class=w100></label><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),Dp=L(`<div class=paletterows>`),Op=L(`<div class=btnrow><button type=button title="put every colour back to the palette this theme was created from">↺ reset palette</button><button type=button title="delete this custom theme">🗑 delete`),kp=L(`<h4 class=cfgsub>background image`),Ap=L(`<div class=bgpreview><img alt="theme background preview"><span class=muted title="this image is stored inside the theme">✓ image set — <!> KB</span><div class=btnrow><label class=trow title="how much the image is dimmed so text stays readable">dim<input type=range min=0 max=0.9 step=0.05><span class="muted mono">%</span></label><button type=button>✕ remove`),jp=L(`<div class=cfggrid><button type=button class=trow title="PNG/JPG/WebP. Stored in this browser, applied behind the panels."></button><input type=file accept=image/* style=display:none>`),Mp=L(`<div class=muted style=margin-top:6px;font-size:var(--text-xs)>the image is uploaded to the server and sits behind the panels, dimmed so text stays readable. No size limit — it is a file now, not browser storage.`),Np=L(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),Pp=L(`<div class="content mdpreview todopane">`),Fp=L(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- task one
21
21
  - task two"title="shared with the agent \\u2014 it may check items off via set_todo; your unsaved edits win until you save">`),Ip=L(`<span class=fsize>`),Lp=L(`<div><span class=ficon></span><span class=fname>`),Rp=L(`<h3 title="the agent's workspace — lazy-loaded, dotfiles hidden; click a folder to expand, a file to preview"style=display:flex;align-items:center;gap:6px>🗂 files <span class=muted style=text-transform:none;letter-spacing:0>· `),zp=L(`<div class=filebox>`),Bp=L(`<div class=muted style=padding:6px>`),Vp=L(`<img>`),Hp=L(`<div class=mediapreview><div class="meta muted"> preview`),Up=L(`<button title="rendered markdown">👁 preview`),Wp=L(`<button title="edit and save back to the workspace">✎ edit`),Gp=L(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),Kp=L(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),qp=L(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),Jp=L(`<div class="content mdpreview">`),Yp=L(`<video controls>`),Xp=L(`<audio controls>`),Zp=L(`<div class=filepreview>`),Qp=L(`<div class=muted style=padding-top:6px;font-size:11.5px>… truncated (first 100 KB)`),$p=L(`<div class=muted style=padding:8px;font-size:12px>✨ highlighting <!>…`),em=L(`<pre class=mono style=max-height:62vh;overflow:auto;white-space:pre-wrap;margin:0>`),tm=L(`<div class=muted style=font-size:11.5px;margin-top:-6px>`),nm=L(`<div class=wizmodels>`),rm=L(`<span style=color:var(--fg)>`),im=L(`<div class=muted style=font-size:11.5px;margin-top:-6px> model`),am=L(`<div class=overlay style=background:var(--bg-darkest)><div class=modal style=max-width:560px><div class=modal-head><b>🫖 welcome to teapot</b></div><p class=muted style="margin:0 0 10px;font-size:13px">first run — pick an OpenAI-compatible provider and you're done. everything below can be changed later in ⚙ settings.</p><form style=display:flex;flex-direction:column;gap:12px><div style=display:flex;gap:6px;flex-wrap:wrap></div><label>base url<input type=text class="w100 mono"list=wiz-preset-urls><datalist id=wiz-preset-urls></datalist></label><label>api key <input type=password class=w100 placeholder="(local providers may not need one)"></label><label>model<input type=text class="w100 mono"list=wiz-model-list><datalist id=wiz-model-list></datalist></label><fieldset><legend>first agent</legend><label>workspace directory<input type=text class="w100 mono"></label><label title="asks for this password when opening the UI or API from another machine — plain-HTTP LAN traffic is NOT encrypted"style=margin-top:4px>protect the API with a password? <input type=password class=w100 placeholder="(optional — LAN traffic is still plain HTTP)"></label></fieldset><button type=submit style="background:var(--acc);border:none;border-radius:8px;color:#fff;padding:9px 14px;font-weight:600;cursor:pointer">`),om=L(`<button type=button>`),sm=L(`<div class=muted style=font-size:11.5px;margin-top:-8px>`),cm=L(`<button type=button><span class=mono>`),lm=L(`<label><input type=number min=0>`),um=L(`<div class=muted style=font-size:11.5px;margin-top:4px>⚠ configured default provider <code></code> has no provider row here<!> Add a provider named <code></code> or pick a default below; otherwise agents fall back to the first provider.`),dm=L(`<div class=cfggrid style=margin-top:8px><label class=trow>dark theme →<select class=w100></select></label><label class=trow>light theme →<select class=w100>`),fm=L(`<form style=display:flex;flex-direction:column;gap:12px;min-height:0><div class=cfgbody><nav class=cfgmenu aria-label="settings sections"></nav><div class=cfgpanel><fieldset><legend>providers</legend><button type=button>+ add custom</button><div style=display:flex;gap:6px;flex-wrap:wrap;margin-top:6px><span class=muted style=font-size:11.5px>quick-add:</span></div><div><label title="agents without an explicit provider use this one"style=display:flex;align-items:center;gap:6px;margin-top:6px>default provider<select><option value>(none — first provider wins)</option></select></label></div></fieldset><fieldset><legend>appearance</legend><div class=cfggrid><label class=trow>follow the system<input type=checkbox></label></div><h4 class=cfgsub>themes</h4></fieldset><fieldset><legend>agent runtime</legend><div class=cfggrid><label title="auto-compact threshold in k tokens. Leave EMPTY to derive per model (75% of its context window) — recommended, since models differ wildly in window size. Set only to force an absolute cap across all models.">compact budget (k tok)<input type=number min=0 placeholder="(derive: 75% of window)"></label></div><label class=cfgtoggle title="prune old tool output early (at 60% of the budget) instead of waiting for the window to fill. Meant for small-window models — on a large window it throws away context you had room for."><input type=checkbox>short-context mode (#161)</label></fieldset><fieldset><legend>MCP servers — external tools, shared by every agent</legend><div class=muted style=font-size:11.5px;margin-bottom:8px>each tool becomes <code class=mono>mcp__server__tool</code> for every agent. saving connects them; the status shown here is live.</div><button type=button>+ add MCP server</button></fieldset><fieldset><legend>scheduled tasks</legend><button type=button>+ add task</button></fieldset><fieldset><legend>archived agents — restore, or delete for good</legend></fieldset><fieldset><legend>agents (read-only — edit config file or use +)</legend></fieldset><fieldset><legend>live update</legend><div class=cfgrow><span class=muted>current version: </span><button type=button style="background:var(--acc);border:none;border-radius:6px;color:#fff;padding:6px 14px;cursor:pointer">update & restart</button><span class=muted style=margin-left:8px;font-size:12px>gracefully stops all agents, spawns new process, then reloads this page</span></div></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>keyboard</h4><div class=helprow><kbd>enter</kbd><span>send (shift+enter for a newline)</span></div><div class=helprow><kbd>↑</kbd><kbd>↓</kbd><span>move between sessions</span></div><div class=helprow><kbd>/</kbd><span>command palette — commands and focus</span></div><div class=helprow><kbd>t</kbd><span>open the terminal panel</span></div><div class=helprow><kbd>d</kbd><span>toggle the details panel</span></div><div class=helprow><kbd>esc</kbd><span>interrupt the running turn</span></div></div><div class=helpsec><h4 class=cfgsub>what the toggles do</h4><div class=helprow><b>auto-continue</b><span>fires after a round only when all hold: the toggle is on, a goal is set and its status is <code>active</code>, and the round ended cleanly (not an error, not stopped). It stops when the goal is marked done, or when you press ■ stop. Sending any prompt starts an idle agent regardless.</span></div><div class=helprow><b>auto-compact</b><span>when the live context passes the budget shown under 📊 runtime, older turns are summarized into notes and the recent stretch is kept verbatim, so work continues without losing the thread. Off means you compact by hand (<code>/compact</code>).</span></div><div class=helprow><b>messages while it works</b><span>anything you send queues up and is handed to the model at its next turn boundary — the timeline shows it as "pending (queued)…" until then. Withdraw it with ✕ cancel while it is still queued.</span></div><div class=helprow><b>👻 ghost sessions</b><span>a session whose workspace directory no longer exists on disk. The session log is intact — recreate the directory and it stops being a ghost.</span></div></div></fieldset></div></div><div class=cfgfoot><button type=submit class=cfgsave>save settings`),pm=L(`<button type=button><span class=cfgmenu-label>`),mm=L(`<div class=cfgrow><input class=cfgname placeholder=name><input placeholder=https://…/v1><input placeholder="default model"><button type=button class=danger title="remove provider">✕</button><div class=cfgkeys><button type=button title="add another key for this provider — they are rotated round-robin, and a rate-limited key is skipped for a minute">+ key`),hm=L(`<button type=button title="remove this key">−`),gm=L(`<div class=cfgkeyrow><input type=password>`),_m=L(`<button type=button>+ `),vm=L(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),ym=L(`<div class=themepick>`),bm=L(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),xm=L(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),Sm=L(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),Cm=L(`<input placeholder="command (e.g. npx)">`),wm=L(`<input placeholder="args, space separated">`),Tm=L(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),Em=L(`<input placeholder="header name"style="flex:0 1 150px">`),Dm=L(`<input type=password placeholder=value style=flex:1>`),Om=L(`<div class=cfgrow><textarea class=mono rows=2 placeholder="{&quot;Authorization&quot;: &quot;Bearer …&quot;, &quot;X-Team&quot;: &quot;infra&quot;}"title="static headers for every request. Use the bearer option unless the server needs something unusual."style=flex:1>`),km=L(`<button type=button class=archrestore title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),Am=L(`<span class="mcpstate connected"title="an OAuth access token is usable">🔑 authorized`),jm=L(`<button type=button title="forget the stored grant (the refresh token is deleted)">disconnect`),Mm=L(`<div class=muted style=font-size:11px;color:var(--warn)>`),Nm=L(`<div class="cfgcol mcpcard"><div class=cfgrow><input class=cfgname placeholder=name title="the name that appears inside mcp__<name>__ in tool names"><input placeholder="https://example.com/mcp (or leave empty for a stdio command)"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>on</label><button type=button class=danger>✕</button></div><div class=cfgrow><select title="streamable HTTP is the current spec; legacy SSE is the 2024-11-05 handshake; stdio spawns a local process"><option value=http>streamable http</option><option value=sse>legacy http+sse</option><option value=stdio>stdio (local command)</option></select></div><div class=cfgrow><select title="how this server authenticates"><option value=none>no auth</option><option value=bearer>bearer token</option><option value=header>custom header</option><option value=json>headers as JSON (advanced)</option></select></div><div class=cfgrow><button type=button title="connect now and list the tools — nothing is saved">test`),Pm=L(`<span class=muted> · needs a grant (🔑 authorize)`),Fm=L(`<ul class=mcptools>`),Im=L(`<div><div class=mcpresult-head><b>`),Lm=L(`<span class=mcptool-desc>`),Rm=L(`<li><code class=mono>`),zm=L(`<div class=cfgcol><div class=cfgrow><input placeholder=id><input placeholder="agent id"><input placeholder="every 30m / cron"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>fork</label><button type=button class=danger>✕</button></div><textarea rows=2 placeholder="prompt to send">`),Bm=L(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),Vm=L(`<div class="cfgrow archrow"><div class=archmain><b></b><span class=muted> session</span><span class="muted mono ellip"></span></div><button type=button class=archrestore title="bring it back and start it again — its history was never touched">↩ restore</button><button type=button class=danger title="erase the config entry AND every session directory — irreversible">🗑 delete`),Hm=L(`<span class=muted>🧩 sub of @`),Um=L(`<div class=cfgrow><b></b><span class=muted>`),Wm=new Map;function Gm(e){let t=Wm.get(e);if(t!==void 0)return t;let n=Pe(e);return Wm.set(e,n),Wm.size>500&&Wm.delete(Wm.keys().next().value),n}var Km=[`minimal`,`low`,`medium`,`high`],qm=1100,Jm={prompt:{name:`you`,icon:`🟧`,color:`#faa81a`},user:{name:`you`,icon:`🟧`,color:`#faa81a`},message:{name:`agent`,icon:`🫖`,color:`#5865f2`},progress:{name:`progress`,icon:`📈`,color:`#3ba55d`},question:{name:`agent`,icon:`❓`,color:`#5865f2`}},Ym={name:`harness`,icon:`📣`,color:`#3ba55d`},[Xm,Zm]=v(``),Qm,Q=e=>{Zm(e),clearTimeout(Qm),Qm=setTimeout(()=>Zm(``),3200)},$m=!1,eh=[{key:`dark`,label:`Dark`,mode:`dark`,sw:[`#1a1c22`,`#2b2e39`,`#5865f2`]},{key:`midnight`,label:`Midnight`,mode:`dark`,sw:[`#0d0f18`,`#252a42`,`#8b7cf7`]},{key:`tea`,label:`Milk Tea`,mode:`dark`,sw:[`#241c16`,`#493b2d`,`#d98e32`]},{key:`coffee`,label:`Coffee`,mode:`dark`,sw:[`#191410`,`#403527`,`#c68a4b`]},{key:`matcha`,label:`Matcha`,mode:`dark`,sw:[`#1b2217`,`#3c4a33`,`#8db64e`]},{key:`matrix`,label:`Matrix`,mode:`dark`,sw:[`#060a06`,`#18301d`,`#2fd558`]},{key:`sunset`,label:`Sunset`,mode:`dark`,sw:[`#1c1422`,`#452f52`,`#f2784b`]},{key:`light`,label:`Light`,mode:`light`,sw:[`#eceef4`,`#ffffff`,`#4757d8`]},{key:`strawberry`,label:`Strawberry`,mode:`light`,sw:[`#fbe4ea`,`#fffafb`,`#e05575`]},{key:`ramune`,label:`Ramune`,mode:`light`,sw:[`#ddeff7`,`#fbfeff`,`#1d86ae`]}],th=e=>{if(e.data?.actor)return{name:`@${String(e.data.actor)}`,icon:`🧩`,color:`#3ba0c9`};if(e.type===`tool_call`||e.type===`tool_result`)return{name:String(e.data?.name??`tool`),icon:`⚙`,color:`#3ba0c9`};if(e.type===`prompt`){let t=String(e.data?.source??`user`);return t===`user`?Jm.prompt:t.startsWith(`scheduler:`)?{name:t.slice(10),icon:`📣`,color:`#3ba55d`}:Ym}return Jm[e.type]??{name:e.type,icon:`•`,color:`#9298a5`}},nh=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`system_note`]),rh=new Set([`system_note`]),ih=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`]),ah=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),oh=e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`};async function $(e,t){let n=localStorage.getItem(`teapot.token`),r=new Headers(t?.headers);n&&!r.has(`authorization`)&&r.set(`authorization`,`Bearer ${n}`);let i=await fetch(e,{...t,headers:r});if(!i.ok){i.status===401&&window.dispatchEvent(new CustomEvent(`teapot:unauthorized`));let t=null;try{t=await i.json()}catch{}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):``)||`${e}: HTTP ${i.status}`;throw Object.assign(Error(n),{payload:t})}return i.json()}var sh=location.hash.match(/[#&]token=([^&]+)/);sh&&(localStorage.setItem(`teapot.token`,decodeURIComponent(sh[1])),history.replaceState(null,``,location.pathname+location.search));var ch=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function lh(){let[e,t]=v([]),[n,r]=v(null),[i,a]=v(``),[o,s]=v(new Map),[c,l]=v(new Map),[u,d]=v(new Map),f=!1;async function p(e=!1){if(!f||e){f=!0;try{let e=await $(`/api/sessions`),t=new Map,n=new Map,r=new Map;for(let i of e.sessions??[]){t.set(i.id,i.agentId),typeof i.title==`string`&&i.title&&r.set(i.id,i.title);let e=n.get(i.agentId)??[];e.push(i.id),n.set(i.agentId,e)}s(t),l(n),d(r)}catch{}}}let[m,h]=v([]),[g,_]=v(0),[w,T]=v([]),[E,te]=v(null),D=new Map,[ne,re]=v(D.get(n()??``)??``),O=e=>{re(e);let t=n();t&&(e?D.set(t,e):D.delete(t))},[k,ie]=v({providers:{}}),[ae,oe]=v(!1),[se,ce]=v(!1),A=new Set,le=()=>window.innerWidth<=qm,[j,ue]=v(le());ee(()=>{let e=()=>ue(le());window.addEventListener(`resize`,e),C(()=>window.removeEventListener(`resize`,e)),e()});let de,M,fe=0,pe=``,me=()=>{fe=0;let e=Vr();if(!e)return;if(ea=e.scrollHeight,ia=e.clientHeight,ut()){Wr();return}let t=ve(e);if(!t)return;let n=e.querySelector(t.sel);if(!n)return;let r=n.getBoundingClientRect().top-t.top;r&&(e.scrollTop+=r,$i={top:e.scrollTop,height:e.scrollHeight}),Tt(Hr())};function he(e,t){if(!t)return;let n=e.querySelector(t.sel);if(!n)return;let r=n.getBoundingClientRect().top-t.top;Math.abs(r)<1||(e.scrollTop+=r,$i={top:e.scrollTop,height:e.scrollHeight})}let ge=()=>{fe||=requestAnimationFrame(me)},_e=e=>{e&&e!==M&&(de??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==pe&&(pe=n,ge())}),M&&de.unobserve(M),M=e,pe=``,de.observe(e))};ee(()=>{window.addEventListener(`resize`,ge),C(()=>{window.removeEventListener(`resize`,ge),de?.disconnect(),de=void 0,M=void 0,fe&&cancelAnimationFrame(fe)})});function ve(e){let t=e.querySelectorAll(`[data-eid]`);if(!t.length)return null;let n=e.getBoundingClientRect().top,r=e=>t[e].getBoundingClientRect(),i=0,a=t.length-1,o=-1;for(;i<=a;){let e=i+a>>1;r(e).bottom>n?(o=e,a=e-1):i=e+1}if(o<0)return null;let s=t[o].dataset.eid??``;return s?{sel:`[data-eid="${CSS.escape(s)}"]`,top:r(o).top}:null}let[ye,be]=v(localStorage.getItem(`teapot.panel`)===null?window.innerWidth>qm:localStorage.getItem(`teapot.panel`)===`1`),xe=e=>{be(e),localStorage.setItem(`teapot.panel`,e?`1`:`0`)},L=()=>xe(!ye()),Se=()=>{ye()&&xe(!1)},[Ce,De]=v(localStorage.getItem(`teapot.theme`)??`dark`),[Oe,ke]=v(localStorage.getItem(`teapot.theme.auto`)===`1`),[Ae,je]=v(localStorage.getItem(`teapot.theme.light`)??`light`),[Me,Ne]=v(cn()),[Fe,Ie]=v(localStorage.getItem(`teapot.theme.dark`)??`dark`),Le=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[Re,ze]=v(Le?.matches??!1);ee(()=>{let e=e=>ze(e.matches);Le?.addEventListener(`change`,e),C(()=>Le?.removeEventListener(`change`,e))}),b(()=>{let e=pn({want:Oe()?Re()?Ae():Fe():Ce(),customIds:Me().map(e=>e.id),presetIds:eh.map(e=>e.key),fallback:`dark`}),t=e.active,n=Me().find(e=>e.id===t)??null;e.repaired&&(Oe()?localStorage.setItem(Re()?`teapot.theme.light`:`teapot.theme.dark`,t):localStorage.setItem(`teapot.theme`,t)),document.documentElement.dataset.theme=t,dn(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??eh.find(e=>e.key===t)?.mode??`dark`}),b(()=>{localStorage.getItem(`teapot.feedCv`)===`0`?delete document.documentElement.dataset.feedcv:document.documentElement.dataset.feedcv=`on`});let[Ue,Ge]=v(``),[Xe,Ze]=v(``),[Qe,$e]=v(``);b(()=>{let t=n();$e(S(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[et,tt]=v([]),nt=()=>Object.keys(k().providers??{});async function rt(e){if(e)try{let t=await $(`/api/models?provider=${encodeURIComponent(e)}`);tt(t.models??[])}catch{tt([])}}let it=e=>{let t={text:`📄`,image:`🖼️`,audio:`🔊`,video:`🎬`,file:`📎`},n=e=>(e??[`text`]).map(e=>t[e]??e).join(``);return e?.modalities?`${n(e.modalities.input)} → ${n(e.modalities.output)}`:``},at=()=>{let e=Xe().trim()||V()?.model||``;if(!e)return``;let t=et().find(t=>t.id===e);if(!t)return``;let n=[],r=it(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${yh(t.contextLength)} tok`);let i=e=>e===void 0?``:`${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=i(t.pricing.prompt),r=i(t.pricing.completion);e&&r?n.push(`${e} in · ${r} out`):(e||r)&&n.push(i(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},ot=null,st=!1;b(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||k().defaultProvider||nt()[0]||``;if(r){if(t!==ot)ot=t,st=!1,S(()=>Ue())!==i&&(Ge(i),rt(i)),S(()=>Xe())&&Ze(``);else{let e=S(()=>Ue());!S(()=>Xe())&&e!==i&&Wt(st)&&(Ge(i),rt(i))}}});let[ct,lt]=v(!1),[ut,ft]=v(!0),[mt,ht]=v(0),[_t,wt]=v(-1),Tt=e=>wt(e?$t(e):-1),[Et,Dt]=v(null),jt=()=>tn().startsWith(`[compact] `),Lt=()=>jt()?tn().slice(10):tn();b(()=>{Et()||qt(e=>e?.text.startsWith(`[compact] `)?null:e)}),b(()=>{Et(),requestAnimationFrame(()=>requestAnimationFrame(()=>{ut()&&Wr()}))});let[Rt,zt]=v(new Map),Vt=()=>{let e=n();return e?Rt().get(e)??null:null},qt=e=>{let t=n();t&&zt(n=>{let r=new Map(n),i=typeof e==`function`?e(n.get(t)??null):e;return i?r.set(t,{...i,at:Date.now()}):r.delete(t),r})},[tn,nn]=v(``),[rn,an]=v(0),on=()=>rn(),[sn,ln]=v(``),un;b(()=>{Vt()?un||=setTimeout(()=>{un=void 0,nn(Vt()?.text??``),ln(Vt()?.reasoning??``)},(Vt()?.text.length??0)>2e4?250:(Vt()?.text.length??0)>6e3?120:60):(clearTimeout(un),un=void 0,nn(``),ln(``))}),C(()=>clearTimeout(un)),b(()=>{let t=e();zt(e=>qe(e,e=>t.find(t=>t.id===e)?.status)),an(e=>Ye(e,t,n(),Vt()))}),b(()=>{let e=tn(),t=Vt()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{ut()&&Wr()})}),b(()=>{let e=V()?.pendingPrompts??0,t=V()?.pendingPromptIds,n=yn(),r=bn(n),i=kt(r,e,t);i!==r&&xn(n,i)}),b(()=>{let e=V()?.pendingPromptQueue;if(!e?.length)return;let t=yn(),n=new Set(bn(t).map(e=>e.promptId).filter(Boolean)),r=e.filter(e=>e.id&&!n.has(e.id));r.length&&xn(t,[...r.map(e=>({id:`p${e.id}`,text:e.text,at:Number(e.at)||Date.now(),promptId:e.id,images:e.images?.map(e=>e.url),...e.source?{source:e.source}:{}})),...bn(t)])}),b(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{Ur()&&(ft(!0),ht(0),Gr(!0),An())})};document.addEventListener(`visibilitychange`,e),C(()=>document.removeEventListener(`visibilitychange`,e))});let V=x(()=>e().find(e=>e.id===n())),fn=()=>{let e=V();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},mn=()=>Pt(V(),i(),fn()),[hn,gn]=v(null);x(()=>{let e=new Set;for(let t of m())t.type===`tool_result`&&t.data?.name===`ask_user`&&e.add(String(t.data.callId));return e});let _n=new Map,[H,vn]=v([]),yn=()=>i()||n()||`?`,bn=e=>_n.get(e)??[],xn=(e,t)=>{let n=new Set,r=[];for(let e=t.length-1;e>=0;e--){let i=t[e],a=i.promptId;a?n.has(a)||(n.add(a),r.push(i)):r.push(i)}r.reverse(),r.length===0?_n.delete(e):_n.set(e,r),yn()===e&&vn(r)},[Sn,Cn]=v([]),[wn,Tn]=v(localStorage.getItem(`teapot.hideGhosts`)===`1`),[En,Dn]=v(!1),On=()=>Sn().filter(e=>!e.read).length,kn=e=>{Cn(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},An=()=>{let e=n();e&&Sn().some(t=>!t.read&&t.agentId===e)&&kn(e)},jn=t=>{let n=Sn().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=jn(r.id));return n},Mn=0,Nn=e=>{Cn(t=>[{...e,id:`n${++Mn}`,at:Date.now(),read:!1},...t].slice(0,50))},Pn=(t,n)=>{let r=e().find(e=>e.id===t)?.id??t,i=typeof n.id==`string`?n.id:void 0;n.type===`message`&&n.data?.final===!0?Nn({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?Nn({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?Nn({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&Nn({agentId:t,kind:`progress`,title:`${r}: ${String(n.data.doing??`progress`)}`.slice(0,120),body:[n.data.recent&&`recent: ${n.data.recent}`,n.data.next&&`next: ${n.data.next}`].filter(Boolean).join(` · `).slice(0,300),eventId:i})},Fn=e=>{let t=document.querySelector(`[data-eid="${e}"]`);t&&(t.scrollIntoView({behavior:`smooth`,block:`center`}),t.classList.add(`flash-target`),setTimeout(()=>t.classList.remove(`flash-target`),1600))},In=x(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of m())if(nh.has(i.type)){if(i.type===`tool_call`){let e=n.get(i.data.callId)??[];e.push(i),n.set(i.data.callId,e)}else if(i.type===`tool_result`){let a=n.get(i.data.callId)?.shift();a?(e.set(a.id,i),t.add(i.id)):r.set(i.id,i)}}return{resFor:e,consumed:t,orphanCalls:r}}),[Ln,Rn]=v(new Set),zn=e=>{e&&Rn(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},Bn=()=>Rn(new Set),Vn=x(()=>Ot(m(),Ln())),Hn=x(()=>dt({events:m(),consumed:In().consumed,pending:H(),echo:Kn,feedTypes:nh,renderedTypes:ih,renderedNoteEvents:ah})),Un=x(()=>{let e=new WeakMap;return Hn().forEach((t,n)=>e.set(t,n)),e}),Wn=(e,t)=>{let n=Un().get(e);if(n!==void 0)return Hn()[n+t]},Gn=new Map;function Kn(e){let t=`${e.id}:${e.sent?`s`:`p`}`,n=Gn.get(t);if(n)return n;Gn.size>64&&Gn.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:V()?.session??``,branch:V()?.branch??`br0`,parent:null,type:`prompt`,data:{source:e.source??`user`,text:e.text,pending:!e.sent,...e.images?.length?{images:e.images}:{},...e.promptId?{promptId:e.promptId}:{}}};return Gn.set(t,r),r}let qn=()=>$(`/api/config`).then(ie).catch(()=>{}),[Jn,Yn]=v(!1);ee(()=>{let e=()=>Yn(!0);window.addEventListener(`teapot:unauthorized`,e),C(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[Xn,Zn]=v(``),[Qn,$n]=v(!0),[er,tr]=v(!1),nr=``;b(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==nr?(nr=t,tr(!1),Zn(r)):t&&!er()&&Zn(r)});let rr=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await $(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:Xn(),notify:e})}),tr(!1),$n(!0),Q(`tasks saved${e&&Xn().trim()?` & notification queued`:``}`),or()}catch(e){Q(`save failed: ${e.message}`)}},ir=x(()=>{let e=0,t=0;for(let n of Xn().split(`
22
22
  `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function ar(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:e})}let or=()=>$(`/api/agents`).then(e=>{let n=!1;t(t=>(t.length!==(e.agents??[]).length&&(n=!0),(e.agents??[]).some(e=>!t.some(t=>t.id===e.id))&&(n=!0),ar(t,e.agents??[]))),n&&p()}).catch(()=>{}),sr=()=>$(`/api/metrics`).then(te).catch(()=>{}),[cr,lr]=v([]),ur=()=>$(`/api/tasks`).then(e=>lr(e.tasks)).catch(()=>{}),dr=e=>cr().filter(t=>t.agent===e),[fr,pr]=v((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[mr,hr]=v((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.collapsed`)??`[]`);return new Set(e.filter(e=>typeof e==`string`&&!e.startsWith(`chat:`)))}catch{return new Set}})()),gr=e=>mr().has(e)||!fr().has(e),_r=e=>{let t=new Set(fr());if(t.has(e)?t.delete(e):t.add(e),pr(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&mr().has(e)){let t=new Set(mr());t.delete(e),hr(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},vr=t=>xt(e(),t),[yr,br]=v((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.wsCollapsed`)??`[]`),t=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(Number(localStorage.getItem(`teapot.wsCollapsed.v`)??`0`)<2){let e=t.filter(e=>!e.startsWith(`chat:`));return t.length-e.length>0&&localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify(e)),localStorage.setItem(`teapot.wsCollapsed.v`,`2`),new Set(e)}return new Set(t)}catch{return new Set}})()),xr=x(()=>{let e=new Set;for(let t of yr())t.startsWith(`chat:`)&&e.add(t);return e}),Sr=x(()=>gt(e(),new Set(e().filter(e=>gr(e.id)).map(e=>e.id)),wn(),xr())),Cr=(t,r,i,a)=>{let o=new Set(yr());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||vr(e().find(e=>e.id===i))===t)&&Q(`hid ${r} — click the header to show it`)}br(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},wr=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,Tr=e=>{let t=Er().get(e)??0;return`${t} chat${t===1?``:`s`}`},Er=x(()=>St(e())),Dr=x(()=>Ct(e(),Sr(),yr())),Or=2e3,[kr,U]=v(null),Ar=new Map;function jr(e){return`${i()||(n()??`?`)}:${e.id}`}function W(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=jr(r),a=Ar.get(i);if(t[n]=a??r,!a&&(Ar.set(i,r),Ar.size>6e3)){let e=Ar.keys().next().value;e!==void 0&&Ar.delete(e)}}return t}let[Mr,Nr]=v(!1),[Pr,G]=v(!1),Fr=0,Ir=-1;function Lr(e){let t=W(e);h(e=>{if(t.length>0&&e.length>0){let n=e[e.length-1],r=t.every(e=>e.seq>n.seq),i=new Set(e.map(e=>e.id));if(r&&t.every(e=>!i.has(e.id)))return[...e,...t]}let n=new Map;for(let t of e)n.set(t.id,t);let r=!1;for(let e of t)n.has(e.id)||(n.set(e.id,e),r=!0);return r?[...n.values()].sort((e,t)=>e.seq-t.seq):e})}async function Rr(){let e=n();if(!e||Pr()||Mr())return;if(m().length>=g()){G(!0);return}let t=()=>{let e=Vr();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!Pr()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(m().length>=g()){G(!0);return}let i=m().length;if(await zr(),m().length===i)return;Yt(Hr())&&n()===e&&Gr(!0)}}async function zr(){let e=n(),t=m()[0];if(e&&t&&!Mr()&&!Pr()){Nr(!0);try{let r=Vr(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=kr(),c=i(),l=c&&c!==e?`&session=${encodeURIComponent(c)}`:``,u=(await $(`/api/agents/${e}/events?limit=${Or}&before=${encodeURIComponent(t.id)}${l}${s?`&branch=${encodeURIComponent(s)}&lineage=true`:``}`)).events??[];if(u.length===0){G(!0);return}if(n()!==e||m()[0]?.id!==t.id)return;Lr(u),requestAnimationFrame(()=>{if(n()===e){let e=Vr();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{Nr(!1)}}}async function Br(e,t){let r=Fr,a=t??i()??``;try{let t=kr(),i=r!==Ir||!w().length,o=a&&a!==e?`&session=${encodeURIComponent(a)}`:``,[s,c,l]=await Promise.all([$(`/api/agents/${e}/events?limit=${Or}${o}${t?`&branch=${encodeURIComponent(t)}&lineage=true`:``}`),i?$(`/api/agents/${e}/branches`):Promise.resolve({branches:w()}),$(`/api/agents/${e}/skills`).catch(()=>({skills:[]}))]);if(i&&(Ir=r),r!==Fr||n()!==e)return;h(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of W(s.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)}),_(s.total??s.events.length),T(c.branches),Ki(l.skills??[])}catch{}}function Vr(){return document.querySelector(`.feed`)}function Hr(){let e=Vr();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function Ur(){return Yt(Hr())}function Wr(){let e=Vr();e&&(e.scrollTop=e.scrollHeight,$i={top:e.scrollTop,height:e.scrollHeight},ht(0))}function Gr(e=!1){(e||ut())&&Wr()}let Kr=new Map,qr=(t,n)=>At(c().get(t),e().find(e=>e.id===t)?.session,n);async function Jr(e,t=!0,o){let s=n(),l=i(),u=m(),d=g();Fr++,c().size||p();let f=qr(e,o)??e;if(s!==e||f!==l){if(l&&u.length&&(Kr.set(l,{events:u,total:d,at:Date.now()}),Kr.size>6)){let e=[...Kr.entries()].sort((e,t)=>e[1].at-t[1].at)[0];e&&Kr.delete(e[0])}h([]),Ar.clear(),Bn(),Dt(null),ht(0),ft(!0),Qi=void 0}r(e),a(f),O(D.get(e)??``),U(null),G(!1),Nr(!1),xn(l||s||`?`,H()),vn(bn(f||e)),localStorage.setItem(`teapot.session`,e),ai(f,t);let v=Kr.get(f);v?.events.length&&(W(v.events),h(W(v.events)),_(v.total),requestAnimationFrame(()=>{n()===e&&Gr(!0)})),$(`/api/agents/${e}/load`,{method:`POST`}).then(or).catch(()=>{}),await Br(e,f),n()===e&&(zt(t=>{let n=t.get(e)??null,r=Je(n,m(),V()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),Dt(V()?.ctx?.compacting?{phase:String(V().ctx.compacting)}:null),requestAnimationFrame(()=>{n()===e&&Gr(!0)}),Rr())}let[Yr,K]=v(!1),Xr=null,Zr=null;C(()=>Xr?.close());let Qr=!1,$r=null;document.addEventListener(`visibilitychange`,()=>$r?.()),C(()=>{$r=null});let ei=!0,ti=null;async function ni(){let e=n(),t=m().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)Qr=!0,a||ti?.();else try{let n=r&&r!==e?`&session=${encodeURIComponent(r)}`:``,i=kr(),o=await $(`/api/agents/${e}/events?after=${encodeURIComponent(t)}${n}${i?`&branch=${encodeURIComponent(i)}&lineage=true`:``}`),s=o.events??[];o.gap?(h(W(s)),_(s.length)):s.length&&(Lr(s),_(e=>e+s.length)),await or(),s.length&&!a&&sr()}catch{Qr=!0}}function ri(){ei=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${ch()}`);Xr=a,a.onopen=()=>{K(!0),ei?ei=!1:ni()},a.onclose=()=>{K(!1),setTimeout(ri,1500)},a.onerror=()=>a.close();let o=new Set([`state`,`usage`,`session_start`]);a.onmessage=r=>{let c=JSON.parse(r.data);if(c.kind===`ping`)try{a.send(JSON.stringify({kind:`pong`}))}catch{}else if(c.kind!==`pong`){if(c.kind===`hello`&&Array.isArray(c.agents)){t(e=>ar(e,c.agents));let n=e();zt(e=>qe(e,e=>n.find(t=>t.id===e)?.status))}else if(c.kind===`event`&&He(c.event))zt(e=>Ve(e,c.agentId));else if(c.kind===`llm-delta`){if(!Nt(c,n(),i()))return;if(zt(e=>Be(e,c.agentId,c)),c.agentId===n()){let e=String(c.reasoning??``),t=String(c.text??``);e&&!t?rn()||an(Date.now()):t&&an(0)}}else if(c.kind===`compaction-progress`){if(c.agentId!==n())return;c.phase===`done`?Dt(null):Dt({phase:c.phase,summarized:c.summarized})}else if(c.kind===`agent-update`&&c.snapshot)t(e=>{let t=e.findIndex(e=>e.id===c.snapshot.id),n=c.snapshot;return t===-1?[...e,n]:ar(e,e.map((e,n)=>n===t?c.snapshot:e))});else{if(c.kind===`event`){let e=c.event?.type,t=c.event?.data??{};if((e===`system_note`&&t.event===`prompt-delivered`&&c.agentId===n()||e===`system_note`&&t.event===`prompt-cancelled`&&c.agentId===n())&&xn(yn(),H().filter(e=>e.promptId!==t.promptId)),o.has(e)&&!rh.has(e)||(Pn(c.agentId,c.event),c.event?.agent!==n())||!Mt(c.event,n(),i()))return;if(Lr([c.event]),c.event?.type===`message`&&c.event.data?.role===`assistant`){let e=Vt();e&&We(e,m(),V()?.status)&&qt(null)}if(Qr=!0,document.visibilityState!==`visible`||Zr)return;Zr=setTimeout(s,60)}document.visibilityState===`hidden`?Qr=!0:Zr||=setTimeout(s,120)}}},Qr=!1;let s=async()=>{if(Zr=null,await or(),await sr(),n()){let e=m().at(-1)?.id,t=m().length;await Br(n());let r=Vt();r&&!Je(r,m(),V()?.status)&&qt(null),m().at(-1)?.id!==e&&(ut()?(Wr(),kn(n())):(ht(e=>e+Math.max(0,m().length-t)),Tt(Hr())))}};ti=s,$r=()=>{document.visibilityState===`visible`&&n()&&(Qr?(Qr=!1,s()):m().at(-1)?.id?ni():(Qr=!0,s()))}}let ii=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function ai(e,t=!0){let n=`/session/${encodeURIComponent(e)}`;t?history.pushState(null,``,n):history.replaceState(null,``,n)}window.addEventListener(`popstate`,()=>{let e=ii(),t=o().get(e);t&&(t!==n()||e!==i())&&Jr(t,!1,e||null)}),b(()=>{let e=V(),t=e?`${fn()?`▶ `:e.status===`error`?`⚠ `:``}${e.id} · teapot`:`teapot`;document.title=On()>0?`(${On()}) ${t}`:t});let oi=()=>ae()||se()||hn()!==null||le()&&ye();window.addEventListener(`keydown`,e=>{let t=e.target;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))e.key===`Escape`&&t.blur();else if(e.key===`Escape`){if(ae()){oe(!1);return}if(se()){ce(!1);return}if(hn()){gn(null);return}if(le()&&ye()){Se();return}let e=V();if(e&&fn()){$(`/api/agents/${e.id}/stop`,{method:`POST`}).then(or);return}}else if(!oi()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)L();else if(e.key===`t`)li();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=Sr().map(e=>e.a);if(t.length===0)return;e.preventDefault();let r=t.findIndex(e=>e.id===n()),i=e.key===`ArrowDown`?Math.min(r+1,t.length-1):Math.max(r-1,0);i!==r&&Jr(t[i].id)}}});let[si,ci]=v(localStorage.getItem(`teapot.term`)===`1`),li=()=>{let e=!si();ci(e),localStorage.setItem(`teapot.term`,e?`1`:`0`)},[ui,di]=v([]),[fi,pi]=v(0),[mi,hi]=v(-1),[gi,_i]=v(!1),[vi,yi]=v(0),[bi,xi]=v(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),Si=new Map,Ci=[null,null],wi=()=>ui()[vi()===0?fi():mi()]??null;function Ti(e){if(!ui()[e])return;let t=vi(),n=t===0?fi():mi(),r=t===0?mi():fi(),i=e=>t===0?pi(e):hi(e);r===e?((e=>t===0?hi(e):pi(e))(n),i(e)):n!==e&&i(e)}let Ei=()=>Di();async function Di(e){let t=e??n();if(t){if(ui().filter(e=>e.agentId===t).length>=10)Q(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await $(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){Q(`could not open a shell`);return}let n=cu(ui());di(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title}]),vi()===0?pi(n):hi(n)}catch(e){Q(`could not open a shell: ${e.message}`)}}}function Oi(e){let t=ui()[e];if(!t)return;$(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=Si.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),Si.delete(t.key)}let r=ui().filter((t,n)=>n!==e);di(r),pi(t=>uu(t,e,r.length)),hi(t=>t===-1?-1:uu(t,e,r.length))}b(()=>{Oe(),Ce(),Re(),Ae(),Fe();for(let[,e]of Si)It(e.term)});function ki(){for(let[,e]of Si){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}Si.clear()}function Ai(e,t){let n=Si.get(e.key);if(n&&It(n.term),n)n.el.parentElement!==t&&(t.appendChild(n.el),setTimeout(()=>{try{n.fit()}catch{}},30));else{let r=document.createElement(`div`);r.className=`termsession`,t.appendChild(r);let i=new iu({cursorBlink:!0,fontSize:12.5,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,theme:Ft()}),a=new su;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=new WebSocket(`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${ch()}`);s.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`exit`?(i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),di(t=>t.filter(t=>t.key!==e.key)),Si.get(e.key)?.term.dispose(),Si.delete(e.key)):n.kind===`attach`&&n.error&&i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)},i.onData(e=>{s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({kind:`input`,data:e}))});let c={cols:0,rows:0},l,u=[],d=()=>{try{a.fit()}catch{}s.readyState===WebSocket.OPEN?(i.cols!==c.cols||i.rows!==c.rows)&&(c={cols:i.cols,rows:i.rows},s.send(JSON.stringify({kind:`resize`,cols:i.cols,rows:i.rows}))):f()};function f(){l||=setInterval(()=>{Si.has(e.key)?s.readyState===WebSocket.OPEN&&(clearInterval(l),l=void 0,d()):(clearInterval(l),l=void 0)},400)}s.addEventListener(`open`,()=>d());let p=r.parentElement??r,m=new ResizeObserver(()=>{u[0]&&clearTimeout(u[0]),u[0]=setTimeout(d,250)});m.observe(p),p!==r&&m.observe(r),setTimeout(d,60),n={el:r,term:i,fit:a,ws:s,ro:m},Si.set(e.key,n)}return n}function ji(e){let t=Ci[e];if(!t)return;let n=ui()[e===0?fi():mi()];if(!n){[...Si.values()].some(e=>e.el.parentElement===t)&&t.replaceChildren();return}let r=Ai(n,t);for(let[e,r]of Si)e!==n.key&&r.el.parentElement===t&&r.el.remove();requestAnimationFrame(()=>{r.el.parentElement!==t&&t.appendChild(r.el);try{r.fit()}catch{}if(vi()===(e===0?0:1))try{r.term.focus()}catch{}})}b(()=>{ui(),gi(),fi(),mi(),bi(),requestAnimationFrame(()=>{ji(0),gi()&&ji(1)})});let Mi=null;b(()=>{if(!si())return;let e=n();if(!e||e===Mi)return;Mi=e;let t=ui().map((e,t)=>({t:e,i:t})).filter(t=>t.t.agentId===e);t.length&&Ti(t[t.length-1].i)}),b(()=>{let e=ui().length,t=lu(fi(),e);if(t!==fi()&&pi(t),gi()){let t=lu(mi(),e);t!==mi()&&hi(t)}});let Ni=e=>{e.preventDefault();let t=e.clientY,n=bi(),r=e=>{let r=Math.min(Math.max(n-(e.clientY-t),140),Math.round(window.innerHeight*.85));xi(r)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),localStorage.setItem(`teapot.termH`,String(bi())),requestAnimationFrame(()=>{ji(0),gi()&&ji(1)})};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},Pi=()=>{let e=!gi();_i(e),e&&(mi()<0||mi()===fi()||mi()>=ui().length)&&hi(du(fi(),ui().length)),requestAnimationFrame(()=>{ji(0),gi()&&ji(1)})};C(ki);let Fi=e=>t=>{Ci[e]=t,t&&requestAnimationFrame(()=>{ji(e),gi()&&ji(1),setTimeout(()=>ji(e),200)})};ee(()=>{qn(),or().then(async()=>{await p();let t=ii(),n=t?o().get(t):void 0,r=(n?e().find(e=>e.id===n):void 0)??e().find(e=>e.id===t&&!o().has(t))??e().find(e=>e.id===localStorage.getItem(`teapot.session`))??e()[0];r&&Jr(r.id,!1,t||null)}),sr(),ur(),zi(),ri(),$(`/api/terminals`).then(e=>{let t=e.terminals??[];t.length&&(di(t.map(e=>({key:e.id,agentId:e.agentId,title:e.title}))),si()&&(pi(0),hi(-1)))}).catch(()=>{});let t=setInterval(()=>{sr(),ur()},3e4);C(()=>clearInterval(t))});let Ii=[{cmd:`/start`,desc:`start working toward the goal`},{cmd:`/stop`,desc:`interrupt the running agent`},{cmd:`/fork`,desc:`branch the conversation here`},{cmd:`/goal`,desc:`/goal <text> — set goal & notify the agent`},{cmd:`/compact`,desc:`force a context compaction now`},{cmd:`/skill`,desc:`/skill <name> — force-load a skill and follow it`}],[Li,Ri]=v([]),zi=()=>$(`/api/personas`).then(e=>Ri(e.personas)).catch(()=>{}),[Bi,Vi]=v(!1),Hi=()=>{let e=ne().match(/^@([A-Za-z0-9._-]*)$/);return e?e[1].toLowerCase():null},Ui=()=>{let t=Hi();return t===null?[]:[...Li().map(e=>({key:e.key,label:`${e.label} — spawns a sub-agent`,kind:`persona`})),...e().filter(e=>e.id!==n()).map(e=>({key:e.id,label:`${e.status} — send directly`,kind:`agent`}))].filter(e=>e.key.toLowerCase().startsWith(t))},Wi=new Set([`start`,`stop`,`fork`,`compact`]),[Gi,Ki]=v([]),[qi,Ji]=v(-1),Yi=()=>{let e=ne();if(!e.startsWith(`/`)||e.includes(`
23
23
  `))return[];let t=e.match(/^\/([a-z]*)(?:\s+(.*))?$/i);if(!t)return[];let n=t[1].toLowerCase(),r=(t[2]??``).trim();if(!r&&n!==`skill`){let e=Ii.filter(e=>e.cmd.slice(1).startsWith(n));return e.find(e=>e.cmd.slice(1)===n)&&Wi.has(n)?[]:e.map(e=>({insert:e.cmd+` `,title:e.desc}))}if(n===`skill`){let e=Gi().filter(e=>e.name.toLowerCase().startsWith(r.toLowerCase()));return e.length===1&&e[0].name.toLowerCase()===r.toLowerCase()?[]:e.map(e=>({insert:`/skill ${e.name} `,title:e.description||`(bundled skill)`}))}return[]},Xi,Zi=()=>{if(!Xi)return;let e=ct();if(!Xi.value&&!e){Xi.style.height=``;return}Xi.style.height=`auto`;let t=e?-1:en(Xi.scrollHeight,360);Xi.style.height=t===-1?``:`${t}px`,Xi.scrollHeight},Qi,$i=null,ea,ta=null,na=0,ra=4,ia;b(()=>{let e=ne();Xi&&Gt($m)&&(Kt(Xi.value,e)&&(Xi.value=e),Zi())});let[aa,oa]=v([]),sa=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){Q(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{oa(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},ca=async(e,t)=>{let r=t??n();if(!r)return;let i=aa();try{let t=await $(`/api/agents/${r}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:e,start:!0,...i.length?{images:i}:{}})});xn(yn(),[...H(),{id:`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`,text:e,at:Date.now(),promptId:t.promptId,...i.length?{images:i.map(e=>e.url)}:{}}]),oa([]),ct()&&lt(!1),Zi(),ut()&&requestAnimationFrame(()=>{ut()&&Wr()})}catch(t){O(e),console.error(`send failed:`,t)}},la=async t=>{t.preventDefault();let r=n(),i=ne().trim();if(r&&i){if(i.startsWith(`@`)){let t=i.indexOf(` `),r=(t===-1?i.slice(1):i.slice(1,t)).toLowerCase(),a=t===-1?``:i.slice(t+1).trim(),o=Li().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){Q(`usage: @${r} <task>`);return}Q(`🧩 spawned ${(await $(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:Bi()?`fork`:`none`})})).id}${Bi()?` (forked context)`:``}`),or(),O(``)}else if(s){if(!a){Q(`usage: @${r} <message>`);return}await $(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),Q(`→ delivered to @${r}`),O(``)}else{Q(`unknown @${r} — personas: ${Li().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){Q(`@${r} failed: ${e.message}`)}}else if(i.startsWith(`/`)){let e=i.indexOf(` `),t=(e===-1?i.slice(1):i.slice(1,e)).toLowerCase(),n=e===-1?``:i.slice(e+1).trim();if(t===`goal`&&!n){O(`/goal `);return}if(t===`skill`&&!n){O(`/skill `);return}O(``);try{await ua(t,n)}catch(e){throw O(ne()?`${i}\n${ne()}`:i),e}}else O(``),await ca(i)}},ua=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>$(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(or);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await Jr(r);else if(e===`compact`)Q((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){Q(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),Q(`goal saved & notification queued`)}else if(e===`skill`){if(!t){Q(`usage: /skill <name>`);return}await ca(`[harness] Force-load and follow the skill "${t}" now: call load_skill("${t}") and execute its playbook for the current task.`),Q(`skill "${t}" dispatched`)}else Q(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){Q(`/${e} failed: ${t.message}`)}},da,fa=0;b(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!da)return;let e=Math.min(fa,da.scrollHeight);Math.abs(da.scrollTop-e)>1&&(da.scrollTop=e)})})});let pa=e=>()=>n()&&$(`/api/agents/${n()}${e}`,{method:`POST`}).then(or),ma=async()=>{let i=n();if(!i)return;let a=new Set([i,...bt(e(),i).map(e=>e.id)]),o=a.size-1;if(!confirm(`archive agent ${i}?\n\n`+(o>0?`Its ${o} sub-agent${o===1?``:`s`} will be archived too.\n\n`:``)+`They stop running and leave the list, but the config and full session history are KEPT — restore any of them from ⚙ settings → archive.`))return;await $(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),p(!0);let s=fu(e(),a);s?Jr(s.id):(r(null),h([]))},ha=async()=>{n()&&(Q(`stopped: ${((await $(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),or())},ga=()=>$(`/api/agents/${V().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await p(!0),await Jr(V().id)}),[_a,va]=v(``),[ya,q]=v(``),[ba,xa]=v(!1),[Sa,Ca]=v(!0),wa=``;b(()=>{let e=n();e&&(V()?.goal,e!==wa&&(wa=e,xa(!1),va(``),q(``)))});let Ta=async e=>{if(e.preventDefault(),n()&&_a().trim())try{await $(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:_a(),notify:Sa(),...ya().trim()?{verify:ya()}:{}})}),va(``),q(``),xa(!1),or()}catch(e){Q(`goal save failed: ${e.message}`)}};return[N(F,{get when(){return k()?.needsSetup},fallback:null,get children(){return N(Bh,{onDone:()=>location.reload()})}}),N(F,{get when(){return Jn()},get children(){var e=yu();return e.firstChild.firstChild.nextSibling.addEventListener(`submit`,e=>{e.preventDefault();let t=document.getElementById(`pw-input`);localStorage.setItem(`teapot.token`,t.value),location.reload()}),e}}),N(F,{get when(){return!k()?.needsSetup},get children(){var t=Gu(),r=t.firstChild,i=r.firstChild,a=i.nextSibling.firstChild,o=a.firstChild;o.firstChild;var s=a.nextSibling,c=s.firstChild.firstChild.nextSibling;c.firstChild;var l=c.nextSibling,d=s.nextSibling,f=r.nextSibling,p=f.nextSibling,g=p.firstChild;g.firstChild,B(i,N(P,{get each(){return Dr()},children:t=>[N(F,{get when(){return I(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=Zu(),n=e.firstChild;return e.$$click=()=>Cr(`ws:${t.wsHeader}`,wr(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),B(n,()=>t.wsCollapsedGroup?`▸`:`▾`),B(e,()=>wr(t.wsHeader),null),B(e,N(F,{get when(){return(Er().get(t.wsHeader)??0)>1||t.wsCollapsedGroup},get children(){var e=Xu();return B(e,()=>Er().get(t.wsHeader)??0),e}}),null),y(()=>R(e,`title`,t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${Tr(t.wsHeader)} hidden). Click to show.`:(Er().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${Tr(t.wsHeader)} in this directory`:t.wsHeader||``)),e}}),N(F,{get when(){return I(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=nd(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>Jr(t.a.id),B(r,N(F,{get when(){return vt({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return rd()},get children(){return(()=>{let e=!t.a.parent,n=e&&xr().has(`chat:${t.a.id}`)||gr(t.a.id);return(()=>{var r=id();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!fr().has(t.a.id)){let e=new Set(fr());e.add(t.a.id),pr(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(mr().has(t.a.id)){let e=new Set(mr());e.delete(t.a.id),hr(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(fr().has(t.a.id)){let e=new Set(fr());e.delete(t.a.id),pr(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}Cr(`chat:${t.a.id}`,t.a.id,n)}else _r(t.a.id)},B(r,n?`▸`:`▾`),y(()=>R(r,`title`,e?n?`show ${t.a.id}`:`hide ${t.a.id} and its sub-agents`:n?`expand sub-agents`:`collapse sub-agents`)),r})()})()}}),i),B(a,()=>t.a.sessionTitle??u().get(t.a.session??``)??t.a.id),B(r,(()=>{var e=I(()=>!!t.a.workspaceMissing);return()=>e()?ad():null})(),null),B(r,N(F,{get when(){return jn(t.a.id)>0},get children(){var e=Qu();return e.firstChild,B(e,()=>jn(t.a.id),null),y(()=>R(e,`title`,`${jn(t.a.id)} unread notification${jn(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),B(r,N(F,{get when(){return gr(t.a.id)||t.chatCollapsedGroup===!0&&xr().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=bt(e(),t.a.id),r=n.filter(e=>e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`)).length;return n.length>0?(()=>{var e=od();return e.firstChild,z(e,`subcount`+(r>0?` live`:``)),B(e,()=>n.length,null),B(e,r>0?` · ▶${r}`:``,null),y(()=>R(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),B(r,N(F,{get when(){return t.a.parent},get children(){return $u()}}),null),B(r,N(F,{get when(){return dr(t.a.id).length>0},get children(){var e=ed();return y(()=>R(e,`title`,dr(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
24
- `))),e}}),null),B(r,N(F,{get when(){return t.a.goal.status===`done`},get children(){return td()}}),null),y(e=>{var o=`agent-item`+(t.a.id===n()?` sel`:``)+(t.depth>0?` sub-row`:``)+(t.chatCollapsedGroup?` collapsed`:``),s=t.depth>0?`padding-left:${10+t.depth*14}px`:``,c=t.a.parent?(()=>{let e=yt(t.a.id,Li().map(e=>e.key));return e?`sub-agent of @${t.a.parent} — "${e}"`:`sub-agent of @${t.a.parent}`})():void 0,l=`dot ${t.a.status}`,d=t.a.status===`needs_operator`?`waiting for your answer`:t.a.status===`waiting`?`waiting on its own work — resumes by itself`:t.a.status,f=t.a.workspaceMissing?` ghost`:``,p=t.a.workspaceMissing?`workspace not found on disk (${t.a.workspace}) — it will be created when this session runs`:t.a.sessionTitle??u().get(t.a.session??``)?`${t.a.sessionTitle??u().get(t.a.session??``)} — ${t.a.id}`:t.a.id;return o!==e.e&&z(r,e.e=o),e.t=we(r,s,e.t),c!==e.a&&R(r,`title`,e.a=c),l!==e.o&&z(i,e.o=l),d!==e.i&&R(i,`title`,e.i=d),f!==e.n&&z(a,e.n=f),p!==e.s&&R(a,`title`,e.s=p),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r}})]})),o.$$click=e=>{e.stopPropagation(),Dn(!En()),En()||Cn(e=>e.map(e=>({...e,read:!0})))},B(o,N(F,{get when(){return On()>0},get children(){var e=bu();return B(e,On),e}}),null),B(a,N(Sh,{icon:`👻`,get active(){return wn()},get title(){return wn()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!wn();if(Tn(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&V()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&Jr(t.id)}}}),null),B(a,N(Sh,{icon:`+`,title:`new agent`,onClick:()=>{qn(),oe(!0)}}),null),B(a,N(Sh,{icon:`⚙`,title:`settings`,onClick:()=>{qn(),ce(!0)}}),null),B(c,`0.35.11`,null),B(d,N(F,{get when(){return E()},get children(){return[`master rss `,I(()=>E().rssMb),`MB · heap `,I(()=>E().heapUsedMb),`MB`,xu(),`load1 `,I(()=>E().loadavg1),` · up `,I(()=>Math.floor(E().uptimeSec/60)),`m`]}})),B(f,N(F,{get when(){return V()?.id},keyed:!0,get fallback(){return sd()},get children(){return[(()=>{var t=wu(),r=t.firstChild.nextSibling,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling.nextSibling,u=l.nextSibling.nextSibling;u.nextSibling;var d=a.nextSibling,f=d.firstChild,p=f.nextSibling;return B(r,()=>V().id),B(i,()=>V().status),B(t,N(F,{get when(){return(V().pendingPromptIds?.length??V().pendingPrompts??0)>0},get children(){var e=Su(),t=e.firstChild.nextSibling;return t.nextSibling,B(e,()=>V().pendingPromptIds?.length??V().pendingPrompts,t),B(e,()=>V().status===`stopped`?` (stopped)`:``,null),y(()=>R(e,`title`,V().status===`stopped`?`${V().pendingPromptIds?.length??V().pendingPrompts??0} message${(V().pendingPromptIds?.length??V().pendingPrompts??0)>1?`s`:``} from you are still queued, but this agent is STOPPED — nothing will run until you press start (or it is resumed). Each can be withdrawn with ✕ cancel while it is still queued.`:`${V().pendingPromptIds?.length??V().pendingPrompts??0} message${(V().pendingPromptIds?.length??V().pendingPrompts??0)>1?`s`:``} from you waiting in the queue. They will be handed to the model at its next turn boundary — the timeline shows them as "pending (queued)…" until then, and each can be withdrawn with ✕ cancel while it's still queued.`)),e}}),a),B(t,N(F,{get when(){return dr(V().id).length>0},get children(){var e=Cu();return e.firstChild,B(e,()=>dr(V().id).length,null),y(()=>R(e,`title`,`scheduled tasks:\n${dr(V().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
24
+ `))),e}}),null),B(r,N(F,{get when(){return t.a.goal.status===`done`},get children(){return td()}}),null),y(e=>{var o=`agent-item`+(t.a.id===n()?` sel`:``)+(t.depth>0?` sub-row`:``)+(t.chatCollapsedGroup?` collapsed`:``),s=t.depth>0?`padding-left:${10+t.depth*14}px`:``,c=t.a.parent?(()=>{let e=yt(t.a.id,Li().map(e=>e.key));return e?`sub-agent of @${t.a.parent} — "${e}"`:`sub-agent of @${t.a.parent}`})():void 0,l=`dot ${t.a.status}`,d=t.a.status===`needs_operator`?`waiting for your answer`:t.a.status===`waiting`?`waiting on its own work — resumes by itself`:t.a.status,f=t.a.workspaceMissing?` ghost`:``,p=t.a.workspaceMissing?`workspace not found on disk (${t.a.workspace}) — it will be created when this session runs`:t.a.sessionTitle??u().get(t.a.session??``)?`${t.a.sessionTitle??u().get(t.a.session??``)} — ${t.a.id}`:t.a.id;return o!==e.e&&z(r,e.e=o),e.t=we(r,s,e.t),c!==e.a&&R(r,`title`,e.a=c),l!==e.o&&z(i,e.o=l),d!==e.i&&R(i,`title`,e.i=d),f!==e.n&&z(a,e.n=f),p!==e.s&&R(a,`title`,e.s=p),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r}})]})),o.$$click=e=>{e.stopPropagation(),Dn(!En()),En()||Cn(e=>e.map(e=>({...e,read:!0})))},B(o,N(F,{get when(){return On()>0},get children(){var e=bu();return B(e,On),e}}),null),B(a,N(Sh,{icon:`👻`,get active(){return wn()},get title(){return wn()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!wn();if(Tn(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&V()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&Jr(t.id)}}}),null),B(a,N(Sh,{icon:`+`,title:`new agent`,onClick:()=>{qn(),oe(!0)}}),null),B(a,N(Sh,{icon:`⚙`,title:`settings`,onClick:()=>{qn(),ce(!0)}}),null),B(c,`0.35.12`,null),B(d,N(F,{get when(){return E()},get children(){return[`master rss `,I(()=>E().rssMb),`MB · heap `,I(()=>E().heapUsedMb),`MB`,xu(),`load1 `,I(()=>E().loadavg1),` · up `,I(()=>Math.floor(E().uptimeSec/60)),`m`]}})),B(f,N(F,{get when(){return V()?.id},keyed:!0,get fallback(){return sd()},get children(){return[(()=>{var t=wu(),r=t.firstChild.nextSibling,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling.nextSibling,u=l.nextSibling.nextSibling;u.nextSibling;var d=a.nextSibling,f=d.firstChild,p=f.nextSibling;return B(r,()=>V().id),B(i,()=>V().status),B(t,N(F,{get when(){return(V().pendingPromptIds?.length??V().pendingPrompts??0)>0},get children(){var e=Su(),t=e.firstChild.nextSibling;return t.nextSibling,B(e,()=>V().pendingPromptIds?.length??V().pendingPrompts,t),B(e,()=>V().status===`stopped`?` (stopped)`:``,null),y(()=>R(e,`title`,V().status===`stopped`?`${V().pendingPromptIds?.length??V().pendingPrompts??0} message${(V().pendingPromptIds?.length??V().pendingPrompts??0)>1?`s`:``} from you are still queued, but this agent is STOPPED — nothing will run until you press start (or it is resumed). Each can be withdrawn with ✕ cancel while it is still queued.`:`${V().pendingPromptIds?.length??V().pendingPrompts??0} message${(V().pendingPromptIds?.length??V().pendingPrompts??0)>1?`s`:``} from you waiting in the queue. They will be handed to the model at its next turn boundary — the timeline shows them as "pending (queued)…" until then, and each can be withdrawn with ✕ cancel while it's still queued.`)),e}}),a),B(t,N(F,{get when(){return dr(V().id).length>0},get children(){var e=Cu();return e.firstChild,B(e,()=>dr(V().id).length,null),y(()=>R(e,`title`,`scheduled tasks:\n${dr(V().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
25
25
  `)}`)),e}}),a),B(a,()=>V().model,o),B(a,()=>V().session,s),B(a,()=>V().branch,c),B(a,()=>V().stats.turns,l),B(a,()=>V().stats.toolCalls,u),f.$$click=()=>(fn()?pa(`/stop`):pa(`/start`))(),B(f,()=>fn()?`■ stop`:`▶ start`),B(d,N(F,{get when(){return e().some(e=>e.parent===n())},get children(){return N(Sh,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ha})}}),p),B(d,N(Sh,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:ga}),null),B(d,N(Sh,{icon:`⌨`,title:`terminal (t)`,onClick:li}),null),B(d,N(Sh,{icon:`▤`,title:`toggle details panel (d)`,get active(){return ye()},onClick:L}),null),B(d,N(Sh,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙ settings → archive)`,onClick:ma}),null),y(e=>{var t=`badge ${V().status}`,n=V().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(V().statusReason)?`${V().status} — ${V().statusReason}`:void 0,r=`${V().model} · ${V().session}/${V().branch} · turns ${V().stats.turns} · tools ${V().stats.toolCalls}`,o=`runbtn`+(fn()?` danger`:``),s=fn()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&z(i,e.e=t),n!==e.t&&R(i,`title`,e.t=n),r!==e.a&&R(a,`title`,e.a=r),o!==e.o&&z(f,e.o=o),s!==e.i&&R(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=ju();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=Xt(r,$i,ea,ia);i===`layout`&&ra>0&&Math.abs(r.height-(ea??r.height))>1&&(ra--,he(t,ta)),$i=null,ea=r.height,ia=r.viewport,Tt(r);let a=ut(),o=performance.now();o-na>100&&(na=o,ta=ve(t));let s=Qt(a,i,r);s!==a&&ft(s),i===`reader`&&(ra=4),s&&i!==`reader`?(mt()&&ht(0),An(),Zt(s,r)&&Jt(r)>0&&Wr()):s&&Yt(r)&&(mt()&&ht(0),An()),r.top<=4&&n()&&!Mr()&&!Pr()&&m().length>0&&zr()}),Ee(e=>_e(e),e),B(e,N(F,{get when(){return Et()},children:e=>(()=>{var t=cd();return t.firstChild,B(t,(()=>{var t=I(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?yh(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),B(e,N(F,{get when(){return I(()=>!!Pr())()&&Hn().length>0},get children(){return Tu()}}),null),B(e,N(F,{get when(){return Mr()},get children(){return Eu()}}),null),B(e,N(F,{get when(){return Hn().length>0},get fallback(){return ld()},get children(){return[N(P,{get each(){return Hn()},children:e=>N(mh,{e,prev:()=>Wn(e,-1),next:()=>Wn(e,1),get showBranch(){return w().length>1},res:()=>In().resFor.get(e.id),get orphan(){return In().orphanCalls.has(e.id)},onOption:e=>void ca(e),answeredIds:Vn,onAnswered:zn,get agentActive(){return I(()=>!!mn())()&&Ke(e)},onResize:()=>{ut()&&Wr()},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.promptId&&e.data?.sent!==!0?()=>{let t=String(e.data.promptId);$(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:t})}).then(e=>{let n=String(e.text??``);O(ne()?`${n}\n\n${ne()}`:n),xn(yn(),H().filter(e=>e.promptId!==t)),Q(`message withdrawn — draft restored`)}).catch(()=>Q(`withdraw failed — it may have already been sent`))}:void 0},get onEdit(){return e.type===`prompt`&&e.data?.source===`user`&&!(e.data?.pending&&e.data?.sent!==!0)&&!e.data?.cancelled&&!fn()?()=>gn({eventId:e.id,text:String(e.data?.text??``)}):void 0}})}),N(F,{get when(){return I(()=>!!mn())()&&Vt()},get children(){var e=Au(),t=e.firstChild.nextSibling;return t.firstChild,B(t,N(F,{get when(){return sn().trim()!==``},get children(){var e=Du(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return B(t,N(dh,{get startedAt(){return on()}}),null),Ee(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),b(()=>{sn(),t&&(e.scrollTop=e.scrollHeight)})},n),B(n,sn),e}}),null),B(t,N(F,{get when(){return tn()},get fallback(){return ud()},get children(){return N(F,{get when(){return jt()},get fallback(){return(()=>{var e=ku();return y(()=>e.innerHTML=Pe(tn()+`▍`)),e})()},get children(){return[Ou(),(()=>{var e=ku();return y(()=>e.innerHTML=Pe(Lt()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),N(F,{get when(){return si()},get children(){var t=Iu(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{xi(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(bi()))},n.$$pointerdown=Ni,B(i,N(P,{get each(){return ui()},children:(e,t)=>(()=>{var n=dd(),r=n.firstChild.nextSibling;return n.$$click=()=>Ti(t()),B(n,()=>e.title,r),r.$$click=e=>{e.stopPropagation(),Oi(t())},y(r=>{var i=`termtab`+(vi()===0&&fi()===t()?` active`:``)+(gi()&&vi()===1&&mi()===t()?` active`:``),a=`${e.title} — click to show in focused pane`;return i!==r.e&&z(n,r.e=i),a!==r.t&&R(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),B(i,N(Sh,{icon:`+`,title:`new shell in this workspace`,onClick:Ei}),null),B(o,(()=>{var t=I(()=>!!wi());return()=>t()?e().find(e=>e.id===wi().agentId)?.workspace.split(`/`).filter(Boolean).pop():V()?.workspace})()),B(a,N(Sh,{icon:`◫`,get title(){return gi()?`single pane`:`split panes (50/50)`},onClick:Pi}),null),B(a,N(Sh,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:li}),null);var l=Fi(0);return typeof l==`function`&&Ee(l,c),c.$$pointerdown=()=>yi(0),B(c,N(F,{get when(){return fi()<0||fi()>=ui().length},get children(){return Mu()}})),B(s,N(F,{get when(){return gi()},get children(){return[Nu(),(()=>{var e=Fu(),t=Fi(1);return typeof t==`function`&&Ee(t,e),e.$$pointerdown=()=>yi(1),B(e,N(F,{get when(){return mi()<0||mi()>=ui().length},get children(){return Pu()}})),y(()=>e.classList.toggle(`focused`,vi()===1)),e})()]}}),null),y(e=>{var n={height:`${bi()}px`},r=!!gi(),i=vi()===0;return e.e=we(t,n,e.e),r!==e.t&&s.classList.toggle(`split`,e.t=r),i!==e.a&&c.classList.toggle(`focused`,e.a=i),e},{e:void 0,t:void 0,a:void 0}),t}}),(()=>{var e=Uu(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return B(e,N(F,{get when(){return I(()=>_t()>32)()&&!ut()},get children(){var e=Lu();return e.firstChild,e.$$click=()=>{Gr(!0),An()},B(e,(()=>{var e=I(()=>mt()>0);return()=>e()?`${mt()} new message${mt()>1?`s`:``}`:`jump to present`})(),null),e}}),t),B(e,N(F,{get when(){return Yi().length>0},get children(){var e=Ru();return B(e,N(P,{get each(){return Yi()},children:(e,t)=>(()=>{var n=fd(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{O(e.insert),Ji(-1)},B(r,()=>e.insert.trim()),B(i,()=>e.title),y(r=>{var i=`cmdrow`+(t()===qi()?` active`:``),a=e.title;return i!==r.e&&z(n,r.e=i),a!==r.t&&R(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),B(e,N(F,{get when(){return Ui().length>0},get children(){var e=Ru();return B(e,N(P,{get each(){return Ui()},children:e=>(()=>{var t=pd(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{O(`@${e.key} `),Ji(-1)},B(n,()=>e.key,null),B(r,()=>e.label),y(()=>R(t,`title`,e.label)),t})()})),e}}),t),t.addEventListener(`submit`,la),B(t,N(F,{get when(){return aa().length>0},get children(){var e=zu(),t=e.firstChild,n=t.firstChild,r=n.nextSibling;return r.nextSibling,B(e,N(P,{get each(){return aa()},children:(e,t)=>(()=>{var n=md(),r=n.firstChild,i=r.nextSibling;return i.$$click=()=>oa(e=>e.filter((e,n)=>n!==t())),y(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&R(n,`title`,t.e=i),a!==t.t&&R(r,`src`,t.t=a),o!==t.a&&R(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),B(t,()=>aa().length,n),B(t,()=>aa().length>1?`s`:``,r),e}}),n),n.$$keydown=e=>{let t=Yi();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),Ji(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),Ji(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&qi()>=0&&!$m?(e.preventDefault(),O(t[qi()].insert),Ji(-1)):e.key===`Escape`&&t.length>0?Ji(-1):e.key===`Enter`&&!e.shiftKey&&!$m&&!ct()&&(e.preventDefault(),la(e))},n.$$input=e=>{O(e.currentTarget.value),Ji(0),Zi()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),sa(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{$m=!1}),O(Xi?.value??``)}),n.addEventListener(`compositionstart`,()=>{$m=!0}),Ee(e=>{Xi=e,e.value=ne()},n),B(t,N(F,{get when(){return I(()=>!!ne().startsWith(`@`))()&&ne().includes(` `)},get children(){var e=Bu(),t=e.firstChild;return t.addEventListener(`change`,e=>Vi(e.currentTarget.checked)),y(()=>t.checked=Bi()),e}}),r),r.$$click=()=>{let e=!ct();lt(e),requestAnimationFrame(()=>Zi())},B(r,()=>ct()?`⤡`:`⤢`),B(t,N(Sh,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),B(t,N(F,{get when(){return aa().length},get children(){var e=Vu();return e.firstChild,B(e,()=>aa().length,null),e}}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&sa(e.currentTarget.files),e.currentTarget.value=``}),B(e,N(F,{get when(){return Xm()},get children(){var e=Hu();return B(e,Xm),e}}),null),y(t=>{var i=`composer`+(ct()?` maximized`:``),a=`message #${V().id} — / for commands · paste or 📎 to attach images`,o=ct()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&z(e,t.e=i),a!==t.t&&R(n,`placeholder`,t.t=a),o!==t.a&&R(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),B(t,N(F,{get when(){return I(()=>!!j())()&&ye()},get children(){var e=Wu();return e.$$click=()=>xe(!1),e}}),p),p.addEventListener(`scroll`,e=>{fa=e.currentTarget.scrollTop});var v=da;return typeof v==`function`?Ee(v,p):da=p,B(g,N(Sh,{icon:`✕`,title:`close details panel (esc)`,onClick:Se}),null),B(p,N(F,{get when(){return V()?.id},keyed:!0,fallback:null,children:t=>[N(F,{get when(){return V().id},keyed:!0,fallback:null,children:e=>N(Ih,{agentId:e,get workspace(){return V().workspace}})}),hd(),(()=>{var t=vd(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.nextSibling,s=i.nextSibling,c=s.firstChild,l=s.nextSibling;return l.firstChild,r.addEventListener(`change`,t=>{let r=t.currentTarget.value;st=!0,Ge(r),Ze(Ht(k().providers,r,e().find(e=>e.id===n()))),rt(r)}),B(r,N(P,{get each(){return nt()},children:e=>(()=>{var t=zd();return t.value=e,B(t,e,null),B(t,()=>e===k().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>Ze(e.currentTarget.value),B(o,N(P,{get each(){return et()},children:e=>(()=>{var t=zd();return y(()=>t.value=e.id),t})()})),B(t,N(F,{get when(){return V().effortSupported},get children(){var e=gd(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>$e(e.currentTarget.value)),B(t,N(P,{get each(){return I(()=>!!V().effortOptions?.length)()?V().effortOptions:Km},children:e=>(()=>{var t=zd();return t.value=e,B(t,e),t})()}),null),y(()=>t.value=Qe()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await $(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:Ue(),model:Xe().trim()||void 0,contextWindowTokens:et().find(e=>e.id===(Xe().trim()||void 0))?.contextLength,...V().effortSupported?{reasoningEffort:Qe()}:{}})}),t.textContent=`✓ applied`,or()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},B(l,()=>V().model,null),B(l,N(F,{get when(){return et().length},get children(){return[` · `,I(()=>et().length),` models loaded`]}}),null),B(t,N(F,{get when(){return at()},get children(){var e=_d();return B(e,at),e}}),null),y(()=>R(a,`placeholder`,Ut(k().providers,Ue(),V(),Bt(V(),k().providers,k().defaultProvider)))),y(()=>r.value=Ue()),y(()=>a.value=Xe()),t})(),(()=>{var e=yd(),t=e.firstChild.firstChild;return t.addEventListener(`change`,e=>{n()&&$(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(or)}),y(()=>t.checked=V().autoContinue??!0),e})(),(()=>{var e=xd();return e.firstChild,B(e,N(F,{get when(){return!!V().goal.text.trim()},get fallback(){return Bd()},get children(){var e=bd();return B(e,()=>V().goal.status),y(()=>z(e,`badge ${V().goal.status===`active`?`running`:V().goal.status}`)),e}}),null),e})(),(()=>{var e=Sd();return e.firstChild,B(e,N(P,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=Vd();return t.$$click=()=>{n()&&$(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(or)},R(t,`title`,e===`active`?`agent keeps working toward the goal (with auto-continue)`:e===`done`?`mark achieved — auto-continue stops`:`parked on purpose — resume by setting active again`),B(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),y(n=>{var r=`goalstate`+(V().goal.text.trim()&&V().goal.status===e?` on ${e}`:``),i=!!V().goal.text.trim()&&V().goal.status===e;return r!==n.e&&z(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),N(F,{get when(){return V().goal.text},get fallback(){return Hd()},get children(){return[(()=>{var e=Cd(),t=e.firstChild;return y(()=>t.innerHTML=Pe(String(V().goal.text))),e})(),N(F,{get when(){return V().goal.verify},get children(){var e=wd(),t=e.firstChild.nextSibling;return y(()=>t.innerHTML=Pe(String(V().goal.verify))),e}}),N(F,{get when(){return V().goal.audit},children:e=>(()=>{var t=Ud(),n=t.firstChild,r=n.firstChild,i=n.nextSibling;return B(n,()=>e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`,r),B(r,()=>vh(e().at)),y(n=>{var r=`card auditcard `+(e().verdict===`approved`?`ok`:`warn`),a=pt(e().feedback)?Pe(`_the auditor returned a verdict with no detail_`):Pe(e().feedback);return r!==n.e&&z(t,n.e=r),a!==n.t&&(i.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t})()})]}}),(()=>{var e=Td(),t=e.firstChild,n=t.nextSibling,r=n.nextSibling.firstChild.firstChild;return e.addEventListener(`submit`,Ta),t.$$input=e=>{va(e.currentTarget.value),xa(!0)},n.$$input=e=>{q(e.currentTarget.value),xa(!0)},r.addEventListener(`change`,e=>Ca(e.currentTarget.checked)),y(()=>t.value=_a()),y(()=>n.value=ya()),y(()=>r.checked=Sa()),e})(),(()=>{var e=Dd(),t=e.firstChild.nextSibling;return B(e,N(F,{get when(){return ir().total>0},get children(){var e=Ed(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,B(e,()=>ir().done,t),B(e,()=>ir().total,n),y(t=>we(e,ir().done===ir().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),t),e})(),N(F,{get when(){return ir().total>0},get children(){var e=Od(),t=e.firstChild;return y(e=>{var n=`barfill `+(ir().done===ir().total?``:`warn`),r=`${Math.round(ir().done/ir().total*100)}%`;return n!==e.e&&z(t,e.e=n),r!==e.t&&Te(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),N(Fh,{get draft(){return Xn()},get preview(){return Qn()},onDraft:e=>{Zn(e),tr(!0)}}),(()=>{var e=kd(),t=e.firstChild,n=t.nextSibling;return B(e,N(Sh,{get icon(){return Qn()?`✎`:`👁`},get title(){return Qn()?`edit markdown`:`rendered checklist`},onClick:()=>$n(!Qn())}),t),n.$$click=rr,e})(),Ad(),N(F,{get when(){return V().latestProgress},get fallback(){return Wd()},children:e=>(()=>{var t=Yd(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return B(t,N(F,{get when(){return e().recent},get children(){var t=Gd(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(e().recent)),t}}),i),B(t,N(F,{get when(){return e().problems},get children(){var t=Kd(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(e().problems)),t}}),i),B(t,N(F,{get when(){return e().next},get children(){var t=qd(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(e().next)),t}}),i),B(t,N(F,{get when(){return e().goalStatus},get children(){var t=Jd(),n=t.firstChild.nextSibling;return B(n,()=>e().goalStatus),t}}),i),B(i,()=>vh(e().ts)),y(()=>r.innerHTML=Gm(e().doing)),t})()}),jd(),(()=>{var e=Pd(),t=e.firstChild,r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling,o=a.firstChild.nextSibling,s=a.nextSibling,c=s.firstChild.nextSibling,l=s.nextSibling,u=l.firstChild.nextSibling,d=l.nextSibling,f=d.firstChild.nextSibling;return B(e,N(F,{get when(){return V().ctx},keyed:!0,get fallback(){return Xd()},children:e=>{let t=x(()=>{let t=e,n=et().find(e=>e.id===V().model),r=t.window||n?.contextLength||0,i=r?Math.min(999,t.usedTokens/r*100):0;return{usedTokens:t.usedTokens,compactAt:t.compactAt,compacting:t.compacting,window:t.window,effectiveWindow:r,pct:i,cls:r?i>=85?`crit`:i>=70?`warn`:`ok`:``,derivedBudget:r?Math.round(r*.75):0,usingDerived:t.compactAtIsManual!==!0}}),r=()=>t(),i=e=>{let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)};return(()=>{var e=ef(),t=e.firstChild,a=t.firstChild.nextSibling,o=a.firstChild.nextSibling;o.nextSibling;var s=t.nextSibling,c=s.firstChild.nextSibling,l=c.firstChild,u=c.nextSibling,d=s.nextSibling,f=d.firstChild.firstChild;return B(a,()=>yh(r().usedTokens),o),B(t,N(F,{get when(){return r().effectiveWindow},get children(){var e=Zd(),t=e.firstChild;return B(e,()=>i(r().pct),t),B(e,()=>yh(r().effectiveWindow),null),y(()=>z(e,`pill ${r().cls}`)),e}}),null),B(e,N(F,{get when(){return r().effectiveWindow},get children(){var e=Qd(),t=e.firstChild;return y(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&z(t,e.e=n),i!==e.t&&Te(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),B(c,()=>yh(r().usingDerived?r().derivedBudget:r().compactAt),l),B(u,()=>r().usingDerived?`75% of window`:`manual`),B(e,N(F,{get when(){return Et()||r().compacting},get children(){var e=$d(),t=e.firstChild.nextSibling.nextSibling;return B(t,()=>Et()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&$(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(or)}),y(()=>f.checked=V().autoCompact!==!1),e})()}}),t),B(i,()=>yh(V().stats.inputTokens)),B(o,()=>yh(V().stats.outputTokens)),B(c,()=>V().stats.turns),B(u,()=>V().stats.toolCalls),B(f,()=>V().stats.compactions??0),B(t,N(F,{get when(){return(V().stats.costUsd??0)>0},get children(){var e=Md(),t=e.firstChild.nextSibling;return t.firstChild,B(t,()=>bh(V().stats.costUsd??0),null),y(()=>R(e,`title`,`≈ ${(V().stats.costUsd??0).toFixed(4)} this session, from the model's USD/token pricing and per-turn usage. Cached input is estimated at ~10% of the prompt rate; treat as an approximation, not an invoice.`)),e}}),null),B(t,N(F,{get when(){return(V().stats.cachedInputTokens??0)>0},get children(){var e=Nd(),t=e.firstChild.nextSibling,n=t.firstChild;return B(t,()=>Math.round(V().stats.cachedInputTokens/Math.max(1,V().stats.inputTokens)*100),n),y(()=>R(e,`title`,`${yh(V().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),y(()=>R(d,`title`,`how many times old turns were summarized into notes to make room. ${V().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=Id();return e.firstChild.nextSibling,B(e,N(F,{get when(){return kr()},get children(){var e=Fd(),t=e.firstChild.nextSibling;return B(t,kr),e}}),null),e})(),N(P,{get each(){return w()},children:e=>(()=>{var t=tf(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=kr()===e.branch?null:e.branch,r=t!==kr();U(t),n()&&(r&&(Fr++,h([]),_(0),G(!1)),Br(n()))},B(r,()=>e.branch,null),B(r,()=>e.branch===V().branch?` (current)`:``,null),B(i,()=>e.events,a),y(n=>{var r=`branch-row`+(e.branch===V().branch||e.branch===kr()?` cur`:``),i=e.branch===kr()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=Rd();return e.firstChild,B(e,N(F,{get when(){return cr().length>0},get children(){var e=Ld(),t=e.firstChild.nextSibling;return t.nextSibling,B(e,()=>cr().length,t),e}}),null),e})(),N(F,{get when(){return cr().length>0},get fallback(){return nf()},get children(){return N(P,{get each(){return cr()},children:e=>(()=>{var t=af(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>Jr(e.agent),B(i,()=>e.id),B(a,()=>e.agent,null),B(r,N(F,{get when(){return e.forked},get children(){return rf()}}),null),B(o,()=>e.schedule,s),B(o,(()=>{var t=I(()=>!!e.next);return()=>t()?vh(e.next):`—`})(),null),B(o,(()=>{var t=I(()=>!!e.last);return()=>t()?` · last ${vh(e.last)}`:` · never ran`})(),null),B(c,()=>xh(e.prompt,90)),y(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${xh(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&z(t,r.e=i),a!==r.t&&R(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),y(e=>{var n=`layout`+(ye()?``:` right-hidden`),r=`iconbtn notifbtn`+(On()>0?` has-unread`:``),i=On()>0?`${On()} unread notifications`:`notifications`,a=`conn`+(Yr()?` ok`:``),s=Yr()?`live (websocket)`:`reconnecting…`,c={"--termh":`${bi()}px`},u=`rightbar`+(ye()?` open`:``);return n!==e.e&&z(t,e.e=n),r!==e.t&&z(o,e.t=r),i!==e.a&&R(o,`title`,e.a=i),a!==e.o&&z(l,e.o=a),s!==e.i&&R(l,`title`,e.i=s),e.n=we(f,c,e.n),u!==e.s&&z(p,e.s=u),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),t}}),N(F,{get when(){return En()},get children(){return[(()=>{var e=Ku();return e.$$click=()=>Dn(!1),e})(),(()=>{var t=Yu(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return B(r,N(F,{get when(){return Sn().length>0},get children(){var e=qu();return e.$$click=()=>Cn([]),e}}),i),i.$$click=()=>Dn(!1),B(t,N(F,{get when(){return Sn().length>0},get fallback(){return of()},get children(){var t=Ju();return B(t,N(P,{get each(){return Sn()},children:t=>(()=>{var r=cf(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{Cn(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&Jr(t.agentId),Dn(!1),t.eventId&&setTimeout(()=>Fn(t.eventId),n()===t.agentId?60:350)},B(i,(()=>{var e=I(()=>t.kind===`finish`);return()=>e()?`✅`:I(()=>t.kind===`question`)()?`❓`:t.kind===`error`?`⚠️`:`📈`})()),B(a,()=>t.title),B(o,()=>vh(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),Cn(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},B(s,()=>t.read?`✓`:`○`),B(r,N(F,{get when(){return t.body},get children(){var e=sf();return B(e,()=>_h(t.body,160)),e}}),null),y(e=>{var n=`notifitem `+t.kind+(t.read?` read`:``),i=`from ${t.agentId}`,a=t.read?`already read`:`mark as read`;return n!==e.e&&z(r,e.e=n),i!==e.t&&R(r,`title`,e.t=i),a!==e.a&&R(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),N(F,{get when(){return ae()},get children(){return N(Th,{get providers(){return Object.keys(k().providers??{})},onClose:()=>oe(!1),onCreated:e=>{oe(!1),or(),Jr(e)}})}}),N(F,{get when(){return se()},get children(){return N(Vh,{get cfg(){return k()},onClose:()=>ce(!1),announcedOAuth:A,onSaved:()=>{qn(),ur()},theme:{themes:Me,activeId:Ce,auto:Oe,setAuto:ke,dark:Fe,setDark:Ie,light:Ae,setLight:je,setThemes:Ne,setActive:De}})}}),N(F,{get when(){return hn()},fallback:null,children:e=>{let t=()=>m().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,m().length-t()-1),[i,a]=v(r()>0?`summarize`:`discard`);return N(wh,{title:`edit prompt — forks the conversation`,onClose:()=>gn(null),get children(){var t=uf(),o=t.firstChild,s=o.nextSibling,c=s.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await $(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value,tail:i()})}),gn(null),or();let t=n();t&&await Jr(t)}catch(e){alert(`edit failed: ${e.message}`)}}),B(t,N(F,{get when(){return r()>0},get children(){var e=lf(),t=e.firstChild,n=t.firstChild,o=t.nextSibling,s=o.firstChild,c=o.nextSibling.firstChild;return B(t,r,n),s.addEventListener(`change`,()=>a(`summarize`)),c.addEventListener(`change`,()=>a(`discard`)),y(()=>s.checked=i()===`summarize`),y(()=>c.checked=i()===`discard`),e}}),s),c.$$click=()=>gn(null),y(()=>o.value=e().text),t}})}})]}function uh(e){let t=new Date(e.startedAt).getTime(),[n,r]=v(Date.now());ee(()=>{let e=setInterval(()=>r(Date.now()),500);C(()=>clearInterval(e))});let i=()=>ze(Math.max(0,n()-t));return e.inline?(()=>{var t=df();return t.firstChild,B(t,i,null),B(t,(()=>{var t=I(()=>!!e.timeoutMs);return()=>t()?` · timeout ${Math.round(e.timeoutMs/1e3)}s`:``})(),null),t})():(()=>{var e=ff(),t=e.firstChild;return B(e,i,t),e})()}function dh(e){let[t,n]=v(Date.now());return ee(()=>{let e=setInterval(()=>n(Date.now()),500);C(()=>clearInterval(e))}),e.startedAt?(()=>{var n=pf();return B(n,()=>ze(Math.max(0,t()-e.startedAt))),n})():null}function fh(e){let t=e.e,n=Dt(e.prev,t),r=()=>e.res?.(),i=()=>!e.agentActive&&!r(),a=t.data??{},o=String(a.name??`tool`),s=()=>String(r()?.data?.result??``),c=e=>String(a.args?.[e]??``),l=()=>o===`bash`?c(`command`):c(`path`)||JSON.stringify(a.args??{},null,1),u=()=>o===`bash`?Number(c(`timeout_ms`))||void 0:o===`wait_children`?Number(c(`timeout_ms`))||3e5:Number(c(`timeout_ms`))||void 0,d=(e,t=1500)=>(()=>{var n=mf();return B(n,()=>_h(e,t)),n})(),f=(e=4e3)=>(()=>{let t=r();return t?[I(()=>d(s(),e)),(()=>{var e=hf();return B(e,()=>ze(t.data?.durationMs),null),B(e,()=>o===`bash`?Rt(Lt(t.data?.ok,String(t.data?.result??``))):t.data?.ok===!1?` · FAILED`:``,null),B(e,N(Ch,{get text(){return s()}}),null),e})()]:gf()})(),p=x(()=>{r();let e=o,t=``,n=(()=>{var e=_f();return B(e,()=>_h(JSON.stringify(a.args??{},null,1),2e3)),e})();try{switch(o){case`bash`:{let i=c(`command`),o=a.args?.background===!0,l=o?String(s()).match(/job (bg\d+)/)?.[1]??``:``;e=(o?`⏳ `:`$ `)+xh(i,96);let u=c(`timeout_ms`)?Number(c(`timeout_ms`)):void 0,p=r(),m=Lt(p?.data?.ok,p?String(p.data?.result??``):``);t=p?o?`background job${l?` ${l}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:zt({outcome:m,durationMs:p.data?.durationMs,timeoutMs:u,fmtDur:ze}):null,n=[o?(()=>{var e=vf(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,B(t,l||`?`,n),B(e,l?[` · kill with `,yf()]:null,null),e})():null,I(()=>I(()=>i!==e.slice(2))()?d(i,800):null),I(()=>f(6e3))];break}case`read_file`:{e=c(`path`)||`(no path)`;let r=[];c(`pattern`)&&r.push(`grep /${xh(c(`pattern`),40)}/`),Number(a.args?.offset)<0?r.push(`last ${-Number(a.args.offset)} lines`):a.args?.offset&&r.push(`from L${a.args.offset}`),a.args?.limit&&r.push(`≤${a.args.limit} lines`),t=r.join(` · `),n=f(6e3);break}case`write_file`:{let i=String(a.args?.content??``);e=c(`path`)||`(no path)`,t=`${yh(i.length)} bytes`,n=[I(()=>d(i,1500)),I(()=>I(()=>i.length>1500)()?(()=>{var e=bf(),t=e.firstChild;return B(e,()=>yh(i.length),t),e})():null),I(()=>I(()=>!!r())()?(()=>{var e=hf();return B(e,()=>xh(s(),160)),e})():xf())];break}case`edit_file`:e=c(`path`)||`(no path)`,t=a.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=Sf();return B(e,()=>_h(`- `+c(`old_text`),900)),e})(),(()=>{var e=Cf();return B(e,()=>`+ `+_h(c(`new_text`),900)),e})(),I(()=>I(()=>!!r())()?(()=>{var e=wf(),t=e.firstChild;return B(e,()=>xh(s(),120),t),B(e,()=>ze(r().data?.durationMs),null),e})():Tf())];break;case`apply_patch`:{let t=c(`patch`).split(`
26
26
  `).filter(e=>e&&!/^---$/.test(e.trim())),i=t.map(e=>e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/)?.[1]).filter(Boolean);e=i.length?`${i.length} file${i.length>1?`s`:``}: ${xh(i.join(`, `),80)}`:`patch`;let a=t.slice(0,60);n=[(()=>{var e=Ef();return B(e,()=>a.map(e=>{let t=e.startsWith(`+`)?` add`:e.startsWith(`-`)?` del`:/^\*\*\*|^@@/.test(e)?` meta`:``;return(()=>{var n=Df();return z(n,`pline`+t),B(n,(()=>{var t=I(()=>e.length>240);return()=>t()?e.slice(0,240)+`…`:e})()),n})()}),null),B(e,(()=>{var e=I(()=>t.length>60);return()=>e()?(()=>{var e=Of(),n=e.firstChild.nextSibling;return n.nextSibling,B(e,()=>t.length-60,n),e})():null})(),null),e})(),I(()=>I(()=>!!r())()?(()=>{var e=hf();return B(e,()=>xh(s().split(`
27
- `)[0]??``,140),null),B(e,()=>r().data?.ok===!1?` · FAILED`:``,null),e})():kf())];break}case`list_dir`:e=c(`path`)||`.`,n=f(4e3);break;case`read_url`:{let r=c(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=xh(r,70),t=`web`,n=[(()=>{var e=hf();return B(e,N(F,{get when(){return/^https?:/i.test(c(`url`))},get fallback(){return(()=>{var e=jf();return B(e,()=>xh(c(`url`),80)),e})()},get children(){var e=Af();return y(()=>R(e,`href`,c(`url`))),e}})),e})(),I(()=>f(3e3))];break}case`bash_output`:{let r=c(`action`)||`read`;e=`bash_output ${c(`job_id`)||`(?)`}`,t=r,n=f(4e3);break}case`load_skill`:{e=`skill: ${c(`name`)}`;let t=s().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=r()?[(()=>{var e=ku();return y(()=>e.innerHTML=Pe(t)),e})(),(()=>{var e=hf();return B(e,()=>ze(r().data?.durationMs)),e})()]:Mf();break}case`save_skill`:{e=`skill: ${c(`name`)}`,t=xh(c(`description`),60);let i=Array.isArray(a.args?.files)?a.args.files.map(e=>e?.name).filter(Boolean):[];n=[I(()=>I(()=>!!i.length)()?(()=>{var e=Nf();return e.firstChild,B(e,()=>i.join(`, `),null),e})():null),I(()=>I(()=>!!r())()?(()=>{var e=wf(),t=e.firstChild;return B(e,()=>xh(s(),160),t),B(e,()=>ze(r().data?.durationMs),null),e})():Pf())];break}default:e=o,t=r()?ze(r().data?.durationMs):null,n=[(()=>{var e=_f();return B(e,()=>_h(JSON.stringify(a.args??{},null,1),2e3)),e})(),I(()=>f(4e3))]}}catch{}return{label:e,hint:t,body:n,key:`${r()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var a=If(),c=a.firstChild,d=c.firstChild,f=d.nextSibling,m=f.nextSibling;return a.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),B(d,()=>p().label),B(c,N(F,{get when(){return t.data?.actor},get children(){var e=Ff();return e.firstChild,B(e,()=>String(t.data.actor),null),e}}),f),B(f,(()=>{var e=I(()=>!!r());return()=>e()?p().hint||``:I(()=>!!i())()?`(result missed)`:I(()=>!!(o===`bash`||u()))()?N(uh,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return u()}}):`running…`})()),B(m,N(Ch,{get text(){return l()},label:`⧉ cmd`,title:`copy the ${o} arguments`}),null),B(m,N(F,{get when(){return r()},get children(){return N(Ch,{get text(){return s()},label:`⧉ out`,title:`copy this tool's full output`})}}),null),B(a,()=>p().body,null),y(e=>{var t=`embed`+(n?` grouped`:``)+(r()?r().data?.ok===!1?` fail`:` done`:i()?` done`:` running`),s=`${o}${p().hint?` — `+p().hint:``}`;return t!==e.e&&z(a,e.e=t),s!==e.t&&R(a,`title`,e.t=s),e},{e:void 0,t:void 0}),a})()}function ph(e){let t=e.data??{};return e.type===`prompt`?String(t.text??``):e.type===`message`?`${typeof t.reasoning==`string`&&t.reasoning.trim()?`<reasoning>\n${t.reasoning}\n</reasoning>\n\n`:``}${String(t.content??``)}`:(e.type,``)}function mh(e){let t=e.e,n=th(t),r=()=>Dt(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&Dt(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=Lf(),r=n.firstChild.nextSibling;return r.nextSibling,B(n,()=>String(e.fromBranch??`?`),r),B(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=ht(t.data??{});return(()=>{var t=Rf(),n=t.firstChild;return B(n,()=>e.label),B(t,N(F,{get when(){return e.hasCard},get children(){var t=Df();return y(n=>{var r=`card `+(e.tone===`ok`?`auditcard ok`:e.tone===`warn`?`auditcard`:`verifycard`),i=e.markdown?Pe(e.detail):Pe(`\`\`\`\n${e.detail}\n\`\`\``);return r!==n.e&&z(t,n.e=r),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),t}}),null),y(()=>z(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`todo`)return(()=>{var e=zf(),n=e.firstChild.nextSibling;return n.nextSibling,B(e,()=>String(t.data?.by??`human`),n),e})();if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=Bf(),n=e.firstChild;return B(e,()=>t.data.from,n),B(e,()=>t.data.to,null),B(e,(()=>{var e=I(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),y(()=>z(e,`divider-msg`+(t.data.to===`error`?` err`:``))),e})();if(t.type===`system_note`){let e=String(t.data?.event??``);if(e===`runaway-detected`)return(()=>{var e=Vf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,B(n,()=>String(t.data?.failures),r),B(n,()=>String(t.data?.limit),i),B(a,()=>String(t.data?.lastTool),o),B(a,()=>String(t.data?.lastError??``).slice(0,200),null),y(()=>R(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=Hf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,B(n,()=>String(t.data?.attempt),r),B(n,()=>Math.round(Number(t.data?.waitMs)/1e3),i),e})();if(e===`background-exit`){let e=t.data?.failed===!0,n=Math.round(Number(t.data?.durationMs??0)/1e3);return(()=>{var r=Df();return z(r,`divider-msg`+(e?` err`:``)),B(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),y(()=>R(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=Uf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,B(e,()=>String(t.data?.tokensBefore??`?`),n),B(e,()=>String(t.data?.tokensAfter??`?`),r),B(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=Wf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,B(e,()=>String(t.data?.messages??`?`),n),B(e,()=>String(t.data?.tokensBefore??`?`),r),B(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=Yf(),o=a.firstChild,s=o.nextSibling;return B(o,(()=>{var e=I(()=>!!r());return()=>e()?``:n.icon})()),B(s,(()=>{var e=I(()=>!!r());return()=>e()&&(()=>{var e=Xf();return y(()=>R(e,`title`,`${oh(t.ts)} · ${t.branch}`)),e})()})(),null),B(s,N(F,{get when(){return!r()},get children(){var r=Jf(),i=r.firstChild,a=i.nextSibling;return B(i,()=>n.name),B(r,N(F,{get when(){return t.data?.actor},get children(){var e=Ff();return e.firstChild,B(e,()=>String(t.data.actor),null),e}}),a),B(a,(()=>{var e=I(()=>!!t.data?.pending);return()=>e()?`queued…`:I(()=>!!t.data?.cancelled)()?`withdrawn`:oh(t.ts)})()),B(r,N(F,{get when(){return e.showBranch},get children(){var e=Gf();return B(e,()=>t.branch),e}}),null),B(r,N(F,{get when(){return e.onCancel},get children(){var t=Kf();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),B(r,N(F,{get when(){return t.type!==`tool_call`},get children(){return N(Ch,{get text(){return ph(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),B(r,N(F,{get when(){return e.onEdit},get children(){var t=qf();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),y(e=>Te(i,`color`,n.color)),r}}),null),B(s,N(gh,{e:t,get prev(){return e.prev?.()},get res(){return e.res},get orphan(){return e.orphan},get onOption(){return e.onOption},get answeredIds(){return e.answeredIds},get onAnswered(){return e.onAnswered},get agentActive(){return e.agentActive},get onResize(){return e.onResize}}),null),y(e=>{var s=`msg`+(r()?` grouped`:``)+(i()?` next-grouped`:``)+(t.data?.pending?` pending`:``)+(t.data?.cancelled?` withdrawn`:``),c=t.id,l=`avatar avghost`+(r()?` ghosted`:``),u=r()?`transparent`:n.color+`33`,d=r()?`1px solid transparent`:`1px solid ${n.color}66`,f=r()?`${oh(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&z(a,e.e=s),c!==e.t&&R(a,`data-eid`,e.t=c),l!==e.a&&z(o,e.a=l),u!==e.o&&Te(o,`background`,e.o=u),d!==e.i&&Te(o,`border`,e.i=d),f!==e.n&&R(o,`title`,e.n=f),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),a})()}function hh(e){let[t,n]=v(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=Zf(),a=i.firstChild,o=a.nextSibling;return a.$$keydown=e=>{e.key===`Enter`&&!e.isComposing&&(e.preventDefault(),r())},a.$$input=e=>n(e.currentTarget.value),o.$$click=r,y(n=>{var r=e.answered?`answered`:`or type your own answer…`,i=e.answered,s=e.answered||!t().trim();return r!==n.e&&R(a,`placeholder`,n.e=r),i!==n.t&&(a.disabled=n.t=i),s!==n.a&&(o.disabled=n.a=s),n},{e:void 0,t:void 0,a:void 0}),y(()=>a.value=t()),i})()}function gh(e){let t=e.e;switch(t.type){case`prompt`:{let e=t.data?.images??[];return[(()=>{var e=ku();return y(()=>e.innerHTML=Gm(String(t.data.text??``))),e})(),N(F,{get when(){return e.length},get children(){var t=Qf();return B(t,N(P,{each:e,children:e=>(()=>{var t=$f();return R(t,`src`,e),t})()})),t}})]}case`message`:return[N(F,{get when(){return I(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=ep(),n=e.firstChild;n.firstChild;var r=n.nextSibling;return B(n,(()=>{var e=I(()=>String(t.data.reasoning).length>4e3);return()=>e()?` (${yh(String(t.data.reasoning).length)} — truncated)`:``})(),null),B(r,()=>_h(String(t.data.reasoning),8e3)),e}}),(()=>{var e=ku();return y(()=>e.innerHTML=Gm(String(t.data.content??``))),e})(),N(F,{get when(){return t.data.interrupted},get children(){return tp()}}),N(F,{get when(){return t.data.final},get children(){var e=np(),n=e.firstChild;return B(e,N(Ch,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return N(fh,{e:t,get prev(){return e.prev},get res(){return e.res},get orphan(){return e.orphan},get agentActive(){return e.agentActive},get onResize(){return e.onResize}});case`tool_result`:{let n=String(t.data.result??``),r=String(t.data.name??`tool`),i=t.data.ok!==!1;return(()=>{var a=ip(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return z(a,`embed `+(i?``:`fail`)),B(s,r===`bash`?`$ (bash, call evicted)`:r),B(o,N(Ch,{text:n}),null),B(c,()=>_h(n,4e3)),B(l,()=>ze(t.data.durationMs),null),B(l,()=>r===`bash`?Rt(Lt(t.data.ok,n)):i?``:` · FAILED`,null),B(a,N(F,{get when(){return e.orphan},get children(){return rp()}}),null),y(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=op(),r=n.firstChild,i=r.firstChild.firstChild.nextSibling,a=r.nextSibling;return B(n,N(F,{get when(){return e.length},get children(){var t=ap();return t.firstChild,B(t,()=>e.join(` / `),null),t}}),null),y(e=>{var n=Gm(String(t.data?.decision??``)),r=Gm(String(t.data?.rationale??``));return n!==e.e&&(i.innerHTML=e.e=n),r!==e.t&&(a.innerHTML=e.t=r),e},{e:void 0,t:void 0}),n})()}case`question`:{let n=Array.isArray(t.data?.options)?t.data.options:[],r=t.data?.callId?String(t.data.callId):``,i=()=>e.answeredIds?.().has(r)??!1;return(()=>{var a=lp(),o=a.firstChild.firstChild.nextSibling;return B(a,N(F,{get when(){return i()},get children(){return sp()}}),null),B(a,N(F,{get when(){return n.length>0},get children(){var a=cp();return B(a,N(P,{each:n,children:n=>(()=>{var a=up();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?$(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>Q(`→ answered @${String(t.data.actor)}`)).catch(()=>Q(`answer failed`)):e.onOption?.(n)},B(a,n),y(()=>a.disabled=i()),a})()})),a}}),null),B(a,N(hh,{get answered(){return i()},get onOption(){return e.onOption}}),null),y(e=>{var n=`embed question`+(i()?` answered`:``),r=Gm(String(t.data?.question??``));return n!==e.e&&z(a,e.e=n),r!==e.t&&(o.innerHTML=e.t=r),e},{e:void 0,t:void 0}),a})()}case`progress`:return(()=>{var e=dp(),n=e.firstChild.firstChild.nextSibling;return B(e,N(F,{get when(){return t.data.goalStatus},get children(){var e=Jd(),n=e.firstChild.nextSibling;return B(n,()=>String(t.data.goalStatus)),e}}),null),B(e,N(F,{get when(){return t.data.recent},get children(){var e=Gd(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(String(t.data.recent))),e}}),null),B(e,N(F,{get when(){return t.data.problems},get children(){var e=Kd(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(String(t.data.problems))),e}}),null),B(e,N(F,{get when(){return t.data.next},get children(){var e=qd(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(String(t.data.next))),e}}),null),y(()=>n.innerHTML=Gm(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=fp(),n=e.firstChild;return n.firstChild,B(n,()=>String(t.data.message??``),null),e})();case`compaction`:return(()=>{var e=mp(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,B(n,()=>String(t.data.mode??``),r),B(n,()=>yh(Number(t.data.tokensBefore??0)),i),B(n,()=>yh(Number(t.data.tokensAfter??0)),a),B(n,(()=>{var e=I(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),B(e,N(F,{get when(){return t.data.summary},get children(){return[pp(),(()=>{var e=ku();return y(()=>e.innerHTML=Gm(String(t.data.summary))),e})()]}}),null),e})();default:return(()=>{var e=hp();return B(e,()=>_h(JSON.stringify(t.data),200)),e})()}}function _h(e,t){return e.length>t?e.slice(0,t)+` …`:e}function vh(e){let t=new Date(e).getTime()-Date.now(),n=Math.abs(t),r=n<9e4?`${Math.round(n/1e3)}s`:n<54e5?`${Math.round(n/6e4)}m`:`${(n/36e5).toFixed(1)}h`;return t>=0?`in ${r}`:`${r} ago`}function yh(e){return e>=1e9?`${+(e/1e9).toFixed(1)}b`:e>=1e6?`${+(e/1e6).toFixed(1)}m`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function bh(e){return e>=100?Math.round(e).toLocaleString():e>=10?e.toFixed(1):e>=1?e.toFixed(2):e>=.01?e.toFixed(3):e.toFixed(4)}function xh(e,t){return _h(e.replace(/\s+/g,` `).trim(),t)}function Sh(e){return(()=>{var t=gp(),n=t.firstChild;return Ce(t,`click`,e.onClick,!0),B(n,()=>e.icon),y(n=>{var r=`iconbtn`+(e.active?` active`:``)+(e.class?` `+e.class:``),i=e.title,a=e.style;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n.a=we(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function Ch(e){let[t,n]=v(!1),[r,i]=v(!1),a=t=>{t.preventDefault(),t.stopPropagation(),wt(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=_p();return n.$$click=a,B(n,(()=>{var n=I(()=>!!t());return()=>n()?`✓`:I(()=>!!r())()?`✗`:e.label??`⧉`})()),y(()=>R(n,`title`,e.title??`copy to clipboard`)),n})()}function wh(e){return(()=>{var t=vp(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),B(r,()=>e.title),Ce(i,`click`,e.onClose,!0),B(n,()=>e.children,null),t})()}function Th(e){let[t,n]=v(`~`),[r,i]=v([]),[a,o]=v(``),[s,c]=v(e.providers[0]??``),[l,u]=v(``),[d,f]=v(``);async function p(e){let r=await $(`/api/fs?path=${encodeURIComponent(e??t())}`);n(r.path),h(r.parent??``),i(r.entries??[])}ee(()=>p(t()));let[m,h]=v(``),g=async n=>{n.preventDefault(),f(``);try{let n=await $(`/api/agents`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspace:t(),id:a(),provider:s()||void 0,model:l()||void 0,start:!1})});e.onCreated(n.agent.id)}catch(e){f(String(e.message))}};return N(wh,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=bp(),f=i.firstChild,h=f.firstChild.nextSibling.firstChild,_=h.nextSibling,v=_.nextSibling,b=f.nextSibling,x=b.nextSibling,S=x.firstChild,ee=S.firstChild.nextSibling,C=S.nextSibling,w=C.firstChild.nextSibling,T=C.nextSibling.firstChild.nextSibling,E=x.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),B(b,N(P,{get each(){return r()},children:e=>(()=>{var n=xp();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),B(n,e,null),n})()})),ee.$$input=e=>o(e.currentTarget.value),w.addEventListener(`change`,e=>c(e.currentTarget.value)),B(w,N(P,{get each(){return e.providers},children:e=>(()=>{var t=zd();return B(t,e),t})()})),T.$$input=e=>u(e.currentTarget.value),B(i,N(F,{get when(){return d()},get children(){var e=yp();return B(e,d),e}}),E),y(()=>h.value=t()),y(()=>ee.value=a()),y(()=>w.value=s()),y(()=>T.value=l()),i}})}var Eh=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),Dh=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Oh=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function kh(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Ah(e);return n===`image`?`🖼`:n===`video`?`🎬`:n===`audio`?`🎵`:[`ts`,`tsx`,`mts`,`cts`].includes(t)?`🟦`:[`js`,`mjs`,`cjs`,`jsx`].includes(t)?`🟨`:t===`json`||t===`jsonc`?`🧾`:t===`md`||t===`mdx`||t===`markdown`?`📝`:t===`css`||t===`scss`||t===`less`?`🎨`:t===`html`||t===`htm`||t===`svg`?`🌐`:[`py`,`pyi`].includes(t)?`🐍`:t===`rs`?`🦀`:t===`go`?`🐹`:t===`java`||t===`kt`||t===`kts`?`☕`:t===`rb`?`💎`:t===`php`?`🐘`:t===`c`||t===`h`||t===`cpp`||t===`hpp`||t===`cc`?`🧩`:t===`sh`||t===`bash`||t===`zsh`||t===`fish`?`🐚`:t===`sql`?`🗄`:t===`yml`||t===`yaml`||t===`toml`||t===`ini`||t===`conf`?`⚙`:t===`lock`?`🔒`:e===`Dockerfile`||t===`dockerfile`?`🐳`:t===`zip`||t===`gz`||t===`tar`||t===`tgz`||t===`bz2`?`📦`:t===`pdf`?`📕`:t===`txt`||t===`log`?`📄`:`·`}function Ah(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return Eh.has(t)?`image`:Dh.has(t)?`video`:Oh.has(t)?`audio`:null}var jh=new Map,Mh=e=>{let t=jh.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},jh.set(e,t)),t};function Nh(e){let t=()=>e.palette;return(()=>{var e=Sp(),n=e.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling,f=d.nextSibling;return y(p=>{var m=t().bgDark,h=t().bgDarkest,g=t().bgDarkest,_=t().bgMid,v=t().fg,y=t().acc,b=t().dim,x=t().acc,S=t().dim,ee=t().ok,C=t().warn,w=t().err;return m!==p.e&&Te(e,`background`,p.e=m),h!==p.t&&Te(n,`background`,p.t=h),g!==p.a&&Te(r,`background`,p.a=g),_!==p.o&&Te(i,`background`,p.o=_),v!==p.i&&Te(a,`background`,p.i=v),y!==p.n&&Te(o,`background`,p.n=y),b!==p.s&&Te(s,`background`,p.s=b),x!==p.h&&Te(c,`background`,p.h=x),S!==p.r&&Te(l,`background`,p.r=S),ee!==p.d&&Te(u,`background`,p.d=ee),C!==p.l&&Te(d,`background`,p.l=C),w!==p.u&&Te(f,`background`,p.u=w),p},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0}),e})()}function Ph(e){let[t,n]=v(e.themes().some(t=>t.id===e.activeId)?e.activeId:e.themes()[0]?.id??``),r=()=>{let n=e.themes();return n.find(e=>e.id===t())??n[0]},[i,a]=v({}),o,s=t=>{let n=r()?.id;if(!n)return;let i=e.themes().map(e=>e.id===n?t(e):e);e.onChange(i)},c=(e,t)=>{let n=fn(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.activeId),r=eh.find(t=>t.key===e.activeId),i=t??r??eh[0],a=getComputedStyle(document.documentElement),o={...rn};for(let{key:e,cssVar:t}of tn){let n=fn(a.getPropertyValue(t));n&&(o[e]=n)}let s=un(e.themes().map(e=>e.id).concat(eh.map(e=>e.key))),c={id:s,label:`${i.label}${t?``:` copy`}`.slice(0,40),mode:i.mode,palette:o,...t?.backgroundImage?{backgroundImage:t.backgroundImage,backgroundDim:t.backgroundDim}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))Q(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{Q(`uploading ${t.name} (${Math.round(t.size/1024)}KB)…`);try{let n=await fetch(`/api/assets`,{method:`POST`,headers:{"content-type":t.type},body:t}).then(async e=>({ok:e.ok,body:await e.json().catch(()=>null)}));if(!n.ok||!n.body?.url){Q(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url}));let i=r()?.id;i&&e.onPick(i),Q(`background image set`)}catch(e){Q(`upload failed: ${e.message}`)}}}};return(()=>{var d=wp(),f=d.firstChild.nextSibling,p=f.firstChild;return p.$$click=l,B(f,N(F,{get when(){return e.themes().length>0},get children(){var r=Cp();return r.addEventListener(`change`,t=>{n(t.currentTarget.value),e.onPick(t.currentTarget.value)}),B(r,N(P,{get each(){return e.themes()},children:e=>(()=>{var t=zd();return B(t,()=>e.label),y(()=>t.value=e.id),t})()})),y(()=>r.value=t()),r}}),null),B(d,N(F,{get when(){return r()},get fallback(){return Tp()},children:t=>[(()=>{var e=Ep(),t=e.firstChild,n=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling;return n.$$input=e=>s(t=>({...t,label:e.currentTarget.value.slice(0,40)})),i.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),y(()=>n.value=r().label),y(()=>i.value=r().mode),e})(),(()=>{var e=Dp();return B(e,N(P,{each:tn,children:e=>(()=>{var t=Np(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),B(o,()=>e.label),s.addEventListener(`blur`,()=>a(t=>{let n={...t};return delete n[e.key],n})),s.$$input=t=>{let n=t.currentTarget.value;a(t=>({...t,[e.key]:n})),c(e.key,n)},R(s,`spellcheck`,!1),y(()=>R(t,`title`,e.cssVar)),y(()=>n.value=fn(r().palette[e.key])??`#000000`),y(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=Op(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...rn}})),a.$$click=()=>{let t=r()?.id;t&&(e.onChange(e.themes().filter(e=>e.id!==t)),n(e.themes().find(e=>e.id!==t)?.id??``))},t})(),kp(),(()=>{var e=jp(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),B(t,()=>r().backgroundImage?`🖼 replace image…`:`🖼 choose image…`),n.addEventListener(`change`,e=>{e.stopPropagation(),u(e.currentTarget.files?.[0]),e.currentTarget.value=``}),n.$$input=e=>e.stopPropagation();var i=o;return typeof i==`function`?Ee(i,n):o=n,B(e,N(F,{get when(){return r().backgroundImage},get children(){var e=Ap(),t=e.firstChild,n=t.nextSibling,i=n.firstChild.nextSibling;i.nextSibling;var a=n.nextSibling.firstChild,o=a.firstChild.nextSibling,c=o.nextSibling,l=c.firstChild,u=a.nextSibling;return B(n,()=>Math.round((r().backgroundImage?.length??0)*3/4/1024),i),o.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),B(c,()=>Math.round((r().backgroundDim??.55)*100),l),u.$$click=()=>s(e=>({...e,backgroundImage:void 0})),y(()=>R(t,`src`,r().backgroundImage)),y(()=>o.value=r().backgroundDim??.55),e}}),null),e})(),Mp()]}),null),d})()}function Fh(e){let t=Number(localStorage.getItem(`teapot.todoH`)??``),[n,r]=v(Number.isFinite(t)&&t>0?t:0),i=()=>n()>0?{height:`${n()}px`}:void 0,a=e=>{let t=new ResizeObserver(()=>{let t=e.offsetHeight;t<=0||r(e=>Math.abs(e-t)<1?e:(localStorage.setItem(`teapot.todoH`,String(t)),t))});t.observe(e),C(()=>t.disconnect())};return N(F,{get when(){return e.preview},get fallback(){return(()=>{var t=Fp();return t.$$input=t=>e.onDraft(t.currentTarget.value),Ee(a,t),y(e=>we(t,i(),e)),y(()=>t.value=e.draft),t})()},get children(){var t=Pp();return Ee(a,t),y(n=>{var r=i(),a=Gm(e.draft);return n.e=we(t,r,n.e),a!==n.t&&(t.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t}})}function Ih(e){let t=Mh(e.agentId),[n,r]=v(new Map),[i,a]=v(t.expanded),[o,s]=v(t.preview),c=e=>{t.preview=e,s(e)},l=e=>{t.expanded=e,a(e)},[u,d]=v(t.media),f=e=>{t.media=e,d(e)},[p,m]=v(t.viewMode),h=e=>{t.viewMode=e,m(e)},[g,_]=v(``),[x,S]=v(localStorage.getItem(`teapot.ignoreMode`)??`dim`),ee=()=>{let e=[`dim`,`hide`,`show`],t=e[(e.indexOf(x())+1)%3];S(t),localStorage.setItem(`teapot.ignoreMode`,t)},w=e=>x()!==`hide`||!e.ignored,[T,E]=v(localStorage.getItem(`teapot.showHidden`)===`1`),te=()=>{let e=!T(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await re(t,e)}))).then(t=>{E(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&O(e,n)})},D=(e,t)=>t.map(t=>({name:String(t.name),path:e?`${e}/${t.name}`:String(t.name),dir:!!t.dir,...typeof t.size==`number`?{size:t.size}:{},...t.ignored?{ignored:!0}:{}}));async function ne(e){return re(e,T())}async function re(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await $(`/api/agents/${e.agentId}/tree?${r.toString()}`);return D(t,i.entries??[])}catch(e){return _(e.message),null}}let O=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=i.map(e=>{let t=n.find(t=>t.path===e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?e:t??e});for(let e of n)i.some(t=>t.path===e.path)||a.push(e);let o=a.filter(e=>n.some(t=>t.path===e.path)||t.preview?.path===e.path),s=new Map(r);return s.set(e,o),s}),k=``;b(()=>{let t=e.agentId;t!==k&&(k=t,l(new Set),c(null),f(null),r(new Map),ne(``).then(e=>{e&&k===t&&r(new Map([[``,e]]))}))});let ie=async e=>{let t=new Set(i());if(t.has(e.path))t.delete(e.path),l(t);else if(t.add(e.path),l(t),!n().has(e.path)){let t=await ne(e.path);t&&O(e.path,t)}},[ae,oe]=v(``),[se,ce]=v(!1),[A,le]=v(``),[j,ue]=v(!1),de=e=>/\.(md|markdown|mdx)$/i.test(e),M=0,fe=async e=>{let t=++M;oe(``),ce(!0);try{let{highlightChunks:n}=await vu(async()=>{let{highlightChunks:e}=await import(`./shiki-DlwNzZqU.js`);return{highlightChunks:e}},[]);for await(let r of n(e.path,e.content)){if(M!==t)return;oe(e=>e+r)}}catch{M===t&&oe(``)}finally{M===t&&ce(!1)}};C(()=>{M++});let pe=async(t,n)=>{let r=Ah(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await $(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),le(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&fe({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){Q(`open failed: ${e.message}`)}},me=async()=>{let t=o();if(t&&!j()){ue(!0);try{await $(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:A(),baseContent:t.content})}),c({...t,content:A()}),Q(`saved ${t.path}`)}catch(e){let n=e.payload,r=n&&typeof n==`object`&&n.error===`file changed on disk`?n:null;r?.current===void 0?Q(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
27
+ `)[0]??``,140),null),B(e,()=>r().data?.ok===!1?` · FAILED`:``,null),e})():kf())];break}case`list_dir`:e=c(`path`)||`.`,n=f(4e3);break;case`read_url`:{let r=c(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=xh(r,70),t=`web`,n=[(()=>{var e=hf();return B(e,N(F,{get when(){return/^https?:/i.test(c(`url`))},get fallback(){return(()=>{var e=jf();return B(e,()=>xh(c(`url`),80)),e})()},get children(){var e=Af();return y(()=>R(e,`href`,c(`url`))),e}})),e})(),I(()=>f(3e3))];break}case`bash_output`:{let r=c(`action`)||`read`;e=`bash_output ${c(`job_id`)||`(?)`}`,t=r,n=f(4e3);break}case`load_skill`:{e=`skill: ${c(`name`)}`;let t=s().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=r()?[(()=>{var e=ku();return y(()=>e.innerHTML=Pe(t)),e})(),(()=>{var e=hf();return B(e,()=>ze(r().data?.durationMs)),e})()]:Mf();break}case`save_skill`:{e=`skill: ${c(`name`)}`,t=xh(c(`description`),60);let i=Array.isArray(a.args?.files)?a.args.files.map(e=>e?.name).filter(Boolean):[];n=[I(()=>I(()=>!!i.length)()?(()=>{var e=Nf();return e.firstChild,B(e,()=>i.join(`, `),null),e})():null),I(()=>I(()=>!!r())()?(()=>{var e=wf(),t=e.firstChild;return B(e,()=>xh(s(),160),t),B(e,()=>ze(r().data?.durationMs),null),e})():Pf())];break}default:e=o,t=r()?ze(r().data?.durationMs):null,n=[(()=>{var e=_f();return B(e,()=>_h(JSON.stringify(a.args??{},null,1),2e3)),e})(),I(()=>f(4e3))]}}catch{}return{label:e,hint:t,body:n,key:`${r()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var a=If(),c=a.firstChild,d=c.firstChild,f=d.nextSibling,m=f.nextSibling;return a.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),B(d,()=>p().label),B(c,N(F,{get when(){return t.data?.actor},get children(){var e=Ff();return e.firstChild,B(e,()=>String(t.data.actor),null),e}}),f),B(f,(()=>{var e=I(()=>!!r());return()=>e()?p().hint||``:I(()=>!!i())()?`(result missed)`:I(()=>!!(o===`bash`||u()))()?N(uh,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return u()}}):`running…`})()),B(m,N(Ch,{get text(){return l()},label:`⧉ cmd`,title:`copy the ${o} arguments`}),null),B(m,N(F,{get when(){return r()},get children(){return N(Ch,{get text(){return s()},label:`⧉ out`,title:`copy this tool's full output`})}}),null),B(a,()=>p().body,null),y(e=>{var t=`embed`+(n?` grouped`:``)+(r()?r().data?.ok===!1?` fail`:` done`:i()?` done`:` running`),s=`${o}${p().hint?` — `+p().hint:``}`;return t!==e.e&&z(a,e.e=t),s!==e.t&&R(a,`title`,e.t=s),e},{e:void 0,t:void 0}),a})()}function ph(e){let t=e.data??{};return e.type===`prompt`?String(t.text??``):e.type===`message`?`${typeof t.reasoning==`string`&&t.reasoning.trim()?`<reasoning>\n${t.reasoning}\n</reasoning>\n\n`:``}${String(t.content??``)}`:(e.type,``)}function mh(e){let t=e.e,n=th(t),r=()=>Dt(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&Dt(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=Lf(),r=n.firstChild.nextSibling;return r.nextSibling,B(n,()=>String(e.fromBranch??`?`),r),B(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=ht(t.data??{});return(()=>{var t=Rf(),n=t.firstChild;return B(n,()=>e.label),B(t,N(F,{get when(){return e.hasCard},get children(){var t=Df();return y(n=>{var r=`card `+(e.tone===`ok`?`auditcard ok`:e.tone===`warn`?`auditcard`:`verifycard`),i=e.markdown?Pe(e.detail):Pe(`\`\`\`\n${e.detail}\n\`\`\``);return r!==n.e&&z(t,n.e=r),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),t}}),null),y(()=>z(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`todo`)return(()=>{var e=zf(),n=e.firstChild.nextSibling;return n.nextSibling,B(e,()=>String(t.data?.by??`human`),n),e})();if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=Bf(),n=e.firstChild;return B(e,()=>t.data.from,n),B(e,()=>t.data.to,null),B(e,(()=>{var e=I(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),y(()=>z(e,`divider-msg`+(t.data.to===`error`?` err`:``))),e})();if(t.type===`system_note`){let e=String(t.data?.event??``);if(e===`runaway-detected`)return(()=>{var e=Vf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,B(n,()=>String(t.data?.failures),r),B(n,()=>String(t.data?.limit),i),B(a,()=>String(t.data?.lastTool),o),B(a,()=>String(t.data?.lastError??``).slice(0,200),null),y(()=>R(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=Hf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,B(n,()=>String(t.data?.attempt),r),B(n,()=>Math.round(Number(t.data?.waitMs)/1e3),i),e})();if(e===`background-exit`){let e=t.data?.failed===!0,n=Math.round(Number(t.data?.durationMs??0)/1e3);return(()=>{var r=Df();return z(r,`divider-msg`+(e?` err`:``)),B(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),y(()=>R(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=Uf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,B(e,()=>String(t.data?.tokensBefore??`?`),n),B(e,()=>String(t.data?.tokensAfter??`?`),r),B(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=Wf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,B(e,()=>String(t.data?.messages??`?`),n),B(e,()=>String(t.data?.tokensBefore??`?`),r),B(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=Yf(),o=a.firstChild,s=o.nextSibling;return B(o,(()=>{var e=I(()=>!!r());return()=>e()?``:n.icon})()),B(s,(()=>{var e=I(()=>!!r());return()=>e()&&(()=>{var e=Xf();return y(()=>R(e,`title`,`${oh(t.ts)} · ${t.branch}`)),e})()})(),null),B(s,N(F,{get when(){return!r()},get children(){var r=Jf(),i=r.firstChild,a=i.nextSibling;return B(i,()=>n.name),B(r,N(F,{get when(){return t.data?.actor},get children(){var e=Ff();return e.firstChild,B(e,()=>String(t.data.actor),null),e}}),a),B(a,(()=>{var e=I(()=>!!t.data?.pending);return()=>e()?`queued…`:I(()=>!!t.data?.cancelled)()?`withdrawn`:oh(t.ts)})()),B(r,N(F,{get when(){return e.showBranch},get children(){var e=Gf();return B(e,()=>t.branch),e}}),null),B(r,N(F,{get when(){return e.onCancel},get children(){var t=Kf();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),B(r,N(F,{get when(){return t.type!==`tool_call`},get children(){return N(Ch,{get text(){return ph(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),B(r,N(F,{get when(){return e.onEdit},get children(){var t=qf();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),y(e=>Te(i,`color`,n.color)),r}}),null),B(s,N(gh,{e:t,get prev(){return e.prev?.()},get res(){return e.res},get orphan(){return e.orphan},get onOption(){return e.onOption},get answeredIds(){return e.answeredIds},get onAnswered(){return e.onAnswered},get agentActive(){return e.agentActive},get onResize(){return e.onResize}}),null),y(e=>{var s=`msg`+(r()?` grouped`:``)+(i()?` next-grouped`:``)+(t.data?.pending?` pending`:``)+(t.data?.cancelled?` withdrawn`:``),c=t.id,l=`avatar avghost`+(r()?` ghosted`:``),u=r()?`transparent`:n.color+`33`,d=r()?`1px solid transparent`:`1px solid ${n.color}66`,f=r()?`${oh(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&z(a,e.e=s),c!==e.t&&R(a,`data-eid`,e.t=c),l!==e.a&&z(o,e.a=l),u!==e.o&&Te(o,`background`,e.o=u),d!==e.i&&Te(o,`border`,e.i=d),f!==e.n&&R(o,`title`,e.n=f),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),a})()}function hh(e){let[t,n]=v(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=Zf(),a=i.firstChild,o=a.nextSibling;return a.$$keydown=e=>{e.key===`Enter`&&!e.isComposing&&(e.preventDefault(),r())},a.$$input=e=>n(e.currentTarget.value),o.$$click=r,y(n=>{var r=e.answered?`answered`:`or type your own answer…`,i=e.answered,s=e.answered||!t().trim();return r!==n.e&&R(a,`placeholder`,n.e=r),i!==n.t&&(a.disabled=n.t=i),s!==n.a&&(o.disabled=n.a=s),n},{e:void 0,t:void 0,a:void 0}),y(()=>a.value=t()),i})()}function gh(e){let t=e.e;switch(t.type){case`prompt`:{let e=t.data?.images??[];return[(()=>{var e=ku();return y(()=>e.innerHTML=Gm(String(t.data.text??``))),e})(),N(F,{get when(){return e.length},get children(){var t=Qf();return B(t,N(P,{each:e,children:e=>(()=>{var t=$f();return R(t,`src`,e),t})()})),t}})]}case`message`:return[N(F,{get when(){return I(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=ep(),n=e.firstChild;n.firstChild;var r=n.nextSibling;return B(n,(()=>{var e=I(()=>String(t.data.reasoning).length>4e3);return()=>e()?` (${yh(String(t.data.reasoning).length)} — truncated)`:``})(),null),B(r,()=>_h(String(t.data.reasoning),8e3)),e}}),(()=>{var e=ku();return y(()=>e.innerHTML=Gm(String(t.data.content??``))),e})(),N(F,{get when(){return t.data.interrupted},get children(){return tp()}}),N(F,{get when(){return t.data.final},get children(){var e=np(),n=e.firstChild;return B(e,N(Ch,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return N(fh,{e:t,get prev(){return e.prev},get res(){return e.res},get orphan(){return e.orphan},get agentActive(){return e.agentActive},get onResize(){return e.onResize}});case`tool_result`:{let n=String(t.data.result??``),r=String(t.data.name??`tool`),i=t.data.ok!==!1;return(()=>{var a=ip(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return z(a,`embed `+(i?``:`fail`)),B(s,r===`bash`?`$ (bash, call evicted)`:r),B(o,N(Ch,{text:n}),null),B(c,()=>_h(n,4e3)),B(l,()=>ze(t.data.durationMs),null),B(l,()=>r===`bash`?Rt(Lt(t.data.ok,n)):i?``:` · FAILED`,null),B(a,N(F,{get when(){return e.orphan},get children(){return rp()}}),null),y(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=op(),r=n.firstChild,i=r.firstChild.firstChild.nextSibling,a=r.nextSibling;return B(n,N(F,{get when(){return e.length},get children(){var t=ap();return t.firstChild,B(t,()=>e.join(` / `),null),t}}),null),y(e=>{var n=Gm(String(t.data?.decision??``)),r=Gm(String(t.data?.rationale??``));return n!==e.e&&(i.innerHTML=e.e=n),r!==e.t&&(a.innerHTML=e.t=r),e},{e:void 0,t:void 0}),n})()}case`question`:{let n=Array.isArray(t.data?.options)?t.data.options:[],r=t.data?.callId?String(t.data.callId):``,i=()=>e.answeredIds?.().has(r)??!1;return(()=>{var a=lp(),o=a.firstChild.firstChild.nextSibling;return B(a,N(F,{get when(){return i()},get children(){return sp()}}),null),B(a,N(F,{get when(){return n.length>0},get children(){var a=cp();return B(a,N(P,{each:n,children:n=>(()=>{var a=up();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?$(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>Q(`→ answered @${String(t.data.actor)}`)).catch(()=>Q(`answer failed`)):e.onOption?.(n)},B(a,n),y(()=>a.disabled=i()),a})()})),a}}),null),B(a,N(hh,{get answered(){return i()},get onOption(){return e.onOption}}),null),y(e=>{var n=`embed question`+(i()?` answered`:``),r=Gm(String(t.data?.question??``));return n!==e.e&&z(a,e.e=n),r!==e.t&&(o.innerHTML=e.t=r),e},{e:void 0,t:void 0}),a})()}case`progress`:return(()=>{var e=dp(),n=e.firstChild.firstChild.nextSibling;return B(e,N(F,{get when(){return t.data.goalStatus},get children(){var e=Jd(),n=e.firstChild.nextSibling;return B(n,()=>String(t.data.goalStatus)),e}}),null),B(e,N(F,{get when(){return t.data.recent},get children(){var e=Gd(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(String(t.data.recent))),e}}),null),B(e,N(F,{get when(){return t.data.problems},get children(){var e=Kd(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(String(t.data.problems))),e}}),null),B(e,N(F,{get when(){return t.data.next},get children(){var e=qd(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=Gm(String(t.data.next))),e}}),null),y(()=>n.innerHTML=Gm(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=fp(),n=e.firstChild;return n.firstChild,B(n,()=>String(t.data.message??``),null),e})();case`compaction`:return(()=>{var e=mp(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,B(n,()=>String(t.data.mode??``),r),B(n,()=>yh(Number(t.data.tokensBefore??0)),i),B(n,()=>yh(Number(t.data.tokensAfter??0)),a),B(n,(()=>{var e=I(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),B(e,N(F,{get when(){return t.data.summary},get children(){return[pp(),(()=>{var e=ku();return y(()=>e.innerHTML=Gm(String(t.data.summary))),e})()]}}),null),e})();default:return(()=>{var e=hp();return B(e,()=>_h(JSON.stringify(t.data),200)),e})()}}function _h(e,t){return e.length>t?e.slice(0,t)+` …`:e}function vh(e){let t=new Date(e).getTime()-Date.now(),n=Math.abs(t),r=n<9e4?`${Math.round(n/1e3)}s`:n<54e5?`${Math.round(n/6e4)}m`:`${(n/36e5).toFixed(1)}h`;return t>=0?`in ${r}`:`${r} ago`}function yh(e){return e>=1e9?`${+(e/1e9).toFixed(1)}b`:e>=1e6?`${+(e/1e6).toFixed(1)}m`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function bh(e){return e>=100?Math.round(e).toLocaleString():e>=10?e.toFixed(1):e>=1?e.toFixed(2):e>=.01?e.toFixed(3):e.toFixed(4)}function xh(e,t){return _h(e.replace(/\s+/g,` `).trim(),t)}function Sh(e){return(()=>{var t=gp(),n=t.firstChild;return Ce(t,`click`,e.onClick,!0),B(n,()=>e.icon),y(n=>{var r=`iconbtn`+(e.active?` active`:``)+(e.class?` `+e.class:``),i=e.title,a=e.style;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n.a=we(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function Ch(e){let[t,n]=v(!1),[r,i]=v(!1),a=t=>{t.preventDefault(),t.stopPropagation(),wt(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=_p();return n.$$click=a,B(n,(()=>{var n=I(()=>!!t());return()=>n()?`✓`:I(()=>!!r())()?`✗`:e.label??`⧉`})()),y(()=>R(n,`title`,e.title??`copy to clipboard`)),n})()}function wh(e){return(()=>{var t=vp(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),B(r,()=>e.title),Ce(i,`click`,e.onClose,!0),B(n,()=>e.children,null),t})()}function Th(e){let[t,n]=v(`~`),[r,i]=v([]),[a,o]=v(``),[s,c]=v(e.providers[0]??``),[l,u]=v(``),[d,f]=v(``);async function p(e){let r=await $(`/api/fs?path=${encodeURIComponent(e??t())}`);n(r.path),h(r.parent??``),i(r.entries??[])}ee(()=>p(t()));let[m,h]=v(``),g=async n=>{n.preventDefault(),f(``);try{let n=await $(`/api/agents`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspace:t(),id:a(),provider:s()||void 0,model:l()||void 0,start:!1})});e.onCreated(n.agent.id)}catch(e){f(String(e.message))}};return N(wh,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=bp(),f=i.firstChild,h=f.firstChild.nextSibling.firstChild,_=h.nextSibling,v=_.nextSibling,b=f.nextSibling,x=b.nextSibling,S=x.firstChild,ee=S.firstChild.nextSibling,C=S.nextSibling,w=C.firstChild.nextSibling,T=C.nextSibling.firstChild.nextSibling,E=x.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),B(b,N(P,{get each(){return r()},children:e=>(()=>{var n=xp();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),B(n,e,null),n})()})),ee.$$input=e=>o(e.currentTarget.value),w.addEventListener(`change`,e=>c(e.currentTarget.value)),B(w,N(P,{get each(){return e.providers},children:e=>(()=>{var t=zd();return B(t,e),t})()})),T.$$input=e=>u(e.currentTarget.value),B(i,N(F,{get when(){return d()},get children(){var e=yp();return B(e,d),e}}),E),y(()=>h.value=t()),y(()=>ee.value=a()),y(()=>w.value=s()),y(()=>T.value=l()),i}})}var Eh=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),Dh=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Oh=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function kh(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Ah(e);return n===`image`?`🖼`:n===`video`?`🎬`:n===`audio`?`🎵`:[`ts`,`tsx`,`mts`,`cts`].includes(t)?`🟦`:[`js`,`mjs`,`cjs`,`jsx`].includes(t)?`🟨`:t===`json`||t===`jsonc`?`🧾`:t===`md`||t===`mdx`||t===`markdown`?`📝`:t===`css`||t===`scss`||t===`less`?`🎨`:t===`html`||t===`htm`||t===`svg`?`🌐`:[`py`,`pyi`].includes(t)?`🐍`:t===`rs`?`🦀`:t===`go`?`🐹`:t===`java`||t===`kt`||t===`kts`?`☕`:t===`rb`?`💎`:t===`php`?`🐘`:t===`c`||t===`h`||t===`cpp`||t===`hpp`||t===`cc`?`🧩`:t===`sh`||t===`bash`||t===`zsh`||t===`fish`?`🐚`:t===`sql`?`🗄`:t===`yml`||t===`yaml`||t===`toml`||t===`ini`||t===`conf`?`⚙`:t===`lock`?`🔒`:e===`Dockerfile`||t===`dockerfile`?`🐳`:t===`zip`||t===`gz`||t===`tar`||t===`tgz`||t===`bz2`?`📦`:t===`pdf`?`📕`:t===`txt`||t===`log`?`📄`:`·`}function Ah(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return Eh.has(t)?`image`:Dh.has(t)?`video`:Oh.has(t)?`audio`:null}var jh=new Map,Mh=e=>{let t=jh.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},jh.set(e,t)),t};function Nh(e){let t=()=>e.palette;return(()=>{var e=Sp(),n=e.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling,f=d.nextSibling;return y(p=>{var m=t().bgDark,h=t().bgDarkest,g=t().bgDarkest,_=t().bgMid,v=t().fg,y=t().acc,b=t().dim,x=t().acc,S=t().dim,ee=t().ok,C=t().warn,w=t().err;return m!==p.e&&Te(e,`background`,p.e=m),h!==p.t&&Te(n,`background`,p.t=h),g!==p.a&&Te(r,`background`,p.a=g),_!==p.o&&Te(i,`background`,p.o=_),v!==p.i&&Te(a,`background`,p.i=v),y!==p.n&&Te(o,`background`,p.n=y),b!==p.s&&Te(s,`background`,p.s=b),x!==p.h&&Te(c,`background`,p.h=x),S!==p.r&&Te(l,`background`,p.r=S),ee!==p.d&&Te(u,`background`,p.d=ee),C!==p.l&&Te(d,`background`,p.l=C),w!==p.u&&Te(f,`background`,p.u=w),p},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0}),e})()}function Ph(e){let[t,n]=v(e.themes().some(t=>t.id===e.activeId)?e.activeId:e.themes()[0]?.id??``),r=()=>{let n=e.themes();return n.find(e=>e.id===t())??n[0]},[i,a]=v({}),o,s=t=>{let n=r()?.id;if(!n)return;let i=e.themes().map(e=>e.id===n?t(e):e);e.onChange(i)},c=(e,t)=>{let n=fn(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.activeId),r=eh.find(t=>t.key===e.activeId),i=t??r??eh[0],a=getComputedStyle(document.documentElement),o={...rn};for(let{key:e,cssVar:t}of tn){let n=fn(a.getPropertyValue(t));n&&(o[e]=n)}let s=un(e.themes().map(e=>e.id).concat(eh.map(e=>e.key))),c={id:s,label:`${i.label}${t?``:` copy`}`.slice(0,40),mode:i.mode,palette:o,...t?.backgroundImage?{backgroundImage:t.backgroundImage,backgroundDim:t.backgroundDim}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))Q(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{Q(`uploading ${t.name} (${Math.round(t.size/1024)}KB)…`);try{let n=await fetch(`/api/assets`,{method:`POST`,headers:{"content-type":t.type},body:t}).then(async e=>({ok:e.ok,body:await e.json().catch(()=>null)}));if(!n.ok||!n.body?.url){Q(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url}));let i=r()?.id;i&&e.onPick(i),Q(`background image set`)}catch(e){Q(`upload failed: ${e.message}`)}}}};return(()=>{var d=wp(),f=d.firstChild.nextSibling,p=f.firstChild;return p.$$click=l,B(f,N(F,{get when(){return e.themes().length>0},get children(){var r=Cp();return r.addEventListener(`change`,t=>{n(t.currentTarget.value),e.onPick(t.currentTarget.value)}),B(r,N(P,{get each(){return e.themes()},children:e=>(()=>{var t=zd();return B(t,()=>e.label),y(()=>t.value=e.id),t})()})),y(()=>r.value=t()),r}}),null),B(d,N(F,{get when(){return r()},get fallback(){return Tp()},children:t=>[(()=>{var e=Ep(),t=e.firstChild,n=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling;return n.$$input=e=>s(t=>({...t,label:e.currentTarget.value.slice(0,40)})),i.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),y(()=>n.value=r().label),y(()=>i.value=r().mode),e})(),(()=>{var e=Dp();return B(e,N(P,{each:tn,children:e=>(()=>{var t=Np(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),B(o,()=>e.label),s.addEventListener(`blur`,()=>a(t=>{let n={...t};return delete n[e.key],n})),s.$$input=t=>{let n=t.currentTarget.value;a(t=>({...t,[e.key]:n})),c(e.key,n)},R(s,`spellcheck`,!1),y(()=>R(t,`title`,e.cssVar)),y(()=>n.value=fn(r().palette[e.key])??`#000000`),y(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=Op(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...rn}})),a.$$click=()=>{let t=r()?.id;t&&(e.onChange(e.themes().filter(e=>e.id!==t)),n(e.themes().find(e=>e.id!==t)?.id??``))},t})(),kp(),(()=>{var e=jp(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),B(t,()=>r().backgroundImage?`🖼 replace image…`:`🖼 choose image…`),n.addEventListener(`change`,e=>{e.stopPropagation(),u(e.currentTarget.files?.[0]),e.currentTarget.value=``}),n.$$input=e=>e.stopPropagation();var i=o;return typeof i==`function`?Ee(i,n):o=n,B(e,N(F,{get when(){return r().backgroundImage},get children(){var e=Ap(),t=e.firstChild,n=t.nextSibling,i=n.firstChild.nextSibling;i.nextSibling;var a=n.nextSibling.firstChild,o=a.firstChild.nextSibling,c=o.nextSibling,l=c.firstChild,u=a.nextSibling;return B(n,()=>Math.round((r().backgroundImage?.length??0)*3/4/1024),i),o.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),B(c,()=>Math.round((r().backgroundDim??.55)*100),l),u.$$click=()=>s(e=>({...e,backgroundImage:void 0})),y(()=>R(t,`src`,r().backgroundImage)),y(()=>o.value=r().backgroundDim??.55),e}}),null),e})(),Mp()]}),null),d})()}function Fh(e){let t=Number(localStorage.getItem(`teapot.todoH`)??``),[n,r]=v(Number.isFinite(t)&&t>0?t:0),i=()=>n()>0?{height:`${n()}px`}:void 0,a=e=>{let t=new ResizeObserver(()=>{let t=e.offsetHeight;t<=0||r(e=>Math.abs(e-t)<1?e:(localStorage.setItem(`teapot.todoH`,String(t)),t))});t.observe(e),C(()=>t.disconnect())};return N(F,{get when(){return e.preview},get fallback(){return(()=>{var t=Fp();return t.$$input=t=>e.onDraft(t.currentTarget.value),Ee(a,t),y(e=>we(t,i(),e)),y(()=>t.value=e.draft),t})()},get children(){var t=Pp();return Ee(a,t),y(n=>{var r=i(),a=Gm(e.draft);return n.e=we(t,r,n.e),a!==n.t&&(t.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t}})}function Ih(e){let t=Mh(e.agentId),[n,r]=v(new Map),[i,a]=v(t.expanded),[o,s]=v(t.preview),c=e=>{t.preview=e,s(e)},l=e=>{t.expanded=e,a(e)},[u,d]=v(t.media),f=e=>{t.media=e,d(e)},[p,m]=v(t.viewMode),h=e=>{t.viewMode=e,m(e)},[g,_]=v(``),[x,S]=v(localStorage.getItem(`teapot.ignoreMode`)??`dim`),ee=()=>{let e=[`dim`,`hide`,`show`],t=e[(e.indexOf(x())+1)%3];S(t),localStorage.setItem(`teapot.ignoreMode`,t)},w=e=>x()!==`hide`||!e.ignored,[T,E]=v(localStorage.getItem(`teapot.showHidden`)===`1`),te=()=>{let e=!T(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await re(t,e)}))).then(t=>{E(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&O(e,n)})},D=(e,t)=>t.map(t=>({name:String(t.name),path:e?`${e}/${t.name}`:String(t.name),dir:!!t.dir,...typeof t.size==`number`?{size:t.size}:{},...t.ignored?{ignored:!0}:{}}));async function ne(e){return re(e,T())}async function re(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await $(`/api/agents/${e.agentId}/tree?${r.toString()}`);return D(t,i.entries??[])}catch(e){return _(e.message),null}}let O=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=i.map(e=>{let t=n.find(t=>t.path===e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?e:t??e});for(let e of n)i.some(t=>t.path===e.path)||a.push(e);let o=a.filter(e=>n.some(t=>t.path===e.path)||t.preview?.path===e.path),s=new Map(r);return s.set(e,o),s}),k=``;b(()=>{let t=e.agentId;t!==k&&(k=t,l(new Set),c(null),f(null),r(new Map),ne(``).then(e=>{e&&k===t&&r(new Map([[``,e]]))}))});let ie=async e=>{let t=new Set(i());if(t.has(e.path))t.delete(e.path),l(t);else if(t.add(e.path),l(t),!n().has(e.path)){let t=await ne(e.path);t&&O(e.path,t)}},[ae,oe]=v(``),[se,ce]=v(!1),[A,le]=v(``),[j,ue]=v(!1),de=e=>/\.(md|markdown|mdx)$/i.test(e),M=0,fe=async e=>{let t=++M;oe(``),ce(!0);try{let{highlightChunks:n}=await vu(async()=>{let{highlightChunks:e}=await import(`./shiki-CQLl0pgT.js`);return{highlightChunks:e}},[]);for await(let r of n(e.path,e.content)){if(M!==t)return;oe(e=>e+r)}}catch{M===t&&oe(``)}finally{M===t&&ce(!1)}};C(()=>{M++});let pe=async(t,n)=>{let r=Ah(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await $(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),le(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&fe({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){Q(`open failed: ${e.message}`)}},me=async()=>{let t=o();if(t&&!j()){ue(!0);try{await $(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:A(),baseContent:t.content})}),c({...t,content:A()}),Q(`saved ${t.path}`)}catch(e){let n=e.payload,r=n&&typeof n==`object`&&n.error===`file changed on disk`?n:null;r?.current===void 0?Q(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
28
28
  OK = load the disk version into the editor (your edits are discarded)
29
- Cancel = keep editing your copy`)?(le(r.current),c({...t,content:r.current}),Q(`loaded the current file from disk`)):Q(`kept your edits — use Save As via bash to force-write`)}finally{ue(!1)}}},he=e=>!e.binary&&!e.truncated,ge=(e,t)=>[(()=>{var n=Lp(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void pe(e,`code`),B(r,(()=>{var t=I(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:kh(e.name)})()),B(a,()=>e.name),B(n,N(F,{get when(){return I(()=>!e.dir)()&&e.size!==void 0},get children(){var t=Ip();return B(t,()=>yh(e.size)),t}}),null),y(r=>{var i=`filerow`+(e.dir?` isdir`:``)+(e.ignored&&x()===`dim`?` gitignored`:``),a=`padding-left:${t*13+8}px`,o=e.dir?`browse ${e.path}`:`preview ${e.path}`;return i!==r.e&&z(n,r.e=i),r.t=we(n,a,r.t),o!==r.a&&R(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),N(F,{get when(){return I(()=>!!e.dir)()&&i().has(e.path)},get children(){return N(P,{get each(){return(n().get(e.path)??[]).filter(w)},children:e=>ge(e,t+1)})}})],_e=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[ve,ye]=v(!1),be=async()=>{if(!ve()){ye(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await re(e,T())})));for(let{p:e,rows:n}of t)n&&O(e,n)}finally{ye(!1)}}};return[(()=>{var e=Rp(),t=e.firstChild.nextSibling;return t.firstChild,B(t,_e,null),B(e,N(Sh,{class:`filetoggle`,get icon(){return ve()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void be()}),null),B(e,N(Sh,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return I(()=>x()===`hide`)()?`🙈`:x()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${x()} — click to cycle (dim → hidden → shown)`},onClick:ee}),null),B(e,N(Sh,{class:`filetoggle`,get icon(){return T()?`◉.`:`○.`},get title(){return T()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:te}),null),e})(),(()=>{var e=zp();return B(e,N(F,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Bp();return B(e,()=>g()||`empty workspace`),e})()},get children(){return N(P,{get each(){return(n().get(``)??[]).filter(w)},children:e=>ge(e,0)})}})),e})(),N(F,{get when(){return o()},children:t=>N(wh,{get title(){return`🗂 ${t().path}`},onClose:()=>{M++,c(null),f(null)},get children(){return N(F,{get when(){return u()},get fallback(){return[(()=>{var e=Gp(),n=e.firstChild;return B(e,N(F,{get when(){return I(()=>!!de(t().path))()&&!t().binary},get children(){var e=Up();return e.$$click=()=>h(`md`),y(()=>z(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||fe({path:t().path,content:t().content,truncated:t().truncated})},B(e,N(F,{get when(){return he(t())},get children(){var e=Wp();return e.$$click=()=>h(`edit`),y(()=>z(e,p()===`edit`?`on`:``)),e}}),null),y(()=>z(n,p()===`code`?`on`:``)),e})(),N(F,{get when(){return!t().binary},get fallback(){return qp()},get children(){return N(F,{get when(){return p()===`edit`},get fallback(){return N(F,{get when(){return I(()=>p()===`md`)()&&de(t().path)},get fallback(){return N(Lh,{get path(){return t().path},get content(){return t().content},get html(){return ae()},get pending(){return se()},get truncated(){return!!t().truncated}})},get children(){var e=Jp();return y(()=>e.innerHTML=Pe(t().content)),e}})},get children(){var e=Kp(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>le(e.currentTarget.value),R(n,`spellcheck`,!1),B(r,()=>yh(A().length),i),a.$$click=()=>void me(),B(a,()=>j()?`saving…`:`💾 save`),y(()=>a.disabled=j()||A()===t().content),y(()=>n.value=A()),e}})}})]},get children(){var t=Hp(),n=t.firstChild,r=n.firstChild;return B(t,N(F,{get when(){return u().kind===`image`},get fallback(){return N(F,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Xp();return y(()=>R(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Yp();return y(()=>R(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Vp();return y(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&R(t,`src`,n.e=r),i!==n.t&&R(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),B(n,()=>u().kind,r),t}})}})})]}function Lh(e){return[N(F,{get when(){return e.html},get fallback(){return I(()=>!!e.pending)()?(()=>{var t=$p(),n=t.firstChild.nextSibling;return n.nextSibling,B(t,()=>e.path.split(`/`).pop(),n),t})():(()=>{var t=em();return B(t,()=>e.content),t})()},get children(){var t=Zp();return y(()=>t.innerHTML=e.html),t}}),N(F,{get when(){return e.truncated},get children(){return Qp()}})]}var Rh=[{key:`openrouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1`,model:``,hint:`400+ models behind one key — teapot sends app-attribution headers automatically`},{key:`orcarouter`,label:`OrcaRouter`,url:`https://api.orcarouter.ai/v1`,model:``,hint:`zero-markup routing gateway — 'orcarouter/auto' grades each prompt and picks the model`},{key:`openai`,label:`OpenAI`,url:`https://api.openai.com/v1`,model:``,hint:`your account's models — pick from the list once the endpoint answers`},{key:`opencode-go`,label:`OpenCode Go`,url:`https://opencode.ai/zen/go/v1`,model:``,hint:`OpenCode's open-model subscription — teapot sends the required x-opencode-session header; choose a chat/completions model`},{key:`llamacpp`,label:`llama.cpp server`,url:`http://localhost:8080/v1`,model:``,hint:`free & local — start it with: llama-server -m ./model.gguf (any model name works)`}],zh={key:`custom`,label:`Custom`,url:``,model:``,hint:`any OpenAI-compatible /v1 endpoint — vLLM, LM Studio, llama.cpp, a company gateway… fill the fields below`};function Bh(e){let[t,n]=v(Rh[0]),[r,i]=v(Rh[0].url),[a,o]=v(``),[s,c]=v(Rh[0].model),[l,u]=v([]),[d,f]=v(`~/teapot-workspace`),[p,m]=v(``),[h,g]=v(!1),[_,x]=v(``),S=e=>{n(e),e.key!==`custom`&&e.url&&(i(e.url),e.model&&c(e.model))};b(()=>{let e=r().trim(),t=a();if(!/^https?:\/\//.test(e)){u([]);return}let n=setTimeout(async()=>{try{let n=await $(`/api/setup/models?baseUrl=${encodeURIComponent(e)}${t?`&apiKey=${encodeURIComponent(t)}`:``}`);u(n.models??[])}catch{u([])}},600);C(()=>clearTimeout(n))});let ee=e=>{let t=l().find(t=>t.id===e.trim());if(!t)return``;let n=[];t.contextLength&&n.push(`ctx ${yh(t.contextLength)} tok`);let r=e=>e===void 0?``:`$${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=r(t.pricing.prompt),i=r(t.pricing.completion);e&&i?n.push(`${e} in · ${i} out`):(e||i)&&n.push(r(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},w=()=>ee(s()),T=()=>{let e=s().trim().toLowerCase();return e?l().filter(t=>t.id.toLowerCase().includes(e)):l()},E=async t=>{if(t.preventDefault(),x(``),!s().trim())x(l().length?`pick a model — choose one from the list, or type its id`:`pick a model — type its id (the endpoint has not listed any yet)`);else{g(!0);try{await $(`/api/setup`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({baseUrl:r(),apiKey:a()||void 0,model:s(),workspace:d(),...p()?{password:p()}:{}})}),e.onDone()}catch(e){x(e.message),g(!1)}}};return(()=>{var e=am(),n=e.firstChild.firstChild.nextSibling.nextSibling,u=n.firstChild,g=u.nextSibling,v=g.firstChild.nextSibling,b=v.nextSibling,x=g.nextSibling,C=x.firstChild.nextSibling,te=x.nextSibling,D=te.firstChild.nextSibling,ne=D.nextSibling,re=te.nextSibling,O=re.firstChild.nextSibling,k=O.firstChild.nextSibling,ie=O.nextSibling.firstChild.nextSibling,ae=re.nextSibling;return n.addEventListener(`submit`,E),B(u,()=>[...Rh,zh].map(e=>(()=>{var n=om();return n.$$click=()=>S(e),B(n,()=>e.label),y(r=>{var i=`presetbtn`+(t().key===e.key?` active`:``),a=e.hint||e.url;return i!==r.e&&z(n,r.e=i),a!==r.t&&R(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})())),B(n,N(F,{get when(){return t().hint},get children(){var e=tm();return B(e,()=>t().hint),e}}),g),v.$$input=e=>i(e.currentTarget.value),B(b,()=>Rh.map(e=>(()=>{var t=zd();return y(()=>t.value=e.url),t})())),C.$$input=e=>o(e.currentTarget.value),D.$$input=e=>c(e.currentTarget.value),B(ne,()=>l().map(e=>(()=>{var t=zd();return y(()=>t.value=e.id),t})())),B(n,N(F,{get when(){return T().length>0},get fallback(){return(()=>{var e=sm();return B(e,()=>l().length?`no model matches that — clear the field to see them all`:`models appear here automatically once the endpoint answers GET /models`),e})()},get children(){return[(()=>{var e=nm();return B(e,()=>T().slice(0,40).map(e=>(()=>{var t=cm(),n=t.firstChild;return t.$$click=()=>c(e.id),B(n,()=>e.id),B(t,N(F,{get when(){return ee(e.id)},get children(){var t=jf();return B(t,()=>ee(e.id)),t}}),null),y(n=>{var r=`wizmodel`+(s()===e.id?` active`:``),i=ee(e.id)||e.id;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})())),e})(),(()=>{var e=im(),t=e.firstChild;return B(e,()=>T().length,t),B(e,()=>T().length>1?`s`:``,null),B(e,N(F,{get when(){return T().length>40},children:` (showing the first 40 — keep typing to narrow)`}),null),B(e,N(F,{get when(){return w()},get children(){return[` · selected: `,(()=>{var e=rm();return B(e,w),e})()]}}),null),e})()]}}),re),k.$$input=e=>f(e.currentTarget.value),ie.$$input=e=>m(e.currentTarget.value),B(n,N(F,{get when(){return _()},get children(){var e=yp();return B(e,_),e}}),ae),B(ae,()=>h()?`saving…`:`finish setup`),y(e=>{var n=t().key===`llamacpp`?`(any name — serves whichever gguf is loaded)`:`(pick from the list below, or type an id)`,r=h();return n!==e.e&&R(D,`placeholder`,e.e=n),r!==e.t&&(ae.disabled=e.t=r),e},{e:void 0,t:void 0}),y(()=>v.value=r()),y(()=>C.value=a()),y(()=>D.value=s()),y(()=>k.value=d()),y(()=>ie.value=p()),e})()}function Vh(e){let t=(e,t)=>{let n=Array.isArray(t?.apiKeys)&&t.apiKeys.length?t.apiKeys.filter(e=>typeof e==`string`&&e.trim()):t?.apiKey?[String(t.apiKey)]:[``];return{name:e,baseUrl:t?.baseUrl??``,apiKeys:n.length?n:[``],model:t?.model??``}},[n,r]=v(Object.entries(e.cfg.providers??{}).map(([e,n])=>t(e,n))),[i,a]=v(e.cfg.defaultProvider??``),o=()=>e.cfg.defaultProvider??``,s=()=>{let e=[...new Set(n().map(e=>e.name.trim()).filter(Boolean))],t=i();return t&&!e.includes(t)&&e.push(t),e},c=()=>{let e=i();return e?n().some(t=>t.name.trim()===e)?``:e:``},[l,u]=v(Math.round((e.cfg.progressIntervalMs??6e5)/6e4)),[d,f]=v(e.cfg.progressMinChars??4e3),[p,m]=v(e.cfg.contextTokenBudget==null?null:Math.round(e.cfg.contextTokenBudget/1e3)),[h,g]=v(e.cfg.contextWindowTokens?Math.round(e.cfg.contextWindowTokens/1e3):0),[_,x]=v(e.cfg.maxSpawnDepth??3),[S,ee]=v(!!e.cfg.shortContext),[C,w]=v((e.cfg.tasks??[]).map(e=>({...e}))),[T,E]=v((e.cfg.mcpServers??[]).map(e=>({...e}))),[te,D]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ne,re]=v({}),[O,k]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(!r.length)return[t,`none`];let i=r.length===1?r[0]:``;return i===`Authorization`&&/^Bearer /i.test(n[i]??``)?[t,`bearer`]:[t,r.length===1?`header`:`json`]}))),[ie,ae]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(r.length!==1)return[t,``];let i=r[0];return[t,i===`Authorization`?(n[i]??``).replace(/^Bearer /i,``):n[i]??``]}))),[oe,se]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=Object.keys(e.headers??{}),r=n.length===1?n[0]:``;return[t,r&&r!==`Authorization`?r:``]}))),[ce,A]=v({}),[le,j]=v({}),[ue,de]=v({}),M=async()=>{let e=await $(`/api/mcp`).catch(()=>null);j(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},fe=async e=>{let t=String(e??``).trim();if(!t)return;let n=await $(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&de(e=>({...e,[t]:n}))},pe=async(t,n)=>{if(!n.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await $(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name})}).catch(()=>null);if(r?.alreadyAuthorized){A(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await fe(n.name),await M();return}if(!r?.ok||!r.url){A(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await fe(n.name);return}window.open(r.url,`_blank`,`noopener`),A(e=>({...e,[t]:{kind:`testing`,text:`waiting for you to finish in the browser…`}}));let i=Date.now()+3e5;for(;Date.now()<i;){await new Promise(e=>setTimeout(e,1e3));let r=await $(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(de(e=>({...e,[t]:r})),r.authorized){A(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await M(),e.onSaved();return}if(r.flow?.phase===`error`){A(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}A(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};b(()=>{ge()===`mcp`&&(M(),T().forEach((e,t)=>{e.name&&fe(e.name)}))});let[me,he]=v(``),[ge,_e]=v(`providers`),[ye,be]=v([]),xe=async()=>{let e=await $(`/api/archived`).catch(()=>null);be(e?.agents??[])},L=()=>ye().filter(e=>!e.parent);b(()=>{ge()===`archive`&&xe()});let Se=[{key:`providers`,label:`🧦 providers`,hint:`endpoints, API keys, default models`},{key:`appearance`,label:`🎨 appearance`,hint:`theme, custom palettes, background image`},{key:`runtime`,label:`⚙️ runtime`,hint:`context budget, retries, spawn depth`},{key:`tasks`,label:`⏰ scheduled tasks`,hint:`cron prompts run against an agent`},{key:`mcp`,label:`🔌 MCP servers`,hint:`external tool servers exposed to every agent`},{key:`archive`,label:`🗄 archive`,hint:`agents you put away — restore or delete for good`},{key:`agents`,label:`👥 agents`,hint:`what exists (read-only)`},{key:`update`,label:`⬆️ live update`,hint:`restart onto a newer build`},{key:`help`,label:`❔ help`,hint:`keyboard shortcuts and what each toggle does`}],Ce=()=>(e.cfg.agents??[]).map(e=>e.id),we=()=>e.theme.themes(),Te=()=>e.theme.activeId(),Ee=t=>e.theme.setActive(t),De=()=>e.theme.auto(),Oe=t=>e.theme.setAuto(t),ke=()=>e.theme.dark(),Ae=t=>e.theme.setDark(t),je=()=>e.theme.light(),Me=t=>e.theme.setLight(t),Ne=t=>e.theme.setThemes(t),Pe=e=>an[e]??rn,Fe=()=>{let e={};for(let t of n()){if(!t.name.trim())return he(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return he(`provider ${t.name}: baseUrl must start with http(s)://`),null;let n=t.apiKeys.map(e=>e.trim()).filter(Boolean);e[t.name.trim()]={baseUrl:t.baseUrl,...n.length?{apiKeys:n,apiKey:n[0]}:{},...t.model?{model:t.model}:{}}}return e},Ie=async t=>{t.preventDefault(),he(``);let n=Fe();if(!n)return;let r=C().filter(e=>e.id?.trim()||e.prompt?.trim()).map((e,t)=>({id:e.id?.trim()||`task-${t+1}`,agent:e.agent,schedule:e.schedule,prompt:e.prompt,...e.forked?{forked:!0}:{}}));for(let e of r){if(!e.agent){he(`task "${e.id}": agent is required`);return}if(!e.schedule?.trim()){he(`task "${e.id}": schedule is required`);return}}let a=[],o=new Set;for(let e of T()){let t=String(e.name??``).trim(),n=String(e.url??``).trim(),r=e.transport??`http`,i=String(e.command??``).trim();if(t||n||i){if(!t){he(`MCP: a server needs a name`);return}if(o.has(t)){he(`MCP: two servers are named "${t}"`);return}if(o.add(t),r===`stdio`?!i:!n){he(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);return}a.push({name:t,transport:r,enabled:e.enabled!==!1,...n?{url:n}:{},...r===`stdio`?{command:i,...e.args?.length?{args:e.args}:{}}:{},...e.headers&&Object.keys(e.headers).length?{headers:e.headers}:{}})}}try{await $(`/api/config`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({providers:n,defaultProvider:i()||void 0,progressIntervalMs:Math.max(1,l())*6e4,progressMinChars:Math.max(100,d()),...p()==null?{}:{contextTokenBudget:Math.max(1,p())*1e3},...h()>0?{contextWindowTokens:h()*1e3}:{},maxSpawnDepth:Math.max(0,_()),shortContext:S(),tasks:r,mcpServers:a})}),await M(),await Promise.all(a.map((e,t)=>e.name?fe(e.name):Promise.resolve())),setTimeout(()=>{M(),a.forEach((e,t)=>{e.name&&fe(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=T().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&ue()[n]?.required&&!ue()[n]?.authorized}).filter(t=>!e.announcedOAuth.has(String(t.name??``)));if(o.length>0){for(let t of o)e.announcedOAuth.add(String(t.name??``));Q(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}else e.onClose()}catch(e){he(e.message)}},Le=(e,t,n,r)=>(()=>{var i=lm(),a=i.firstChild;return R(i,`title`,r),B(i,e,a),a.$$input=e=>n(Number(e.currentTarget.value)),a.value=t,i})();return N(wh,{title:`settings`,get onClose(){return e.onClose},get children(){var t=fm(),v=t.firstChild,b=v.firstChild,j=b.nextSibling.firstChild,de=j.firstChild.nextSibling,M=de.nextSibling;M.firstChild;var ye=M.nextSibling.firstChild.firstChild.nextSibling;ye.firstChild;var be=j.nextSibling,Fe=be.firstChild.nextSibling,Re=Fe.firstChild.firstChild.nextSibling,ze=Fe.nextSibling,Be=be.nextSibling,Ve=Be.firstChild.nextSibling,He=Ve.firstChild,Ue=He.firstChild.nextSibling,We=Ve.nextSibling.firstChild,Ge=Be.nextSibling,Ke=Ge.firstChild.nextSibling.nextSibling,qe=Ge.nextSibling,Je=qe.firstChild.nextSibling,Ye=qe.nextSibling;Ye.firstChild;var Xe=Ye.nextSibling;Xe.firstChild;var Ze=Xe.nextSibling,Qe=Ze.firstChild.nextSibling.firstChild;Qe.firstChild;var $e=Qe.nextSibling,et=Ze.nextSibling,tt=v.nextSibling,nt=tt.firstChild;return t.addEventListener(`submit`,Ie),B(b,N(P,{each:Se,children:e=>(()=>{var t=pm(),n=t.firstChild;return t.$$click=()=>_e(e.key),B(n,()=>e.label),y(n=>{var r=`cfgmenu-item`+(ge()===e.key?` on`:``),i=e.hint,a=ge()===e.key?`page`:void 0;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),B(j,N(ve,{get each(){return n()},children:(e,t)=>(()=>{var i=mm(),a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild;return a.$$input=e=>r(n().map((n,r)=>r===t?{...n,name:e.currentTarget.value}:n)),o.$$input=e=>r(n().map((n,r)=>r===t?{...n,baseUrl:e.currentTarget.value}:n)),s.$$input=e=>r(n().map((n,r)=>r===t?{...n,model:e.currentTarget.value}:n)),c.$$click=()=>r(n().filter((e,n)=>n!==t)),B(l,N(P,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=gm(),s=o.firstChild;return s.$$input=e=>r(n().map((n,r)=>r===t?{...n,apiKeys:n.apiKeys.map((t,n)=>n===a()?e.currentTarget.value:t)}:n)),s.value=i,B(o,N(F,{get when(){return e().apiKeys.length>1},get children(){var e=hm();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),y(()=>R(s,`placeholder`,a()===0?`api key`:`api key (backup)`)),o})()}),u),u.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:[...e.apiKeys,``]}:e)),y(()=>a.value=e().name),y(()=>o.value=e().baseUrl),y(()=>s.value=e().model),i})()}),de),de.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),B(M,N(P,{each:Rh,children:e=>(()=>{var t=_m();return t.firstChild,t.$$click=()=>{let t=n().filter(t=>t.name!==e.key);r([...t,{name:e.key,baseUrl:e.url,apiKeys:[``],model:e.model}]),i()||a(e.key)},B(t,()=>e.label,null),y(()=>R(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ye.addEventListener(`change`,e=>a(e.currentTarget.value)),B(ye,N(P,{get each(){return s()},children:e=>(()=>{var t=zd();return t.value=e,B(t,e),t})()}),null),B(j,N(F,{get when(){return c()},get children(){var e=um(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return B(t,c),B(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),B(r,c),e}}),null),Re.addEventListener(`change`,e=>{Oe(e.currentTarget.checked),localStorage.setItem(`teapot.theme.auto`,e.currentTarget.checked?`1`:`0`)}),B(be,N(F,{get when(){return De()},get children(){var e=dm(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ae(e.currentTarget.value),localStorage.setItem(`teapot.theme.dark`,e.currentTarget.value)}),B(n,N(P,{get each(){return we().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(eh.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=zd();return B(t,()=>e.label),y(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{Me(e.currentTarget.value),localStorage.setItem(`teapot.theme.light`,e.currentTarget.value)}),B(r,N(P,{get each(){return we().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(eh.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=zd();return B(t,()=>e.label),y(()=>t.value=e.key),t})()})),y(()=>n.value=ke()),y(()=>r.value=je()),e}}),ze),B(be,N(P,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>N(F,{get when(){return[...we(),...eh].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=vm();return B(t,()=>e.title),t})(),(()=>{var t=ym();return B(t,N(P,{get each(){return we().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=bm(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>{Ee(e.id),localStorage.setItem(`teapot.theme`,e.id)},B(n,N(Nh,{get palette(){return e.palette}})),B(r,()=>e.label,i),y(n=>{var r=`themecard`+(Te()===e.id?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Te()===e.id;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),B(t,N(P,{get each(){return eh.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=xm(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>{Ee(e.key),localStorage.setItem(`teapot.theme`,e.key)},B(n,N(Nh,{get palette(){return Pe(e.key)}})),B(r,()=>e.label),y(n=>{var r=`themecard`+(Te()===e.key?` on`:``),i=`${e.label} (${e.mode})`,a=Te()===e.key;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),B(be,N(Ph,{themes:we,get activeId(){return Te()},onChange:e=>{let t=ln(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0}:e),r=ln(t);if(r.ok)n=t,Q(`storage was full — saved without the background image(s)`);else{Q(r.error??`could not save theme`);return}}Ne(n);let r=e=>n.some(t=>t.id===e)||eh.some(t=>t.key===e);r(Te())||(Ee(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(ke())||(Ae(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(je())||(Me(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{Ee(e),localStorage.setItem(`teapot.theme`,e)}}),null),B(Ve,()=>Le(`progress interval (min)`,l(),e=>u(e),`how often the harness asks for a progress report`),He),B(Ve,()=>Le(`progress min chars`,d(),e=>f(e),`progress prompts wait for this much real output`),He),Ue.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),B(Ve,()=>Le(`context window (k tok)`,h(),e=>g(e),`model's real window — 0/blank hides the % gauge`),null),B(Ve,()=>Le(`max spawn depth`,_(),e=>x(e),`sub-agent nesting limit (0 = no spawning)`),null),We.addEventListener(`change`,e=>ee(e.currentTarget.checked)),B(Ge,N(F,{get when(){return T().length>0},get fallback(){return Sm()},get children(){return N(ve,{get each(){return T()},children:(e,t)=>{let n=()=>le()[e().name],r=e=>E(T().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=Nm(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling,l=c.firstChild,u=c.nextSibling,d=a.nextSibling,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>r({url:e.currentTarget.value}),l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>E(T().filter((e,n)=>n!==t)),f.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),B(d,N(F,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=Cm();return t.$$input=e=>r({command:e.currentTarget.value}),y(()=>t.value=e().command??``),t})(),(()=>{var t=wm();return t.$$input=e=>r({args:e.currentTarget.value.split(` `).filter(Boolean)}),y(()=>t.value=(e().args??[]).join(` `)),t})()]}}),null),m.addEventListener(`change`,e=>{let n=e.currentTarget.value;if(k(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ie()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=oe()[t]??``,n=ie()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),B(p,N(F,{get when(){return O()[t]===`bearer`},get children(){var e=Tm();return e.$$input=e=>{let n=e.currentTarget.value;ae(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},y(()=>e.value=ie()[t]??``),e}}),null),B(p,N(F,{get when(){return O()[t]===`header`},get children(){return[(()=>{var e=Em();return e.$$input=e=>{let n=e.currentTarget.value;se(e=>({...e,[t]:n}));let i=ie()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},y(()=>e.value=oe()[t]??``),e})(),(()=>{var e=Dm();return e.$$input=e=>{let n=e.currentTarget.value;ae(e=>({...e,[t]:n}));let i=oe()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},y(()=>e.value=ie()[t]??``),e})()]}}),null),B(i,N(F,{get when(){return O()[t]===`json`},get children(){var e=Om(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(D(e=>({...e,[t]:n})),!n.trim())r({headers:void 0});else try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`not an object`);r({headers:e}),re(e=>({...e,[t]:``}))}catch{re(e=>({...e,[t]:`must be a JSON object — not applied`}))}},y(()=>n.value=te()[t]??``),e}}),h),g.$$click=async()=>{let e=T()[t];if(!e.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await $(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);A(e=>({...e,[t]:n?.ok?{kind:`ok`,text:`${n.tools?.length??0} tool${n.tools?.length===1?``:`s`}`,tools:n.tools??[]}:{kind:`err`,text:n?.error??`no response`,...n?.needsOAuth?{needsOAuth:!0}:{}}})),n?.ok||await fe(e.name)},B(h,N(F,{get when(){return I(()=>!!ue()[String(e().name??``).trim()]?.required)()&&!ue()[String(e().name??``).trim()]?.authorized},get children(){var n=km();return n.$$click=()=>void pe(t,e()),n}}),null),B(h,N(F,{get when(){return ue()[String(e().name??``).trim()]?.authorized},get children(){return[Am(),(()=>{var n=jm();return n.$$click=async()=>{await $(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await fe(e().name),A(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}}))},n})()]}}),null),B(h,N(F,{get when(){return n()},get children(){var e=bd();return B(e,(()=>{var e=I(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:I(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),y(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&z(e,t.e=r),i!==t.t&&R(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),B(i,N(F,{get when(){return ne()[t]},get children(){var e=Mm();return B(e,()=>ne()[t]),e}}),null),B(i,N(F,{get when(){return ce()[t]},children:e=>(()=>{var t=Im(),n=t.firstChild,r=n.firstChild;return B(r,()=>e().text),B(n,N(F,{get when(){return e().needsOAuth},get children(){return Pm()}}),null),B(t,N(F,{get when(){return(e().tools?.length??0)>0},get children(){var t=Fm();return B(t,N(P,{get each(){return e().tools??[]},children:e=>(()=>{var t=Rm(),n=t.firstChild;return B(n,()=>e.name),B(t,N(F,{get when(){return e.description},get children(){var t=Lm();return B(t,()=>e.description),t}}),null),y(()=>R(t,`title`,e.description??``)),t})()})),t}}),null),y(()=>z(t,`mcpresult `+(e().kind===`err`?`err`:`ok`))),t})()}),null),y(()=>o.value=e().name),y(()=>s.value=e().url??``),y(()=>l.checked=e().enabled!==!1),y(()=>f.value=e().transport??`http`),y(()=>m.value=O()[t]??`none`),i})()}})}}),Ke),Ke.$$click=()=>E([...T(),{name:``,url:``,transport:`http`,enabled:!0}]),B(qe,N(F,{get when(){return C().length>0},get children(){return N(ve,{get each(){return C()},children:(e,t)=>(()=>{var n=zm(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.firstChild,l=s.nextSibling,u=r.nextSibling;return i.$$input=e=>w(C().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>w(C().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>w(C().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>w(C().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>w(C().filter((e,n)=>n!==t)),u.$$input=e=>w(C().map((n,r)=>r===t?{...n,prompt:e.currentTarget.value}:n)),y(()=>i.value=e().id),y(()=>a.value=e().agent),y(()=>o.value=e().schedule),y(()=>c.checked=!!e().forked),y(()=>u.value=e().prompt),n})()})}}),Je),Je.$$click=()=>w([...C(),{id:``,agent:Ce()[0]??``,schedule:`every 30m`,prompt:``}]),B(Ye,N(F,{get when(){return L().length>0},get fallback(){return Bm()},get children(){return N(P,{get each(){return L()},children:t=>(()=>{var n=Vm(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return B(i,()=>t.id),B(a,()=>t.sessions,o),B(a,()=>t.sessions===1?``:`s`,null),B(a,(()=>{var e=I(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),B(a,(()=>{var e=I(()=>!!t.archivedAt);return()=>e()?` · archived ${vh(new Date(t.archivedAt).toISOString())}`:``})(),null),B(s,()=>t.workspace),c.$$click=async()=>{let n=await $(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await xe(),e.onSaved();let r=(n?.ids?.length??1)-1;Q((n?.live===!1?`restored ${t.id} — it could not be started (check its provider)`:`restored ${t.id}`)+(r>0?` + ${r} sub-agent${r===1?``:`s`}`:``))},l.$$click=async()=>{confirm(`PERMANENTLY DELETE ${t.id}?\n\n${t.sessions} session${t.sessions===1?``:`s`} of history will be erased from disk along with the config entry. This cannot be undone — archiving was the reversible option.`)&&(await $(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await xe(),e.onSaved(),Q(`deleted ${t.id} for good`))},y(()=>R(s,`title`,t.workspace)),n})()})}}),null),B(Xe,N(P,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=Um(),n=t.firstChild,r=n.nextSibling;return B(n,()=>e.id),B(r,()=>e.workspace),B(t,N(F,{get when(){return e.parent},get children(){var t=Hm();return t.firstChild,B(t,()=>e.parent,null),t}}),null),t})()}),null),B(Qe,()=>e.cfg.version??`unknown`,null),$e.$$click=async e=>{try{he(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await $(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=!1;for(let e=0;e<90&&!r;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await $(`/api/version`);e.version&&e.version!==`0.35.11`&&(r=!0,window.location.reload())}catch{}}if(!r)throw Error(`restart timeout — new server did not come up`)}catch(e){he(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},B(tt,N(F,{get when(){return me()},get children(){var e=yp();return B(e,me),e}}),nt),y(e=>{var t=ge()!==`providers`,n=ge()!==`appearance`,r=ge()!==`runtime`,i=ge()!==`mcp`,a=ge()!==`tasks`,o=ge()!==`archive`,s=ge()!==`agents`,c=ge()!==`update`,l=ge()!==`help`;return t!==e.e&&j.classList.toggle(`hide`,e.e=t),n!==e.t&&be.classList.toggle(`hide`,e.t=n),r!==e.a&&Be.classList.toggle(`hide`,e.a=r),i!==e.o&&Ge.classList.toggle(`hide`,e.o=i),a!==e.i&&qe.classList.toggle(`hide`,e.i=a),o!==e.n&&Ye.classList.toggle(`hide`,e.n=o),s!==e.s&&Xe.classList.toggle(`hide`,e.s=s),c!==e.h&&Ze.classList.toggle(`hide`,e.h=c),l!==e.r&&et.classList.toggle(`hide`,e.r=l),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),y(()=>ye.value=i()),y(()=>Re.checked=De()),y(()=>Ue.value=p()??``),y(()=>We.checked=S()),t}})}Se([`click`,`pointerdown`,`dblclick`,`input`,`keydown`]),xe(()=>N(lh,{}),document.getElementById(`root`));export{vu as t};
30
- //# sourceMappingURL=index-Crow33lC.js.map
29
+ Cancel = keep editing your copy`)?(le(r.current),c({...t,content:r.current}),Q(`loaded the current file from disk`)):Q(`kept your edits — use Save As via bash to force-write`)}finally{ue(!1)}}},he=e=>!e.binary&&!e.truncated,ge=(e,t)=>[(()=>{var n=Lp(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void pe(e,`code`),B(r,(()=>{var t=I(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:kh(e.name)})()),B(a,()=>e.name),B(n,N(F,{get when(){return I(()=>!e.dir)()&&e.size!==void 0},get children(){var t=Ip();return B(t,()=>yh(e.size)),t}}),null),y(r=>{var i=`filerow`+(e.dir?` isdir`:``)+(e.ignored&&x()===`dim`?` gitignored`:``),a=`padding-left:${t*13+8}px`,o=e.dir?`browse ${e.path}`:`preview ${e.path}`;return i!==r.e&&z(n,r.e=i),r.t=we(n,a,r.t),o!==r.a&&R(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),N(F,{get when(){return I(()=>!!e.dir)()&&i().has(e.path)},get children(){return N(P,{get each(){return(n().get(e.path)??[]).filter(w)},children:e=>ge(e,t+1)})}})],_e=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[ve,ye]=v(!1),be=async()=>{if(!ve()){ye(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await re(e,T())})));for(let{p:e,rows:n}of t)n&&O(e,n)}finally{ye(!1)}}};return[(()=>{var e=Rp(),t=e.firstChild.nextSibling;return t.firstChild,B(t,_e,null),B(e,N(Sh,{class:`filetoggle`,get icon(){return ve()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void be()}),null),B(e,N(Sh,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return I(()=>x()===`hide`)()?`🙈`:x()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${x()} — click to cycle (dim → hidden → shown)`},onClick:ee}),null),B(e,N(Sh,{class:`filetoggle`,get icon(){return T()?`◉.`:`○.`},get title(){return T()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:te}),null),e})(),(()=>{var e=zp();return B(e,N(F,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Bp();return B(e,()=>g()||`empty workspace`),e})()},get children(){return N(P,{get each(){return(n().get(``)??[]).filter(w)},children:e=>ge(e,0)})}})),e})(),N(F,{get when(){return o()},children:t=>N(wh,{get title(){return`🗂 ${t().path}`},onClose:()=>{M++,c(null),f(null)},get children(){return N(F,{get when(){return u()},get fallback(){return[(()=>{var e=Gp(),n=e.firstChild;return B(e,N(F,{get when(){return I(()=>!!de(t().path))()&&!t().binary},get children(){var e=Up();return e.$$click=()=>h(`md`),y(()=>z(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||fe({path:t().path,content:t().content,truncated:t().truncated})},B(e,N(F,{get when(){return he(t())},get children(){var e=Wp();return e.$$click=()=>h(`edit`),y(()=>z(e,p()===`edit`?`on`:``)),e}}),null),y(()=>z(n,p()===`code`?`on`:``)),e})(),N(F,{get when(){return!t().binary},get fallback(){return qp()},get children(){return N(F,{get when(){return p()===`edit`},get fallback(){return N(F,{get when(){return I(()=>p()===`md`)()&&de(t().path)},get fallback(){return N(Lh,{get path(){return t().path},get content(){return t().content},get html(){return ae()},get pending(){return se()},get truncated(){return!!t().truncated}})},get children(){var e=Jp();return y(()=>e.innerHTML=Pe(t().content)),e}})},get children(){var e=Kp(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>le(e.currentTarget.value),R(n,`spellcheck`,!1),B(r,()=>yh(A().length),i),a.$$click=()=>void me(),B(a,()=>j()?`saving…`:`💾 save`),y(()=>a.disabled=j()||A()===t().content),y(()=>n.value=A()),e}})}})]},get children(){var t=Hp(),n=t.firstChild,r=n.firstChild;return B(t,N(F,{get when(){return u().kind===`image`},get fallback(){return N(F,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Xp();return y(()=>R(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Yp();return y(()=>R(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Vp();return y(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&R(t,`src`,n.e=r),i!==n.t&&R(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),B(n,()=>u().kind,r),t}})}})})]}function Lh(e){return[N(F,{get when(){return e.html},get fallback(){return I(()=>!!e.pending)()?(()=>{var t=$p(),n=t.firstChild.nextSibling;return n.nextSibling,B(t,()=>e.path.split(`/`).pop(),n),t})():(()=>{var t=em();return B(t,()=>e.content),t})()},get children(){var t=Zp();return y(()=>t.innerHTML=e.html),t}}),N(F,{get when(){return e.truncated},get children(){return Qp()}})]}var Rh=[{key:`openrouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1`,model:``,hint:`400+ models behind one key — teapot sends app-attribution headers automatically`},{key:`orcarouter`,label:`OrcaRouter`,url:`https://api.orcarouter.ai/v1`,model:``,hint:`zero-markup routing gateway — 'orcarouter/auto' grades each prompt and picks the model`},{key:`openai`,label:`OpenAI`,url:`https://api.openai.com/v1`,model:``,hint:`your account's models — pick from the list once the endpoint answers`},{key:`opencode-go`,label:`OpenCode Go`,url:`https://opencode.ai/zen/go/v1`,model:``,hint:`OpenCode's open-model subscription — teapot sends the required x-opencode-session header; choose a chat/completions model`},{key:`llamacpp`,label:`llama.cpp server`,url:`http://localhost:8080/v1`,model:``,hint:`free & local — start it with: llama-server -m ./model.gguf (any model name works)`}],zh={key:`custom`,label:`Custom`,url:``,model:``,hint:`any OpenAI-compatible /v1 endpoint — vLLM, LM Studio, llama.cpp, a company gateway… fill the fields below`};function Bh(e){let[t,n]=v(Rh[0]),[r,i]=v(Rh[0].url),[a,o]=v(``),[s,c]=v(Rh[0].model),[l,u]=v([]),[d,f]=v(`~/teapot-workspace`),[p,m]=v(``),[h,g]=v(!1),[_,x]=v(``),S=e=>{n(e),e.key!==`custom`&&e.url&&(i(e.url),e.model&&c(e.model))};b(()=>{let e=r().trim(),t=a();if(!/^https?:\/\//.test(e)){u([]);return}let n=setTimeout(async()=>{try{let n=await $(`/api/setup/models?baseUrl=${encodeURIComponent(e)}${t?`&apiKey=${encodeURIComponent(t)}`:``}`);u(n.models??[])}catch{u([])}},600);C(()=>clearTimeout(n))});let ee=e=>{let t=l().find(t=>t.id===e.trim());if(!t)return``;let n=[];t.contextLength&&n.push(`ctx ${yh(t.contextLength)} tok`);let r=e=>e===void 0?``:`$${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=r(t.pricing.prompt),i=r(t.pricing.completion);e&&i?n.push(`${e} in · ${i} out`):(e||i)&&n.push(r(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},w=()=>ee(s()),T=()=>{let e=s().trim().toLowerCase();return e?l().filter(t=>t.id.toLowerCase().includes(e)):l()},E=async t=>{if(t.preventDefault(),x(``),!s().trim())x(l().length?`pick a model — choose one from the list, or type its id`:`pick a model — type its id (the endpoint has not listed any yet)`);else{g(!0);try{await $(`/api/setup`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({baseUrl:r(),apiKey:a()||void 0,model:s(),workspace:d(),...p()?{password:p()}:{}})}),e.onDone()}catch(e){x(e.message),g(!1)}}};return(()=>{var e=am(),n=e.firstChild.firstChild.nextSibling.nextSibling,u=n.firstChild,g=u.nextSibling,v=g.firstChild.nextSibling,b=v.nextSibling,x=g.nextSibling,C=x.firstChild.nextSibling,te=x.nextSibling,D=te.firstChild.nextSibling,ne=D.nextSibling,re=te.nextSibling,O=re.firstChild.nextSibling,k=O.firstChild.nextSibling,ie=O.nextSibling.firstChild.nextSibling,ae=re.nextSibling;return n.addEventListener(`submit`,E),B(u,()=>[...Rh,zh].map(e=>(()=>{var n=om();return n.$$click=()=>S(e),B(n,()=>e.label),y(r=>{var i=`presetbtn`+(t().key===e.key?` active`:``),a=e.hint||e.url;return i!==r.e&&z(n,r.e=i),a!==r.t&&R(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})())),B(n,N(F,{get when(){return t().hint},get children(){var e=tm();return B(e,()=>t().hint),e}}),g),v.$$input=e=>i(e.currentTarget.value),B(b,()=>Rh.map(e=>(()=>{var t=zd();return y(()=>t.value=e.url),t})())),C.$$input=e=>o(e.currentTarget.value),D.$$input=e=>c(e.currentTarget.value),B(ne,()=>l().map(e=>(()=>{var t=zd();return y(()=>t.value=e.id),t})())),B(n,N(F,{get when(){return T().length>0},get fallback(){return(()=>{var e=sm();return B(e,()=>l().length?`no model matches that — clear the field to see them all`:`models appear here automatically once the endpoint answers GET /models`),e})()},get children(){return[(()=>{var e=nm();return B(e,()=>T().slice(0,40).map(e=>(()=>{var t=cm(),n=t.firstChild;return t.$$click=()=>c(e.id),B(n,()=>e.id),B(t,N(F,{get when(){return ee(e.id)},get children(){var t=jf();return B(t,()=>ee(e.id)),t}}),null),y(n=>{var r=`wizmodel`+(s()===e.id?` active`:``),i=ee(e.id)||e.id;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})())),e})(),(()=>{var e=im(),t=e.firstChild;return B(e,()=>T().length,t),B(e,()=>T().length>1?`s`:``,null),B(e,N(F,{get when(){return T().length>40},children:` (showing the first 40 — keep typing to narrow)`}),null),B(e,N(F,{get when(){return w()},get children(){return[` · selected: `,(()=>{var e=rm();return B(e,w),e})()]}}),null),e})()]}}),re),k.$$input=e=>f(e.currentTarget.value),ie.$$input=e=>m(e.currentTarget.value),B(n,N(F,{get when(){return _()},get children(){var e=yp();return B(e,_),e}}),ae),B(ae,()=>h()?`saving…`:`finish setup`),y(e=>{var n=t().key===`llamacpp`?`(any name — serves whichever gguf is loaded)`:`(pick from the list below, or type an id)`,r=h();return n!==e.e&&R(D,`placeholder`,e.e=n),r!==e.t&&(ae.disabled=e.t=r),e},{e:void 0,t:void 0}),y(()=>v.value=r()),y(()=>C.value=a()),y(()=>D.value=s()),y(()=>k.value=d()),y(()=>ie.value=p()),e})()}function Vh(e){let t=(e,t)=>{let n=Array.isArray(t?.apiKeys)&&t.apiKeys.length?t.apiKeys.filter(e=>typeof e==`string`&&e.trim()):t?.apiKey?[String(t.apiKey)]:[``];return{name:e,baseUrl:t?.baseUrl??``,apiKeys:n.length?n:[``],model:t?.model??``}},[n,r]=v(Object.entries(e.cfg.providers??{}).map(([e,n])=>t(e,n))),[i,a]=v(e.cfg.defaultProvider??``),o=()=>e.cfg.defaultProvider??``,s=()=>{let e=[...new Set(n().map(e=>e.name.trim()).filter(Boolean))],t=i();return t&&!e.includes(t)&&e.push(t),e},c=()=>{let e=i();return e?n().some(t=>t.name.trim()===e)?``:e:``},[l,u]=v(Math.round((e.cfg.progressIntervalMs??6e5)/6e4)),[d,f]=v(e.cfg.progressMinChars??4e3),[p,m]=v(e.cfg.contextTokenBudget==null?null:Math.round(e.cfg.contextTokenBudget/1e3)),[h,g]=v(e.cfg.contextWindowTokens?Math.round(e.cfg.contextWindowTokens/1e3):0),[_,x]=v(e.cfg.maxSpawnDepth??3),[S,ee]=v(!!e.cfg.shortContext),[C,w]=v((e.cfg.tasks??[]).map(e=>({...e}))),[T,E]=v((e.cfg.mcpServers??[]).map(e=>({...e}))),[te,D]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ne,re]=v({}),[O,k]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(!r.length)return[t,`none`];let i=r.length===1?r[0]:``;return i===`Authorization`&&/^Bearer /i.test(n[i]??``)?[t,`bearer`]:[t,r.length===1?`header`:`json`]}))),[ie,ae]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(r.length!==1)return[t,``];let i=r[0];return[t,i===`Authorization`?(n[i]??``).replace(/^Bearer /i,``):n[i]??``]}))),[oe,se]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=Object.keys(e.headers??{}),r=n.length===1?n[0]:``;return[t,r&&r!==`Authorization`?r:``]}))),[ce,A]=v({}),[le,j]=v({}),[ue,de]=v({}),M=async()=>{let e=await $(`/api/mcp`).catch(()=>null);j(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},fe=async e=>{let t=String(e??``).trim();if(!t)return;let n=await $(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&de(e=>({...e,[t]:n}))},pe=async(t,n)=>{if(!n.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await $(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name})}).catch(()=>null);if(r?.alreadyAuthorized){A(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await fe(n.name),await M();return}if(!r?.ok||!r.url){A(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await fe(n.name);return}window.open(r.url,`_blank`,`noopener`),A(e=>({...e,[t]:{kind:`testing`,text:`waiting for you to finish in the browser…`}}));let i=Date.now()+3e5;for(;Date.now()<i;){await new Promise(e=>setTimeout(e,1e3));let r=await $(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(de(e=>({...e,[t]:r})),r.authorized){A(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await M(),e.onSaved();return}if(r.flow?.phase===`error`){A(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}A(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};b(()=>{ge()===`mcp`&&(M(),T().forEach((e,t)=>{e.name&&fe(e.name)}))});let[me,he]=v(``),[ge,_e]=v(`providers`),[ye,be]=v([]),xe=async()=>{let e=await $(`/api/archived`).catch(()=>null);be(e?.agents??[])},L=()=>ye().filter(e=>!e.parent);b(()=>{ge()===`archive`&&xe()});let Se=[{key:`providers`,label:`🧦 providers`,hint:`endpoints, API keys, default models`},{key:`appearance`,label:`🎨 appearance`,hint:`theme, custom palettes, background image`},{key:`runtime`,label:`⚙️ runtime`,hint:`context budget, retries, spawn depth`},{key:`tasks`,label:`⏰ scheduled tasks`,hint:`cron prompts run against an agent`},{key:`mcp`,label:`🔌 MCP servers`,hint:`external tool servers exposed to every agent`},{key:`archive`,label:`🗄 archive`,hint:`agents you put away — restore or delete for good`},{key:`agents`,label:`👥 agents`,hint:`what exists (read-only)`},{key:`update`,label:`⬆️ live update`,hint:`restart onto a newer build`},{key:`help`,label:`❔ help`,hint:`keyboard shortcuts and what each toggle does`}],Ce=()=>(e.cfg.agents??[]).map(e=>e.id),we=()=>e.theme.themes(),Te=()=>e.theme.activeId(),Ee=t=>e.theme.setActive(t),De=()=>e.theme.auto(),Oe=t=>e.theme.setAuto(t),ke=()=>e.theme.dark(),Ae=t=>e.theme.setDark(t),je=()=>e.theme.light(),Me=t=>e.theme.setLight(t),Ne=t=>e.theme.setThemes(t),Pe=e=>an[e]??rn,Fe=()=>{let e={};for(let t of n()){if(!t.name.trim())return he(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return he(`provider ${t.name}: baseUrl must start with http(s)://`),null;let n=t.apiKeys.map(e=>e.trim()).filter(Boolean);e[t.name.trim()]={baseUrl:t.baseUrl,...n.length?{apiKeys:n,apiKey:n[0]}:{},...t.model?{model:t.model}:{}}}return e},Ie=async t=>{t.preventDefault(),he(``);let n=Fe();if(!n)return;let r=C().filter(e=>e.id?.trim()||e.prompt?.trim()).map((e,t)=>({id:e.id?.trim()||`task-${t+1}`,agent:e.agent,schedule:e.schedule,prompt:e.prompt,...e.forked?{forked:!0}:{}}));for(let e of r){if(!e.agent){he(`task "${e.id}": agent is required`);return}if(!e.schedule?.trim()){he(`task "${e.id}": schedule is required`);return}}let a=[],o=new Set;for(let e of T()){let t=String(e.name??``).trim(),n=String(e.url??``).trim(),r=e.transport??`http`,i=String(e.command??``).trim();if(t||n||i){if(!t){he(`MCP: a server needs a name`);return}if(o.has(t)){he(`MCP: two servers are named "${t}"`);return}if(o.add(t),r===`stdio`?!i:!n){he(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);return}a.push({name:t,transport:r,enabled:e.enabled!==!1,...n?{url:n}:{},...r===`stdio`?{command:i,...e.args?.length?{args:e.args}:{}}:{},...e.headers&&Object.keys(e.headers).length?{headers:e.headers}:{}})}}try{await $(`/api/config`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({providers:n,defaultProvider:i()||void 0,progressIntervalMs:Math.max(1,l())*6e4,progressMinChars:Math.max(100,d()),...p()==null?{}:{contextTokenBudget:Math.max(1,p())*1e3},...h()>0?{contextWindowTokens:h()*1e3}:{},maxSpawnDepth:Math.max(0,_()),shortContext:S(),tasks:r,mcpServers:a})}),await M(),await Promise.all(a.map((e,t)=>e.name?fe(e.name):Promise.resolve())),setTimeout(()=>{M(),a.forEach((e,t)=>{e.name&&fe(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=T().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&ue()[n]?.required&&!ue()[n]?.authorized}).filter(t=>!e.announcedOAuth.has(String(t.name??``)));if(o.length>0){for(let t of o)e.announcedOAuth.add(String(t.name??``));Q(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}else e.onClose()}catch(e){he(e.message)}},Le=(e,t,n,r)=>(()=>{var i=lm(),a=i.firstChild;return R(i,`title`,r),B(i,e,a),a.$$input=e=>n(Number(e.currentTarget.value)),a.value=t,i})();return N(wh,{title:`settings`,get onClose(){return e.onClose},get children(){var t=fm(),v=t.firstChild,b=v.firstChild,j=b.nextSibling.firstChild,de=j.firstChild.nextSibling,M=de.nextSibling;M.firstChild;var ye=M.nextSibling.firstChild.firstChild.nextSibling;ye.firstChild;var be=j.nextSibling,Fe=be.firstChild.nextSibling,Re=Fe.firstChild.firstChild.nextSibling,ze=Fe.nextSibling,Be=be.nextSibling,Ve=Be.firstChild.nextSibling,He=Ve.firstChild,Ue=He.firstChild.nextSibling,We=Ve.nextSibling.firstChild,Ge=Be.nextSibling,Ke=Ge.firstChild.nextSibling.nextSibling,qe=Ge.nextSibling,Je=qe.firstChild.nextSibling,Ye=qe.nextSibling;Ye.firstChild;var Xe=Ye.nextSibling;Xe.firstChild;var Ze=Xe.nextSibling,Qe=Ze.firstChild.nextSibling.firstChild;Qe.firstChild;var $e=Qe.nextSibling,et=Ze.nextSibling,tt=v.nextSibling,nt=tt.firstChild;return t.addEventListener(`submit`,Ie),B(b,N(P,{each:Se,children:e=>(()=>{var t=pm(),n=t.firstChild;return t.$$click=()=>_e(e.key),B(n,()=>e.label),y(n=>{var r=`cfgmenu-item`+(ge()===e.key?` on`:``),i=e.hint,a=ge()===e.key?`page`:void 0;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),B(j,N(ve,{get each(){return n()},children:(e,t)=>(()=>{var i=mm(),a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild;return a.$$input=e=>r(n().map((n,r)=>r===t?{...n,name:e.currentTarget.value}:n)),o.$$input=e=>r(n().map((n,r)=>r===t?{...n,baseUrl:e.currentTarget.value}:n)),s.$$input=e=>r(n().map((n,r)=>r===t?{...n,model:e.currentTarget.value}:n)),c.$$click=()=>r(n().filter((e,n)=>n!==t)),B(l,N(P,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=gm(),s=o.firstChild;return s.$$input=e=>r(n().map((n,r)=>r===t?{...n,apiKeys:n.apiKeys.map((t,n)=>n===a()?e.currentTarget.value:t)}:n)),s.value=i,B(o,N(F,{get when(){return e().apiKeys.length>1},get children(){var e=hm();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),y(()=>R(s,`placeholder`,a()===0?`api key`:`api key (backup)`)),o})()}),u),u.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:[...e.apiKeys,``]}:e)),y(()=>a.value=e().name),y(()=>o.value=e().baseUrl),y(()=>s.value=e().model),i})()}),de),de.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),B(M,N(P,{each:Rh,children:e=>(()=>{var t=_m();return t.firstChild,t.$$click=()=>{let t=n().filter(t=>t.name!==e.key);r([...t,{name:e.key,baseUrl:e.url,apiKeys:[``],model:e.model}]),i()||a(e.key)},B(t,()=>e.label,null),y(()=>R(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ye.addEventListener(`change`,e=>a(e.currentTarget.value)),B(ye,N(P,{get each(){return s()},children:e=>(()=>{var t=zd();return t.value=e,B(t,e),t})()}),null),B(j,N(F,{get when(){return c()},get children(){var e=um(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return B(t,c),B(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),B(r,c),e}}),null),Re.addEventListener(`change`,e=>{Oe(e.currentTarget.checked),localStorage.setItem(`teapot.theme.auto`,e.currentTarget.checked?`1`:`0`)}),B(be,N(F,{get when(){return De()},get children(){var e=dm(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ae(e.currentTarget.value),localStorage.setItem(`teapot.theme.dark`,e.currentTarget.value)}),B(n,N(P,{get each(){return we().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(eh.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=zd();return B(t,()=>e.label),y(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{Me(e.currentTarget.value),localStorage.setItem(`teapot.theme.light`,e.currentTarget.value)}),B(r,N(P,{get each(){return we().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(eh.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=zd();return B(t,()=>e.label),y(()=>t.value=e.key),t})()})),y(()=>n.value=ke()),y(()=>r.value=je()),e}}),ze),B(be,N(P,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>N(F,{get when(){return[...we(),...eh].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=vm();return B(t,()=>e.title),t})(),(()=>{var t=ym();return B(t,N(P,{get each(){return we().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=bm(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>{Ee(e.id),localStorage.setItem(`teapot.theme`,e.id)},B(n,N(Nh,{get palette(){return e.palette}})),B(r,()=>e.label,i),y(n=>{var r=`themecard`+(Te()===e.id?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Te()===e.id;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),B(t,N(P,{get each(){return eh.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=xm(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>{Ee(e.key),localStorage.setItem(`teapot.theme`,e.key)},B(n,N(Nh,{get palette(){return Pe(e.key)}})),B(r,()=>e.label),y(n=>{var r=`themecard`+(Te()===e.key?` on`:``),i=`${e.label} (${e.mode})`,a=Te()===e.key;return r!==n.e&&z(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),B(be,N(Ph,{themes:we,get activeId(){return Te()},onChange:e=>{let t=ln(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0}:e),r=ln(t);if(r.ok)n=t,Q(`storage was full — saved without the background image(s)`);else{Q(r.error??`could not save theme`);return}}Ne(n);let r=e=>n.some(t=>t.id===e)||eh.some(t=>t.key===e);r(Te())||(Ee(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(ke())||(Ae(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(je())||(Me(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{Ee(e),localStorage.setItem(`teapot.theme`,e)}}),null),B(Ve,()=>Le(`progress interval (min)`,l(),e=>u(e),`how often the harness asks for a progress report`),He),B(Ve,()=>Le(`progress min chars`,d(),e=>f(e),`progress prompts wait for this much real output`),He),Ue.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),B(Ve,()=>Le(`context window (k tok)`,h(),e=>g(e),`model's real window — 0/blank hides the % gauge`),null),B(Ve,()=>Le(`max spawn depth`,_(),e=>x(e),`sub-agent nesting limit (0 = no spawning)`),null),We.addEventListener(`change`,e=>ee(e.currentTarget.checked)),B(Ge,N(F,{get when(){return T().length>0},get fallback(){return Sm()},get children(){return N(ve,{get each(){return T()},children:(e,t)=>{let n=()=>le()[e().name],r=e=>E(T().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=Nm(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling,l=c.firstChild,u=c.nextSibling,d=a.nextSibling,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>r({url:e.currentTarget.value}),l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>E(T().filter((e,n)=>n!==t)),f.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),B(d,N(F,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=Cm();return t.$$input=e=>r({command:e.currentTarget.value}),y(()=>t.value=e().command??``),t})(),(()=>{var t=wm();return t.$$input=e=>r({args:e.currentTarget.value.split(` `).filter(Boolean)}),y(()=>t.value=(e().args??[]).join(` `)),t})()]}}),null),m.addEventListener(`change`,e=>{let n=e.currentTarget.value;if(k(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ie()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=oe()[t]??``,n=ie()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),B(p,N(F,{get when(){return O()[t]===`bearer`},get children(){var e=Tm();return e.$$input=e=>{let n=e.currentTarget.value;ae(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},y(()=>e.value=ie()[t]??``),e}}),null),B(p,N(F,{get when(){return O()[t]===`header`},get children(){return[(()=>{var e=Em();return e.$$input=e=>{let n=e.currentTarget.value;se(e=>({...e,[t]:n}));let i=ie()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},y(()=>e.value=oe()[t]??``),e})(),(()=>{var e=Dm();return e.$$input=e=>{let n=e.currentTarget.value;ae(e=>({...e,[t]:n}));let i=oe()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},y(()=>e.value=ie()[t]??``),e})()]}}),null),B(i,N(F,{get when(){return O()[t]===`json`},get children(){var e=Om(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(D(e=>({...e,[t]:n})),!n.trim())r({headers:void 0});else try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`not an object`);r({headers:e}),re(e=>({...e,[t]:``}))}catch{re(e=>({...e,[t]:`must be a JSON object — not applied`}))}},y(()=>n.value=te()[t]??``),e}}),h),g.$$click=async()=>{let e=T()[t];if(!e.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await $(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);A(e=>({...e,[t]:n?.ok?{kind:`ok`,text:`${n.tools?.length??0} tool${n.tools?.length===1?``:`s`}`,tools:n.tools??[]}:{kind:`err`,text:n?.error??`no response`,...n?.needsOAuth?{needsOAuth:!0}:{}}})),n?.ok||await fe(e.name)},B(h,N(F,{get when(){return I(()=>!!ue()[String(e().name??``).trim()]?.required)()&&!ue()[String(e().name??``).trim()]?.authorized},get children(){var n=km();return n.$$click=()=>void pe(t,e()),n}}),null),B(h,N(F,{get when(){return ue()[String(e().name??``).trim()]?.authorized},get children(){return[Am(),(()=>{var n=jm();return n.$$click=async()=>{await $(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await fe(e().name),A(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}}))},n})()]}}),null),B(h,N(F,{get when(){return n()},get children(){var e=bd();return B(e,(()=>{var e=I(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:I(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),y(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&z(e,t.e=r),i!==t.t&&R(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),B(i,N(F,{get when(){return ne()[t]},get children(){var e=Mm();return B(e,()=>ne()[t]),e}}),null),B(i,N(F,{get when(){return ce()[t]},children:e=>(()=>{var t=Im(),n=t.firstChild,r=n.firstChild;return B(r,()=>e().text),B(n,N(F,{get when(){return e().needsOAuth},get children(){return Pm()}}),null),B(t,N(F,{get when(){return(e().tools?.length??0)>0},get children(){var t=Fm();return B(t,N(P,{get each(){return e().tools??[]},children:e=>(()=>{var t=Rm(),n=t.firstChild;return B(n,()=>e.name),B(t,N(F,{get when(){return e.description},get children(){var t=Lm();return B(t,()=>e.description),t}}),null),y(()=>R(t,`title`,e.description??``)),t})()})),t}}),null),y(()=>z(t,`mcpresult `+(e().kind===`err`?`err`:`ok`))),t})()}),null),y(()=>o.value=e().name),y(()=>s.value=e().url??``),y(()=>l.checked=e().enabled!==!1),y(()=>f.value=e().transport??`http`),y(()=>m.value=O()[t]??`none`),i})()}})}}),Ke),Ke.$$click=()=>E([...T(),{name:``,url:``,transport:`http`,enabled:!0}]),B(qe,N(F,{get when(){return C().length>0},get children(){return N(ve,{get each(){return C()},children:(e,t)=>(()=>{var n=zm(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.firstChild,l=s.nextSibling,u=r.nextSibling;return i.$$input=e=>w(C().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>w(C().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>w(C().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>w(C().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>w(C().filter((e,n)=>n!==t)),u.$$input=e=>w(C().map((n,r)=>r===t?{...n,prompt:e.currentTarget.value}:n)),y(()=>i.value=e().id),y(()=>a.value=e().agent),y(()=>o.value=e().schedule),y(()=>c.checked=!!e().forked),y(()=>u.value=e().prompt),n})()})}}),Je),Je.$$click=()=>w([...C(),{id:``,agent:Ce()[0]??``,schedule:`every 30m`,prompt:``}]),B(Ye,N(F,{get when(){return L().length>0},get fallback(){return Bm()},get children(){return N(P,{get each(){return L()},children:t=>(()=>{var n=Vm(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return B(i,()=>t.id),B(a,()=>t.sessions,o),B(a,()=>t.sessions===1?``:`s`,null),B(a,(()=>{var e=I(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),B(a,(()=>{var e=I(()=>!!t.archivedAt);return()=>e()?` · archived ${vh(new Date(t.archivedAt).toISOString())}`:``})(),null),B(s,()=>t.workspace),c.$$click=async()=>{let n=await $(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await xe(),e.onSaved();let r=(n?.ids?.length??1)-1;Q((n?.live===!1?`restored ${t.id} — it could not be started (check its provider)`:`restored ${t.id}`)+(r>0?` + ${r} sub-agent${r===1?``:`s`}`:``))},l.$$click=async()=>{confirm(`PERMANENTLY DELETE ${t.id}?\n\n${t.sessions} session${t.sessions===1?``:`s`} of history will be erased from disk along with the config entry. This cannot be undone — archiving was the reversible option.`)&&(await $(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await xe(),e.onSaved(),Q(`deleted ${t.id} for good`))},y(()=>R(s,`title`,t.workspace)),n})()})}}),null),B(Xe,N(P,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=Um(),n=t.firstChild,r=n.nextSibling;return B(n,()=>e.id),B(r,()=>e.workspace),B(t,N(F,{get when(){return e.parent},get children(){var t=Hm();return t.firstChild,B(t,()=>e.parent,null),t}}),null),t})()}),null),B(Qe,()=>e.cfg.version??`unknown`,null),$e.$$click=async e=>{try{he(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await $(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=!1;for(let e=0;e<90&&!r;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await $(`/api/version`);e.version&&e.version!==`0.35.12`&&(r=!0,window.location.reload())}catch{}}if(!r)throw Error(`restart timeout — new server did not come up`)}catch(e){he(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},B(tt,N(F,{get when(){return me()},get children(){var e=yp();return B(e,me),e}}),nt),y(e=>{var t=ge()!==`providers`,n=ge()!==`appearance`,r=ge()!==`runtime`,i=ge()!==`mcp`,a=ge()!==`tasks`,o=ge()!==`archive`,s=ge()!==`agents`,c=ge()!==`update`,l=ge()!==`help`;return t!==e.e&&j.classList.toggle(`hide`,e.e=t),n!==e.t&&be.classList.toggle(`hide`,e.t=n),r!==e.a&&Be.classList.toggle(`hide`,e.a=r),i!==e.o&&Ge.classList.toggle(`hide`,e.o=i),a!==e.i&&qe.classList.toggle(`hide`,e.i=a),o!==e.n&&Ye.classList.toggle(`hide`,e.n=o),s!==e.s&&Xe.classList.toggle(`hide`,e.s=s),c!==e.h&&Ze.classList.toggle(`hide`,e.h=c),l!==e.r&&et.classList.toggle(`hide`,e.r=l),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),y(()=>ye.value=i()),y(()=>Re.checked=De()),y(()=>Ue.value=p()??``),y(()=>We.checked=S()),t}})}Se([`click`,`pointerdown`,`dblclick`,`input`,`keydown`]),xe(()=>N(lh,{}),document.getElementById(`root`));export{vu as t};
30
+ //# sourceMappingURL=index-Ch7-gRkl.js.map