teapot-coding-agent 0.37.72 → 0.37.73

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.
@@ -19,18 +19,18 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
19
19
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===lu+1&&(this._liveRegion.textContent+=Hn.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})`}};uu=zn([z(1,hr),z(2,wr),z(3,Er)],uu);var du=class extends U{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 G),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new G),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(H(()=>{Jr(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(K(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(K(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(K(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(K(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&&fu(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,Jr(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}}};du=zn([z(1,Tr),z(2,Er),z(3,dr),z(4,Ar)],du);function fu(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 pu=class extends Ql{constructor(e={}){super(e),this._linkifier=this._register(new Qr),this.browser=Ds,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Qr),this._onCursorMove=this._register(new G),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new G),this.onKey=this._onKey.event,this._onRender=this._register(new G),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new G),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new G),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new G),this.onBell=this._onBell.event,this._onFocus=this._register(new G),this._onBlur=this._register(new G),this._onA11yCharEmitter=this._register(new G),this._onA11yTabEmitter=this._register(new G),this._onWillOpen=this._register(new G),this._setup(),this._decorationService=this._instantiationService.createInstance(au),this._instantiationService.setService(br,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Ss),this._instantiationService.setService(Ar,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(xr)),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(ii.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(ii.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(ii.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(ii.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(H(()=>{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};${Il(r)}${Lo.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Wo.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Wo.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(uu,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(K(this.element,`copy`,e=>{this.hasSelection()&&Gn(e,this._selectionService)}));let e=e=>Kn(e,this.textarea,this.coreService,this.optionsService);this._register(K(this.textarea,`paste`,e)),this._register(K(this.element,`paste`,e)),js?this._register(K(this.element,`mousedown`,e=>{e.button===2&&Yn(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(K(this.element,`contextmenu`,e=>{Yn(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),zs&&this._register(K(this.element,`auxclick`,e=>{e.button===1&&Jn(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(K(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(K(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(K(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(K(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(K(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(K(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(K(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(K(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`,Vn.get()),Bs||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(bs,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(wr,this._coreBrowserService),this._register(K(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(K(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(gs,this._document,this._helperContainer),this._instantiationService.setService(Cr,this._charSizeService),this._themeService=this._instantiationService.createInstance(wc),this._instantiationService.setService(kr,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Zo),this._instantiationService.setService(Or,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ks,this.rows,this.screenElement)),this._instantiationService.setService(Er,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(Ro,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Ts),this._instantiationService.setService(Tr,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(du,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(ko,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(mc,this.element,this.screenElement,r)),this._instantiationService.setService(Dr,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(ii.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Ao,this.screenElement)),this._register(K(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(uu,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Fo,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Fo,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(hs,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(K(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(K(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){qn(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=eu(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)&&(mu(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(Mc));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 mu(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var hu=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)}},gu=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 ir)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},_u=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 gu(t)}getNullCell(){return new ir}},vu=class extends U{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new G),this.onBufferChange=this._onBufferChange.event,this._normal=new _u(this._core.buffers.normal,`normal`),this._alternate=new _u(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)}},yu=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)}},bu=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}},xu=[`cols`,`rows`],Su=0,Cu=class extends U{constructor(e){super(),this._core=this._register(new pu(e)),this._addonManager=this._register(new hu),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(xu.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 yu(this._core),this._parser}get unicode(){return this._checkProposedApi(),new bu(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 vu(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
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 Vn.get()},set promptLabel(e){Vn.set(e)},get tooMuchOutput(){return Hn.get()},set tooMuchOutput(e){Hn.set(e)}}}_verifyIntegers(...e){for(Su of e)if(Su===1/0||isNaN(Su)||Su%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(Su of e)if(Su&&(Su===1/0||isNaN(Su)||Su%1!=0||Su<0))throw Error(`This API only accepts positive integers`)}},wu=2,Tu=1,Eu=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(wu,Math.floor(u/e.css.cell.width)),rows:Math.max(Tu,Math.floor(l/e.css.cell.height))}}};function Du(e){return e.length}function Ou(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function ku(e,t,n){return Ou(e===t?t:e>t?e-1:e,n)}function Au(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function ju(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}function Mu(e){return!(e.key!==`Enter`||e.shiftKey||e.composing||e.maximized)}function Nu(e){return e}async function Pu(e,t={}){if(!e)return`unsupported`;let n=t.clipboard===void 0?typeof navigator<`u`?navigator.clipboard??null:null:t.clipboard,r=t.execCommand??(typeof document<`u`?document.execCommand.bind(document):void 0),i=t.makeTextarea??(()=>{let e=document.createElement(`textarea`);return document.body.appendChild(e),{set value(t){e.value=t},get value(){return e.value},style:{get position(){return e.style.position},set position(t){e.style.position=t},get opacity(){return e.style.opacity},set opacity(t){e.style.opacity=t}},select:()=>e.select(),remove:()=>e.remove()}}),a=n?.writeText;if(typeof a==`function`)try{return await a.call(n,e),`copied`}catch{}let o=null;try{let t=i();return o=t,t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,t.select(),r&&r(`copy`)?`copied`:`failed`}catch{return`failed`}finally{o?.remove()}}var Fu=F(`<button type=button><span class=iconbtn-glyph>`),Iu=F(`<button class=copybtn>`),Lu=F(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`);function Ru(e){return(()=>{var t=Fu(),n=t.firstChild;return Te(t,`click`,e.onClick,!0),R(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&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n.a=Ee(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function zu(e){let[t,n]=v(!1),[r,i]=v(!1),a=t=>{t.preventDefault(),t.stopPropagation(),Pu(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=Iu();return n.$$click=a,R(n,(()=>{var n=P(()=>!!t());return()=>n()?`✓`:P(()=>!!r())()?`✗`:e.label??`⧉`})()),y(()=>I(n,`title`,e.title??`copy to clipboard`)),n})()}function Bu(e){return(()=>{var t=Lu(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),R(r,()=>e.title),Te(i,`click`,e.onClose,!0),R(n,()=>e.children,null),t})()}we([`click`]);var Vu={fg:void 0,bg:void 0,bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},Hu=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`];function Uu(e){let t=[];return e.fg&&t.push(`ansi-fg-${e.fg}`),e.bg&&t.push(`ansi-bg-${e.bg}`),e.bold&&t.push(`ansi-bold`),e.dim&&t.push(`ansi-dim`),e.italic&&t.push(`ansi-italic`),e.underline&&t.push(`ansi-underline`),e.inverse&&t.push(`ansi-inverse`),t}function Wu(e,t){let n={...e};t.length===0&&(t=[0]);for(let e=0;e<t.length;e++){let r=t[e];if(r===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.inverse=!1;else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===7)n.inverse=!0;else if(r===21||r===22)n.bold=!1,n.dim=!1;else if(r===23)n.italic=!1;else if(r===24)n.underline=!1;else if(r===27)n.inverse=!1;else if(r>=30&&r<=37)n.fg=Hu[r-30];else if(r>=90&&r<=97)n.fg=`bright-${Hu[r-90]}`;else if(r===39)n.fg=void 0;else if(r>=40&&r<=47)n.bg=Hu[r-40];else if(r>=100&&r<=107)n.bg=`bright-${Hu[r-100]}`;else if(r===49)n.bg=void 0;else if(r===38||r===48){let i=t[e+1],a=r===38?`fg`:`bg`;i===5&&t[e+2]!==void 0?(n[a]=`ext`,e+=2):i===2&&t[e+4]!==void 0?(n[a]=`ext`,e+=4):(n[a]=`ext`,e+=1)}}return n}var Gu=/\x1b\[([0-9;]*)m/;function Ku(e){if(!e)return[];let t=[],n={...Vu},r=``,i=()=>{if(!r)return;let e=Uu(n),i=t[t.length-1];i&&i.classes.join(` `)===e.join(` `)?i.text+=r:t.push({text:r,classes:e}),r=``};for(let t=0;t<e.length;t++){let a=e[t];if(a===`\x1B`){let r=e.slice(t),a=Gu.exec(r);if(a){i();let e=(a[1]??``).split(`;`).filter(e=>e!==``).map(e=>Number(e)).filter(e=>Number.isFinite(e));n=Wu(n,e),t+=a[0].length-1;continue}let o=/^\x1b\[[0-9;?]*[A-Za-z]/.exec(r);if(o){t+=o[0].length-1;continue}let s=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(r);if(s){t+=s[0].length-1;continue}}else if(a===`\r`){if(e[t+1]===`
21
21
  `){r+=`
22
- `,t++;continue}r=``}else r+=a}return i(),t}function qu(e){return Ku(e).map(e=>e.text).join(``)}function Ju(e){return e.includes(`\x1B`)}var Yu=400,Xu=new Map;function Zu(e){return Xu.get(e)}function Qu(e,t){if(Xu.size>=Yu){let e=Xu.keys().next();e.done||Xu.delete(e.value)}Xu.set(e,t)}var $u=`modulepreload`,ed=function(e){return`/`+e},td={},nd=function(e){return e.pathname.endsWith(`.css`)},rd=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},id=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=ed(t,n);let r=s(t),i=nd(r);return rd(td,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`:$u,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)})},ad=F(`<span class=bashelapsed>running… `),od=F(`<span class=bashelapsed> elapsed`),sd=F(`<span class=thinktimer>`),cd=F(`<pre class="mono toolbody ansi">`),ld=F(`<pre class="mono toolbody">`),ud=F(`<span>`),dd=F(`<div class="toolbody shiki">`);function fd(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=()=>Ve(Math.max(0,n()-t));return e.inline?(()=>{var t=ad();return t.firstChild,R(t,i,null),R(t,(()=>{var t=P(()=>!!e.timeoutMs);return()=>t()?` · timeout ${Math.round(e.timeoutMs/1e3)}s`:``})(),null),t})():(()=>{var e=od(),t=e.firstChild;return R(e,i,t),e})()}function pd(e){let[t,n]=v(Date.now());ee(()=>{let e=setInterval(()=>n(Date.now()),500);C(()=>clearInterval(e))});let r=()=>{if(!e.startedAt)return null;let n=Math.max(0,t()-e.startedAt);return n>864e5?null:Ve(n)};return j(N,{get when(){return r()!==null},fallback:null,get children(){var e=sd();return R(e,r),e}})}function md(e){let t=x(()=>Ju(e.text)?Ku(e.text):null);return j(N,{get when(){return t()},get fallback(){return(()=>{var t=ld();return R(t,()=>e.text),t})()},get children(){var e=cd();return R(e,j(M,{get each(){return t()},children:e=>e.classes.length?(()=>{var t=ud();return R(t,()=>e.text),y(()=>L(t,e.classes.join(` `))),t})():e.text})),e}})}function hd(e){let t=()=>e.lang?`${e.lang}::${e.text.length}::${e.text}`:``,[n,r]=v((e.lang?Zu(t()):void 0)??``);return b(()=>{let n=t(),i=e.text,a=e.lang;if(!a||!i.trim()){r(``);return}let o=Zu(n);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await id(async()=>{let{highlightLangChunks:e}=await import(`./shiki-CNiDVOMg.js`);return{highlightLangChunks:e}},[]),o=``;for await(let t of e(a,i))o+=t;if(!o)return;Qu(n,o),t()===n&&r(o)}catch{}})():r(o)}),j(N,{get when(){return!!n()},get fallback(){return(()=>{var t=ld();return R(t,()=>e.text),t})()},get children(){var e=dd();return y(()=>e.innerHTML=n()),e}})}var gd=[{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`]}];async function Q(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 _d=new Map;function vd(e){let t=_d.get(e);if(t!==void 0)return t;let n=Ie(e);return _d.set(e,n),_d.size>500&&_d.delete(_d.keys().next().value),n}var yd=.82,bd=.9,xd=e=>{if(Number.isFinite(e))return e<0?0:e>1?1:e};function Sd(e,t){let n=xd(e??yd)??yd;return{dim:xd(t??bd)??bd,panel:Math.max(0,Math.min(1,n-.05)),raised:Math.max(0,Math.min(1,n+.06))}}function Cd(e,t){return`color-mix(in srgb, ${e} ${Math.round((xd(t)??bd)*100)}%, transparent)`}function wd(e){let t=e?.trim();if(t)return`url("${t.replace(/"/g,`%22`)}")`}var Td=F(`<div class="content mdpreview todopane">`),Ed=F(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- [ ] task one
22
+ `,t++;continue}r=``}else r+=a}return i(),t}function qu(e){return Ku(e).map(e=>e.text).join(``)}function Ju(e){return e.includes(`\x1B`)}var Yu=400,Xu=new Map;function Zu(e){return Xu.get(e)}function Qu(e,t){if(Xu.size>=Yu){let e=Xu.keys().next();e.done||Xu.delete(e.value)}Xu.set(e,t)}var $u=`modulepreload`,ed=function(e){return`/`+e},td={},nd=function(e){return e.pathname.endsWith(`.css`)},rd=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},id=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=ed(t,n);let r=s(t),i=nd(r);return rd(td,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`:$u,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)})},ad=F(`<span class=bashelapsed>running… `),od=F(`<span class=bashelapsed> elapsed`),sd=F(`<span class=thinktimer>`),cd=F(`<pre class="mono toolbody ansi">`),ld=F(`<pre class="mono toolbody">`),ud=F(`<span>`),dd=F(`<div class="toolbody shiki">`);function fd(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=()=>Ve(Math.max(0,n()-t));return e.inline?(()=>{var t=ad();return t.firstChild,R(t,i,null),R(t,(()=>{var t=P(()=>!!e.timeoutMs);return()=>t()?` · timeout ${Math.round(e.timeoutMs/1e3)}s`:``})(),null),t})():(()=>{var e=od(),t=e.firstChild;return R(e,i,t),e})()}function pd(e){let[t,n]=v(Date.now());ee(()=>{let e=setInterval(()=>n(Date.now()),500);C(()=>clearInterval(e))});let r=()=>{if(!e.startedAt)return null;let n=Math.max(0,t()-e.startedAt);return n>864e5?null:Ve(n)};return j(N,{get when(){return r()!==null},fallback:null,get children(){var e=sd();return R(e,r),e}})}function md(e){let t=x(()=>Ju(e.text)?Ku(e.text):null);return j(N,{get when(){return t()},get fallback(){return(()=>{var t=ld();return R(t,()=>e.text),t})()},get children(){var e=cd();return R(e,j(M,{get each(){return t()},children:e=>e.classes.length?(()=>{var t=ud();return R(t,()=>e.text),y(()=>L(t,e.classes.join(` `))),t})():e.text})),e}})}function hd(e){let t=()=>e.lang?`${e.lang}::${e.text.length}::${e.text}`:``,[n,r]=v((e.lang?Zu(t()):void 0)??``);return b(()=>{let n=t(),i=e.text,a=e.lang;if(!a||!i.trim()){r(``);return}let o=Zu(n);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await id(async()=>{let{highlightLangChunks:e}=await import(`./shiki-qHmIppt3.js`);return{highlightLangChunks:e}},[]),o=``;for await(let t of e(a,i))o+=t;if(!o)return;Qu(n,o),t()===n&&r(o)}catch{}})():r(o)}),j(N,{get when(){return!!n()},get fallback(){return(()=>{var t=ld();return R(t,()=>e.text),t})()},get children(){var e=dd();return y(()=>e.innerHTML=n()),e}})}var gd=[{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`]}];async function Q(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 _d=new Map;function vd(e){let t=_d.get(e);if(t!==void 0)return t;let n=Ie(e);return _d.set(e,n),_d.size>500&&_d.delete(_d.keys().next().value),n}var yd=.82,bd=.9,xd=e=>{if(Number.isFinite(e))return e<0?0:e>1?1:e};function Sd(e,t){let n=xd(e??yd)??yd;return{dim:xd(t??bd)??bd,panel:Math.max(0,Math.min(1,n-.05)),raised:Math.max(0,Math.min(1,n+.06))}}function Cd(e,t){return`color-mix(in srgb, ${e} ${Math.round((xd(t)??bd)*100)}%, transparent)`}function wd(e){let t=e?.trim();if(t)return`url("${t.replace(/"/g,`%22`)}")`}var Td=F(`<div class="content mdpreview todopane">`),Ed=F(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- [ ] task one
23
23
  - [ ] task two"title="shared with the agent \\u2014 it may check items off via set_todo; your unsaved edits win until you save">`),Dd=F(`<div class="filepreview shikiwrap">`),Od=F(`<div class=muted style=padding-top:6px;font-size:11.5px>… truncated (first 100 KB)`),kd=F(`<div class=muted style=padding:8px;font-size:12px>✨ highlighting <!>…`),Ad=F(`<pre class=mono style=max-height:62vh;overflow:auto;white-space:pre-wrap;margin:0>`),jd=F(`<label><input type=number min=0>`),Md=F(`<span class=tprev-bg>`),Nd=F(`<span class=tprev-veil>`),Pd=F(`<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%>`);function Fd(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 j(N,{get when(){return e.preview},get fallback(){return(()=>{var t=Ed();return t.$$input=t=>e.onDraft(t.currentTarget.value),Oe(a,t),y(e=>Ee(t,i(),e)),y(()=>t.value=e.draft),t})()},get children(){var t=Td();return Oe(a,t),y(n=>{var r=i(),a=vd(e.draft);return n.e=Ee(t,r,n.e),a!==n.t&&(t.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t}})}function Id(e){return[j(N,{get when(){return e.html},get fallback(){return P(()=>!!e.pending)()?(()=>{var t=kd(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.path.split(`/`).pop(),n),t})():(()=>{var t=Ad();return R(t,()=>e.content),t})()},get children(){var t=Dd();return y(()=>t.innerHTML=e.html),t}}),j(N,{get when(){return e.truncated},get children(){return Od()}})]}function Ld(e){return(()=>{var t=jd(),n=t.firstChild;return R(t,()=>e.label,n),n.$$input=t=>e.onValue(Number(t.currentTarget.value)),y(()=>I(t,`title`,e.hint)),y(()=>n.value=e.value),t})()}function Rd(e){let t=()=>e.palette,n=()=>Sd(e.surfaceAlpha,e.backgroundDim);return(()=>{var r=Pd(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return R(r,j(N,{get when(){return e.backgroundImage},get children(){return[(()=>{var t=Md();return y(n=>De(t,`background-image`,wd(e.backgroundImage))),t})(),(()=>{var e=Nd();return y(r=>De(e,`background`,Cd(t().bgDark,n().dim))),e})()]}}),i),y(h=>{var g=t().bgDark,_=t().bgDarkest,v=e.backgroundImage?String(n().panel):`1`,y=t().bgDarkest,b=e.backgroundImage?String(n().panel):`1`,x=t().bgMid,S=e.backgroundImage?String(n().raised):`1`,ee=t().fg,C=t().acc,te=t().dim,ne=t().acc,w=t().dim,T=t().ok,E=t().warn,D=t().err;return g!==h.e&&De(r,`background`,h.e=g),_!==h.t&&De(i,`background`,h.t=_),v!==h.a&&De(i,`opacity`,h.a=v),y!==h.o&&De(a,`background`,h.o=y),b!==h.i&&De(a,`opacity`,h.i=b),x!==h.n&&De(o,`background`,h.n=x),S!==h.s&&De(o,`opacity`,h.s=S),ee!==h.h&&De(s,`background`,h.h=ee),C!==h.r&&De(c,`background`,h.r=C),te!==h.d&&De(l,`background`,h.d=te),ne!==h.l&&De(u,`background`,h.l=ne),w!==h.u&&De(d,`background`,h.u=w),T!==h.c&&De(f,`background`,h.c=T),E!==h.w&&De(p,`background`,h.w=E),D!==h.m&&De(m,`background`,h.m=D),h},{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,c:void 0,w:void 0,m:void 0}),r})()}we([`input`]);var[zd,Bd]=v(``),Vd,Hd=e=>{Bd(e),clearTimeout(Vd),Vd=setTimeout(()=>Bd(``),3200)},Ud={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`}},Wd={name:`harness`,icon:`📣`,color:`#3ba55d`},Gd={"#faa81a":`you`,"#5865f2":`agent`,"#3ba55d":`progress`,"#3ba0c9":`tool`},Kd=e=>Gd[e]??`agent`,qd=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`?Ud.prompt:t.startsWith(`scheduler:`)?{name:t.slice(10),icon:`📣`,color:`#3ba55d`}:Wd}return Ud[e.type]??{name:e.type,icon:`•`,color:`#9298a5`}},Jd=e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`};function Yd(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 Xd(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 Zd(e,t){return He(e.replace(/\s+/g,` `).trim(),t)}function Qd(e){return e.type===`prompt`&&e.data?.source===`user`?`you`:e.type===`message`?`agent`:`harness`}function $d(e){let t=e.data??{};if(e.data?.actor)return`sub:${String(e.data.actor)}`;if(e.type===`tool_call`||e.type===`tool_result`){let e=typeof t.name==`string`?t.name:``;return e===`load_skill`?`agent-skill`:`tool:${e}`}return e.type===`prompt`?`src:${String(t.source??`user`)}`:`type:${e.type}`}function ef(e,t){return!(!e||t.data?.pending||e.data?.pending||t.data?.cancelled||$d(e)!==$d(t)||Qd(e)!==Qd(t)||t.session!==e.session||t.branch!==e.branch)}function tf(e,t){let n=String(t??``);return/^TIMEOUT after\b/.test(n)?`timeout`:/^ABORTED\b/.test(n)?`aborted`:/^exit=\d+/.test(n)||e===!1?`exit`:n.trim()?`ok`:`empty`}function nf(e){switch(e){case`timeout`:return` · TIMED OUT`;case`aborted`:return` · ABORTED`;case`exit`:return` · FAILED`;default:return``}}function rf(e){let t=[];e.outcome!==`empty`&&t.push(e.fmtDur(e.durationMs)),e.timeoutMs&&t.push(`timeout ${Math.round(e.timeoutMs/1e3)}s`);let n=nf(e.outcome).replace(/^\s*·\s*/,``);return n&&t.push(n),t.join(` · `)}function af(e){let t=e.trim();if(!t)return;let n=t[0];if(n===`{`||n===`[`||n===`"`)try{let e=JSON.parse(t);return typeof e==`object`&&e?`json`:void 0}catch{return}}function of(e){if(af(e)!==`json`)return e;try{let t=JSON.parse(e.trim()),n=JSON.stringify(t,null,1);return e.trim().split(`
24
- `).length>1?e:n}catch{return e}}var sf=12e4,cf=6e5,lf=e=>{let t=Number(e);return Math.min(Number.isFinite(t)&&t>0?t:sf,cf)},uf=F(`<div class=qfree><input type=text><button>reply`),df=F(`<div class=meta>`),ff=F(`<div class=meta>waiting for output…`),pf=F(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),mf=F(`<b>action="kill"`),hf=F(`<div class="meta muted"> bytes — open it from 🗂 files for the full view`),gf=F(`<div class=meta>writing…`),_f=F(`<pre class="mono toolbody del">`),vf=F(`<pre class="mono toolbody add">`),yf=F(`<div class=meta> · `),bf=F(`<div class=meta>applying…`),xf=F(`<pre class="mono toolbody patch">`),Sf=F(`<div>`),Cf=F(`<div class="pline meta">… <!> more lines`),wf=F(`<div class=meta>validating…`),Tf=F(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),Ef=F(`<span class=muted>`),Df=F(`<div class=content>`),Of=F(`<div class=meta>loading…`),kf=F(`<div class=meta>bundled: `),Af=F(`<div class=meta>saving…`),jf=F(`<span class=actor>@`),Mf=F(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),Nf=F(`<div class=divider-msg>⑂ forked from <!> → `),Pf=F(`<div><div class=goalline-label>`),Ff=F(`<span class="meta muted">`),If=F(`<pre class="mono toolbody">`),Lf=F(`<details class="embed auditstep"><summary><span class=meta>`),Rf=F(`<div class=divider-msg>✅ tasks updated (<!>)`),zf=F(`<div> → `),Bf=F(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),Vf=F(`<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…`),Hf=F(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),Uf=F(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),Wf=F(`<span class=ts>`),Gf=F(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),Kf=F(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),qf=F(`<div class=msg-head><span></span><span class=ts>`),Jf=F(`<div><div></div><div class=msg-body>`),Yf=F(`<span class=grouptime>`),Xf=F(`<div class=promptimgs>`),Zf=F(`<img class=promptimg alt=attachment>`),Qf=F(`<details class=reasoning><summary>💭 thinking</summary><div class=mono>`),$f=F(`<div class=interrupted>⚠ interrupted — partial output kept`),ep=F(`<div class=msgfoot><span>copy summary`),tp=F(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),np=F(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),rp=F(`<div class="content muted">Rejected: `),ip=F(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged</span></summary><div class=content>`),ap=F(`<div class="meta answerdone">✓ answered — continuing below`),op=F(`<div class=qopts>`),sp=F(`<div><div>❓️ <div class="content inline-md">`),cp=F(`<button class=qopt>`),lp=F(`<div class=progrow><b>goal</b><span>`),up=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),dp=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),fp=F(`<div class=progrow><b>next</b><span class="content inline-md">`),pp=F(`<div class="embed progembed"><div>📈 <div class="content inline-md">`),mp=F(`<div class="embed fail"><div class=mono>⚠ `),hp=F(`<div class="muted compactnote">the summary pass produced nothing, so the oldest messages were dropped instead — the session continues with the recent tail intact`),gp=F(`<div class="embed compaction"><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),_p=F(`<div class="vtitle compactkept">what the agent kept`),vp=F(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),yp=F(`<div class="content muted">`);function bp(e){let[t,n]=v(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=uf(),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&&I(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 xp(e){let t=e.e,n=ef(e.prev,t),r=x(()=>e.res?.(),void 0,{equals:(e,t)=>e?.id===t?.id}),i=()=>r(),a=()=>!e.agentActive&&!i(),o=t.data??{},s=String(o.name??`tool`),c=()=>String(i()?.data?.result??``),l=e=>String(o.args?.[e]??``),u=()=>s===`bash`?l(`command`):l(`path`)||JSON.stringify(o.args??{},null,1),d=()=>s===`bash`?lf(l(`timeout_ms`)):s===`wait_children`?Number(l(`timeout_ms`))||3e5:Number(l(`timeout_ms`))||void 0,f=(e,t=1500,n)=>j(hd,{get text(){return He(e,t)},lang:n}),p=()=>j(hd,{get text(){return JSON.stringify(o.args??{},null,1)},lang:`json`}),m=()=>(()=>{let e=i();return e?[P(()=>P(()=>!!Ju(c()))()?j(md,{get text(){return c()}}):j(hd,{get text(){return of(c())},get lang(){return af(c())}})),(()=>{var t=df();return R(t,()=>Ve(e.data?.durationMs),null),R(t,()=>s===`bash`?nf(tf(e.data?.ok,String(e.data?.result??``))):e.data?.ok===!1?` · FAILED`:``,null),R(t,j(zu,{get text(){return P(()=>!!Ju(c()))()?qu(c()):of(c())}}),null),t})()]:ff()})(),h=x(()=>{i();let e=s,t=``,n=p();try{switch(s){case`bash`:{let r=l(`command`),a=o.args?.background===!0,s=a?String(c()).match(/job (bg\d+)/)?.[1]??``:``;e=(a?`⏳ `:`$ `)+Zd(r,96);let u=l(`timeout_ms`)?Number(l(`timeout_ms`)):void 0,d=i(),f=tf(d?.data?.ok,d?String(d.data?.result??``):``);t=d?a?`background job${s?` ${s}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:rf({outcome:f,durationMs:d.data?.durationMs,timeoutMs:u,fmtDur:Ve}):null,n=[a?(()=>{var e=pf(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,R(t,s||`?`,n),R(e,s?[` · kill with `,mf()]:null,null),e})():null,P(()=>P(()=>r!==e.slice(2))()?j(hd,{text:r,lang:`shellscript`}):null),P(m)];break}case`read_file`:{e=l(`path`)||`(no path)`;let r=[];l(`pattern`)&&r.push(`grep /${Zd(l(`pattern`),40)}/`),Number(o.args?.offset)<0?r.push(`last ${-Number(o.args.offset)} lines`):o.args?.offset&&r.push(`from L${o.args.offset}`),o.args?.limit&&r.push(`≤${o.args.limit} lines`),t=r.join(` · `),n=m();break}case`write_file`:{let r=String(o.args?.content??``);e=l(`path`)||`(no path)`,t=`${Xd(r.length)} bytes`,n=[P(()=>f(r,1500)),P(()=>P(()=>r.length>1500)()?(()=>{var e=hf(),t=e.firstChild;return R(e,()=>Xd(r.length),t),e})():null),P(()=>P(()=>!!i())()?(()=>{var e=df();return R(e,()=>Zd(c(),160)),e})():gf())];break}case`edit_file`:e=l(`path`)||`(no path)`,t=o.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=_f();return R(e,()=>He(`- `+l(`old_text`),900)),e})(),(()=>{var e=vf();return R(e,()=>`+ `+He(l(`new_text`),900)),e})(),P(()=>P(()=>!!i())()?(()=>{var e=yf(),t=e.firstChild;return R(e,()=>Zd(c(),120),t),R(e,()=>Ve(i().data?.durationMs),null),e})():bf())];break;case`apply_patch`:{let t=l(`patch`).split(`
25
- `).filter(e=>e&&!/^---$/.test(e.trim())),r=t.map(e=>e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/)?.[1]).filter(Boolean);e=r.length?`${r.length} file${r.length>1?`s`:``}: ${Zd(r.join(`, `),80)}`:`patch`;let a=t.slice(0,60);n=[(()=>{var e=xf();return R(e,()=>a.map(e=>{let t=e.startsWith(`+`)?` add`:e.startsWith(`-`)?` del`:/^\*\*\*|^@@/.test(e)?` meta`:``;return(()=>{var n=Sf();return L(n,`pline`+t),R(n,(()=>{var t=P(()=>e.length>240);return()=>t()?e.slice(0,240)+`…`:e})()),n})()}),null),R(e,(()=>{var e=P(()=>t.length>60);return()=>e()?(()=>{var e=Cf(),n=e.firstChild.nextSibling;return n.nextSibling,R(e,()=>t.length-60,n),e})():null})(),null),e})(),P(()=>P(()=>!!i())()?(()=>{var e=df();return R(e,()=>Zd(c().split(`
26
- `)[0]??``,140),null),R(e,()=>i().data?.ok===!1?` · FAILED`:``,null),e})():wf())];break}case`list_dir`:e=l(`path`)||`.`,n=m();break;case`read_url`:{let r=l(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=Zd(r,70),t=`web`,n=[(()=>{var e=df();return R(e,j(N,{get when(){return/^https?:/i.test(l(`url`))},get fallback(){return(()=>{var e=Ef();return R(e,()=>Zd(l(`url`),80)),e})()},get children(){var e=Tf();return y(()=>I(e,`href`,l(`url`))),e}})),e})(),P(m)];break}case`bash_output`:{let r=l(`action`)||`read`;e=`bash_output ${l(`job_id`)||`(?)`}`,t=r,n=m();break}case`load_skill`:{e=`skill: ${l(`name`)}`;let t=c().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=i()?[(()=>{var e=Df();return y(()=>e.innerHTML=Ie(t)),e})(),(()=>{var e=df();return R(e,()=>Ve(i().data?.durationMs)),e})()]:Of();break}case`save_skill`:{e=`skill: ${l(`name`)}`,t=Zd(l(`description`),60);let r=Array.isArray(o.args?.files)?o.args.files.map(e=>e?.name).filter(Boolean):[];n=[P(()=>P(()=>!!r.length)()?(()=>{var e=kf();return e.firstChild,R(e,()=>r.join(`, `),null),e})():null),P(()=>P(()=>!!i())()?(()=>{var e=yf(),t=e.firstChild;return R(e,()=>Zd(c(),160),t),R(e,()=>Ve(i().data?.durationMs),null),e})():Af())];break}default:e=s,t=i()?Ve(i().data?.durationMs):null,n=[P(p),P(m)]}}catch{}return{label:e,hint:t,body:n,key:`${i()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var r=Mf(),o=r.firstChild,l=o.firstChild,f=l.nextSibling,p=f.nextSibling;return r.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),R(l,()=>h().label),R(o,j(N,{get when(){return t.data?.actor},get children(){var e=jf();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),f),R(f,(()=>{var e=P(()=>!!i());return()=>e()?h().hint||``:P(()=>!!a())()?`(result missed)`:P(()=>!!(s===`bash`||d()))()?j(fd,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return d()}}):`running…`})()),R(p,j(zu,{get text(){return u()},label:`⧉ cmd`,title:`copy the ${s} arguments`}),null),R(p,j(N,{get when(){return i()},get children(){return j(zu,{get text(){return P(()=>!!Ju(c()))()?qu(c()):c()},label:`⧉ out`,title:`copy this tool's full output (escapes removed)`})}}),null),R(r,()=>h().body,null),y(e=>{var t=`embed`+(n?` grouped`:``)+(i()?i().data?.ok===!1?` fail`:` done`:a()?` done`:` running`),o=`${s}${h().hint?` — `+h().hint:``}`;return t!==e.e&&L(r,e.e=t),o!==e.t&&I(r,`title`,e.t=o),e},{e:void 0,t:void 0}),r})()}function Sp(e){let t=e.e,n=qd(t),r=()=>ef(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&ef(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=Nf(),r=n.firstChild.nextSibling;return r.nextSibling,R(n,()=>String(e.fromBranch??`?`),r),R(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=St(t.data??{});return(()=>{var t=Pf(),n=t.firstChild;return R(n,()=>e.label),R(t,j(N,{get when(){return e.hasCard},get children(){return j(Dt,{get tone(){return P(()=>e.tone===`ok`)()?`ok`:e.tone===`warn`?`warn`:`tool`},get markdown(){return e.markdown},get body(){return e.detail}})}}),null),y(()=>L(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`audit_step`){let e=String(t.data?.step??``),n=String(t.data?.name??``),r=e===`started`?`🔍️ auditor started`:e===`tool`?`🔍️ auditor → ${n}`:e===`tool_done`?`🔍️ auditor ← ${n} ${t.data?.ok===!1?`failed`:`${String(t.data?.chars??0)} chars`}`:e===`reply`?`🔍️ auditor replied`:`🔍️ auditor`;return(()=>{var n=Lf(),i=n.firstChild,a=i.firstChild;return R(a,r),R(i,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=Ff();return R(e,()=>He(String(t.data?.args??``),120)),e}}),null),R(n,j(N,{get when(){return e===`reply`&&t.data?.text},get children(){var e=If();return R(e,()=>String(t.data?.text??``)),e}}),null),R(n,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=If();return R(e,()=>String(t.data?.args??``)),e}}),null),n})()}if(t.type===`todo`)return(()=>{var e=Rf(),n=e.firstChild.nextSibling;return n.nextSibling,R(e,()=>String(t.data?.by??`human`),n),e})();if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=zf(),n=e.firstChild;return R(e,()=>t.data.from,n),R(e,()=>t.data.to,null),R(e,(()=>{var e=P(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),y(()=>L(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=Bf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,R(n,()=>String(t.data?.failures),r),R(n,()=>String(t.data?.limit),i),R(a,()=>String(t.data?.lastTool),o),R(a,()=>String(t.data?.lastError??``).slice(0,200),null),y(()=>I(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=Vf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(n,()=>String(t.data?.attempt),r),R(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=Sf();return L(r,`divider-msg`+(e?` err`:``)),R(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),y(()=>I(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=Hf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.tokensBefore??`?`),n),R(e,()=>String(t.data?.tokensAfter??`?`),r),R(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=Uf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.messages??`?`),n),R(e,()=>String(t.data?.tokensBefore??`?`),r),R(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=Jf(),o=a.firstChild,s=o.nextSibling;return R(o,(()=>{var e=P(()=>!!r());return()=>e()?``:n.icon})()),R(s,(()=>{var e=P(()=>!!r());return()=>e()&&(()=>{var e=Yf();return y(()=>I(e,`title`,`${Jd(t.ts)} · ${t.branch}`)),e})()})(),null),R(s,j(N,{get when(){return!r()},get children(){var r=qf(),i=r.firstChild,a=i.nextSibling;return R(i,()=>n.name),R(r,j(N,{get when(){return t.data?.actor},get children(){var e=jf();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),a),R(a,(()=>{var e=P(()=>!!t.data?.pending);return()=>e()?`queued…`:P(()=>!!t.data?.cancelled)()?`withdrawn`:Jd(t.ts)})()),R(r,j(N,{get when(){return e.showBranch},get children(){var e=Wf();return R(e,()=>t.branch),e}}),null),R(r,j(N,{get when(){return e.onCancel},get children(){var t=Gf();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),R(r,j(N,{get when(){return t.type!==`tool_call`},get children(){return j(zu,{get text(){return Yd(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),R(r,j(N,{get when(){return e.onEdit},get children(){var t=Kf();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),y(()=>L(i,`author tone-${Kd(n.color)}`)),r}}),null),R(s,j(Cp,{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 tone-${Kd(n.color)}`+(r()?` ghosted`:``),u=r()?`${Jd(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&L(a,e.e=s),c!==e.t&&I(a,`data-eid`,e.t=c),l!==e.a&&L(o,e.a=l),u!==e.o&&I(o,`title`,e.o=u),e},{e:void 0,t:void 0,a:void 0,o:void 0}),a})()}function Cp(e){let t=e.e;switch(t.type){case`prompt`:{let e=(t.data?.images??[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0);return[(()=>{var e=Df();return y(()=>e.innerHTML=vd(String(t.data.text??``))),e})(),j(N,{get when(){return e.length},get children(){var t=Xf();return R(t,j(M,{each:e,children:e=>(()=>{var t=Zf();return I(t,`src`,e),t})()})),t}})]}case`message`:return[j(N,{get when(){return P(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=Qf(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.reasoning)),e}}),(()=>{var e=Df();return y(()=>e.innerHTML=vd(String(t.data.content??``))),e})(),j(N,{get when(){return t.data.interrupted},get children(){return $f()}}),j(N,{get when(){return t.data.final},get children(){var e=ep(),n=e.firstChild;return R(e,j(zu,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return j(xp,{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=np(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return L(a,`embed `+(i?``:`fail`)),R(s,r===`bash`?`$ (bash, call evicted)`:r),R(o,j(zu,{text:n}),null),R(c,n),R(l,()=>Ve(t.data.durationMs),null),R(l,()=>r===`bash`?nf(tf(t.data.ok,n)):i?``:` · FAILED`,null),R(a,j(N,{get when(){return e.orphan},get children(){return tp()}}),null),y(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=ip(),r=n.firstChild,i=r.firstChild.firstChild.nextSibling,a=r.nextSibling;return R(n,j(N,{get when(){return e.length},get children(){var t=rp();return t.firstChild,R(t,()=>e.join(` / `),null),t}}),null),y(e=>{var n=vd(String(t.data?.decision??``)),r=vd(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=sp(),o=a.firstChild.firstChild.nextSibling;return R(a,j(N,{get when(){return i()},get children(){return ap()}}),null),R(a,j(N,{get when(){return n.length>0},get children(){var a=op();return R(a,j(M,{each:n,children:n=>(()=>{var a=cp();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?Q(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>Hd(`→ answered @${String(t.data.actor)}`)).catch(()=>Hd(`answer failed`)):e.onOption?.(n)},R(a,n),y(()=>a.disabled=i()),a})()})),a}}),null),R(a,j(bp,{get answered(){return i()},get onOption(){return e.onOption}}),null),y(e=>{var n=`embed question`+(i()?` answered`:``),r=vd(String(t.data?.question??``));return n!==e.e&&L(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=pp(),n=e.firstChild.firstChild.nextSibling;return R(e,j(N,{get when(){return t.data.goalStatus},get children(){var e=lp(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.goalStatus)),e}}),null),R(e,j(N,{get when(){return t.data.recent},get children(){var e=up(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=vd(String(t.data.recent))),e}}),null),R(e,j(N,{get when(){return t.data.problems},get children(){var e=dp(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=vd(String(t.data.problems))),e}}),null),R(e,j(N,{get when(){return t.data.next},get children(){var e=fp(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=vd(String(t.data.next))),e}}),null),y(()=>n.innerHTML=vd(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=mp(),n=e.firstChild;return n.firstChild,R(n,()=>String(t.data.message??``),null),e})();case`compaction`:return t.data.summary?(()=>{var e=vp(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Xd(Number(t.data.tokensBefore??0)),i),R(n,()=>Xd(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(e,j(N,{get when(){return t.data.summary},get children(){return[_p(),(()=>{var e=Df();return y(()=>e.innerHTML=vd(String(t.data.summary))),e})()]}}),null),e})():(()=>{var e=gp(),n=e.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Xd(Number(t.data.tokensBefore??0)),i),R(n,()=>Xd(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(n,()=>String(t.data.mode??``)===`truncate`?` · older history dropped`:``,null),R(e,j(N,{get when(){return String(t.data.mode??``)===`truncate`},get children(){return hp()}}),null),e})();default:return(()=>{var e=yp();return R(e,()=>He(JSON.stringify(t.data),200)),e})()}}we([`input`,`keydown`,`click`]);var wp=(e,t)=>{let n=String(t??``).trim();return!n||/^\d+$/.test(n)?null:e?.[n]??null},Tp=[{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)`}];function Ep(e,t){return e?t===`dark`?{slot:`dark`,key:`teapot.theme.dark`}:{slot:`light`,key:`teapot.theme.light`}:{slot:`fixed`,key:`teapot.theme`}}var Dp=F(`<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`),Op=F(`<div class=muted style="margin:6px 0">`),kp=F(`<b>+ duplicate current`),Ap=F(`<div class=cfggrid style=margin-top:8px><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),jp=F(`<div class=paletterows>`),Mp=F(`<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`),Np=F(`<h4 class=cfgsub>background image`),Pp=F(`<img sizes=260px alt="current background"decoding=async loading=lazy>`,!0,!1,!1),Fp=F(`<span class=bgpick-hint>🖼 replace…`),Ip=F(`<div class=bgpreview><span class=muted title="this image is served from the server; the theme stores only its URL">✓ image set</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><label title="how much of the background shows through code blocks and tool cards — lower is more transparent">surfaces<input type=range min=0.35 max=1 step=0.01><span class="muted mono">%</span></label><button type=button>✕ remove`),Lp=F(`<div class=cfggrid><button type=button></button><input type=file accept=image/* style=display:none>`),Rp=F(`<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.`),zp=F(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),Bp=F(`<span class=bgpick-empty>🖼 choose a background image…`),Vp=F(`<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.`),Hp=F(`<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>`),Up=F(`<div class=skilllist>`),Wp=F(`<span style=color:var(--err);font-size:13px>`),Gp=F(`<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=cfgrow><label style=flex:1>API password<input type=password class=w100></label><span class=muted style=font-size:11.5px;max-width:34ch>bearer token for /api. empty = loopback only.</span></div><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</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 class=primarybtn>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>skills</legend></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>this host</h4><div class=featgrid><div class=featrow><b>image downscaling</b><span class=muted></span></div><div class=featrow><b>terminal pty</b><span class=muted></span></div></div></div><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><span class=kbdgroup><kbd>↑</kbd><kbd>↓</kbd></span><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>`),Kp=F(`<button type=button><span class=cfgmenu-label>`),qp=F(`<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`),Jp=F(`<button type=button title="remove this key">−`),Yp=F(`<div class=cfgkeyrow><input type=password>`),Xp=F(`<button type=button>+ `),Zp=F(`<option>`),Qp=F(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),$p=F(`<div class=themepick>`),em=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),tm=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),nm=F(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),rm=F(`<input placeholder="command (e.g. npx)">`),im=F(`<input placeholder="args, space separated">`),am=F(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),om=F(`<input placeholder="header name"style="flex:0 1 150px">`),sm=F(`<input type=password placeholder=value style=flex:1>`),cm=F(`<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>`),lm=F(`<button type=button class=mcpauthorize title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),um=F(`<span class="mcpstate connected"title="an OAuth access token is usable — disconnect it under the server's details">🔑 authorized`),dm=F(`<span>`),fm=F(`<div class=muted style=font-size:11px;color:var(--warn)>`),pm=F(`<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`),mm=F(`<option value=oauth selected>`),hm=F(`<span class=muted> · needs a grant (🔑 authorize)`),gm=F(`<details class=mcptools-wrap><summary>show <!> tool</summary><ul class=mcptools>`),_m=F(`<div class=mcpdanger><span class=muted>OAuth grant</span><button type=button class=mcpdisconnect title="forget the stored grant (the refresh token is deleted, so authorizing again needs a browser)">disconnect`),vm=F(`<div><div class=mcpresult-head><b>`),ym=F(`<span class=mcptool-desc>`),bm=F(`<li><code class=mono>`),xm=F(`<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">`),Sm=F(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),Cm=F(`<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`),wm=F(`<span class=muted>🧩 sub of @`),Tm=F(`<div class=cfgrow><b></b><span class=muted>`),Em=F(`<div class=muted>`),Dm=F(`<div class=skillbody>`),Om=F(`<div class=skillrow><button type=button class=skillhead title="show the playbook"><span class=skillcaret></span><b class=mono></b><span class=muted>`),km=F(`<div class="muted skillbody">`);function Am(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.find(t=>t.id===e.activeId)??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=Pn(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.paintedId),r=gd.find(t=>t.key===e.paintedId),i=t??r??gd[0],a=getComputedStyle(document.documentElement),o={...wn};for(let{key:e,cssVar:t}of Sn){let n=Pn(a.getPropertyValue(t));n&&(o[e]=n)}let s=jn(e.themes().map(e=>e.id).concat(gd.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,surfaceAlpha:t.surfaceAlpha}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))Hd(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{Hd(`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){Hd(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url,backgroundImageBytes:n.body.bytes}));let i=r()?.id;i&&e.onPick(i),Hd(`background image set`)}catch(e){Hd(`upload failed: ${e.message}`)}}}};return(()=>{var t=Dp(),d=t.firstChild.nextSibling.firstChild;return d.$$click=l,R(t,j(N,{get when(){return P(()=>!!(r()&&e.themes().some(t=>t.id===e.activeId)))()?r():null},get fallback(){return(()=>{var t=Op();return R(t,(()=>{var t=P(()=>e.themes().length===0);return()=>t()?[`no custom themes yet — press `,kp(),` to start from the palette you are using.`]:[`the editor shows when one of your themes is ACTIVE — pick one under "your themes" above (or press `,kp(),`).`]})()),t})()},children:t=>[(()=>{var e=Ap(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),y(()=>t.value=r().mode),e})(),(()=>{var e=jp();return R(e,j(M,{each:Sn,children:e=>(()=>{var t=zp(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),R(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)},I(s,`spellcheck`,!1),y(()=>I(t,`title`,e.cssVar)),y(()=>n.value=Pn(r().palette[e.key])??`#000000`),y(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=Mp(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...wn}})),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})(),Np(),(()=>{var e=Lp(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),R(t,j(N,{get when(){return r().backgroundImage},get fallback(){return Bp()},get children(){return[(()=>{var e=Pp();return y(t=>{var n=Mt(r().backgroundImage),i=jt(r().backgroundImage);return n!==t.e&&I(e,`src`,t.e=n),i!==t.t&&I(e,`srcset`,t.t=i),t},{e:void 0,t:void 0}),e})(),Fp()]}})),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`?Oe(i,n):o=n,R(e,j(N,{get when(){return r().backgroundImage},get children(){var e=Ip(),t=e.firstChild;t.firstChild;var n=t.nextSibling.firstChild,i=n.firstChild.nextSibling,a=i.nextSibling,o=a.firstChild,c=n.nextSibling,l=c.firstChild.nextSibling,u=l.nextSibling,d=u.firstChild,f=c.nextSibling;return R(t,()=>{let e=r()?.backgroundImageBytes;return e?` — ${Math.max(1,Math.round(e/1024))} KB`:``},null),i.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),R(a,()=>Math.round((r().backgroundDim??.55)*100),o),l.$$input=e=>s(t=>({...t,surfaceAlpha:Number(e.currentTarget.value)})),R(u,()=>Math.round((r().surfaceAlpha??.82)*100),d),f.$$click=()=>s(e=>({...e,backgroundImage:void 0})),y(()=>i.value=r().backgroundDim??.55),y(()=>l.value=r().surfaceAlpha??.82),e}}),null),y(e=>{var n=`bgpick`+(r().backgroundImage?` has`:``),i=r().backgroundImage?`click to replace this background image (PNG/JPG/WebP)`:`choose a background image (PNG/JPG/WebP)`;return n!==e.e&&L(t,e.e=n),i!==e.t&&I(t,`title`,e.t=i),e},{e:void 0,t:void 0}),e})(),Rp()]}),null),t})()}function jm(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,te]=v(``),[ne,w]=v(!1),[T,E]=v((e.cfg.tasks??[]).map(e=>({...e}))),[D,O]=v((e.cfg.mcpServers??[]).map(e=>({...e}))),[re,k]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ie,ae]=v({}),[oe,se]=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`]}))),[ce,le]=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]??``]}))),[ue,A]=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:``]}))),[de,fe]=v({}),pe={},me=async(e,t)=>{if(!D()[e])return;let n=await Q(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).catch(()=>null);D()[e]&&n&&fe(t=>({...t,[e]:n.ok?{kind:`ok`,text:`${n.tools?.length??0} tools`}:{kind:`err`,text:n.needsOAuth?`needs authorization — press 🔑`:n.error??`no response`,...n.needsOAuth?{needsOAuth:!0}:{}}}))},[he,ge]=v({}),[_e,ve]=v({}),ye=e=>{let t=wp(_e(),e);return t&&(t.required||t.authorized)?t:null},xe=async()=>{let e=await Q(`/api/mcp`).catch(()=>null);ge(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},Se=async e=>{let t=String(e??``).trim();if(!t)return;let n=await Q(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&ve(e=>({...e,[t]:n}))},Ce=async(t,n)=>{if(!n.name){fe(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}fe(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await Q(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name,url:n.url})}).catch(()=>null);if(r?.alreadyAuthorized){fe(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await Se(n.name),await xe();return}if(!r?.ok||!r.url){fe(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await Se(n.name);return}window.open(r.url,`_blank`,`noopener`),fe(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 Q(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(ve(e=>({...e,[n.name]:r})),r.authorized){fe(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await xe(),e.onSaved();return}if(r.flow?.phase===`error`){fe(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}fe(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};b(()=>{Te()===`mcp`&&(xe(),D().forEach((e,t)=>{e.name&&Se(e.name)}))});let[F,we]=v(``),[Te,Ee]=v(`providers`),De=(t,n)=>{let{slot:r}=Ep(e.theme.auto(),n);r===`dark`?Ke(t):r===`light`?Je(t):Ve(t)},Oe=t=>e.theme.auto()?t===e.theme.dark()||t===e.theme.light():t===e.theme.activeId(),[ke,Ae]=v([]),je=async()=>{let e=await Q(`/api/archived`).catch(()=>null);Ae(e?.agents??[])},Me=()=>ke().filter(e=>!e.parent);b(()=>{Te()===`archive`&&je()});let Ne=[{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:`skills`,label:`🧠 skills`,hint:`reusable playbooks available to the selected session`},{key:`help`,label:`❔️ help`,hint:`keyboard shortcuts and what each toggle does`}],Pe=()=>(e.cfg.agents??[]).map(e=>e.id),Fe=()=>e.theme.themes(),Ie=()=>e.theme.activeId(),Le={auto:localStorage.getItem(`teapot.theme.auto`)===`1`,dark:localStorage.getItem(`teapot.theme.dark`)??`dark`,light:localStorage.getItem(`teapot.theme.light`)??`light`,fixed:localStorage.getItem(`teapot.theme`)??`dark`},Re=v(Le),ze=Re[0],Be=t=>{let n={...ze(),...t};Re[1](n),e.theme.setAuto(n.auto),e.theme.setDark(n.dark),e.theme.setLight(n.light),e.theme.setActive(n.fixed);let r=t.dark??t.light??t.fixed;r&&e.theme.preview(r)},Ve=e=>Be({fixed:e}),He=()=>ze().auto,We=e=>Be({auto:e}),Ge=()=>ze().dark,Ke=e=>Be({dark:e}),qe=()=>ze().light,Je=e=>Be({light:e}),Ye=t=>e.theme.setThemes(t),Xe=()=>{let t=Le;e.theme.setAuto(t.auto),e.theme.setDark(t.dark),e.theme.setLight(t.light),e.theme.setActive(t.fixed),e.theme.preview(null)},Ze=e=>Tn[e]??wn,Qe=()=>{let e={};for(let t of n()){if(!t.name.trim())return we(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return we(`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},[$e,et]=v(`idle`),tt=e=>{we(e),et(e=>e===`saving`?`idle`:e)},nt=async t=>{t.preventDefault(),we(``),et(`saving`);let n=Qe();if(!n)return et(`idle`);let r=T().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)return tt(`task "${e.id}": agent is required`);if(!e.schedule?.trim())return tt(`task "${e.id}": schedule is required`)}let a=[],o=new Set;for(let e of D()){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)return tt(`MCP: a server needs a name`);if(o.has(t))return tt(`MCP: two servers are named "${t}"`);if(o.add(t),r===`stdio`?!i:!n)return tt(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);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 Q(`/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(),...ne()?{password:C()}:{},tasks:r,mcpServers:a})}),await xe(),await Promise.all(a.map((e,t)=>e.name?Se(e.name):Promise.resolve())),setTimeout(()=>{xe(),a.forEach((e,t)=>{e.name&&Se(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=D().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&_e()[n]?.required&&!_e()[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??``));Hd(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}e.theme.commitAppearance(ze()),e.theme.preview(null),et(`saved`),Object.assign(Le,ze()),setTimeout(()=>{et(`idle`),e.onClose()},400)}catch(e){we(e.message),et(`error`),setTimeout(()=>et(`idle`),1600)}};return j(Bu,{title:`settings`,onClose:()=>{Xe(),e.onClose()},get children(){var t=Gp(),b=t.firstChild,ne=b.firstChild,ge=ne.nextSibling.firstChild,ve=ge.firstChild.nextSibling,xe=ve.nextSibling;xe.firstChild;var ke=xe.nextSibling.firstChild.firstChild.nextSibling;ke.firstChild;var Ae=ge.nextSibling,Le=Ae.firstChild.nextSibling,Re=Le.firstChild.firstChild.nextSibling,ze=Le.nextSibling,Be=Ae.nextSibling,Xe=Be.firstChild.nextSibling,Qe=Xe.firstChild.firstChild.nextSibling,et=Xe.nextSibling,tt=et.firstChild,rt=tt.firstChild.nextSibling,it=et.nextSibling.firstChild,at=Be.nextSibling,ot=at.firstChild.nextSibling.nextSibling,st=at.nextSibling,ct=st.firstChild.nextSibling,lt=st.nextSibling;lt.firstChild;var ut=lt.nextSibling;ut.firstChild;var dt=ut.nextSibling,ft=dt.firstChild.nextSibling.firstChild;ft.firstChild;var pt=ft.nextSibling,mt=dt.nextSibling;mt.firstChild;var ht=mt.nextSibling,gt=ht.firstChild.nextSibling.firstChild.nextSibling.firstChild,_t=gt.firstChild.nextSibling,vt=gt.nextSibling.firstChild.nextSibling,yt=b.nextSibling,bt=yt.firstChild;return t.addEventListener(`submit`,nt),R(ne,j(M,{each:Ne,children:e=>(()=>{var t=Kp(),n=t.firstChild;return t.$$click=()=>Ee(e.key),R(n,()=>e.label),y(n=>{var r=`cfgmenu-item`+(Te()===e.key?` on`:``),i=e.hint,a=Te()===e.key?`page`:void 0;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),R(ge,j(be,{get each(){return n()},children:(e,t)=>(()=>{var i=qp(),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)),R(l,j(M,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=Yp(),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,R(o,j(N,{get when(){return e().apiKeys.length>1},get children(){var e=Jp();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),y(()=>I(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})()}),ve),ve.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),R(xe,j(M,{each:Tp,children:e=>(()=>{var t=Xp();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)},R(t,()=>e.label,null),y(()=>I(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ke.addEventListener(`change`,e=>a(e.currentTarget.value)),R(ke,j(M,{get each(){return s()},children:e=>(()=>{var t=Zp();return t.value=e,R(t,e),t})()}),null),R(ge,j(N,{get when(){return c()},get children(){var e=Vp(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return R(t,c),R(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),R(r,c),e}}),null),Re.addEventListener(`change`,e=>{We(e.currentTarget.checked)}),R(Ae,j(N,{get when(){return He()},get children(){var e=Hp(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ke(e.currentTarget.value)}),R(n,j(M,{get each(){return Fe().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(gd.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=Zp();return R(t,()=>e.label),y(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{Je(e.currentTarget.value)}),R(r,j(M,{get each(){return Fe().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(gd.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=Zp();return R(t,()=>e.label),y(()=>t.value=e.key),t})()})),y(()=>n.value=Ge()),y(()=>r.value=qe()),e}}),ze),R(Ae,j(M,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>j(N,{get when(){return[...Fe(),...gd].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=Qp();return R(t,()=>e.title),t})(),(()=>{var t=$p();return R(t,j(M,{get each(){return Fe().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=em(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>De(e.id,e.mode),R(n,j(Rd,{get palette(){return e.palette},get backgroundImage(){return e.backgroundImage},get surfaceAlpha(){return e.surfaceAlpha},get backgroundDim(){return e.backgroundDim}})),R(r,()=>e.label,i),y(n=>{var r=`themecard`+(Oe(e.id)?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Oe(e.id);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(t,j(M,{get each(){return gd.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=tm(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>De(e.key,e.mode),R(n,j(Rd,{get palette(){return Ze(e.key)}})),R(r,()=>e.label),y(n=>{var r=`themecard`+(Oe(e.key)?` on`:``),i=`${e.label} (${e.mode})`,a=Oe(e.key);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),R(Ae,j(Am,{themes:Fe,get activeId(){return Ie()},get paintedId(){return e.theme.paintedId()},onChange:e=>{let t=kn(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0,surfaceAlpha:void 0,backgroundImageBytes:void 0}:e),r=kn(t);if(r.ok)n=t,Hd(`storage was full — saved without the background image(s)`);else{Hd(r.error??`could not save theme`);return}}Ye(n);let r=e=>n.some(t=>t.id===e)||gd.some(t=>t.key===e);r(Ie())||(Ve(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(Ge())||(Ke(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(qe())||(Je(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{let t=Fe().find(t=>t.id===e)?.mode??gd.find(t=>t.key===e)?.mode??`dark`,n=Ep(He(),t);n.slot===`dark`?Ke(e):n.slot===`light`?Je(e):Ve(e)}}),null),Qe.$$input=e=>{te(e.currentTarget.value),w(!0)},R(et,j(Ld,{label:`progress interval (min)`,get value(){return l()},onValue:e=>u(e),hint:`how often the harness asks for a progress report`}),tt),R(et,j(Ld,{label:`progress min chars`,get value(){return d()},onValue:e=>f(e),hint:`progress prompts wait for this much real output`}),tt),rt.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),R(et,j(Ld,{label:`context window (k tok)`,get value(){return h()},onValue:e=>g(e),hint:`model's real window — 0/blank hides the % gauge`}),null),R(et,j(Ld,{label:`max spawn depth`,get value(){return _()},onValue:e=>x(e),hint:`sub-agent nesting limit (0 = no spawning)`}),null),it.addEventListener(`change`,e=>ee(e.currentTarget.checked)),R(at,j(N,{get when(){return D().length>0},get fallback(){return nm()},get children(){return j(be,{get each(){return D()},children:(e,t)=>{let n=()=>he()[e().name],r=e=>O(D().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=pm(),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=m.firstChild,g=p.nextSibling,_=g.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>{r({url:e.currentTarget.value});let n=e.currentTarget.value.trim();clearTimeout(pe[t]),/^https?:\/\//.test(n)&&(pe[t]=setTimeout(()=>{me(t,{...D()[t],url:n})},700))},l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>O(D().filter((e,n)=>n!==t)),f.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),R(d,j(N,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=rm();return t.$$input=e=>r({command:e.currentTarget.value}),y(()=>t.value=e().command??``),t})(),(()=>{var t=im();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(se(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ce()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=ue()[t]??``,n=ce()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),R(m,j(N,{get when(){return ye(String(e().name??``))},children:e=>(()=>{var t=mm();return R(t,()=>e().authorized?`OAuth — authorized`:`OAuth — authorization needed`),t})()}),h),R(p,j(N,{get when(){return oe()[t]===`bearer`},get children(){var e=am();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},y(()=>e.value=ce()[t]??``),e}}),null),R(p,j(N,{get when(){return oe()[t]===`header`},get children(){return[(()=>{var e=om();return e.$$input=e=>{let n=e.currentTarget.value;A(e=>({...e,[t]:n}));let i=ce()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},y(()=>e.value=ue()[t]??``),e})(),(()=>{var e=sm();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n}));let i=ue()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},y(()=>e.value=ce()[t]??``),e})()]}}),null),R(i,j(N,{get when(){return oe()[t]===`json`},get children(){var e=cm(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(k(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}),ae(e=>({...e,[t]:``}))}catch{ae(e=>({...e,[t]:`must be a JSON object — not applied`}))}},y(()=>n.value=re()[t]??``),e}}),g),_.$$click=async()=>{let e=D()[t];if(!e.name){fe(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}fe(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await Q(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);fe(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 Se(e.name)},R(g,j(N,{get when(){return P(()=>!!wp(_e(),String(e().name??``))?.required)()&&!wp(_e(),String(e().name??``))?.authorized},get children(){var n=lm();return n.$$click=()=>void Ce(t,e()),n}}),null),R(g,j(N,{get when(){return wp(_e(),String(e().name??``))?.authorized},get children(){return um()}}),null),R(g,j(N,{get when(){return n()},get children(){var e=dm();return R(e,(()=>{var e=P(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:P(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),y(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&L(e,t.e=r),i!==t.t&&I(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),R(i,j(N,{get when(){return ie()[t]},get children(){var e=fm();return R(e,()=>ie()[t]),e}}),null),R(i,j(N,{get when(){return de()[t]},children:n=>(()=>{var r=vm(),i=r.firstChild,a=i.firstChild;return R(a,()=>n().text),R(i,j(N,{get when(){return n().needsOAuth},get children(){return hm()}}),null),R(r,j(N,{get when(){return(n().tools?.length??0)>0},get children(){var e=gm(),t=e.firstChild,r=t.firstChild.nextSibling;r.nextSibling;var i=t.nextSibling;return R(t,()=>n().tools?.length,r),R(t,()=>n().tools?.length===1?``:`s`,null),R(i,j(M,{get each(){return n().tools??[]},children:e=>(()=>{var t=bm(),n=t.firstChild;return R(n,()=>e.name),R(t,j(N,{get when(){return e.description},get children(){var t=ym();return R(t,()=>e.description),t}}),null),y(()=>I(t,`title`,e.description??``)),t})()})),e}}),null),R(r,j(N,{get when(){return wp(_e(),String(e().name??``))?.authorized},get children(){var n=_m(),r=n.firstChild.nextSibling;return r.$$click=async()=>{confirm(`Disconnect ${e().name}?\n\nThe stored OAuth grant is deleted and you will have to authorize again in a browser.`)&&(await Q(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await Se(e().name),fe(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}})))},n}}),null),y(()=>L(r,`mcpresult `+(n().kind===`err`?`err`:`ok`))),r})()}),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=ye(String(e().name??``))?`oauth`:oe()[t]??`none`),i})()}})}}),ot),ot.$$click=()=>O([...D(),{name:``,url:``,transport:`http`,enabled:!0}]),R(st,j(N,{get when(){return T().length>0},get children(){return j(be,{get each(){return T()},children:(e,t)=>(()=>{var n=xm(),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=>E(T().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>E(T().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>E(T().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>E(T().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>E(T().filter((e,n)=>n!==t)),u.$$input=e=>E(T().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})()})}}),ct),ct.$$click=()=>E([...T(),{id:``,agent:Pe()[0]??``,schedule:`every 30m`,prompt:``}]),R(lt,j(N,{get when(){return Me().length>0},get fallback(){return Sm()},get children(){return j(M,{get each(){return Me()},children:t=>(()=>{var n=Cm(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return R(i,()=>t.id),R(a,()=>t.sessions,o),R(a,()=>t.sessions===1?``:`s`,null),R(a,(()=>{var e=P(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),R(a,(()=>{var e=P(()=>!!t.archivedAt);return()=>e()?` · archived ${Ue(new Date(t.archivedAt).toISOString())}`:``})(),null),R(s,()=>t.workspace),c.$$click=async()=>{let n=await Q(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await je(),e.onSaved();let r=(n?.ids?.length??1)-1;Hd((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 Q(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await je(),e.onSaved(),Hd(`deleted ${t.id} for good`))},y(()=>I(s,`title`,t.workspace)),n})()})}}),null),R(ut,j(M,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=Tm(),n=t.firstChild,r=n.nextSibling;return R(n,()=>e.id),R(r,()=>e.workspace),R(t,j(N,{get when(){return e.parent},get children(){var t=wm();return t.firstChild,R(t,()=>e.parent,null),t}}),null),t})()}),null),R(ft,()=>e.cfg.version??`unknown`,null),pt.$$click=async e=>{try{we(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await Q(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=null,i=!1;for(let e=0;e<120&&!i;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await Q(`/api/version`);if(!e.version)continue;r===null&&(r=e.uptimeSeconds??null),(e.version!==`0.37.72`||typeof e.uptimeSeconds==`number`&&r!==null&&e.uptimeSeconds<r)&&(i=!0,window.location.reload())}catch{}}if(!i)throw Error(`restart timeout — new server did not come up`)}catch(e){we(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},R(mt,j(N,{get when(){return e.skills.length>0},get fallback(){return(()=>{var t=Em();return R(t,()=>e.hasSelection?`this session has no skills yet — the agent saves them with save_skill once a procedure proves itself`:`select a session to see the skills available to it`),t})()},get children(){var t=Up();return R(t,j(M,{get each(){return e.skills},children:t=>{let[n,r]=v(!1),[i,a]=v(null),[o,s]=v(``),c=async()=>{if(n())return r(!1);if(r(!0),i()===null&&e.agentId)try{let n=await Q(`/api/agents/${e.agentId}/skills/${encodeURIComponent(t.name)}`);a(String(n.text??``))}catch(e){s(e.message)}};return(()=>{var e=Om(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,l=s.nextSibling;return r.$$click=c,R(a,()=>n()?`▾`:`▸`),R(s,()=>t.name),R(l,()=>t.description),R(e,j(N,{get when(){return n()},get children(){return j(N,{get when(){return i()!==null},get fallback(){return(()=>{var e=km();return R(e,()=>o()||`loading…`),e})()},get children(){var e=Dm();return y(()=>e.innerHTML=vd(String(i()??``))),e}})}}),null),y(()=>e.classList.toggle(`open`,!!n())),e})()}})),t}}),null),R(_t,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.imageResize.available)()?`on — ${e.features.imageResize.tool}, long edge ≤ ${e.features.imageResize.maxEdge}px`:`off — no ffmpeg / ImageMagick found; uploads are served as-is`:`checking…`})()),R(vt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.pty.available)()?`on — ${e.features.pty.provider}`:`off — no pty provider; terminals run on plain pipes (no resize)`:`checking…`})()),R(yt,j(N,{get when(){return F()},get children(){var e=Wp();return R(e,F),e}}),bt),R(bt,(()=>{var e=P(()=>$e()===`saving`);return()=>e()?`saving…`:P(()=>$e()===`saved`)()?`✓ saved`:$e()===`error`?`✕ failed`:`save settings`})()),y(t=>{var n=Te()!==`providers`,r=Te()!==`appearance`,i=Te()!==`runtime`,a=e.cfg.hasPassword?`(unchanged — type to replace)`:`(none — loopback only)`,o=Te()!==`mcp`,s=Te()!==`tasks`,c=Te()!==`archive`,l=Te()!==`agents`,u=Te()!==`update`,d=Te()!==`skills`,f=Te()!==`help`,p=$e()===`saved`,m=$e()===`error`,h=$e()===`saving`;return n!==t.e&&ge.classList.toggle(`hide`,t.e=n),r!==t.t&&Ae.classList.toggle(`hide`,t.t=r),i!==t.a&&Be.classList.toggle(`hide`,t.a=i),a!==t.o&&I(Qe,`placeholder`,t.o=a),o!==t.i&&at.classList.toggle(`hide`,t.i=o),s!==t.n&&st.classList.toggle(`hide`,t.n=s),c!==t.s&&lt.classList.toggle(`hide`,t.s=c),l!==t.h&&ut.classList.toggle(`hide`,t.h=l),u!==t.r&&dt.classList.toggle(`hide`,t.r=u),d!==t.d&&mt.classList.toggle(`hide`,t.d=d),f!==t.l&&ht.classList.toggle(`hide`,t.l=f),p!==t.u&&bt.classList.toggle(`saved`,t.u=p),m!==t.c&&bt.classList.toggle(`error`,t.c=m),h!==t.w&&(bt.disabled=t.w=h),t},{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,c:void 0,w:void 0}),y(()=>ke.value=i()),y(()=>Re.checked=He()),y(()=>Qe.value=C()),y(()=>rt.value=p()??``),y(()=>it.checked=S()),t}})}we([`click`,`input`]);var Mm=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),Nm=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Pm=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function Fm(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Im(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 Im(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return Mm.has(t)?`image`:Nm.has(t)?`video`:Pm.has(t)?`audio`:null}var Lm=new Map,Rm=e=>{let t=Lm.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},Lm.set(e,t)),t},zm=F(`<span class=fsize>`),Bm=F(`<div><span class=ficon></span><span class=fname>`),Vm=F(`<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>· `),Hm=F(`<div class=filebox>`),Um=F(`<div class=muted style=padding:6px>`),Wm=F(`<img>`),Gm=F(`<div class=mediapreview><div class="meta muted"> preview`),Km=F(`<button title="rendered markdown">👁 preview`),qm=F(`<button title="edit and save back to the workspace">✎ edit`),Jm=F(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),Ym=F(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),Xm=F(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),Zm=F(`<div class="content mdpreview shikiwrap">`),Qm=F(`<video controls>`),$m=F(`<audio controls>`);function eh(e){let t=Rm(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)},te=e=>x()!==`hide`||!e.ignored,[ne,w]=v(localStorage.getItem(`teapot.showHidden`)===`1`),T=()=>{let e=!ne(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await O(t,e)}))).then(t=>{w(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&re(e,n)})},E=(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 D(e){return O(e,ne())}async function O(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await Q(`/api/agents/${e.agentId}/tree?${r.toString()}`);return E(t,i.entries??[])}catch(e){return _(e.message),null}}let re=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=new Map(i.map(e=>[e.path,e])),o=n.map(e=>{let t=a.get(e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?t:e}).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),D(``).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 D(e.path);t&&re(e.path,t)}},[ae,oe]=v(``),[se,ce]=v(!1),[le,ue]=v(``),[A,de]=v(!1),fe=e=>/\.(md|markdown|mdx)$/i.test(e),pe=0,me=async e=>{let t=++pe;oe(``),ce(!0);try{let{highlightChunks:n}=await id(async()=>{let{highlightChunks:e}=await import(`./shiki-CNiDVOMg.js`);return{highlightChunks:e}},[]);for await(let r of n(e.path,e.content)){if(pe!==t)return;oe(e=>e+r)}}catch{pe===t&&oe(``)}finally{pe===t&&ce(!1)}};C(()=>{pe++});let he=async(t,n)=>{let r=Im(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await Q(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),ue(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&me({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){Hd(`open failed: ${e.message}`)}},ge=async()=>{let t=o();if(t&&!A()){de(!0);try{await Q(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:le(),baseContent:t.content})}),c({...t,content:le()}),Hd(`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?Hd(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
24
+ `).length>1?e:n}catch{return e}}var sf=12e4,cf=6e5,lf=e=>{let t=Number(e);return Math.min(Number.isFinite(t)&&t>0?t:sf,cf)},uf=F(`<div class=qfree><input type=text><button>reply`),df=F(`<div class=meta>`),ff=F(`<div class=meta>waiting for output…`),pf=F(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),mf=F(`<b>action="kill"`),hf=F(`<div class=meta>writing…`),gf=F(`<pre class="mono toolbody del">`),_f=F(`<pre class="mono toolbody add">`),vf=F(`<div class=meta> · `),yf=F(`<div class=meta>applying…`),bf=F(`<pre class="mono toolbody patch">`),xf=F(`<div>`),Sf=F(`<div class=meta>validating…`),Cf=F(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),wf=F(`<span class=muted>`),Tf=F(`<div class=content>`),Ef=F(`<div class=meta>loading…`),Df=F(`<div class=meta>bundled: `),Of=F(`<div class=meta>saving…`),kf=F(`<span class=actor>@`),Af=F(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),jf=F(`<div class=divider-msg>⑂ forked from <!> → `),Mf=F(`<div><div class=goalline-label>`),Nf=F(`<span class="meta muted">`),Pf=F(`<pre class="mono toolbody">`),Ff=F(`<details class="embed auditstep"><summary><span class=meta>`),If=F(`<div class=divider-msg>✅ tasks updated (<!>)`),Lf=F(`<div> → `),Rf=F(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),zf=F(`<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…`),Bf=F(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),Vf=F(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),Hf=F(`<span class=ts>`),Uf=F(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),Wf=F(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),Gf=F(`<div class=msg-head><span></span><span class=ts>`),Kf=F(`<div><div></div><div class=msg-body>`),qf=F(`<span class=grouptime>`),Jf=F(`<div class=promptimgs>`),Yf=F(`<img class=promptimg alt=attachment>`),Xf=F(`<details class=reasoning><summary>💭 thinking</summary><div class=mono>`),Zf=F(`<div class=interrupted>⚠ interrupted — partial output kept`),Qf=F(`<div class=msgfoot><span>copy summary`),$f=F(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),ep=F(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),tp=F(`<div class="content muted">Rejected: `),np=F(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged</span></summary><div class=content>`),rp=F(`<div class="meta answerdone">✓ answered — continuing below`),ip=F(`<div class=qopts>`),ap=F(`<div><div>❓️ <div class="content inline-md">`),op=F(`<button class=qopt>`),sp=F(`<div class=progrow><b>goal</b><span>`),cp=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),lp=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),up=F(`<div class=progrow><b>next</b><span class="content inline-md">`),dp=F(`<div class="embed progembed"><div>📈 <div class="content inline-md">`),fp=F(`<div class="embed fail"><div class=mono>⚠ `),pp=F(`<div class="muted compactnote">the summary pass produced nothing, so the oldest messages were dropped instead — the session continues with the recent tail intact`),mp=F(`<div class="embed compaction"><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),hp=F(`<div class="vtitle compactkept">what the agent kept`),gp=F(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),_p=F(`<div class="content muted">`);function vp(e){let[t,n]=v(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=uf(),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&&I(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 yp(e){let t=e.e,n=ef(e.prev,t),r=x(()=>e.res?.(),void 0,{equals:(e,t)=>e?.id===t?.id}),i=()=>r(),a=()=>!e.agentActive&&!i(),o=t.data??{},s=String(o.name??`tool`),c=()=>String(i()?.data?.result??``),l=e=>String(o.args?.[e]??``),u=()=>s===`bash`?l(`command`):l(`path`)||JSON.stringify(o.args??{},null,1),d=()=>s===`bash`?lf(l(`timeout_ms`)):s===`wait_children`?Number(l(`timeout_ms`))||3e5:Number(l(`timeout_ms`))||void 0,f=(e,t,n)=>j(hd,{text:e,lang:n}),p=()=>j(hd,{get text(){return JSON.stringify(o.args??{},null,1)},lang:`json`}),m=()=>(()=>{let e=i();return e?[P(()=>P(()=>!!Ju(c()))()?j(md,{get text(){return c()}}):j(hd,{get text(){return of(c())},get lang(){return af(c())}})),(()=>{var t=df();return R(t,()=>Ve(e.data?.durationMs),null),R(t,()=>s===`bash`?nf(tf(e.data?.ok,String(e.data?.result??``))):e.data?.ok===!1?` · FAILED`:``,null),R(t,j(zu,{get text(){return P(()=>!!Ju(c()))()?qu(c()):of(c())}}),null),t})()]:ff()})(),h=x(()=>{i();let e=s,t=``,n=p();try{switch(s){case`bash`:{let r=l(`command`),a=o.args?.background===!0,s=a?String(c()).match(/job (bg\d+)/)?.[1]??``:``;e=(a?`⏳ `:`$ `)+Zd(r,96);let u=l(`timeout_ms`)?Number(l(`timeout_ms`)):void 0,d=i(),f=tf(d?.data?.ok,d?String(d.data?.result??``):``);t=d?a?`background job${s?` ${s}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:rf({outcome:f,durationMs:d.data?.durationMs,timeoutMs:u,fmtDur:Ve}):null,n=[a?(()=>{var e=pf(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,R(t,s||`?`,n),R(e,s?[` · kill with `,mf()]:null,null),e})():null,P(()=>P(()=>r!==e.slice(2))()?j(hd,{text:r,lang:`shellscript`}):null),P(m)];break}case`read_file`:{e=l(`path`)||`(no path)`;let r=[];l(`pattern`)&&r.push(`grep /${Zd(l(`pattern`),40)}/`),Number(o.args?.offset)<0?r.push(`last ${-Number(o.args.offset)} lines`):o.args?.offset&&r.push(`from L${o.args.offset}`),o.args?.limit&&r.push(`≤${o.args.limit} lines`),t=r.join(` · `),n=m();break}case`write_file`:{let r=String(o.args?.content??``);e=l(`path`)||`(no path)`,t=`${Xd(r.length)} bytes`,n=[P(()=>f(r)),P(()=>P(()=>!!i())()?(()=>{var e=df();return R(e,()=>Zd(c(),160)),e})():hf())];break}case`edit_file`:e=l(`path`)||`(no path)`,t=o.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=gf();return R(e,()=>`- `+l(`old_text`)),e})(),(()=>{var e=_f();return R(e,()=>`+ `+l(`new_text`)),e})(),P(()=>P(()=>!!i())()?(()=>{var e=vf(),t=e.firstChild;return R(e,()=>Zd(c(),120),t),R(e,()=>Ve(i().data?.durationMs),null),e})():yf())];break;case`apply_patch`:{let t=l(`patch`).split(`
25
+ `).filter(e=>e&&!/^---$/.test(e.trim())),r=t.map(e=>e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/)?.[1]).filter(Boolean);e=r.length?`${r.length} file${r.length>1?`s`:``}: ${Zd(r.join(`, `),80)}`:`patch`,n=[(()=>{var e=bf();return R(e,()=>t.map(e=>{let t=e.startsWith(`+`)?` add`:e.startsWith(`-`)?` del`:/^\*\*\*|^@@/.test(e)?` meta`:``;return(()=>{var n=xf();return L(n,`pline`+t),R(n,e),n})()})),e})(),P(()=>P(()=>!!i())()?(()=>{var e=df();return R(e,()=>Zd(c().split(`
26
+ `)[0]??``,140),null),R(e,()=>i().data?.ok===!1?` · FAILED`:``,null),e})():Sf())];break}case`list_dir`:e=l(`path`)||`.`,n=m();break;case`read_url`:{let r=l(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=Zd(r,70),t=`web`,n=[(()=>{var e=df();return R(e,j(N,{get when(){return/^https?:/i.test(l(`url`))},get fallback(){return(()=>{var e=wf();return R(e,()=>Zd(l(`url`),80)),e})()},get children(){var e=Cf();return y(()=>I(e,`href`,l(`url`))),e}})),e})(),P(m)];break}case`bash_output`:{let r=l(`action`)||`read`;e=`bash_output ${l(`job_id`)||`(?)`}`,t=r,n=m();break}case`load_skill`:{e=`skill: ${l(`name`)}`;let t=c().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=i()?[(()=>{var e=Tf();return y(()=>e.innerHTML=Ie(t)),e})(),(()=>{var e=df();return R(e,()=>Ve(i().data?.durationMs)),e})()]:Ef();break}case`save_skill`:{e=`skill: ${l(`name`)}`,t=Zd(l(`description`),60);let r=Array.isArray(o.args?.files)?o.args.files.map(e=>e?.name).filter(Boolean):[];n=[P(()=>P(()=>!!r.length)()?(()=>{var e=Df();return e.firstChild,R(e,()=>r.join(`, `),null),e})():null),P(()=>P(()=>!!i())()?(()=>{var e=vf(),t=e.firstChild;return R(e,()=>Zd(c(),160),t),R(e,()=>Ve(i().data?.durationMs),null),e})():Of())];break}default:e=s,t=i()?Ve(i().data?.durationMs):null,n=[P(p),P(m)]}}catch{}return{label:e,hint:t,body:n,key:`${i()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var r=Af(),o=r.firstChild,l=o.firstChild,f=l.nextSibling,p=f.nextSibling;return r.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),R(l,()=>h().label),R(o,j(N,{get when(){return t.data?.actor},get children(){var e=kf();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),f),R(f,(()=>{var e=P(()=>!!i());return()=>e()?h().hint||``:P(()=>!!a())()?`(result missed)`:P(()=>!!(s===`bash`||d()))()?j(fd,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return d()}}):`running…`})()),R(p,j(zu,{get text(){return u()},label:`⧉ cmd`,title:`copy the ${s} arguments`}),null),R(p,j(N,{get when(){return i()},get children(){return j(zu,{get text(){return P(()=>!!Ju(c()))()?qu(c()):c()},label:`⧉ out`,title:`copy this tool's full output (escapes removed)`})}}),null),R(r,()=>h().body,null),y(e=>{var t=`embed`+(n?` grouped`:``)+(i()?i().data?.ok===!1?` fail`:` done`:a()?` done`:` running`),o=`${s}${h().hint?` — `+h().hint:``}`;return t!==e.e&&L(r,e.e=t),o!==e.t&&I(r,`title`,e.t=o),e},{e:void 0,t:void 0}),r})()}function bp(e){let t=e.e,n=qd(t),r=()=>ef(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&ef(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=jf(),r=n.firstChild.nextSibling;return r.nextSibling,R(n,()=>String(e.fromBranch??`?`),r),R(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=St(t.data??{});return(()=>{var t=Mf(),n=t.firstChild;return R(n,()=>e.label),R(t,j(N,{get when(){return e.hasCard},get children(){return j(Dt,{get tone(){return P(()=>e.tone===`ok`)()?`ok`:e.tone===`warn`?`warn`:`tool`},get markdown(){return e.markdown},get body(){return e.detail}})}}),null),y(()=>L(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`audit_step`){let e=String(t.data?.step??``),n=String(t.data?.name??``),r=e===`started`?`🔍️ auditor started`:e===`tool`?`🔍️ auditor → ${n}`:e===`tool_done`?`🔍️ auditor ← ${n} ${t.data?.ok===!1?`failed`:`${String(t.data?.chars??0)} chars`}`:e===`reply`?`🔍️ auditor replied`:`🔍️ auditor`;return(()=>{var n=Ff(),i=n.firstChild,a=i.firstChild;return R(a,r),R(i,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=Nf();return R(e,()=>He(String(t.data?.args??``),120)),e}}),null),R(n,j(N,{get when(){return e===`reply`&&t.data?.text},get children(){var e=Pf();return R(e,()=>String(t.data?.text??``)),e}}),null),R(n,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=Pf();return R(e,()=>String(t.data?.args??``)),e}}),null),n})()}if(t.type===`todo`)return(()=>{var e=If(),n=e.firstChild.nextSibling;return n.nextSibling,R(e,()=>String(t.data?.by??`human`),n),e})();if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=Lf(),n=e.firstChild;return R(e,()=>t.data.from,n),R(e,()=>t.data.to,null),R(e,(()=>{var e=P(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),y(()=>L(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=Rf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,R(n,()=>String(t.data?.failures),r),R(n,()=>String(t.data?.limit),i),R(a,()=>String(t.data?.lastTool),o),R(a,()=>String(t.data?.lastError??``).slice(0,200),null),y(()=>I(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=zf(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(n,()=>String(t.data?.attempt),r),R(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=xf();return L(r,`divider-msg`+(e?` err`:``)),R(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),y(()=>I(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=Bf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.tokensBefore??`?`),n),R(e,()=>String(t.data?.tokensAfter??`?`),r),R(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=Vf(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.messages??`?`),n),R(e,()=>String(t.data?.tokensBefore??`?`),r),R(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=Kf(),o=a.firstChild,s=o.nextSibling;return R(o,(()=>{var e=P(()=>!!r());return()=>e()?``:n.icon})()),R(s,(()=>{var e=P(()=>!!r());return()=>e()&&(()=>{var e=qf();return y(()=>I(e,`title`,`${Jd(t.ts)} · ${t.branch}`)),e})()})(),null),R(s,j(N,{get when(){return!r()},get children(){var r=Gf(),i=r.firstChild,a=i.nextSibling;return R(i,()=>n.name),R(r,j(N,{get when(){return t.data?.actor},get children(){var e=kf();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),a),R(a,(()=>{var e=P(()=>!!t.data?.pending);return()=>e()?`queued…`:P(()=>!!t.data?.cancelled)()?`withdrawn`:Jd(t.ts)})()),R(r,j(N,{get when(){return e.showBranch},get children(){var e=Hf();return R(e,()=>t.branch),e}}),null),R(r,j(N,{get when(){return e.onCancel},get children(){var t=Uf();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),R(r,j(N,{get when(){return t.type!==`tool_call`},get children(){return j(zu,{get text(){return Yd(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),R(r,j(N,{get when(){return e.onEdit},get children(){var t=Wf();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),y(()=>L(i,`author tone-${Kd(n.color)}`)),r}}),null),R(s,j(xp,{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 tone-${Kd(n.color)}`+(r()?` ghosted`:``),u=r()?`${Jd(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&L(a,e.e=s),c!==e.t&&I(a,`data-eid`,e.t=c),l!==e.a&&L(o,e.a=l),u!==e.o&&I(o,`title`,e.o=u),e},{e:void 0,t:void 0,a:void 0,o:void 0}),a})()}function xp(e){let t=e.e;switch(t.type){case`prompt`:{let e=(t.data?.images??[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0);return[(()=>{var e=Tf();return y(()=>e.innerHTML=vd(String(t.data.text??``))),e})(),j(N,{get when(){return e.length},get children(){var t=Jf();return R(t,j(M,{each:e,children:e=>(()=>{var t=Yf();return I(t,`src`,e),t})()})),t}})]}case`message`:return[j(N,{get when(){return P(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=Xf(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.reasoning)),e}}),(()=>{var e=Tf();return y(()=>e.innerHTML=vd(String(t.data.content??``))),e})(),j(N,{get when(){return t.data.interrupted},get children(){return Zf()}}),j(N,{get when(){return t.data.final},get children(){var e=Qf(),n=e.firstChild;return R(e,j(zu,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return j(yp,{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=ep(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return L(a,`embed `+(i?``:`fail`)),R(s,r===`bash`?`$ (bash, call evicted)`:r),R(o,j(zu,{text:n}),null),R(c,n),R(l,()=>Ve(t.data.durationMs),null),R(l,()=>r===`bash`?nf(tf(t.data.ok,n)):i?``:` · FAILED`,null),R(a,j(N,{get when(){return e.orphan},get children(){return $f()}}),null),y(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=np(),r=n.firstChild,i=r.firstChild.firstChild.nextSibling,a=r.nextSibling;return R(n,j(N,{get when(){return e.length},get children(){var t=tp();return t.firstChild,R(t,()=>e.join(` / `),null),t}}),null),y(e=>{var n=vd(String(t.data?.decision??``)),r=vd(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=ap(),o=a.firstChild.firstChild.nextSibling;return R(a,j(N,{get when(){return i()},get children(){return rp()}}),null),R(a,j(N,{get when(){return n.length>0},get children(){var a=ip();return R(a,j(M,{each:n,children:n=>(()=>{var a=op();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?Q(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>Hd(`→ answered @${String(t.data.actor)}`)).catch(()=>Hd(`answer failed`)):e.onOption?.(n)},R(a,n),y(()=>a.disabled=i()),a})()})),a}}),null),R(a,j(vp,{get answered(){return i()},get onOption(){return e.onOption}}),null),y(e=>{var n=`embed question`+(i()?` answered`:``),r=vd(String(t.data?.question??``));return n!==e.e&&L(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 R(e,j(N,{get when(){return t.data.goalStatus},get children(){var e=sp(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.goalStatus)),e}}),null),R(e,j(N,{get when(){return t.data.recent},get children(){var e=cp(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=vd(String(t.data.recent))),e}}),null),R(e,j(N,{get when(){return t.data.problems},get children(){var e=lp(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=vd(String(t.data.problems))),e}}),null),R(e,j(N,{get when(){return t.data.next},get children(){var e=up(),n=e.firstChild.nextSibling;return y(()=>n.innerHTML=vd(String(t.data.next))),e}}),null),y(()=>n.innerHTML=vd(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=fp(),n=e.firstChild;return n.firstChild,R(n,()=>String(t.data.message??``),null),e})();case`compaction`:return t.data.summary?(()=>{var e=gp(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Xd(Number(t.data.tokensBefore??0)),i),R(n,()=>Xd(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(e,j(N,{get when(){return t.data.summary},get children(){return[hp(),(()=>{var e=Tf();return y(()=>e.innerHTML=vd(String(t.data.summary))),e})()]}}),null),e})():(()=>{var e=mp(),n=e.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Xd(Number(t.data.tokensBefore??0)),i),R(n,()=>Xd(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(n,()=>String(t.data.mode??``)===`truncate`?` · older history dropped`:``,null),R(e,j(N,{get when(){return String(t.data.mode??``)===`truncate`},get children(){return pp()}}),null),e})();default:return(()=>{var e=_p();return R(e,()=>He(JSON.stringify(t.data),200)),e})()}}we([`input`,`keydown`,`click`]);var Sp=(e,t)=>{let n=String(t??``).trim();return!n||/^\d+$/.test(n)?null:e?.[n]??null},Cp=[{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)`}];function wp(e,t){return e?t===`dark`?{slot:`dark`,key:`teapot.theme.dark`}:{slot:`light`,key:`teapot.theme.light`}:{slot:`fixed`,key:`teapot.theme`}}var Tp=F(`<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`),Ep=F(`<div class=muted style="margin:6px 0">`),Dp=F(`<b>+ duplicate current`),Op=F(`<div class=cfggrid style=margin-top:8px><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),kp=F(`<div class=paletterows>`),Ap=F(`<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`),jp=F(`<h4 class=cfgsub>background image`),Mp=F(`<img sizes=260px alt="current background"decoding=async loading=lazy>`,!0,!1,!1),Np=F(`<span class=bgpick-hint>🖼 replace…`),Pp=F(`<div class=bgpreview><span class=muted title="this image is served from the server; the theme stores only its URL">✓ image set</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><label title="how much of the background shows through code blocks and tool cards — lower is more transparent">surfaces<input type=range min=0.35 max=1 step=0.01><span class="muted mono">%</span></label><button type=button>✕ remove`),Fp=F(`<div class=cfggrid><button type=button></button><input type=file accept=image/* style=display:none>`),Ip=F(`<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.`),Lp=F(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),Rp=F(`<span class=bgpick-empty>🖼 choose a background image…`),zp=F(`<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.`),Bp=F(`<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>`),Vp=F(`<div class=skilllist>`),Hp=F(`<span style=color:var(--err);font-size:13px>`),Up=F(`<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=cfgrow><label style=flex:1>API password<input type=password class=w100></label><span class=muted style=font-size:11.5px;max-width:34ch>bearer token for /api. empty = loopback only.</span></div><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</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 class=primarybtn>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>skills</legend></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>this host</h4><div class=featgrid><div class=featrow><b>image downscaling</b><span class=muted></span></div><div class=featrow><b>terminal pty</b><span class=muted></span></div></div></div><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><span class=kbdgroup><kbd>↑</kbd><kbd>↓</kbd></span><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>`),Wp=F(`<button type=button><span class=cfgmenu-label>`),Gp=F(`<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`),Kp=F(`<button type=button title="remove this key">−`),qp=F(`<div class=cfgkeyrow><input type=password>`),Jp=F(`<button type=button>+ `),Yp=F(`<option>`),Xp=F(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),Zp=F(`<div class=themepick>`),Qp=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),$p=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),em=F(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),tm=F(`<input placeholder="command (e.g. npx)">`),nm=F(`<input placeholder="args, space separated">`),rm=F(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),im=F(`<input placeholder="header name"style="flex:0 1 150px">`),am=F(`<input type=password placeholder=value style=flex:1>`),om=F(`<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>`),sm=F(`<button type=button class=mcpauthorize title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),cm=F(`<span class="mcpstate connected"title="an OAuth access token is usable — disconnect it under the server's details">🔑 authorized`),lm=F(`<span>`),um=F(`<div class=muted style=font-size:11px;color:var(--warn)>`),dm=F(`<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`),fm=F(`<option value=oauth selected>`),pm=F(`<span class=muted> · needs a grant (🔑 authorize)`),mm=F(`<details class=mcptools-wrap><summary>show <!> tool</summary><ul class=mcptools>`),hm=F(`<div class=mcpdanger><span class=muted>OAuth grant</span><button type=button class=mcpdisconnect title="forget the stored grant (the refresh token is deleted, so authorizing again needs a browser)">disconnect`),gm=F(`<div><div class=mcpresult-head><b>`),_m=F(`<span class=mcptool-desc>`),vm=F(`<li><code class=mono>`),ym=F(`<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=F(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),xm=F(`<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`),Sm=F(`<span class=muted>🧩 sub of @`),Cm=F(`<div class=cfgrow><b></b><span class=muted>`),wm=F(`<div class=muted>`),Tm=F(`<div class=skillbody>`),Em=F(`<div class=skillrow><button type=button class=skillhead title="show the playbook"><span class=skillcaret></span><b class=mono></b><span class=muted>`),Dm=F(`<div class="muted skillbody">`);function Om(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.find(t=>t.id===e.activeId)??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=Pn(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.paintedId),r=gd.find(t=>t.key===e.paintedId),i=t??r??gd[0],a=getComputedStyle(document.documentElement),o={...wn};for(let{key:e,cssVar:t}of Sn){let n=Pn(a.getPropertyValue(t));n&&(o[e]=n)}let s=jn(e.themes().map(e=>e.id).concat(gd.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,surfaceAlpha:t.surfaceAlpha}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))Hd(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{Hd(`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){Hd(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url,backgroundImageBytes:n.body.bytes}));let i=r()?.id;i&&e.onPick(i),Hd(`background image set`)}catch(e){Hd(`upload failed: ${e.message}`)}}}};return(()=>{var t=Tp(),d=t.firstChild.nextSibling.firstChild;return d.$$click=l,R(t,j(N,{get when(){return P(()=>!!(r()&&e.themes().some(t=>t.id===e.activeId)))()?r():null},get fallback(){return(()=>{var t=Ep();return R(t,(()=>{var t=P(()=>e.themes().length===0);return()=>t()?[`no custom themes yet — press `,Dp(),` to start from the palette you are using.`]:[`the editor shows when one of your themes is ACTIVE — pick one under "your themes" above (or press `,Dp(),`).`]})()),t})()},children:t=>[(()=>{var e=Op(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),y(()=>t.value=r().mode),e})(),(()=>{var e=kp();return R(e,j(M,{each:Sn,children:e=>(()=>{var t=Lp(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),R(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)},I(s,`spellcheck`,!1),y(()=>I(t,`title`,e.cssVar)),y(()=>n.value=Pn(r().palette[e.key])??`#000000`),y(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=Ap(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...wn}})),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})(),jp(),(()=>{var e=Fp(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),R(t,j(N,{get when(){return r().backgroundImage},get fallback(){return Rp()},get children(){return[(()=>{var e=Mp();return y(t=>{var n=Mt(r().backgroundImage),i=jt(r().backgroundImage);return n!==t.e&&I(e,`src`,t.e=n),i!==t.t&&I(e,`srcset`,t.t=i),t},{e:void 0,t:void 0}),e})(),Np()]}})),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`?Oe(i,n):o=n,R(e,j(N,{get when(){return r().backgroundImage},get children(){var e=Pp(),t=e.firstChild;t.firstChild;var n=t.nextSibling.firstChild,i=n.firstChild.nextSibling,a=i.nextSibling,o=a.firstChild,c=n.nextSibling,l=c.firstChild.nextSibling,u=l.nextSibling,d=u.firstChild,f=c.nextSibling;return R(t,()=>{let e=r()?.backgroundImageBytes;return e?` — ${Math.max(1,Math.round(e/1024))} KB`:``},null),i.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),R(a,()=>Math.round((r().backgroundDim??.55)*100),o),l.$$input=e=>s(t=>({...t,surfaceAlpha:Number(e.currentTarget.value)})),R(u,()=>Math.round((r().surfaceAlpha??.82)*100),d),f.$$click=()=>s(e=>({...e,backgroundImage:void 0})),y(()=>i.value=r().backgroundDim??.55),y(()=>l.value=r().surfaceAlpha??.82),e}}),null),y(e=>{var n=`bgpick`+(r().backgroundImage?` has`:``),i=r().backgroundImage?`click to replace this background image (PNG/JPG/WebP)`:`choose a background image (PNG/JPG/WebP)`;return n!==e.e&&L(t,e.e=n),i!==e.t&&I(t,`title`,e.t=i),e},{e:void 0,t:void 0}),e})(),Ip()]}),null),t})()}function km(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,te]=v(``),[ne,w]=v(!1),[T,E]=v((e.cfg.tasks??[]).map(e=>({...e}))),[D,O]=v((e.cfg.mcpServers??[]).map(e=>({...e}))),[re,k]=v(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ie,ae]=v({}),[oe,se]=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`]}))),[ce,le]=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]??``]}))),[ue,A]=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:``]}))),[de,fe]=v({}),pe={},me=async(e,t)=>{if(!D()[e])return;let n=await Q(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).catch(()=>null);D()[e]&&n&&fe(t=>({...t,[e]:n.ok?{kind:`ok`,text:`${n.tools?.length??0} tools`}:{kind:`err`,text:n.needsOAuth?`needs authorization — press 🔑`:n.error??`no response`,...n.needsOAuth?{needsOAuth:!0}:{}}}))},[he,ge]=v({}),[_e,ve]=v({}),ye=e=>{let t=Sp(_e(),e);return t&&(t.required||t.authorized)?t:null},xe=async()=>{let e=await Q(`/api/mcp`).catch(()=>null);ge(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},Se=async e=>{let t=String(e??``).trim();if(!t)return;let n=await Q(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&ve(e=>({...e,[t]:n}))},Ce=async(t,n)=>{if(!n.name){fe(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}fe(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await Q(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name,url:n.url})}).catch(()=>null);if(r?.alreadyAuthorized){fe(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await Se(n.name),await xe();return}if(!r?.ok||!r.url){fe(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await Se(n.name);return}window.open(r.url,`_blank`,`noopener`),fe(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 Q(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(ve(e=>({...e,[n.name]:r})),r.authorized){fe(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await xe(),e.onSaved();return}if(r.flow?.phase===`error`){fe(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}fe(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};b(()=>{Te()===`mcp`&&(xe(),D().forEach((e,t)=>{e.name&&Se(e.name)}))});let[F,we]=v(``),[Te,Ee]=v(`providers`),De=(t,n)=>{let{slot:r}=wp(e.theme.auto(),n);r===`dark`?Ke(t):r===`light`?Je(t):Ve(t)},Oe=t=>e.theme.auto()?t===e.theme.dark()||t===e.theme.light():t===e.theme.activeId(),[ke,Ae]=v([]),je=async()=>{let e=await Q(`/api/archived`).catch(()=>null);Ae(e?.agents??[])},Me=()=>ke().filter(e=>!e.parent);b(()=>{Te()===`archive`&&je()});let Ne=[{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:`skills`,label:`🧠 skills`,hint:`reusable playbooks available to the selected session`},{key:`help`,label:`❔️ help`,hint:`keyboard shortcuts and what each toggle does`}],Pe=()=>(e.cfg.agents??[]).map(e=>e.id),Fe=()=>e.theme.themes(),Ie=()=>e.theme.activeId(),Le={auto:localStorage.getItem(`teapot.theme.auto`)===`1`,dark:localStorage.getItem(`teapot.theme.dark`)??`dark`,light:localStorage.getItem(`teapot.theme.light`)??`light`,fixed:localStorage.getItem(`teapot.theme`)??`dark`},Re=v(Le),ze=Re[0],Be=t=>{let n={...ze(),...t};Re[1](n),e.theme.setAuto(n.auto),e.theme.setDark(n.dark),e.theme.setLight(n.light),e.theme.setActive(n.fixed);let r=t.dark??t.light??t.fixed;r&&e.theme.preview(r)},Ve=e=>Be({fixed:e}),He=()=>ze().auto,We=e=>Be({auto:e}),Ge=()=>ze().dark,Ke=e=>Be({dark:e}),qe=()=>ze().light,Je=e=>Be({light:e}),Ye=t=>e.theme.setThemes(t),Xe=()=>{let t=Le;e.theme.setAuto(t.auto),e.theme.setDark(t.dark),e.theme.setLight(t.light),e.theme.setActive(t.fixed),e.theme.preview(null)},Ze=e=>Tn[e]??wn,Qe=()=>{let e={};for(let t of n()){if(!t.name.trim())return we(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return we(`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},[$e,et]=v(`idle`),tt=e=>{we(e),et(e=>e===`saving`?`idle`:e)},nt=async t=>{t.preventDefault(),we(``),et(`saving`);let n=Qe();if(!n)return et(`idle`);let r=T().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)return tt(`task "${e.id}": agent is required`);if(!e.schedule?.trim())return tt(`task "${e.id}": schedule is required`)}let a=[],o=new Set;for(let e of D()){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)return tt(`MCP: a server needs a name`);if(o.has(t))return tt(`MCP: two servers are named "${t}"`);if(o.add(t),r===`stdio`?!i:!n)return tt(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);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 Q(`/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(),...ne()?{password:C()}:{},tasks:r,mcpServers:a})}),await xe(),await Promise.all(a.map((e,t)=>e.name?Se(e.name):Promise.resolve())),setTimeout(()=>{xe(),a.forEach((e,t)=>{e.name&&Se(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=D().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&_e()[n]?.required&&!_e()[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??``));Hd(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}e.theme.commitAppearance(ze()),e.theme.preview(null),et(`saved`),Object.assign(Le,ze()),setTimeout(()=>{et(`idle`),e.onClose()},400)}catch(e){we(e.message),et(`error`),setTimeout(()=>et(`idle`),1600)}};return j(Bu,{title:`settings`,onClose:()=>{Xe(),e.onClose()},get children(){var t=Up(),b=t.firstChild,ne=b.firstChild,ge=ne.nextSibling.firstChild,ve=ge.firstChild.nextSibling,xe=ve.nextSibling;xe.firstChild;var ke=xe.nextSibling.firstChild.firstChild.nextSibling;ke.firstChild;var Ae=ge.nextSibling,Le=Ae.firstChild.nextSibling,Re=Le.firstChild.firstChild.nextSibling,ze=Le.nextSibling,Be=Ae.nextSibling,Xe=Be.firstChild.nextSibling,Qe=Xe.firstChild.firstChild.nextSibling,et=Xe.nextSibling,tt=et.firstChild,rt=tt.firstChild.nextSibling,it=et.nextSibling.firstChild,at=Be.nextSibling,ot=at.firstChild.nextSibling.nextSibling,st=at.nextSibling,ct=st.firstChild.nextSibling,lt=st.nextSibling;lt.firstChild;var ut=lt.nextSibling;ut.firstChild;var dt=ut.nextSibling,ft=dt.firstChild.nextSibling.firstChild;ft.firstChild;var pt=ft.nextSibling,mt=dt.nextSibling;mt.firstChild;var ht=mt.nextSibling,gt=ht.firstChild.nextSibling.firstChild.nextSibling.firstChild,_t=gt.firstChild.nextSibling,vt=gt.nextSibling.firstChild.nextSibling,yt=b.nextSibling,bt=yt.firstChild;return t.addEventListener(`submit`,nt),R(ne,j(M,{each:Ne,children:e=>(()=>{var t=Wp(),n=t.firstChild;return t.$$click=()=>Ee(e.key),R(n,()=>e.label),y(n=>{var r=`cfgmenu-item`+(Te()===e.key?` on`:``),i=e.hint,a=Te()===e.key?`page`:void 0;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),R(ge,j(be,{get each(){return n()},children:(e,t)=>(()=>{var i=Gp(),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)),R(l,j(M,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=qp(),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,R(o,j(N,{get when(){return e().apiKeys.length>1},get children(){var e=Kp();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),y(()=>I(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})()}),ve),ve.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),R(xe,j(M,{each:Cp,children:e=>(()=>{var t=Jp();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)},R(t,()=>e.label,null),y(()=>I(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ke.addEventListener(`change`,e=>a(e.currentTarget.value)),R(ke,j(M,{get each(){return s()},children:e=>(()=>{var t=Yp();return t.value=e,R(t,e),t})()}),null),R(ge,j(N,{get when(){return c()},get children(){var e=zp(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return R(t,c),R(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),R(r,c),e}}),null),Re.addEventListener(`change`,e=>{We(e.currentTarget.checked)}),R(Ae,j(N,{get when(){return He()},get children(){var e=Bp(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ke(e.currentTarget.value)}),R(n,j(M,{get each(){return Fe().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(gd.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=Yp();return R(t,()=>e.label),y(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{Je(e.currentTarget.value)}),R(r,j(M,{get each(){return Fe().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(gd.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=Yp();return R(t,()=>e.label),y(()=>t.value=e.key),t})()})),y(()=>n.value=Ge()),y(()=>r.value=qe()),e}}),ze),R(Ae,j(M,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>j(N,{get when(){return[...Fe(),...gd].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=Xp();return R(t,()=>e.title),t})(),(()=>{var t=Zp();return R(t,j(M,{get each(){return Fe().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=Qp(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>De(e.id,e.mode),R(n,j(Rd,{get palette(){return e.palette},get backgroundImage(){return e.backgroundImage},get surfaceAlpha(){return e.surfaceAlpha},get backgroundDim(){return e.backgroundDim}})),R(r,()=>e.label,i),y(n=>{var r=`themecard`+(Oe(e.id)?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Oe(e.id);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(t,j(M,{get each(){return gd.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=$p(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>De(e.key,e.mode),R(n,j(Rd,{get palette(){return Ze(e.key)}})),R(r,()=>e.label),y(n=>{var r=`themecard`+(Oe(e.key)?` on`:``),i=`${e.label} (${e.mode})`,a=Oe(e.key);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),R(Ae,j(Om,{themes:Fe,get activeId(){return Ie()},get paintedId(){return e.theme.paintedId()},onChange:e=>{let t=kn(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0,surfaceAlpha:void 0,backgroundImageBytes:void 0}:e),r=kn(t);if(r.ok)n=t,Hd(`storage was full — saved without the background image(s)`);else{Hd(r.error??`could not save theme`);return}}Ye(n);let r=e=>n.some(t=>t.id===e)||gd.some(t=>t.key===e);r(Ie())||(Ve(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(Ge())||(Ke(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(qe())||(Je(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{let t=Fe().find(t=>t.id===e)?.mode??gd.find(t=>t.key===e)?.mode??`dark`,n=wp(He(),t);n.slot===`dark`?Ke(e):n.slot===`light`?Je(e):Ve(e)}}),null),Qe.$$input=e=>{te(e.currentTarget.value),w(!0)},R(et,j(Ld,{label:`progress interval (min)`,get value(){return l()},onValue:e=>u(e),hint:`how often the harness asks for a progress report`}),tt),R(et,j(Ld,{label:`progress min chars`,get value(){return d()},onValue:e=>f(e),hint:`progress prompts wait for this much real output`}),tt),rt.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),R(et,j(Ld,{label:`context window (k tok)`,get value(){return h()},onValue:e=>g(e),hint:`model's real window — 0/blank hides the % gauge`}),null),R(et,j(Ld,{label:`max spawn depth`,get value(){return _()},onValue:e=>x(e),hint:`sub-agent nesting limit (0 = no spawning)`}),null),it.addEventListener(`change`,e=>ee(e.currentTarget.checked)),R(at,j(N,{get when(){return D().length>0},get fallback(){return em()},get children(){return j(be,{get each(){return D()},children:(e,t)=>{let n=()=>he()[e().name],r=e=>O(D().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=dm(),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=m.firstChild,g=p.nextSibling,_=g.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>{r({url:e.currentTarget.value});let n=e.currentTarget.value.trim();clearTimeout(pe[t]),/^https?:\/\//.test(n)&&(pe[t]=setTimeout(()=>{me(t,{...D()[t],url:n})},700))},l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>O(D().filter((e,n)=>n!==t)),f.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),R(d,j(N,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=tm();return t.$$input=e=>r({command:e.currentTarget.value}),y(()=>t.value=e().command??``),t})(),(()=>{var t=nm();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(se(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ce()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=ue()[t]??``,n=ce()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),R(m,j(N,{get when(){return ye(String(e().name??``))},children:e=>(()=>{var t=fm();return R(t,()=>e().authorized?`OAuth — authorized`:`OAuth — authorization needed`),t})()}),h),R(p,j(N,{get when(){return oe()[t]===`bearer`},get children(){var e=rm();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},y(()=>e.value=ce()[t]??``),e}}),null),R(p,j(N,{get when(){return oe()[t]===`header`},get children(){return[(()=>{var e=im();return e.$$input=e=>{let n=e.currentTarget.value;A(e=>({...e,[t]:n}));let i=ce()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},y(()=>e.value=ue()[t]??``),e})(),(()=>{var e=am();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n}));let i=ue()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},y(()=>e.value=ce()[t]??``),e})()]}}),null),R(i,j(N,{get when(){return oe()[t]===`json`},get children(){var e=om(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(k(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}),ae(e=>({...e,[t]:``}))}catch{ae(e=>({...e,[t]:`must be a JSON object — not applied`}))}},y(()=>n.value=re()[t]??``),e}}),g),_.$$click=async()=>{let e=D()[t];if(!e.name){fe(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}fe(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await Q(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);fe(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 Se(e.name)},R(g,j(N,{get when(){return P(()=>!!Sp(_e(),String(e().name??``))?.required)()&&!Sp(_e(),String(e().name??``))?.authorized},get children(){var n=sm();return n.$$click=()=>void Ce(t,e()),n}}),null),R(g,j(N,{get when(){return Sp(_e(),String(e().name??``))?.authorized},get children(){return cm()}}),null),R(g,j(N,{get when(){return n()},get children(){var e=lm();return R(e,(()=>{var e=P(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:P(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),y(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&L(e,t.e=r),i!==t.t&&I(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),R(i,j(N,{get when(){return ie()[t]},get children(){var e=um();return R(e,()=>ie()[t]),e}}),null),R(i,j(N,{get when(){return de()[t]},children:n=>(()=>{var r=gm(),i=r.firstChild,a=i.firstChild;return R(a,()=>n().text),R(i,j(N,{get when(){return n().needsOAuth},get children(){return pm()}}),null),R(r,j(N,{get when(){return(n().tools?.length??0)>0},get children(){var e=mm(),t=e.firstChild,r=t.firstChild.nextSibling;r.nextSibling;var i=t.nextSibling;return R(t,()=>n().tools?.length,r),R(t,()=>n().tools?.length===1?``:`s`,null),R(i,j(M,{get each(){return n().tools??[]},children:e=>(()=>{var t=vm(),n=t.firstChild;return R(n,()=>e.name),R(t,j(N,{get when(){return e.description},get children(){var t=_m();return R(t,()=>e.description),t}}),null),y(()=>I(t,`title`,e.description??``)),t})()})),e}}),null),R(r,j(N,{get when(){return Sp(_e(),String(e().name??``))?.authorized},get children(){var n=hm(),r=n.firstChild.nextSibling;return r.$$click=async()=>{confirm(`Disconnect ${e().name}?\n\nThe stored OAuth grant is deleted and you will have to authorize again in a browser.`)&&(await Q(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await Se(e().name),fe(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}})))},n}}),null),y(()=>L(r,`mcpresult `+(n().kind===`err`?`err`:`ok`))),r})()}),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=ye(String(e().name??``))?`oauth`:oe()[t]??`none`),i})()}})}}),ot),ot.$$click=()=>O([...D(),{name:``,url:``,transport:`http`,enabled:!0}]),R(st,j(N,{get when(){return T().length>0},get children(){return j(be,{get each(){return T()},children:(e,t)=>(()=>{var n=ym(),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=>E(T().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>E(T().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>E(T().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>E(T().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>E(T().filter((e,n)=>n!==t)),u.$$input=e=>E(T().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})()})}}),ct),ct.$$click=()=>E([...T(),{id:``,agent:Pe()[0]??``,schedule:`every 30m`,prompt:``}]),R(lt,j(N,{get when(){return Me().length>0},get fallback(){return bm()},get children(){return j(M,{get each(){return Me()},children:t=>(()=>{var n=xm(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return R(i,()=>t.id),R(a,()=>t.sessions,o),R(a,()=>t.sessions===1?``:`s`,null),R(a,(()=>{var e=P(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),R(a,(()=>{var e=P(()=>!!t.archivedAt);return()=>e()?` · archived ${Ue(new Date(t.archivedAt).toISOString())}`:``})(),null),R(s,()=>t.workspace),c.$$click=async()=>{let n=await Q(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await je(),e.onSaved();let r=(n?.ids?.length??1)-1;Hd((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 Q(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await je(),e.onSaved(),Hd(`deleted ${t.id} for good`))},y(()=>I(s,`title`,t.workspace)),n})()})}}),null),R(ut,j(M,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=Cm(),n=t.firstChild,r=n.nextSibling;return R(n,()=>e.id),R(r,()=>e.workspace),R(t,j(N,{get when(){return e.parent},get children(){var t=Sm();return t.firstChild,R(t,()=>e.parent,null),t}}),null),t})()}),null),R(ft,()=>e.cfg.version??`unknown`,null),pt.$$click=async e=>{try{we(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await Q(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=null,i=!1;for(let e=0;e<120&&!i;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await Q(`/api/version`);if(!e.version)continue;r===null&&(r=e.uptimeSeconds??null),(e.version!==`0.37.73`||typeof e.uptimeSeconds==`number`&&r!==null&&e.uptimeSeconds<r)&&(i=!0,window.location.reload())}catch{}}if(!i)throw Error(`restart timeout — new server did not come up`)}catch(e){we(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},R(mt,j(N,{get when(){return e.skills.length>0},get fallback(){return(()=>{var t=wm();return R(t,()=>e.hasSelection?`this session has no skills yet — the agent saves them with save_skill once a procedure proves itself`:`select a session to see the skills available to it`),t})()},get children(){var t=Vp();return R(t,j(M,{get each(){return e.skills},children:t=>{let[n,r]=v(!1),[i,a]=v(null),[o,s]=v(``),c=async()=>{if(n())return r(!1);if(r(!0),i()===null&&e.agentId)try{let n=await Q(`/api/agents/${e.agentId}/skills/${encodeURIComponent(t.name)}`);a(String(n.text??``))}catch(e){s(e.message)}};return(()=>{var e=Em(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,l=s.nextSibling;return r.$$click=c,R(a,()=>n()?`▾`:`▸`),R(s,()=>t.name),R(l,()=>t.description),R(e,j(N,{get when(){return n()},get children(){return j(N,{get when(){return i()!==null},get fallback(){return(()=>{var e=Dm();return R(e,()=>o()||`loading…`),e})()},get children(){var e=Tm();return y(()=>e.innerHTML=vd(String(i()??``))),e}})}}),null),y(()=>e.classList.toggle(`open`,!!n())),e})()}})),t}}),null),R(_t,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.imageResize.available)()?`on — ${e.features.imageResize.tool}, long edge ≤ ${e.features.imageResize.maxEdge}px`:`off — no ffmpeg / ImageMagick found; uploads are served as-is`:`checking…`})()),R(vt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.pty.available)()?`on — ${e.features.pty.provider}`:`off — no pty provider; terminals run on plain pipes (no resize)`:`checking…`})()),R(yt,j(N,{get when(){return F()},get children(){var e=Hp();return R(e,F),e}}),bt),R(bt,(()=>{var e=P(()=>$e()===`saving`);return()=>e()?`saving…`:P(()=>$e()===`saved`)()?`✓ saved`:$e()===`error`?`✕ failed`:`save settings`})()),y(t=>{var n=Te()!==`providers`,r=Te()!==`appearance`,i=Te()!==`runtime`,a=e.cfg.hasPassword?`(unchanged — type to replace)`:`(none — loopback only)`,o=Te()!==`mcp`,s=Te()!==`tasks`,c=Te()!==`archive`,l=Te()!==`agents`,u=Te()!==`update`,d=Te()!==`skills`,f=Te()!==`help`,p=$e()===`saved`,m=$e()===`error`,h=$e()===`saving`;return n!==t.e&&ge.classList.toggle(`hide`,t.e=n),r!==t.t&&Ae.classList.toggle(`hide`,t.t=r),i!==t.a&&Be.classList.toggle(`hide`,t.a=i),a!==t.o&&I(Qe,`placeholder`,t.o=a),o!==t.i&&at.classList.toggle(`hide`,t.i=o),s!==t.n&&st.classList.toggle(`hide`,t.n=s),c!==t.s&&lt.classList.toggle(`hide`,t.s=c),l!==t.h&&ut.classList.toggle(`hide`,t.h=l),u!==t.r&&dt.classList.toggle(`hide`,t.r=u),d!==t.d&&mt.classList.toggle(`hide`,t.d=d),f!==t.l&&ht.classList.toggle(`hide`,t.l=f),p!==t.u&&bt.classList.toggle(`saved`,t.u=p),m!==t.c&&bt.classList.toggle(`error`,t.c=m),h!==t.w&&(bt.disabled=t.w=h),t},{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,c:void 0,w:void 0}),y(()=>ke.value=i()),y(()=>Re.checked=He()),y(()=>Qe.value=C()),y(()=>rt.value=p()??``),y(()=>it.checked=S()),t}})}we([`click`,`input`]);var Am=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),jm=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Mm=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function Nm(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Pm(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 Pm(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return Am.has(t)?`image`:jm.has(t)?`video`:Mm.has(t)?`audio`:null}var Fm=new Map,Im=e=>{let t=Fm.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},Fm.set(e,t)),t},Lm=F(`<span class=fsize>`),Rm=F(`<div><span class=ficon></span><span class=fname>`),zm=F(`<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>· `),Bm=F(`<div class=filebox>`),Vm=F(`<div class=muted style=padding:6px>`),Hm=F(`<img>`),Um=F(`<div class=mediapreview><div class="meta muted"> preview`),Wm=F(`<button title="rendered markdown">👁 preview`),Gm=F(`<button title="edit and save back to the workspace">✎ edit`),Km=F(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),qm=F(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),Jm=F(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),Ym=F(`<div class="content mdpreview shikiwrap">`),Xm=F(`<video controls>`),Zm=F(`<audio controls>`);function Qm(e){let t=Im(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)},te=e=>x()!==`hide`||!e.ignored,[ne,w]=v(localStorage.getItem(`teapot.showHidden`)===`1`),T=()=>{let e=!ne(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await O(t,e)}))).then(t=>{w(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&re(e,n)})},E=(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 D(e){return O(e,ne())}async function O(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await Q(`/api/agents/${e.agentId}/tree?${r.toString()}`);return E(t,i.entries??[])}catch(e){return _(e.message),null}}let re=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=new Map(i.map(e=>[e.path,e])),o=n.map(e=>{let t=a.get(e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?t:e}).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),D(``).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 D(e.path);t&&re(e.path,t)}},[ae,oe]=v(``),[se,ce]=v(!1),[le,ue]=v(``),[A,de]=v(!1),fe=e=>/\.(md|markdown|mdx)$/i.test(e),pe=0,me=async e=>{let t=++pe;oe(``),ce(!0);try{let{highlightChunks:n}=await id(async()=>{let{highlightChunks:e}=await import(`./shiki-qHmIppt3.js`);return{highlightChunks:e}},[]);for await(let r of n(e.path,e.content)){if(pe!==t)return;oe(e=>e+r)}}catch{pe===t&&oe(``)}finally{pe===t&&ce(!1)}};C(()=>{pe++});let he=async(t,n)=>{let r=Pm(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await Q(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),ue(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&me({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){Hd(`open failed: ${e.message}`)}},ge=async()=>{let t=o();if(t&&!A()){de(!0);try{await Q(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:le(),baseContent:t.content})}),c({...t,content:le()}),Hd(`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?Hd(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
27
27
  OK = load the disk version into the editor (your edits are discarded)
28
- Cancel = keep editing your copy`)?(ue(r.current),c({...t,content:r.current}),Hd(`loaded the current file from disk`)):Hd(`kept your edits — use Save As via bash to force-write`)}finally{de(!1)}}},_e=e=>!e.binary&&!e.truncated,ve=(e,t)=>[(()=>{var n=Bm(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void he(e,`code`),R(r,(()=>{var t=P(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:Fm(e.name)})()),R(a,()=>e.name),R(n,j(N,{get when(){return P(()=>!e.dir)()&&e.size!==void 0},get children(){var t=zm();return R(t,()=>Xd(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&&L(n,r.e=i),r.t=Ee(n,a,r.t),o!==r.a&&I(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),j(N,{get when(){return P(()=>!!e.dir)()&&i().has(e.path)},get children(){return j(M,{get each(){return(n().get(e.path)??[]).filter(te)},children:e=>ve(e,t+1)})}})],ye=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[be,xe]=v(!1),Se=async()=>{if(!be()){xe(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await O(e,ne())})));for(let{p:e,rows:n}of t)n&&re(e,n)}finally{xe(!1)}}};return[(()=>{var e=Vm(),t=e.firstChild.nextSibling;return t.firstChild,R(t,ye,null),R(e,j(Ru,{class:`filetoggle`,get icon(){return be()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void Se()}),null),R(e,j(Ru,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return P(()=>x()===`hide`)()?`🙈`:x()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${x()} — click to cycle (dim → hidden → shown)`},onClick:ee}),null),R(e,j(Ru,{class:`filetoggle`,get icon(){return ne()?`◉.`:`○.`},get title(){return ne()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:T}),null),e})(),(()=>{var e=Hm();return R(e,j(N,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Um();return R(e,()=>g()||`empty workspace`),e})()},get children(){return j(M,{get each(){return(n().get(``)??[]).filter(te)},children:e=>ve(e,0)})}})),e})(),j(N,{get when(){return o()},children:t=>j(Bu,{get title(){return`🗂 ${t().path}`},onClose:()=>{pe++,c(null),f(null)},get children(){return j(N,{get when(){return u()},get fallback(){return[(()=>{var e=Jm(),n=e.firstChild;return R(e,j(N,{get when(){return P(()=>!!fe(t().path))()&&!t().binary},get children(){var e=Km();return e.$$click=()=>h(`md`),y(()=>L(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||me({path:t().path,content:t().content,truncated:t().truncated})},R(e,j(N,{get when(){return _e(t())},get children(){var e=qm();return e.$$click=()=>h(`edit`),y(()=>L(e,p()===`edit`?`on`:``)),e}}),null),y(()=>L(n,p()===`code`?`on`:``)),e})(),j(N,{get when(){return!t().binary},get fallback(){return Xm()},get children(){return j(N,{get when(){return p()===`edit`},get fallback(){return j(N,{get when(){return P(()=>p()===`md`)()&&fe(t().path)},get fallback(){return j(Id,{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=Zm();return y(()=>e.innerHTML=Ie(t().content)),e}})},get children(){var e=Ym(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>ue(e.currentTarget.value),I(n,`spellcheck`,!1),R(r,()=>Xd(le().length),i),a.$$click=()=>void ge(),R(a,()=>A()?`saving…`:`💾 save`),y(()=>a.disabled=A()||le()===t().content),y(()=>n.value=le()),e}})}})]},get children(){var t=Gm(),n=t.firstChild,r=n.firstChild;return R(t,j(N,{get when(){return u().kind===`image`},get fallback(){return j(N,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=$m();return y(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Qm();return y(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Wm();return y(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&I(t,`src`,n.e=r),i!==n.t&&I(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),R(n,()=>u().kind,r),t}})}})})]}we([`click`,`input`]);var th=F(`<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 class=primarybtn>unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),nh=F(`<div class=leftbarbackdrop>`),rh=F(`<div class=sidehead><b>agents</b><button class=iconbtn title="close the agent list">✕`),ih=F(`<i class=notifdot>`),ah=F(`<br>`),oh=F(`<button class="iconbtn ham"title="agent list">☰`),sh=F(`<input class="title titleedit">`),ch=F(`<span class="badge queued">⏳ <!> <!> queued`),lh=F(`<button type=button class="badge bgjobs">⚙️ `),uh=F(`<span class="badge cron">⏰ `),dh=F(`<div class=bgjobs-pop role=dialog aria-label="background shells"><div class=bgjobs-head><span>background shells</span><button type=button class=iconbtn title=close>✕`),fh=F(`<header class=chan-head><span class=hash title="rename this chat">#</span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙️</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),ph=F(`<div class=divider-msg>── beginning of log ──`),mh=F(`<div class=divider-msg>loading older events…`),hh=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading newer events…`),gh=F(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),_h=F(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),vh=F(`<div class=content>`),yh=F(`<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…`),bh=F(`<div class=feed>`),xh=F(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),Sh=F(`<div class=termsplit>`),Ch=F(`<div class="termempty muted">no shell here — click a tab or + to add`),wh=F(`<div class=termpane>`),Th=F(`<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>`),Eh=F(`<button class=jump>↓ `),Dh=F(`<div class=cmds>`),Oh=F(`<div class=imgstage><span class=muted style=font-size:11px;align-self:center> image<!> attached`),kh=F(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),Ah=F(`<span class=muted style=font-size:11.5px;white-space:nowrap>🖼 `),jh=F(`<div class="hint flashhint">`),Mh=F(`<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>`),Nh=F(`<div class=rightbarbackdrop>`),Ph=F(`<div><nav><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`),Fh=F(`<div class=notifbackdrop>`),Ih=F(`<button class=editbtn>clear all`),Lh=F(`<div class=notiflist>`),Rh=F(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),zh=F(`<div class=bgphoto aria-hidden=true><img sizes=100vw alt decoding=async><span class=bgphoto-veil>`),Bh=F(`<span class=wscount>`),Vh=F(`<div class=wsheader><span class=wscaret>`),Hh=F(`<span class=notifbadge>🔔️`),Uh=F(`<span class=subtag>🧩`),Wh=F(`<span class=mini-cron>⏰`),Gh=F(`<span class=goaldone title="goal done">✓`),Kh=F(`<div><span></span><span>`),qh=F(`<span class=caret-spacer>`),Jh=F(`<span class=caret>`),Yh=F(`<span class=ghosttag title="workspace missing">👻`),Xh=F(`<span>🧩 `),Zh=F(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),Qh=F(`<span class=title>`),$h=F(`<div class="muted bgjobs-empty">no background jobs for this agent`),eg=F(`<pre class="mono bgjob-tail">`),tg=F(`<div class=bgjob><div class=bgjob-line><span></span><code class="mono bgjob-cmd"></code><span class="muted bgjob-meta"></span><button type=button class=bgjob-kill>`),ng=F(`<div class="muted bgjob-detached">this job outlived a harness restart, so its output is no longer captured here. it is still running as pid <!> — read its own log, or stop it yourself.`),rg=F(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),ig=F(`<div class=muted style=display:grid;place-items:center;height:100%><span><span class=spinner aria-hidden=true></span> loading timeline…`),ag=F(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),og=F(`<div class="content muted">thinking…`),sg=F(`<span>⌨ <button class=tabx title="close this shell">✕`),cg=F(`<div><b class=mono></b><span class=muted>`),lg=F(`<div class=cmdrow><b>@</b><span class=muted>`),ug=F(`<span class=imgchip><img><button type=button class=imgx title=remove>✕`),dg=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> models`),fg=F(`<h3 title="switch provider/model live — applies from the agent's next turn">🧦 model`),pg=F(`<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`),mg=F(`<div class=meta style=color:var(--fg)>`),hg=F(`<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: `),gg=F(`<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`),_g=F(`<span>`),vg=F(`<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`),yg=F(`<div class=statrow style=margin-bottom:6px><span class=k>status`),bg=F(`<div class="card goalcard"><div class=content>`),xg=F(`<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…"title="drag the bottom edge to make this taller — the height is remembered"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 class=primarybtn>✓ save goal`),Sg=F(`<span class=badge>/<!> done`),Cg=F(`<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`),wg=F(`<div class=bartrack style=margin-bottom:6px><div>`),Tg=F(`<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 class=okbtn>✓ save tasks`),Eg=F(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),Dg=F(`<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`),Og=F(`<div class=rtcell><span>cost</span><b>$`),kg=F(`<div class=rtcell><span>cached</span><b>%`),Ag=F(`<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>`),jg=F(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),Mg=F(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),Ng=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),Pg=F(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙️ settings → scheduled tasks.">⏰ schedule`),Fg=F(`<option>`),Ig=F(`<span class=badge title="no goal set yet">no goal`),Lg=F(`<button>`),Rg=F(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),zg=F(`<div class=muted>none yet`),Bg=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),Vg=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),Hg=F(`<div class=progrow><b>next</b><span class="content inline-md">`),Ug=F(`<div class=progrow><b>goal</b><span>`),Wg=F(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),Gg=F(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),Kg=F(`<span>% of `),qg=F(`<div class=bartrack><div>`),Jg=F(`<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)>`),Yg=F(`<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`),Xg=F(`<div><span></span><span> events`),Zg=F(`<div class=muted>no scheduled tasks — add them in ⚙️ settings ("scheduled tasks")`),Qg=F(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),$g=F(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),e_=F(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),t_=F(`<div class=nbody>`),n_=F(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),r_=F(`<div style=font-size:12.5px;color:var(--dim)> event(s) came after this prompt and will be discarded — the new branch starts from your edited text.`),i_=F(`<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 class=primarybtn>⑂ fork & resend`),a_=F(`<span style=color:var(--err);font-size:13px>`),o_=F(`<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`),s_=F(`<div class=direntry>📁 `),c_=new Map;function l_(e){let t=c_.get(e);if(t!==void 0)return t;let n=Ie(e);return c_.set(e,n),c_.size>500&&c_.delete(c_.keys().next().value),n}var u_=[`minimal`,`low`,`medium`,`high`],d_=1100,[f_,p_]=v(``),m_,$=e=>{p_(e),clearTimeout(m_),m_=setTimeout(()=>p_(``),3200)},h_=!1,g_=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`,`system_note`]),__=new Set([`system_note`]),v_=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`]),y_=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),b_=location.hash.match(/[#&]token=([^&]+)/);b_&&(localStorage.setItem(`teapot.token`,decodeURIComponent(b_[1])),history.replaceState(null,``,location.pathname+location.search));var x_=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function S_(){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,p=null;async function m(e=!1){if(p)return p;if(f&&!e)return;let t=(async()=>{try{let e=await Q(`/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),f=!0}catch{}})();p=t;try{await t}finally{p===t&&(p=null)}}let[h,g]=v([]),[_,te]=v(0),[ne,w]=v([]),[T,E]=v(null),D=new Map,[O,re]=v(D.get(n()??``)??``),k=e=>{re(e);let t=n();t&&(e?D.set(t,e):D.delete(t))},[ie,ae]=v({providers:{}}),[oe,se]=v(!1),ce=()=>{let e=Xe()??(He()?st()?Je():it():ze());return Qe().find(t=>t.id===e)?.backgroundImage??``},le=()=>{let e=He()?st()?Je():it():ze();return Qe().some(t=>t.id===e)||gd.some(t=>t.key===e)?e:`dark`},[ue,A]=v(!1),de=!1;b(()=>{!de&&ie()?.needsSetup&&(de=!0,requestAnimationFrame(()=>{Er(),A(!0)}))}),b(()=>{ue()&&!Ha()&&Q(`/api/features`).then(e=>Ua(e)).catch(()=>Ua(null))});let fe=new Set,pe=()=>window.innerWidth<=d_,[me,he]=v(pe());ee(()=>{let e=()=>he(pe());window.addEventListener(`resize`,e),C(()=>window.removeEventListener(`resize`,e)),e()});let ge=0,_e=null,ve=0,ye,be,xe=0,Se=``,Ce=()=>{xe=0;let e=xi();if(!e)return;if(eo=e.scrollHeight,ro=e.clientHeight,At()){wi();return}let t=_e;if(!t)return;let n=e.querySelector(t.sel);if(!n)return;let r=n.getBoundingClientRect().top-t.top;r&&(e.scrollTop+=r,$a={top:e.scrollTop,height:e.scrollHeight}),un(Si())};function F(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||Math.abs(r)>to||(e.scrollTop+=r,$a={top:e.scrollTop,height:e.scrollHeight})}let we=()=>{xe||=requestAnimationFrame(Ce)},Te=e=>{e&&e!==be&&(ye??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==Se&&(Se=n,we())}),be&&ye.unobserve(be),be=e,Se=``,ye.observe(e))};ee(()=>{window.addEventListener(`resize`,we),C(()=>{window.removeEventListener(`resize`,we),ye?.disconnect(),ye=void 0,be=void 0,xe&&cancelAnimationFrame(xe)})});function ke(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[Ae,je]=v(localStorage.getItem(`teapot.panel`)===null?window.innerWidth>d_:localStorage.getItem(`teapot.panel`)===`1`),Me=e=>{je(e),localStorage.setItem(`teapot.panel`,e?`1`:`0`)},Ne=()=>Me(!Ae()),Pe=()=>{Ae()&&Me(!1)},[Fe,Le]=v(!1),Re=()=>Le(!1),[ze,Be]=v(localStorage.getItem(`teapot.theme`)??`dark`),[He,qe]=v(localStorage.getItem(`teapot.theme.auto`)===`1`),[Je,Ye]=v(localStorage.getItem(`teapot.theme.light`)??`light`),[Xe,Ze]=v(null),[Qe,rt]=v(On());ee(()=>{An().then(e=>{if(e===null)return;let t=Ot(Qe(),e);rt(t),kn(t)})});let[it,at]=v(localStorage.getItem(`teapot.theme.dark`)??`dark`),ot=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[st,ct]=v(ot?.matches??!1);ee(()=>{let e=e=>ct(e.matches);ot?.addEventListener(`change`,e),C(()=>ot?.removeEventListener(`change`,e))}),b(()=>{let e=Fn({want:Xe()??(He()?st()?Je():it():ze()),customIds:Qe().map(e=>e.id),presetIds:gd.map(e=>e.key),fallback:`dark`}),t=e.active,n=Qe().find(e=>e.id===t)??null;e.repaired&&(He()?localStorage.setItem(st()?`teapot.theme.light`:`teapot.theme.dark`,t):localStorage.setItem(`teapot.theme`,t)),document.documentElement.dataset.theme=t,Mn(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??gd.find(e=>e.key===t)?.mode??`dark`});let[lt,ut]=v(``),[dt,ft]=v(``),[pt,mt]=v(``);b(()=>{let t=n();mt(S(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[ht,gt]=v([]),_t=()=>Object.keys(ie().providers??{});async function yt(e){if(e)try{let t=await Q(`/api/models?provider=${encodeURIComponent(e)}`);gt(t.models??[])}catch{gt([])}}let xt=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)}`:``},St=()=>{let e=dt().trim()||B()?.model||``;if(!e)return``;let t=ht().find(t=>t.id===e);if(!t)return``;let n=[],r=xt(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${Xd(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(` · `)},Ct=null,wt=!1;b(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||ie().defaultProvider||_t()[0]||``;if(r){if(t!==Ct)Ct=t,wt=!1,S(()=>lt())!==i&&(ut(i),yt(i)),S(()=>dt())&&ft(``);else{let e=S(()=>lt());!S(()=>dt())&&e!==i&&sn(wt)&&(ut(i),yt(i))}}});let[Tt,Et]=v(!1),[At,Pt]=v(!0),[Gt,Yt]=v(0),[tn,rn]=v(-1),un=e=>rn(e?gn(e):-1),[bn,Sn]=v(null),Cn=()=>Pn().startsWith(`[compact] `),wn=()=>{let e=Cn()?Pn().slice(10):Pn();return e.length>1200?`…`+e.slice(-1200):e};b(()=>{bn()||jn(e=>e?.text.startsWith(`[compact] `)?null:e)}),b(()=>{h().length,_(),bn(),br().length,fi(),ui(),ci();let e=xi();if(!e)return;let t=e.scrollHeight;t!==ge&&(ge=t,requestAnimationFrame(()=>requestAnimationFrame(()=>{At()&&wi()})))});let[Tn,En]=v(new Map),Dn=()=>{let e=n();return e?Tn().get(e)??null:null},jn=e=>{let t=n();t&&En(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})},Nn=()=>{let e=Dn();if(!e)return;let t=tt(e,h(),B()?.status);t?(t.text!==e.text||t.reasoning!==e.reasoning)&&jn(t):jn(null)},[Pn,In]=v(``),[Ln,Rn]=v(0),zn=()=>Ln(),[z,Bn]=v(``),Vn;b(()=>{Dn()?Vn||=setTimeout(()=>{Vn=void 0,In(Dn()?.text??``),Bn(Dn()?.reasoning??``)},(Dn()?.text.length??0)>2e4?250:(Dn()?.text.length??0)>6e3?120:60):(clearTimeout(Vn),Vn=void 0,In(``),Bn(``))}),C(()=>clearTimeout(Vn)),b(()=>{let t=e();En(e=>et(e,e=>t.find(t=>t.id===e)?.status)),Rn(e=>nt(e,t,n(),Dn()))}),b(()=>{let e=Pn(),t=Dn()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{At()&&wi()})}),b(()=>{let e=B()?.pendingPrompts??0,t=B()?.pendingPromptIds,n=Xn(),r=Zn(n),i=Ht(r,e,t);i!==r&&Qn(n,i)}),b(()=>{let e=B()?.pendingPromptQueue;if(!e?.length)return;let t=B()?.session||Xn(),n=new Set(Zn(t).map(e=>e.promptId).filter(Boolean)),r=e.filter(e=>e.id&&!n.has(e.id));r.length&&Qn(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}:{}})),...Zn(t)])}),b(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{Ci()&&(Pt(!0),Yt(0),Ti(!0),sr())})};document.addEventListener(`visibilitychange`,e),C(()=>document.removeEventListener(`visibilitychange`,e))});let B=x(()=>e().find(e=>e.id===n())),Hn=()=>xn({sameSession:!(B()?.session!==Xn()&&B()?.session),agent:B(),echoCount:xr()}),Un=()=>{let e=B();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},Wn=()=>Qt(B(),i(),Un()),[Gn,Kn]=v(null);x(()=>{let e=new Set;for(let t of h())t.type===`tool_result`&&t.data?.name===`ask_user`&&e.add(String(t.data.callId));return e});let qn=new Map,[Jn,Yn]=v([]),Xn=()=>i()||n()||`?`,Zn=e=>qn.get(e)??[],Qn=(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?qn.delete(e):qn.set(e,r),Xn()===e&&Yn(r)},[$n,er]=v([]),[tr,nr]=v(localStorage.getItem(`teapot.hideGhosts`)===`1`),[rr,ir]=v(!1),ar=()=>$n().filter(e=>!e.read).length,or=e=>{er(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},sr=()=>{let e=n();e&&$n().some(t=>!t.read&&t.agentId===e)&&or(e)},cr=t=>{let n=$n().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=cr(r.id));return n},lr=0,ur=e=>{er(t=>[{...e,id:`n${++lr}`,at:Date.now(),read:!1},...t].slice(0,50))},dr=(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?ur({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?ur({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?ur({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&ur({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})},fr=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))},pr=x(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of h())if(g_.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}}),[mr,hr]=v(new Set),gr=e=>{e&&hr(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},_r=()=>hr(new Set),vr=x(()=>Vt(h(),mr())),yr=x(()=>vt({events:h(),consumed:pr().consumed,pending:Jn(),echo:Tr,feedTypes:g_,renderedTypes:v_,renderedNoteEvents:y_})),br=()=>yr().rows,xr=()=>yr().pendingCount,Sr=x(()=>{let e=new WeakMap;return br().forEach((t,n)=>e.set(t,n)),e}),Cr=(e,t)=>{let n=Sr().get(e);if(n!==void 0)return br()[n+t]},wr=new Map;function Tr(e){let t=`${e.id}:${e.sent?`s`:`p`}`,n=wr.get(t);if(n)return n;wr.size>64&&wr.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:B()?.session??``,branch:B()?.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 wr.set(t,r),r}let Er=()=>Q(`/api/config`).then(ae).catch(()=>{}),[Dr,Or]=v(!1);ee(()=>{let e=()=>Or(!0);window.addEventListener(`teapot:unauthorized`,e),C(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[kr,Ar]=v(``),[jr,Mr]=v(!0),[Nr,Pr]=v(!1),Fr=``;b(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==Fr?(Fr=t,Pr(!1),Ar(r)):t&&!Nr()&&Ar(r)});let Ir=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await Q(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:kr(),notify:e})}),Pr(!1),Mr(!0),$(`tasks saved${e&&kr().trim()?` & notification queued`:``}`),V()}catch(e){$(`save failed: ${e.message}`)}},Lr=x(()=>{let e=0,t=0;for(let n of kr().split(`
29
- `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function Rr(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 V=()=>Q(`/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),Rr(t,e.agents??[]))),n&&m()}).catch(()=>{}),zr=()=>Q(`/api/metrics`).then(E).catch(()=>{}),[Br,Vr]=v([]),Hr=()=>Q(`/api/tasks`).then(e=>Vr(e.tasks)).catch(()=>{}),Ur=e=>Br().filter(t=>t.agent===e),[Wr,Gr]=v((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[Kr,qr]=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}})()),Jr=e=>Kr().has(e)||!Wr().has(e),Yr=e=>{let t=new Set(Wr());if(t.has(e)?t.delete(e):t.add(e),Gr(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&Kr().has(e)){let t=new Set(Kr());t.delete(e),qr(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},H=t=>Rt(e(),t),[Xr,Zr]=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}})()),U=x(()=>{let e=new Set;for(let t of Xr())t.startsWith(`chat:`)&&e.add(t);return e}),Qr=x(()=>Nt(e(),new Set(e().filter(e=>Jr(e.id)).map(e=>e.id)),tr(),U())),$r=(t,r,i,a)=>{let o=new Set(Xr());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||H(e().find(e=>e.id===i))===t)&&$(`hid ${r} — click the header to show it`)}Zr(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},ei=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,W=e=>{let t=ti().get(e)??0;return`${t} chat${t===1?``:`s`}`},ti=x(()=>zt(e())),ni=x(()=>Bt(e(),Qr(),Xr())),[ri,ii]=v(null),ai=new Map;function oi(e){return`${i()||(n()??`?`)}:${e.id}`}function si(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=oi(r),a=ai.get(i);if(t[n]=a??r,!a&&(ai.set(i,r),ai.size>6e3)){let e=ai.keys().next().value;e!==void 0&&ai.delete(e)}}return t}let[ci,li]=v(!1),[ui,di]=v(!1),[fi,pi]=v(!1),mi=0,hi=-1;function G(e){let t=si(e);g(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 gi(){let e=n();if(!e||fi()||ci()||At())return;if(h().length>=_()){pi(!0);return}let t=()=>{let e=xi();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!fi()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(h().length>=_()){pi(!0);return}let i=h().length;if(await _i(),h().length===i)return;fn(Si())&&n()===e&&Ti(!0)}}async function _i(){let e=n(),t=h()[0];if(e&&t&&!ci()&&!fi()){li(!0);try{let r=xi(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=ri(),c=i(),l=(await Q(yi(e,{before:t.id},c,s))).events??[];if(l.length===0){pi(!0);return}if(n()!==e||h()[0]?.id!==t.id)return;G(l),requestAnimationFrame(()=>{if(n()===e){let e=xi();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{li(!1)}}}function vi(e,t){return t&&o().has(t)?`&session=${encodeURIComponent(t)}`:``}function yi(e,t,n,r){let i=[`/api/agents/${encodeURIComponent(e)}/events?limit=2000`];t.before&&i.push(`&before=${encodeURIComponent(t.before)}`),t.after&&i.push(`&after=${encodeURIComponent(t.after)}`);let a=vi(e,n);return a&&i.push(a),r&&i.push(`&branch=${encodeURIComponent(r)}&lineage=true`),i.join(``)}async function bi(e,t){let r=mi,a=t??i()??``;try{let t=ri(),i=r!==hi||!ne().length;h().length||di(!0),Q(`/api/agents/${e}/skills`).then(t=>{r===mi&&n()===e&&Va(t.skills??[])}).catch(()=>{});let[o,s]=await Promise.all([Q(yi(e,{},a,t)),i?Q(`/api/agents/${e}/branches`):Promise.resolve({branches:ne()})]);if(i&&(hi=r),r!==mi||n()!==e)return;g(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of si(o.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)}),te(o.total??o.events.length),w(s.branches)}catch{}finally{di(!1)}}function xi(){return document.querySelector(`.feed`)}function Si(){let e=xi();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function Ci(){return fn(Si())}function wi(){let e=xi();e&&(e.scrollTop=e.scrollHeight,$a={top:e.scrollTop,height:e.scrollHeight},Yt(0))}function Ti(e=!1){(e||At())&&wi()}let Ei=new Map,Di=new Map,Oi=25165824,ki=e=>{let t=e.data,n=64;if(t)for(let e of Object.values(t))typeof e==`string`&&(n+=e.length*2);return n},Ai=(t,n)=>Ut(c().get(t),e().find(e=>e.id===t)?.session,n);async function ji(e,t=!0,s){let l=n(),u=i(),d=h(),f=_();mi++,c().size||m();let p=Ai(e,s),v=s&&o().has(s)?s:null,y=p??v??e;if(l!==e||y!==u){{let e=xi(),t=e?ke(e):null,n=u||l;if(e&&n&&t){let r=e.querySelector(t.sel)?.dataset.eid??``,i=e.scrollHeight-e.scrollTop-e.clientHeight<=24;for(r&&Di.set(n,{eid:r,delta:e.getBoundingClientRect().top-t.top,atTail:i});Di.size>24;){let e=Di.keys().next().value;if(e===void 0)break;Di.delete(e)}}}if(u&&d.length){let e=d.reduce((e,t)=>e+ki(t),0);e<=Oi&&Ei.set(u,{events:d,total:f,at:Date.now(),bytes:e});let t=()=>[...Ei.values()].reduce((e,t)=>e+t.bytes,0);for(;Ei.size>6||t()>Oi;){let e=[...Ei.entries()].sort((e,t)=>e[1].at-t[1].at)[0];if(!e)break;Ei.delete(e[0])}}g([]),ai.clear(),_r(),Sn(null),Yt(0),Pt(Di.get(y)?.atTail??!0),Qa=void 0}r(e),a(y),k(D.get(e)??``),ii(null),pi(!1),li(!1),Qn(u||l||`?`,Jn()),Yn(Zn(y||e)),localStorage.setItem(`teapot.session`,e),Wi(y,t);let b=Ei.get(y);if(b?.events.length&&(g(si(b.events)),te(b.total),di(!0),Di.has(y)||requestAnimationFrame(()=>{n()===e&&Ti(!0)})),Q(`/api/agents/${e}/load`,{method:`POST`}).then(V).catch(()=>{}),await bi(e,y),n()!==e)return;En(t=>{let n=t.get(e)??null,r=tt(n,h(),B()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),Sn(B()?.ctx?.compacting?{phase:String(B().ctx.compacting)}:null);let x=Di.get(y);Pt(!x||x.atTail),requestAnimationFrame(()=>{if(n()===e){if(x){let e=xi(),t=e?.querySelector(`[data-eid="${CSS.escape(x.eid)}"]`);if(e&&t){e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top+x.delta,$a={top:e.scrollTop,height:e.scrollHeight},x.atTail&&Ti(!0);return}x.atTail&&Ti(!0)}else Ti(!0)}}),gi()}let[Mi,Ni]=v(!1),Pi=null,Fi=null;C(()=>Pi?.close());let Ii=!1,Li=!1,Ri=null;document.addEventListener(`visibilitychange`,()=>Ri?.()),C(()=>{Ri=null});let zi=!0,Bi=null;async function Vi(){let e=n(),t=h().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)Ii=!0,a||Bi?.();else try{let n=ri(),i=await Q(yi(e,{after:t},r,n)),o=i.events??[];i.gap?(g(si(o)),te(o.length)):o.length&&(G(o),te(e=>e+o.length)),await V(),o.length&&!a&&zr()}catch{Ii=!0}}function Hi(){zi=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${x_()}`);Pi=a,a.onopen=()=>{Ni(!0),zi?zi=!1:Vi()},a.onclose=()=>{Ni(!1),setTimeout(Hi,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=>Rr(e,c.agents));let n=e();En(e=>et(e,e=>n.find(t=>t.id===e)?.status))}else if(c.kind===`event`&&Ke(c.event))En(e=>Ge(e,c.agentId));else if(c.kind===`llm-delta`){if(!Zt(c,n(),i()))return;if(En(e=>We(e,c.agentId,c)),c.agentId===n()){let e=String(c.reasoning??``),t=String(c.text??``);e&&!t?Ln()||Rn(Date.now()):t&&Rn(0)}}else if(c.kind===`compaction-progress`){if(c.agentId!==n())return;c.phase===`done`?Sn(null):Sn({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]:Rr(e,e.map((e,n)=>n===t?c.snapshot:e))});else if(c.kind===`metrics`&&c.metrics)E(c.metrics);else if(c.kind===`tasks`&&Array.isArray(c.tasks))Vr(c.tasks);else{if(c.kind===`event`){let e=c.event?.type,t=c.event?.data??{};if(e===`system_note`&&(t.event===`prompt-delivered`||t.event===`prompt-cancelled`)){let e=String(t.promptId??``);if(e){let t=String(c.event?.session??``),n=new Set;t&&n.add(t),n.add(Xn());for(let[t,r]of qn)r.some(t=>t.promptId===e)&&n.add(t);for(let t of n){let n=Zn(t);n.some(t=>t.promptId===e)&&Qn(t,n.filter(t=>t.promptId!==e))}}}if(o.has(e)&&!__.has(e)||(dr(c.agentId,c.event),c.event?.agent!==n())||!Xt(c.event,n(),i()))return;{let e=h().at(-1)?.seq??0,t=Number(c.event?.seq??0);(!e||t>0&&t>e+1)&&(Li=!0)}if(G([c.event]),c.event&&Nn(),Ii=!0,document.visibilityState!==`visible`||Fi)return;Fi=setTimeout(s,60)}document.visibilityState===`hidden`?Ii=!0:Fi||=setTimeout(s,120)}}},Ii=!1;let s=async()=>{if(Fi=null,n()){let e=h().at(-1)?.id,t=h().length;Li&&(Li=!1,await bi(n()));let r=Dn();r&&!tt(r,h(),B()?.status)&&jn(null),h().at(-1)?.id!==e&&(At()?(wi(),or(n())):(Yt(e=>e+Math.max(0,h().length-t)),un(Si())))}};Bi=s,Ri=()=>{document.visibilityState===`visible`&&(zr(),Hr(),n()&&(Ii?(Ii=!1,s()):h().at(-1)?.id?Vi():(Ii=!0,s())))}}let Ui=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function Wi(t,n=!0){let r=Wt(t,o(),e().map(e=>e.id));if(!r)return;let i=`/session/${encodeURIComponent(r)}`;n?history.pushState(null,``,i):history.replaceState(null,``,i)}window.addEventListener(`popstate`,()=>{let e=Ui(),t=o().get(e);t&&(t!==n()||e!==i())&&ji(t,!1,e||null)}),b(()=>{let e=B(),t=e?`${Un()?`▶ `:e.status===`error`?`⚠ `:``}${vn(e)} · teapot`:`teapot`;document.title=ar()>0?`(${ar()}) ${t}`:t});let Gi=()=>oe()||ue()||Gn()!==null||pe()&&Ae();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(oe()){se(!1);return}if(ue()){A(!1);return}if(Gn()){Kn(null);return}if(pe()&&Ae()){Pe();return}let e=B();if(e&&Un()){Q(`/api/agents/${e.id}/stop`,{method:`POST`}).then(V);return}}else if(!Gi()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)Ne();else if(e.key===`t`)aa();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=Qr().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&&ji(t[i].id)}}});let[Ki,qi]=v(localStorage.getItem(`teapot.term`)===`1`),[Ji,Yi]=v([]),[Xi,Zi]=v(!1),Qi=async()=>{let e=n();if(!e)return;let t=await Q(`/api/agents/${encodeURIComponent(e)}/bg-jobs`).catch(()=>null);t?.jobs&&Yi(t.jobs)};b(()=>{n(),Qi()}),b(()=>{if(!Xi())return;let e=setInterval(()=>void Qi(),2e3);C(()=>clearInterval(e))});let[$i,ea]=v(!1),[ta,na]=v(``),ra=()=>{let e=B();e&&(na(vn(e)),ea(!0))},ia=async()=>{if(!$i())return;let e=B();ea(!1);let t=ta().replace(/\s+/g,` `).trim();if(!e||!t||t===vn(e))return;let n=await Q(`/api/agents/${encodeURIComponent(e.id)}/session-title?session=${encodeURIComponent(e.session)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({title:t})}).catch(e=>({error:String(e)}));n?.error?$(`rename failed: ${n.error}`):(d(n=>new Map(n).set(e.session,t)),V())},aa=()=>{let e=!Ki();qi(e),localStorage.setItem(`teapot.term`,e?`1`:`0`)},[oa,sa]=v([]),[ca,la]=v(0),[ua,da]=v(-1),[fa,pa]=v(!1),[ma,ha]=v(0),[ga,_a]=v(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),va=new Map,ya=[null,null],ba=()=>oa()[ma()===0?ca():ua()]??null;function xa(e){if(!oa()[e])return;let t=ma(),n=t===0?ca():ua(),r=t===0?ua():ca(),i=e=>t===0?la(e):da(e);r===e?((e=>t===0?da(e):la(e))(n),i(e)):n!==e&&i(e)}let Sa=()=>Ca();async function Ca(e){let t=e??n();if(t){if(oa().filter(e=>e.agentId===t).length>=10)$(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await Q(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){$(`could not open a shell`);return}let n=Du(oa());sa(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title}]),ma()===0?la(n):da(n)}catch(e){$(`could not open a shell: ${e.message}`)}}}function wa(e){let t=oa()[e];if(!t)return;Q(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=va.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),va.delete(t.key)}let r=oa().filter((t,n)=>n!==e);sa(r),la(t=>ku(t,e,r.length)),da(t=>t===-1?-1:ku(t,e,r.length))}b(()=>{He(),ze(),st(),Je(),it();for(let[,e]of va)en(e.term)});function Ta(){for(let[,e]of va){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}va.clear()}function Ea(e,t){let n=va.get(e.key);if(n&&en(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 Cu({cursorBlink:!0,fontSize:12.5,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,theme:$t()}),a=new Eu;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=()=>`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${x_()}`,c=new WebSocket(s()),l,u=!1,d=t=>{t.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`ping`||(n.kind===`exit`?(u=!0,i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),sa(t=>t.filter(t=>t.key!==e.key)),va.get(e.key)?.term.dispose(),va.delete(e.key)):n.kind===`attach`&&n.error&&(u=!0,i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)))},t.onclose=()=>{!u&&va.has(e.key)&&(l||=(i.write(`\r
28
+ Cancel = keep editing your copy`)?(ue(r.current),c({...t,content:r.current}),Hd(`loaded the current file from disk`)):Hd(`kept your edits — use Save As via bash to force-write`)}finally{de(!1)}}},_e=e=>!e.binary&&!e.truncated,ve=(e,t)=>[(()=>{var n=Rm(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void he(e,`code`),R(r,(()=>{var t=P(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:Nm(e.name)})()),R(a,()=>e.name),R(n,j(N,{get when(){return P(()=>!e.dir)()&&e.size!==void 0},get children(){var t=Lm();return R(t,()=>Xd(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&&L(n,r.e=i),r.t=Ee(n,a,r.t),o!==r.a&&I(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),j(N,{get when(){return P(()=>!!e.dir)()&&i().has(e.path)},get children(){return j(M,{get each(){return(n().get(e.path)??[]).filter(te)},children:e=>ve(e,t+1)})}})],ye=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[be,xe]=v(!1),Se=async()=>{if(!be()){xe(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await O(e,ne())})));for(let{p:e,rows:n}of t)n&&re(e,n)}finally{xe(!1)}}};return[(()=>{var e=zm(),t=e.firstChild.nextSibling;return t.firstChild,R(t,ye,null),R(e,j(Ru,{class:`filetoggle`,get icon(){return be()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void Se()}),null),R(e,j(Ru,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return P(()=>x()===`hide`)()?`🙈`:x()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${x()} — click to cycle (dim → hidden → shown)`},onClick:ee}),null),R(e,j(Ru,{class:`filetoggle`,get icon(){return ne()?`◉.`:`○.`},get title(){return ne()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:T}),null),e})(),(()=>{var e=Bm();return R(e,j(N,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Vm();return R(e,()=>g()||`empty workspace`),e})()},get children(){return j(M,{get each(){return(n().get(``)??[]).filter(te)},children:e=>ve(e,0)})}})),e})(),j(N,{get when(){return o()},children:t=>j(Bu,{get title(){return`🗂 ${t().path}`},onClose:()=>{pe++,c(null),f(null)},get children(){return j(N,{get when(){return u()},get fallback(){return[(()=>{var e=Km(),n=e.firstChild;return R(e,j(N,{get when(){return P(()=>!!fe(t().path))()&&!t().binary},get children(){var e=Wm();return e.$$click=()=>h(`md`),y(()=>L(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||me({path:t().path,content:t().content,truncated:t().truncated})},R(e,j(N,{get when(){return _e(t())},get children(){var e=Gm();return e.$$click=()=>h(`edit`),y(()=>L(e,p()===`edit`?`on`:``)),e}}),null),y(()=>L(n,p()===`code`?`on`:``)),e})(),j(N,{get when(){return!t().binary},get fallback(){return Jm()},get children(){return j(N,{get when(){return p()===`edit`},get fallback(){return j(N,{get when(){return P(()=>p()===`md`)()&&fe(t().path)},get fallback(){return j(Id,{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=Ym();return y(()=>e.innerHTML=Ie(t().content)),e}})},get children(){var e=qm(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>ue(e.currentTarget.value),I(n,`spellcheck`,!1),R(r,()=>Xd(le().length),i),a.$$click=()=>void ge(),R(a,()=>A()?`saving…`:`💾 save`),y(()=>a.disabled=A()||le()===t().content),y(()=>n.value=le()),e}})}})]},get children(){var t=Um(),n=t.firstChild,r=n.firstChild;return R(t,j(N,{get when(){return u().kind===`image`},get fallback(){return j(N,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Zm();return y(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Xm();return y(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Hm();return y(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&I(t,`src`,n.e=r),i!==n.t&&I(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),R(n,()=>u().kind,r),t}})}})})]}we([`click`,`input`]);var $m=F(`<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 class=primarybtn>unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),eh=F(`<div class=leftbarbackdrop>`),th=F(`<div class=sidehead><b>agents</b><button class=iconbtn title="close the agent list">✕`),nh=F(`<i class=notifdot>`),rh=F(`<br>`),ih=F(`<button class="iconbtn ham"title="agent list">☰`),ah=F(`<input class="title titleedit">`),oh=F(`<span class="badge queued">⏳ <!> <!> queued`),sh=F(`<button type=button class="badge bgjobs">⚙️ `),ch=F(`<span class="badge cron">⏰ `),lh=F(`<div class=bgjobs-pop role=dialog aria-label="background shells"><div class=bgjobs-head><span>background shells</span><button type=button class=iconbtn title=close>✕`),uh=F(`<header class=chan-head><span class=hash title="rename this chat">#</span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙️</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),dh=F(`<div class=divider-msg>── beginning of log ──`),fh=F(`<div class=divider-msg>loading older events…`),ph=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading newer events…`),mh=F(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),hh=F(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),gh=F(`<div class=content>`),_h=F(`<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…`),vh=F(`<div class=feed>`),yh=F(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),bh=F(`<div class=termsplit>`),xh=F(`<div class="termempty muted">no shell here — click a tab or + to add`),Sh=F(`<div class=termpane>`),Ch=F(`<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>`),wh=F(`<button class=jump>↓ `),Th=F(`<div class=cmds>`),Eh=F(`<div class=imgstage><span class=muted style=font-size:11px;align-self:center> image<!> attached`),Dh=F(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),Oh=F(`<span class=muted style=font-size:11.5px;white-space:nowrap>🖼 `),kh=F(`<div class="hint flashhint">`),Ah=F(`<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>`),jh=F(`<div class=rightbarbackdrop>`),Mh=F(`<div><nav><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`),Nh=F(`<div class=notifbackdrop>`),Ph=F(`<button class=editbtn>clear all`),Fh=F(`<div class=notiflist>`),Ih=F(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),Lh=F(`<div class=bgphoto aria-hidden=true><img sizes=100vw alt decoding=async><span class=bgphoto-veil>`),Rh=F(`<span class=wscount>`),zh=F(`<div class=wsheader><span class=wscaret>`),Bh=F(`<span class=notifbadge>🔔️`),Vh=F(`<span class=subtag>🧩`),Hh=F(`<span class=mini-cron>⏰`),Uh=F(`<span class=goaldone title="goal done">✓`),Wh=F(`<div><span></span><span>`),Gh=F(`<span class=caret-spacer>`),Kh=F(`<span class=caret>`),qh=F(`<span class=ghosttag title="workspace missing">👻`),Jh=F(`<span>🧩 `),Yh=F(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),Xh=F(`<span class=title>`),Zh=F(`<div class="muted bgjobs-empty">no background jobs for this agent`),Qh=F(`<pre class="mono bgjob-tail">`),$h=F(`<div class=bgjob><div class=bgjob-line><span></span><code class="mono bgjob-cmd"></code><span class="muted bgjob-meta"></span><button type=button class=bgjob-kill>`),eg=F(`<div class="muted bgjob-detached">this job outlived a harness restart, so its output is no longer captured here. it is still running as pid <!> — read its own log, or stop it yourself.`),tg=F(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),ng=F(`<div class=muted style=display:grid;place-items:center;height:100%><span><span class=spinner aria-hidden=true></span> loading timeline…`),rg=F(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),ig=F(`<div class="content muted">thinking…`),ag=F(`<span>⌨ <button class=tabx title="close this shell">✕`),og=F(`<div><b class=mono></b><span class=muted>`),sg=F(`<div class=cmdrow><b>@</b><span class=muted>`),cg=F(`<span class=imgchip><img><button type=button class=imgx title=remove>✕`),lg=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> models`),ug=F(`<h3 title="switch provider/model live — applies from the agent's next turn">🧦 model`),dg=F(`<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`),fg=F(`<div class=meta style=color:var(--fg)>`),pg=F(`<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: `),mg=F(`<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`),hg=F(`<span>`),gg=F(`<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`),_g=F(`<div class=statrow style=margin-bottom:6px><span class=k>status`),vg=F(`<div class="card goalcard"><div class=content>`),yg=F(`<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…"title="drag the bottom edge to make this taller — the height is remembered"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 class=primarybtn>✓ save goal`),bg=F(`<span class=badge>/<!> done`),xg=F(`<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`),Sg=F(`<div class=bartrack style=margin-bottom:6px><div>`),Cg=F(`<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 class=okbtn>✓ save tasks`),wg=F(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),Tg=F(`<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`),Eg=F(`<div class=rtcell><span>cost</span><b>$`),Dg=F(`<div class=rtcell><span>cached</span><b>%`),Og=F(`<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>`),kg=F(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),Ag=F(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),jg=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),Mg=F(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙️ settings → scheduled tasks.">⏰ schedule`),Ng=F(`<option>`),Pg=F(`<span class=badge title="no goal set yet">no goal`),Fg=F(`<button>`),Ig=F(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),Lg=F(`<div class=muted>none yet`),Rg=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),zg=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),Bg=F(`<div class=progrow><b>next</b><span class="content inline-md">`),Vg=F(`<div class=progrow><b>goal</b><span>`),Hg=F(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),Ug=F(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),Wg=F(`<span>% of `),Gg=F(`<div class=bartrack><div>`),Kg=F(`<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)>`),qg=F(`<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`),Jg=F(`<div><span></span><span> events`),Yg=F(`<div class=muted>no scheduled tasks — add them in ⚙️ settings ("scheduled tasks")`),Xg=F(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),Zg=F(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),Qg=F(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),$g=F(`<div class=nbody>`),e_=F(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),t_=F(`<div style=font-size:12.5px;color:var(--dim)> event(s) came after this prompt and will be discarded — the new branch starts from your edited text.`),n_=F(`<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 class=primarybtn>⑂ fork & resend`),r_=F(`<span style=color:var(--err);font-size:13px>`),i_=F(`<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`),a_=F(`<div class=direntry>📁 `),o_=new Map;function s_(e){let t=o_.get(e);if(t!==void 0)return t;let n=Ie(e);return o_.set(e,n),o_.size>500&&o_.delete(o_.keys().next().value),n}var c_=[`minimal`,`low`,`medium`,`high`],l_=1100,[u_,d_]=v(``),f_,$=e=>{d_(e),clearTimeout(f_),f_=setTimeout(()=>d_(``),3200)},p_=!1,m_=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`,`system_note`]),h_=new Set([`system_note`]),g_=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`]),__=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),v_=location.hash.match(/[#&]token=([^&]+)/);v_&&(localStorage.setItem(`teapot.token`,decodeURIComponent(v_[1])),history.replaceState(null,``,location.pathname+location.search));var y_=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function b_(){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,p=null;async function m(e=!1){if(p)return p;if(f&&!e)return;let t=(async()=>{try{let e=await Q(`/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),f=!0}catch{}})();p=t;try{await t}finally{p===t&&(p=null)}}let[h,g]=v([]),[_,te]=v(0),[ne,w]=v([]),[T,E]=v(null),D=new Map,[O,re]=v(D.get(n()??``)??``),k=e=>{re(e);let t=n();t&&(e?D.set(t,e):D.delete(t))},[ie,ae]=v({providers:{}}),[oe,se]=v(!1),ce=()=>{let e=Xe()??(He()?st()?Je():it():ze());return Qe().find(t=>t.id===e)?.backgroundImage??``},le=()=>{let e=He()?st()?Je():it():ze();return Qe().some(t=>t.id===e)||gd.some(t=>t.key===e)?e:`dark`},[ue,A]=v(!1),de=!1;b(()=>{!de&&ie()?.needsSetup&&(de=!0,requestAnimationFrame(()=>{Er(),A(!0)}))}),b(()=>{ue()&&!Ha()&&Q(`/api/features`).then(e=>Ua(e)).catch(()=>Ua(null))});let fe=new Set,pe=()=>window.innerWidth<=l_,[me,he]=v(pe());ee(()=>{let e=()=>he(pe());window.addEventListener(`resize`,e),C(()=>window.removeEventListener(`resize`,e)),e()});let ge=0,_e=null,ve=0,ye,be,xe=0,Se=``,Ce=()=>{xe=0;let e=xi();if(!e)return;if(eo=e.scrollHeight,ro=e.clientHeight,At()){wi();return}let t=_e;if(!t)return;let n=e.querySelector(t.sel);if(!n)return;let r=n.getBoundingClientRect().top-t.top;r&&(e.scrollTop+=r,$a={top:e.scrollTop,height:e.scrollHeight}),un(Si())};function F(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||Math.abs(r)>to||(e.scrollTop+=r,$a={top:e.scrollTop,height:e.scrollHeight})}let we=()=>{xe||=requestAnimationFrame(Ce)},Te=e=>{e&&e!==be&&(ye??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==Se&&(Se=n,we())}),be&&ye.unobserve(be),be=e,Se=``,ye.observe(e))};ee(()=>{window.addEventListener(`resize`,we),C(()=>{window.removeEventListener(`resize`,we),ye?.disconnect(),ye=void 0,be=void 0,xe&&cancelAnimationFrame(xe)})});function ke(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[Ae,je]=v(localStorage.getItem(`teapot.panel`)===null?window.innerWidth>l_:localStorage.getItem(`teapot.panel`)===`1`),Me=e=>{je(e),localStorage.setItem(`teapot.panel`,e?`1`:`0`)},Ne=()=>Me(!Ae()),Pe=()=>{Ae()&&Me(!1)},[Fe,Le]=v(!1),Re=()=>Le(!1),[ze,Be]=v(localStorage.getItem(`teapot.theme`)??`dark`),[He,qe]=v(localStorage.getItem(`teapot.theme.auto`)===`1`),[Je,Ye]=v(localStorage.getItem(`teapot.theme.light`)??`light`),[Xe,Ze]=v(null),[Qe,rt]=v(On());ee(()=>{An().then(e=>{if(e===null)return;let t=Ot(Qe(),e);rt(t),kn(t)})});let[it,at]=v(localStorage.getItem(`teapot.theme.dark`)??`dark`),ot=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[st,ct]=v(ot?.matches??!1);ee(()=>{let e=e=>ct(e.matches);ot?.addEventListener(`change`,e),C(()=>ot?.removeEventListener(`change`,e))}),b(()=>{let e=Fn({want:Xe()??(He()?st()?Je():it():ze()),customIds:Qe().map(e=>e.id),presetIds:gd.map(e=>e.key),fallback:`dark`}),t=e.active,n=Qe().find(e=>e.id===t)??null;e.repaired&&(He()?localStorage.setItem(st()?`teapot.theme.light`:`teapot.theme.dark`,t):localStorage.setItem(`teapot.theme`,t)),document.documentElement.dataset.theme=t,Mn(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??gd.find(e=>e.key===t)?.mode??`dark`});let[lt,ut]=v(``),[dt,ft]=v(``),[pt,mt]=v(``);b(()=>{let t=n();mt(S(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[ht,gt]=v([]),_t=()=>Object.keys(ie().providers??{});async function yt(e){if(e)try{let t=await Q(`/api/models?provider=${encodeURIComponent(e)}`);gt(t.models??[])}catch{gt([])}}let xt=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)}`:``},St=()=>{let e=dt().trim()||B()?.model||``;if(!e)return``;let t=ht().find(t=>t.id===e);if(!t)return``;let n=[],r=xt(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${Xd(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(` · `)},Ct=null,wt=!1;b(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||ie().defaultProvider||_t()[0]||``;if(r){if(t!==Ct)Ct=t,wt=!1,S(()=>lt())!==i&&(ut(i),yt(i)),S(()=>dt())&&ft(``);else{let e=S(()=>lt());!S(()=>dt())&&e!==i&&sn(wt)&&(ut(i),yt(i))}}});let[Tt,Et]=v(!1),[At,Pt]=v(!0),[Gt,Yt]=v(0),[tn,rn]=v(-1),un=e=>rn(e?gn(e):-1),[bn,Sn]=v(null),Cn=()=>Pn().startsWith(`[compact] `),wn=()=>{let e=Cn()?Pn().slice(10):Pn();return e.length>1200?`…`+e.slice(-1200):e};b(()=>{bn()||jn(e=>e?.text.startsWith(`[compact] `)?null:e)}),b(()=>{h().length,_(),bn(),br().length,fi(),ui(),ci();let e=xi();if(!e)return;let t=e.scrollHeight;t!==ge&&(ge=t,requestAnimationFrame(()=>requestAnimationFrame(()=>{At()&&wi()})))});let[Tn,En]=v(new Map),Dn=()=>{let e=n();return e?Tn().get(e)??null:null},jn=e=>{let t=n();t&&En(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})},Nn=()=>{let e=Dn();if(!e)return;let t=tt(e,h(),B()?.status);t?(t.text!==e.text||t.reasoning!==e.reasoning)&&jn(t):jn(null)},[Pn,In]=v(``),[Ln,Rn]=v(0),zn=()=>Ln(),[z,Bn]=v(``),Vn;b(()=>{Dn()?Vn||=setTimeout(()=>{Vn=void 0,In(Dn()?.text??``),Bn(Dn()?.reasoning??``)},(Dn()?.text.length??0)>2e4?250:(Dn()?.text.length??0)>6e3?120:60):(clearTimeout(Vn),Vn=void 0,In(``),Bn(``))}),C(()=>clearTimeout(Vn)),b(()=>{let t=e();En(e=>et(e,e=>t.find(t=>t.id===e)?.status)),Rn(e=>nt(e,t,n(),Dn()))}),b(()=>{let e=Pn(),t=Dn()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{At()&&wi()})}),b(()=>{let e=B()?.pendingPrompts??0,t=B()?.pendingPromptIds,n=Xn(),r=Zn(n),i=Ht(r,e,t);i!==r&&Qn(n,i)}),b(()=>{let e=B()?.pendingPromptQueue;if(!e?.length)return;let t=B()?.session||Xn(),n=new Set(Zn(t).map(e=>e.promptId).filter(Boolean)),r=e.filter(e=>e.id&&!n.has(e.id));r.length&&Qn(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}:{}})),...Zn(t)])}),b(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{Ci()&&(Pt(!0),Yt(0),Ti(!0),sr())})};document.addEventListener(`visibilitychange`,e),C(()=>document.removeEventListener(`visibilitychange`,e))});let B=x(()=>e().find(e=>e.id===n())),Hn=()=>xn({sameSession:!(B()?.session!==Xn()&&B()?.session),agent:B(),echoCount:xr()}),Un=()=>{let e=B();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},Wn=()=>Qt(B(),i(),Un()),[Gn,Kn]=v(null);x(()=>{let e=new Set;for(let t of h())t.type===`tool_result`&&t.data?.name===`ask_user`&&e.add(String(t.data.callId));return e});let qn=new Map,[Jn,Yn]=v([]),Xn=()=>i()||n()||`?`,Zn=e=>qn.get(e)??[],Qn=(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?qn.delete(e):qn.set(e,r),Xn()===e&&Yn(r)},[$n,er]=v([]),[tr,nr]=v(localStorage.getItem(`teapot.hideGhosts`)===`1`),[rr,ir]=v(!1),ar=()=>$n().filter(e=>!e.read).length,or=e=>{er(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},sr=()=>{let e=n();e&&$n().some(t=>!t.read&&t.agentId===e)&&or(e)},cr=t=>{let n=$n().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=cr(r.id));return n},lr=0,ur=e=>{er(t=>[{...e,id:`n${++lr}`,at:Date.now(),read:!1},...t].slice(0,50))},dr=(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?ur({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?ur({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?ur({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&ur({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})},fr=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))},pr=x(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of h())if(m_.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}}),[mr,hr]=v(new Set),gr=e=>{e&&hr(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},_r=()=>hr(new Set),vr=x(()=>Vt(h(),mr())),yr=x(()=>vt({events:h(),consumed:pr().consumed,pending:Jn(),echo:Tr,feedTypes:m_,renderedTypes:g_,renderedNoteEvents:__})),br=()=>yr().rows,xr=()=>yr().pendingCount,Sr=x(()=>{let e=new WeakMap;return br().forEach((t,n)=>e.set(t,n)),e}),Cr=(e,t)=>{let n=Sr().get(e);if(n!==void 0)return br()[n+t]},wr=new Map;function Tr(e){let t=`${e.id}:${e.sent?`s`:`p`}`,n=wr.get(t);if(n)return n;wr.size>64&&wr.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:B()?.session??``,branch:B()?.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 wr.set(t,r),r}let Er=()=>Q(`/api/config`).then(ae).catch(()=>{}),[Dr,Or]=v(!1);ee(()=>{let e=()=>Or(!0);window.addEventListener(`teapot:unauthorized`,e),C(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[kr,Ar]=v(``),[jr,Mr]=v(!0),[Nr,Pr]=v(!1),Fr=``;b(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==Fr?(Fr=t,Pr(!1),Ar(r)):t&&!Nr()&&Ar(r)});let Ir=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await Q(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:kr(),notify:e})}),Pr(!1),Mr(!0),$(`tasks saved${e&&kr().trim()?` & notification queued`:``}`),V()}catch(e){$(`save failed: ${e.message}`)}},Lr=x(()=>{let e=0,t=0;for(let n of kr().split(`
29
+ `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function Rr(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 V=()=>Q(`/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),Rr(t,e.agents??[]))),n&&m()}).catch(()=>{}),zr=()=>Q(`/api/metrics`).then(E).catch(()=>{}),[Br,Vr]=v([]),Hr=()=>Q(`/api/tasks`).then(e=>Vr(e.tasks)).catch(()=>{}),Ur=e=>Br().filter(t=>t.agent===e),[Wr,Gr]=v((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[Kr,qr]=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}})()),Jr=e=>Kr().has(e)||!Wr().has(e),Yr=e=>{let t=new Set(Wr());if(t.has(e)?t.delete(e):t.add(e),Gr(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&Kr().has(e)){let t=new Set(Kr());t.delete(e),qr(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},H=t=>Rt(e(),t),[Xr,Zr]=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}})()),U=x(()=>{let e=new Set;for(let t of Xr())t.startsWith(`chat:`)&&e.add(t);return e}),Qr=x(()=>Nt(e(),new Set(e().filter(e=>Jr(e.id)).map(e=>e.id)),tr(),U())),$r=(t,r,i,a)=>{let o=new Set(Xr());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||H(e().find(e=>e.id===i))===t)&&$(`hid ${r} — click the header to show it`)}Zr(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},ei=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,W=e=>{let t=ti().get(e)??0;return`${t} chat${t===1?``:`s`}`},ti=x(()=>zt(e())),ni=x(()=>Bt(e(),Qr(),Xr())),[ri,ii]=v(null),ai=new Map;function oi(e){return`${i()||(n()??`?`)}:${e.id}`}function si(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=oi(r),a=ai.get(i);if(t[n]=a??r,!a&&(ai.set(i,r),ai.size>6e3)){let e=ai.keys().next().value;e!==void 0&&ai.delete(e)}}return t}let[ci,li]=v(!1),[ui,di]=v(!1),[fi,pi]=v(!1),mi=0,hi=-1;function G(e){let t=si(e);g(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 gi(){let e=n();if(!e||fi()||ci()||At())return;if(h().length>=_()){pi(!0);return}let t=()=>{let e=xi();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!fi()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(h().length>=_()){pi(!0);return}let i=h().length;if(await _i(),h().length===i)return;fn(Si())&&n()===e&&Ti(!0)}}async function _i(){let e=n(),t=h()[0];if(e&&t&&!ci()&&!fi()){li(!0);try{let r=xi(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=ri(),c=i(),l=(await Q(yi(e,{before:t.id},c,s))).events??[];if(l.length===0){pi(!0);return}if(n()!==e||h()[0]?.id!==t.id)return;G(l),requestAnimationFrame(()=>{if(n()===e){let e=xi();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{li(!1)}}}function vi(e,t){return t&&o().has(t)?`&session=${encodeURIComponent(t)}`:``}function yi(e,t,n,r){let i=[`/api/agents/${encodeURIComponent(e)}/events?limit=2000`];t.before&&i.push(`&before=${encodeURIComponent(t.before)}`),t.after&&i.push(`&after=${encodeURIComponent(t.after)}`);let a=vi(e,n);return a&&i.push(a),r&&i.push(`&branch=${encodeURIComponent(r)}&lineage=true`),i.join(``)}async function bi(e,t){let r=mi,a=t??i()??``;try{let t=ri(),i=r!==hi||!ne().length;h().length||di(!0),Q(`/api/agents/${e}/skills`).then(t=>{r===mi&&n()===e&&Va(t.skills??[])}).catch(()=>{});let[o,s]=await Promise.all([Q(yi(e,{},a,t)),i?Q(`/api/agents/${e}/branches`):Promise.resolve({branches:ne()})]);if(i&&(hi=r),r!==mi||n()!==e)return;g(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of si(o.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)}),te(o.total??o.events.length),w(s.branches)}catch{}finally{di(!1)}}function xi(){return document.querySelector(`.feed`)}function Si(){let e=xi();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function Ci(){return fn(Si())}function wi(){let e=xi();e&&(e.scrollTop=e.scrollHeight,$a={top:e.scrollTop,height:e.scrollHeight},Yt(0))}function Ti(e=!1){(e||At())&&wi()}let Ei=new Map,Di=new Map,Oi=25165824,ki=e=>{let t=e.data,n=64;if(t)for(let e of Object.values(t))typeof e==`string`&&(n+=e.length*2);return n},Ai=(t,n)=>Ut(c().get(t),e().find(e=>e.id===t)?.session,n);async function ji(e,t=!0,s){let l=n(),u=i(),d=h(),f=_();mi++,c().size||m();let p=Ai(e,s),v=s&&o().has(s)?s:null,y=p??v??e;if(l!==e||y!==u){{let e=xi(),t=e?ke(e):null,n=u||l;if(e&&n&&t){let r=e.querySelector(t.sel)?.dataset.eid??``,i=e.scrollHeight-e.scrollTop-e.clientHeight<=24;for(r&&Di.set(n,{eid:r,delta:e.getBoundingClientRect().top-t.top,atTail:i});Di.size>24;){let e=Di.keys().next().value;if(e===void 0)break;Di.delete(e)}}}if(u&&d.length){let e=d.reduce((e,t)=>e+ki(t),0);e<=Oi&&Ei.set(u,{events:d,total:f,at:Date.now(),bytes:e});let t=()=>[...Ei.values()].reduce((e,t)=>e+t.bytes,0);for(;Ei.size>6||t()>Oi;){let e=[...Ei.entries()].sort((e,t)=>e[1].at-t[1].at)[0];if(!e)break;Ei.delete(e[0])}}g([]),ai.clear(),_r(),Sn(null),Yt(0),Pt(Di.get(y)?.atTail??!0),Qa=void 0}r(e),a(y),k(D.get(e)??``),ii(null),pi(!1),li(!1),Qn(u||l||`?`,Jn()),Yn(Zn(y||e)),localStorage.setItem(`teapot.session`,e),Wi(y,t);let b=Ei.get(y);if(b?.events.length&&(g(si(b.events)),te(b.total),di(!0),Di.has(y)||requestAnimationFrame(()=>{n()===e&&Ti(!0)})),Q(`/api/agents/${e}/load`,{method:`POST`}).then(V).catch(()=>{}),await bi(e,y),n()!==e)return;En(t=>{let n=t.get(e)??null,r=tt(n,h(),B()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),Sn(B()?.ctx?.compacting?{phase:String(B().ctx.compacting)}:null);let x=Di.get(y);Pt(!x||x.atTail),requestAnimationFrame(()=>{if(n()===e){if(x){let e=xi(),t=e?.querySelector(`[data-eid="${CSS.escape(x.eid)}"]`);if(e&&t){e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top+x.delta,$a={top:e.scrollTop,height:e.scrollHeight},x.atTail&&Ti(!0);return}x.atTail&&Ti(!0)}else Ti(!0)}}),gi()}let[Mi,Ni]=v(!1),Pi=null,Fi=null;C(()=>Pi?.close());let Ii=!1,Li=!1,Ri=null;document.addEventListener(`visibilitychange`,()=>Ri?.()),C(()=>{Ri=null});let zi=!0,Bi=null;async function Vi(){let e=n(),t=h().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)Ii=!0,a||Bi?.();else try{let n=ri(),i=await Q(yi(e,{after:t},r,n)),o=i.events??[];i.gap?(g(si(o)),te(o.length)):o.length&&(G(o),te(e=>e+o.length)),await V(),o.length&&!a&&zr()}catch{Ii=!0}}function Hi(){zi=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${y_()}`);Pi=a,a.onopen=()=>{Ni(!0),zi?zi=!1:Vi()},a.onclose=()=>{Ni(!1),setTimeout(Hi,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=>Rr(e,c.agents));let n=e();En(e=>et(e,e=>n.find(t=>t.id===e)?.status))}else if(c.kind===`event`&&Ke(c.event))En(e=>Ge(e,c.agentId));else if(c.kind===`llm-delta`){if(!Zt(c,n(),i()))return;if(En(e=>We(e,c.agentId,c)),c.agentId===n()){let e=String(c.reasoning??``),t=String(c.text??``);e&&!t?Ln()||Rn(Date.now()):t&&Rn(0)}}else if(c.kind===`compaction-progress`){if(c.agentId!==n())return;c.phase===`done`?Sn(null):Sn({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]:Rr(e,e.map((e,n)=>n===t?c.snapshot:e))});else if(c.kind===`metrics`&&c.metrics)E(c.metrics);else if(c.kind===`tasks`&&Array.isArray(c.tasks))Vr(c.tasks);else{if(c.kind===`event`){let e=c.event?.type,t=c.event?.data??{};if(e===`system_note`&&(t.event===`prompt-delivered`||t.event===`prompt-cancelled`)){let e=String(t.promptId??``);if(e){let t=String(c.event?.session??``),n=new Set;t&&n.add(t),n.add(Xn());for(let[t,r]of qn)r.some(t=>t.promptId===e)&&n.add(t);for(let t of n){let n=Zn(t);n.some(t=>t.promptId===e)&&Qn(t,n.filter(t=>t.promptId!==e))}}}if(o.has(e)&&!h_.has(e)||(dr(c.agentId,c.event),c.event?.agent!==n())||!Xt(c.event,n(),i()))return;{let e=h().at(-1)?.seq??0,t=Number(c.event?.seq??0);(!e||t>0&&t>e+1)&&(Li=!0)}if(G([c.event]),c.event&&Nn(),Ii=!0,document.visibilityState!==`visible`||Fi)return;Fi=setTimeout(s,60)}document.visibilityState===`hidden`?Ii=!0:Fi||=setTimeout(s,120)}}},Ii=!1;let s=async()=>{if(Fi=null,n()){let e=h().at(-1)?.id,t=h().length;Li&&(Li=!1,await bi(n()));let r=Dn();r&&!tt(r,h(),B()?.status)&&jn(null),h().at(-1)?.id!==e&&(At()?(wi(),or(n())):(Yt(e=>e+Math.max(0,h().length-t)),un(Si())))}};Bi=s,Ri=()=>{document.visibilityState===`visible`&&(zr(),Hr(),n()&&(Ii?(Ii=!1,s()):h().at(-1)?.id?Vi():(Ii=!0,s())))}}let Ui=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function Wi(t,n=!0){let r=Wt(t,o(),e().map(e=>e.id));if(!r)return;let i=`/session/${encodeURIComponent(r)}`;n?history.pushState(null,``,i):history.replaceState(null,``,i)}window.addEventListener(`popstate`,()=>{let e=Ui(),t=o().get(e);t&&(t!==n()||e!==i())&&ji(t,!1,e||null)}),b(()=>{let e=B(),t=e?`${Un()?`▶ `:e.status===`error`?`⚠ `:``}${vn(e)} · teapot`:`teapot`;document.title=ar()>0?`(${ar()}) ${t}`:t});let Gi=()=>oe()||ue()||Gn()!==null||pe()&&Ae();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(oe()){se(!1);return}if(ue()){A(!1);return}if(Gn()){Kn(null);return}if(pe()&&Ae()){Pe();return}let e=B();if(e&&Un()){Q(`/api/agents/${e.id}/stop`,{method:`POST`}).then(V);return}}else if(!Gi()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)Ne();else if(e.key===`t`)aa();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=Qr().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&&ji(t[i].id)}}});let[Ki,qi]=v(localStorage.getItem(`teapot.term`)===`1`),[Ji,Yi]=v([]),[Xi,Zi]=v(!1),Qi=async()=>{let e=n();if(!e)return;let t=await Q(`/api/agents/${encodeURIComponent(e)}/bg-jobs`).catch(()=>null);t?.jobs&&Yi(t.jobs)};b(()=>{n(),Qi()}),b(()=>{if(!Xi())return;let e=setInterval(()=>void Qi(),2e3);C(()=>clearInterval(e))});let[$i,ea]=v(!1),[ta,na]=v(``),ra=()=>{let e=B();e&&(na(vn(e)),ea(!0))},ia=async()=>{if(!$i())return;let e=B();ea(!1);let t=ta().replace(/\s+/g,` `).trim();if(!e||!t||t===vn(e))return;let n=await Q(`/api/agents/${encodeURIComponent(e.id)}/session-title?session=${encodeURIComponent(e.session)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({title:t})}).catch(e=>({error:String(e)}));n?.error?$(`rename failed: ${n.error}`):(d(n=>new Map(n).set(e.session,t)),V())},aa=()=>{let e=!Ki();qi(e),localStorage.setItem(`teapot.term`,e?`1`:`0`)},[oa,sa]=v([]),[ca,la]=v(0),[ua,da]=v(-1),[fa,pa]=v(!1),[ma,ha]=v(0),[ga,_a]=v(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),va=new Map,ya=[null,null],ba=()=>oa()[ma()===0?ca():ua()]??null;function xa(e){if(!oa()[e])return;let t=ma(),n=t===0?ca():ua(),r=t===0?ua():ca(),i=e=>t===0?la(e):da(e);r===e?((e=>t===0?da(e):la(e))(n),i(e)):n!==e&&i(e)}let Sa=()=>Ca();async function Ca(e){let t=e??n();if(t){if(oa().filter(e=>e.agentId===t).length>=10)$(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await Q(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){$(`could not open a shell`);return}let n=Du(oa());sa(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title}]),ma()===0?la(n):da(n)}catch(e){$(`could not open a shell: ${e.message}`)}}}function wa(e){let t=oa()[e];if(!t)return;Q(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=va.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),va.delete(t.key)}let r=oa().filter((t,n)=>n!==e);sa(r),la(t=>ku(t,e,r.length)),da(t=>t===-1?-1:ku(t,e,r.length))}b(()=>{He(),ze(),st(),Je(),it();for(let[,e]of va)en(e.term)});function Ta(){for(let[,e]of va){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}va.clear()}function Ea(e,t){let n=va.get(e.key);if(n&&en(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 Cu({cursorBlink:!0,fontSize:12.5,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,theme:$t()}),a=new Eu;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=()=>`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${y_()}`,c=new WebSocket(s()),l,u=!1,d=t=>{t.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`ping`||(n.kind===`exit`?(u=!0,i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),sa(t=>t.filter(t=>t.key!==e.key)),va.get(e.key)?.term.dispose(),va.delete(e.key)):n.kind===`attach`&&n.error&&(u=!0,i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)))},t.onclose=()=>{!u&&va.has(e.key)&&(l||=(i.write(`\r
30
30
  \x1B[2m[connection lost — reconnecting…]\x1B[0m\r
31
31
  `),setTimeout(function(){if(l=void 0,!va.has(e.key))return;let t=new WebSocket(s());c=t,d(t),t.addEventListener(`open`,()=>h())},1500)))}};d(c),i.onData(e=>{c.readyState===WebSocket.OPEN&&c.send(JSON.stringify({kind:`input`,data:e}))});let f={cols:0,rows:0},p,m=[],h=()=>{try{a.fit()}catch{}c.readyState===WebSocket.OPEN?(i.cols!==f.cols||i.rows!==f.rows)&&(f={cols:i.cols,rows:i.rows},c.send(JSON.stringify({kind:`resize`,cols:i.cols,rows:i.rows}))):g()};function g(){p||=setInterval(()=>{va.has(e.key)?c.readyState===WebSocket.OPEN&&(clearInterval(p),p=void 0,h()):(clearInterval(p),p=void 0)},400)}c.addEventListener(`open`,()=>h());let _=r.parentElement??r,v=new ResizeObserver(()=>{m[0]&&clearTimeout(m[0]),m[0]=setTimeout(h,250)});v.observe(_),_!==r&&v.observe(r),setTimeout(h,60),n={el:r,term:i,fit:a,ws:c,ro:v},va.set(e.key,n)}return n}function Da(e){let t=ya[e];if(!t)return;let n=oa()[e===0?ca():ua()];if(!n){[...va.values()].some(e=>e.el.parentElement===t)&&t.replaceChildren();return}let r=Ea(n,t);for(let[e,r]of va)e!==n.key&&r.el.parentElement===t&&r.el.remove();requestAnimationFrame(()=>{r.el.parentElement!==t&&t.appendChild(r.el);try{r.fit()}catch{}if(ma()===(e===0?0:1))try{r.term.focus()}catch{}})}b(()=>{oa(),fa(),ca(),ua(),ga(),requestAnimationFrame(()=>{Da(0),fa()&&Da(1)})});let Oa=null;b(()=>{if(!Ki())return;let e=n();if(!e||e===Oa)return;Oa=e;let t=oa().map((e,t)=>({t:e,i:t})).filter(t=>t.t.agentId===e);t.length&&xa(t[t.length-1].i)}),b(()=>{let e=oa().length,t=Ou(ca(),e);if(t!==ca()&&la(t),fa()){let t=Ou(ua(),e);t!==ua()&&da(t)}});let ka=e=>{e.preventDefault();let t=e.clientY,n=ga(),r=e=>{let r=Math.min(Math.max(n-(e.clientY-t),140),Math.round(window.innerHeight*.85));_a(r)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),localStorage.setItem(`teapot.termH`,String(ga())),requestAnimationFrame(()=>{Da(0),fa()&&Da(1)})};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},Aa=()=>{let e=!fa();pa(e),e&&(ua()<0||ua()===ca()||ua()>=oa().length)&&da(Au(ca(),oa().length)),requestAnimationFrame(()=>{Da(0),fa()&&Da(1)})};C(Ta);let ja=e=>t=>{ya[e]=t,t&&requestAnimationFrame(()=>{Da(e),fa()&&Da(1),setTimeout(()=>Da(e),200)})};ee(()=>{Er(),V().then(async()=>{await m();let t=Ui(),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&&ji(r.id,!1,t||null)}),zr(),Hr(),Fa(),Hi(),Q(`/api/terminals`).then(e=>{let t=e.terminals??[];t.length&&(sa(t.map(e=>({key:e.id,agentId:e.agentId,title:e.title}))),Ki()&&(la(0),da(-1)))}).catch(()=>{}),C(()=>{})});let Ma=[{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`}],[Na,Pa]=v([]),Fa=()=>Q(`/api/personas`).then(e=>Pa(e.personas)).catch(()=>{}),[Ia,La]=v(!1),Ra=()=>{let e=O().match(/^@([A-Za-z0-9._-]*)$/);return e?e[1].toLowerCase():null},za=()=>{let t=Ra();return t===null?[]:[...Na().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))},K=new Set([`start`,`stop`,`fork`,`compact`]),[Ba,Va]=v([]),[Ha,Ua]=v(null),[Wa,Ga]=v(-1),Ka=()=>{let e=O();if(!e.startsWith(`/`)||e.includes(`
32
32
  `))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=Ma.filter(e=>e.cmd.slice(1).startsWith(n));return e.find(e=>e.cmd.slice(1)===n)&&K.has(n)?[]:e.map(e=>({insert:e.cmd+` `,title:e.desc}))}if(n===`skill`){let e=Ba().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[]},qa,q,Ja,Ya=!1;function Xa(e){if(!q){q=document.createElement(`div`),q.setAttribute(`aria-hidden`,`true`);let e=q.style;e.position=`absolute`,e.visibility=`hidden`,e.pointerEvents=`none`,e.top=`0`,e.left=`-9999px`,e.whiteSpace=`pre-wrap`,e.overflowWrap=`anywhere`,e.wordBreak=`break-word`,q.dataset.mirror=``}let t=getComputedStyle(e);for(let e of[`font-family`,`font-size`,`font-weight`,`line-height`,`letter-spacing`,`padding-top`,`padding-bottom`,`padding-left`,`padding-right`,`border-top-width`,`border-bottom-width`,`box-sizing`])q.style.setProperty(e,t.getPropertyValue(e));if(q.style.width=`${e.clientWidth}px`,q.setAttribute(`data-mirror-text`,e.value.endsWith(`
33
- `)?`${e.value} `:e.value),Ja||(Ja=document.createElement(`div`),Ja.setAttribute(`aria-hidden`,`true`),Ja.style.cssText=`position:absolute;left:-9999px;top:0;pointer-events:none`,document.body.appendChild(Ja)),q.parentElement!==Ja&&Ja.appendChild(q),!Ya){let e=document.createElement(`style`);e.textContent=`[data-mirror]::after{content:attr(data-mirror-text);white-space:pre-wrap;display:block}`,document.head.appendChild(e),Ya=!0}return q.scrollHeight}let Za=()=>{if(!qa)return;let e=Tt();if(!qa.value&&!e){qa.style.height=``;return}let t=Xa(qa),n=e?-1:_n(t,360);qa.style.height=n===-1?``:`${n}px`},Qa,$a=null,eo,to=240,no=4,ro;b(()=>{let e=O();qa&&cn(h_)&&(ln(qa.value,e)&&(qa.value=e),Za())}),ee(()=>{let e=0,t=()=>{e||=requestAnimationFrame(()=>{e=0,Za()})};window.addEventListener(`resize`,t),C(()=>{window.removeEventListener(`resize`,t),e&&cancelAnimationFrame(e)})});let[io,ao]=v([]),oo=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){$(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{ao(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},so=async(t,r,i)=>{let a=r??n();if(!a)return;let o=io(),s=e().find(e=>e.id===a)?.session||a;try{let e=await Q(`/api/agents/${a}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:t,start:!0,...i?{source:i}:{},...o.length?{images:o}:{}})});Qn(s,[...Zn(s),{id:`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`,text:t,at:Date.now(),promptId:e.promptId,...o.length?{images:o.map(e=>e.url)}:{}}]),ao([]),Nu(Tt())&&Et(!1),Za(),At()&&requestAnimationFrame(()=>{At()&&wi()})}catch(e){k(t),console.error(`send failed:`,e)}},co=async t=>{t.preventDefault();let r=n(),i=O().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=Na().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){$(`usage: @${r} <task>`);return}$(`🧩 spawned ${(await Q(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:Ia()?`fork`:`none`})})).id}${Ia()?` (forked context)`:``}`),V(),k(``)}else if(s){if(!a){$(`usage: @${r} <message>`);return}await Q(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),$(`→ delivered to @${r}`),k(``)}else{$(`unknown @${r} — personas: ${Na().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){$(`@${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){k(`/goal `);return}if(t===`skill`&&!n){k(`/skill `);return}k(``);try{await lo(t,n)}catch(e){throw k(O()?`${i}\n${O()}`:i),e}}else k(``),await so(i)}},lo=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>Q(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(V);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await ji(r);else if(e===`compact`)$((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){$(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),$(`goal saved & notification queued`)}else if(e===`skill`){if(!t){$(`usage: /skill <name>`);return}await so(`[harness] Force-load and follow the skill "${t}" now: call load_skill("${t}") and execute its playbook for the current task.`,void 0,`harness`),$(`skill "${t}" dispatched`)}else $(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){$(`/${e} failed: ${t.message}`)}},uo,fo=0;b(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!uo)return;let e=Math.min(fo,uo.scrollHeight);Math.abs(uo.scrollTop-e)>1&&(uo.scrollTop=e)})})});let po=e=>()=>n()&&Q(`/api/agents/${n()}${e}`,{method:`POST`}).then(V),mo=async()=>{let i=n();if(!i)return;let a=new Set([i,...Lt(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 Q(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),m(!0);let s=ju(e(),a);s?ji(s.id):(r(null),g([]))},ho=async()=>{n()&&($(`stopped: ${((await Q(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),V())},go=()=>Q(`/api/agents/${B().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await m(!0),await ji(B().id)}),[_o,vo]=v(``),[yo,bo]=v(Kt(`goal`)),[xo,So]=v(Kt(`goalPreview`)),Co=()=>{let e={"max-height":`none`,"overflow-y":`auto`,resize:`vertical`};return xo()>0&&(e.height=`${xo()}px`),e},wo=e=>{C(Jt(e,e=>{So(t=>Math.abs(t-e)<1?t:(qt(`goalPreview`,e),e))}))},To=()=>yo()>0?{height:`${yo()}px`}:void 0,Eo=e=>{C(Jt(e,e=>{bo(t=>Math.abs(t-e)<1?t:(qt(`goal`,e),e))}))},[Do,Oo]=v(``),[ko,Ao]=v(!1),[jo,Mo]=v(!0),No=``;b(()=>{let e=n();e&&(B()?.goal,e!==No&&(No=e,Ao(!1),vo(``),Oo(``)))});let Po=async e=>{if(e.preventDefault(),n()&&_o().trim())try{await Q(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:_o(),notify:jo(),...Do().trim()?{verify:Do()}:{}})}),vo(``),Oo(``),Ao(!1),V()}catch(e){$(`goal save failed: ${e.message}`)}};return[j(N,{get when(){return Dr()},get children(){var e=th();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}}),j(N,{get when(){return ce()},children:e=>(()=>{var t=zh(),n=t.firstChild;return y(t=>{var r=Mt(e(),kt[kt.length-1]),i=jt(e());return r!==t.e&&I(n,`src`,t.e=r),i!==t.t&&I(n,`srcset`,t.t=i),t},{e:void 0,t:void 0}),t})()}),(()=>{var t=Ph(),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,m=p.firstChild;m.firstChild,R(t,j(N,{get when(){return P(()=>!!me())()&&Fe()},get children(){var e=nh();return e.$$click=Re,e}}),r),R(r,j(N,{get when(){return me()},get children(){var e=rh(),t=e.firstChild.nextSibling;return t.$$click=Re,e}}),i),R(i,j(M,{get each(){return ni()},children:t=>[j(N,{get when(){return P(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=Vh(),n=e.firstChild;return e.$$click=()=>$r(`ws:${t.wsHeader}`,ei(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),R(n,()=>t.wsCollapsedGroup?`▸`:`▾`),R(e,()=>ei(t.wsHeader),null),R(e,j(N,{get when(){return(ti().get(t.wsHeader)??0)>1||t.wsCollapsedGroup},get children(){var e=Bh();return R(e,()=>ti().get(t.wsHeader)??0),e}}),null),y(()=>I(e,`title`,t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${W(t.wsHeader)} hidden). Click to show.`:(ti().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${W(t.wsHeader)} in this directory`:t.wsHeader||``)),e}}),j(N,{get when(){return P(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=Kh(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>ji(t.a.id),R(r,j(N,{get when(){return Ft({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return qh()},get children(){return(()=>{let e=!t.a.parent,n=e&&U().has(`chat:${t.a.id}`)||Jr(t.a.id);return(()=>{var r=Jh();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!Wr().has(t.a.id)){let e=new Set(Wr());e.add(t.a.id),Gr(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(Kr().has(t.a.id)){let e=new Set(Kr());e.delete(t.a.id),qr(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(Wr().has(t.a.id)){let e=new Set(Wr());e.delete(t.a.id),Gr(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}$r(`chat:${t.a.id}`,t.a.id,n)}else Yr(t.a.id)},R(r,n?`▸`:`▾`),y(()=>I(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),R(a,()=>vn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)})),R(r,(()=>{var e=P(()=>!!t.a.workspaceMissing);return()=>e()?Yh():null})(),null),R(r,j(N,{get when(){return cr(t.a.id)>0},get children(){var e=Hh();return e.firstChild,R(e,()=>cr(t.a.id),null),y(()=>I(e,`title`,`${cr(t.a.id)} unread notification${cr(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),R(r,j(N,{get when(){return Jr(t.a.id)||t.chatCollapsedGroup===!0&&U().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=Lt(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=Xh();return e.firstChild,L(e,`subcount`+(r>0?` live`:``)),R(e,()=>n.length,null),R(e,r>0?` · ▶${r}`:``,null),y(()=>I(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),R(r,j(N,{get when(){return t.a.parent},get children(){return Uh()}}),null),R(r,j(N,{get when(){return Ur(t.a.id).length>0},get children(){var e=Wh();return y(()=>I(e,`title`,Ur(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
34
- `))),e}}),null),R(r,j(N,{get when(){return t.a.goal.status===`done`},get children(){return Gh()}}),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=It(t.a.id,Na().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`:yn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)});return o!==e.e&&L(r,e.e=o),e.t=Ee(r,s,e.t),c!==e.a&&I(r,`title`,e.a=c),l!==e.o&&L(i,e.o=l),d!==e.i&&I(i,`title`,e.i=d),f!==e.n&&L(a,e.n=f),p!==e.s&&I(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(),ir(!rr()),rr()||er(e=>e.map(e=>({...e,read:!0})))},R(o,j(N,{get when(){return ar()>0},get children(){var e=ih();return R(e,ar),e}}),null),R(a,j(Ru,{icon:`👻`,get active(){return tr()},get title(){return tr()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!tr();if(nr(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&B()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&ji(t.id)}}}),null),R(a,j(Ru,{icon:`+`,title:`new agent`,onClick:()=>{Er(),se(!0)}}),null),R(a,j(Ru,{icon:`⚙️`,title:`settings`,onClick:()=>{Er(),A(!0)}}),null),R(c,`0.37.72`,null),R(d,j(N,{get when(){return T()},get children(){return[`master rss `,P(()=>T().rssMb),`MB · heap `,P(()=>T().heapUsedMb),`MB`,j(N,{get when(){return T().heapTotalMb!==void 0},get children(){return[` · total `,P(()=>T().heapTotalMb),`MB`]}}),j(N,{get when(){return T().externalMb!==void 0},get children(){return[` · ext `,P(()=>T().externalMb),`MB`]}}),ah(),`load1 `,P(()=>T().loadavg1),` · up `,P(()=>Math.floor(T().uptimeSec/60)),`m`]}})),R(f,j(N,{get when(){return B()?.id},keyed:!0,get fallback(){return Zh()},get children(){return[(()=>{var t=fh(),r=t.firstChild,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 R(t,j(N,{get when(){return me()},get children(){var e=oh();return e.$$click=()=>Le(!Fe()),y(()=>I(e,`aria-expanded`,Fe())),e}}),r),r.$$click=()=>ra(),R(t,j(N,{get when(){return $i()},get fallback(){return(()=>{var e=Qh();return e.$$click=()=>ra(),R(e,()=>vn(B())),y(()=>I(e,`title`,`${yn(B(),B().session)} — click to rename`)),e})()},get children(){var e=sh();return e.addEventListener(`blur`,()=>void ia()),e.$$keydown=e=>{e.key===`Enter`?(e.preventDefault(),ia()):e.key===`Escape`&&(e.preventDefault(),ea(!1))},e.$$input=e=>na(e.currentTarget.value),Oe(e=>{requestAnimationFrame(()=>{e.focus(),e.select()})},e),I(e,`spellcheck`,!1),y(()=>e.value=ta()),e}}),i),R(i,()=>B().status),R(t,j(N,{get when(){return Hn()>0},get children(){var e=ch(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return n.nextSibling,R(e,Hn,t),R(e,()=>Hn()===1?`message`:`messages`,n),R(e,()=>B().status===`stopped`?` (stopped)`:``,null),y(()=>I(e,`title`,(()=>{let e=B().pendingPromptQueue??[],t=e.length||B().pendingPromptIds?.length||B().pendingPrompts||0,n=e.length?e.filter(e=>(e.source??`user`)===`user`).length:t,r=t-n;return`${`${t} message${t>1?`s`:``} queued${r?` — ${n} from you, ${r} from the harness`:` from you`}`}. ${B().status===`stopped`?`This agent is STOPPED, so nothing will run until you press start (or it is resumed).`:`They are handed to the model at its next turn boundary — the timeline shows them as queued… until then.`}`+(n?` Yours can be withdrawn with ✕ cancel while still queued.`:``)})())),e}}),a),R(t,j(N,{get when(){return Ji().length>0},get children(){var e=lh();return e.firstChild,e.$$click=()=>{Zi(!Xi()),Xi()&&Qi()},R(e,()=>Ji().filter(e=>e.running).length||Ji().length,null),R(e,()=>Ji().some(e=>e.running)?` running`:` done`,null),y(t=>{var n=Xi(),r=`background shells — ${Ji().filter(e=>e.running).length} running, ${Ji().length} total (click to inspect)`;return n!==t.e&&I(e,`aria-expanded`,t.e=n),r!==t.t&&I(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),a),R(t,j(N,{get when(){return Ur(B().id).length>0},get children(){var e=uh();return e.firstChild,R(e,()=>Ur(B().id).length,null),y(()=>I(e,`title`,`scheduled tasks:\n${Ur(B().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
35
- `)}`)),e}}),a),R(a,()=>B().model,o),R(a,()=>B().session,s),R(a,()=>B().branch,c),R(a,()=>B().stats.turns,l),R(a,()=>B().stats.toolCalls,u),f.$$click=()=>(Un()?po(`/stop`):po(`/start`))(),R(f,()=>Un()?`■ stop`:`▶ start`),R(d,j(N,{get when(){return e().some(e=>e.parent===n())},get children(){return j(Ru,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ho})}}),p),R(d,j(Ru,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙️ settings → archive)`,onClick:mo}),null),R(d,j(Ru,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:go}),null),R(d,j(Ru,{icon:`⌨`,title:`terminal (t)`,onClick:aa}),null),R(d,j(Ru,{icon:`▤`,title:`toggle details panel (d)`,get active(){return Ae()},onClick:Ne}),null),R(t,j(N,{get when(){return Xi()},get children(){var e=dh(),t=e.firstChild.firstChild.nextSibling;return t.$$click=()=>Zi(!1),R(e,j(N,{get when(){return Ji().length>0},get fallback(){return $h()},get children(){return j(M,{get each(){return Ji()},children:e=>(()=>{var t=tg(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(r,()=>Zd(e.cmd,80)),R(i,(()=>{var t=P(()=>!!e.detached);return()=>t()?`detached · pid ${e.pid??`?`}`:P(()=>!!e.running)()?Ve(Date.now()-e.startedAt):`exit ${e.code??`?`}`})(),null),R(i,()=>e.truncated?` · truncated`:``,null),a.$$click=async()=>{await Q(`/api/agents/${encodeURIComponent(B().id)}/bg-jobs/${encodeURIComponent(e.id)}`,{method:`DELETE`}).catch(()=>{}),await Qi()},R(a,(()=>{var t=P(()=>!!e.detached);return()=>t()?`forget`:e.running?`kill`:`clear`})()),R(t,j(N,{get when(){return e.tail.trim()},get fallback(){return j(N,{get when(){return e.detached},get children(){var t=ng(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.pid??`?`,n),t}})},get children(){var t=eg();return R(t,()=>e.tail),t}}),null),y(t=>{var i=`bgjob-dot `+(e.running?`running`:`done`),o=e.running?`running`:`finished`,s=e.cmd,c=e.detached?`this job survived a harness restart (pid ${e.pid??`?`}) — its output can no longer be read here; stop it yourself if needed`:e.running?`kill this job (whole process group)`:`forget this finished job`;return i!==t.e&&L(n,t.e=i),o!==t.t&&I(n,`title`,t.t=o),s!==t.a&&I(r,`title`,t.a=s),c!==t.o&&I(a,`title`,t.o=c),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()})}}),null),e}}),null),y(e=>{var t=`badge ${B().status}`,n=B().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(B().statusReason)?`${B().status} — ${B().statusReason}`:void 0,r=`${B().model} · ${B().session}/${B().branch} · turns ${B().stats.turns} · tools ${B().stats.toolCalls}`,o=`runbtn`+(Un()?` danger`:``),s=Un()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&L(i,e.e=t),n!==e.t&&I(i,`title`,e.t=n),r!==e.a&&I(a,`title`,e.a=r),o!==e.o&&L(f,e.o=o),s!==e.i&&I(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=bh();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=pn(r,$a,eo,ro);i===`layout`&&!At()&&no>0&&Math.abs(r.height-(eo??r.height))>1&&(no--,F(t,_e)),$a=null,eo=r.height,ro=r.viewport,un(r);let a=At(),o=performance.now();o-ve>100&&(ve=o,_e=ke(t));let s=hn(a,i,r);s!==a&&Pt(s),i===`reader`&&(no=4),s&&i!==`reader`?(Gt()&&Yt(0),sr(),mn(s,r)&&dn(r)>0&&wi()):s&&fn(r)&&(Gt()&&Yt(0),sr()),r.top<=4&&n()&&!ci()&&!fi()&&h().length>0&&_i()}),Oe(e=>Te(e),e),R(e,j(N,{get when(){return bn()},children:e=>(()=>{var t=rg();return t.firstChild,R(t,(()=>{var t=P(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?Xd(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),R(e,j(N,{get when(){return P(()=>!!fi())()&&br().length>0},get children(){return ph()}}),null),R(e,j(N,{get when(){return ci()},get children(){return mh()}}),null),R(e,j(N,{get when(){return br().length>0},get fallback(){return P(()=>!!ui())()?ig():ag()},get children(){return[j(M,{get each(){return br()},children:e=>j(Sp,{e,prev:()=>Cr(e,-1),next:()=>Cr(e,1),get showBranch(){return ne().length>1},res:()=>pr().resFor.get(e.id),get orphan(){return pr().orphanCalls.has(e.id)},onOption:e=>void so(e),answeredIds:vr,onAnswered:gr,get agentActive(){return P(()=>!!Wn())()&&$e(e)},onResize:()=>{At()&&wi()},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.promptId&&e.data?.sent!==!0?()=>{let t=String(e.data.promptId);Q(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:t})}).then(e=>{let n=String(e.text??``);k(O()?`${n}\n\n${O()}`:n),Qn(Xn(),Jn().filter(e=>e.promptId!==t)),$(`message withdrawn — draft restored`)}).catch(()=>$(`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?async()=>{Un()&&(await Q(`/api/agents/${n()}/stop`,{method:`POST`}).catch(()=>{}),await V()),Kn({eventId:e.id,text:String(e.data?.text??``)})}:void 0}})}),j(N,{get when(){return ui()},get children(){return hh()}}),j(N,{get when(){return P(()=>!!Wn())()&&Dn()},get children(){var e=yh(),t=e.firstChild.nextSibling;return t.firstChild,R(t,j(N,{get when(){return z().trim()!==``},get children(){var e=gh(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return R(t,j(pd,{get startedAt(){return zn()}}),null),Oe(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),b(()=>{z(),t&&(e.scrollTop=e.scrollHeight)})},n),R(n,z),e}}),null),R(t,j(N,{get when(){return Pn()},get fallback(){return og()},get children(){return j(N,{get when(){return Cn()},get fallback(){return(()=>{var e=vh();return y(()=>e.innerHTML=Ie(Pn()+`▍`)),e})()},get children(){return[_h(),(()=>{var e=vh();return y(()=>e.innerHTML=Ie(wn()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),j(N,{get when(){return Ki()},get children(){var t=Th(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{_a(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(ga()))},n.$$pointerdown=ka,R(i,j(M,{get each(){return oa()},children:(e,t)=>(()=>{var n=sg(),r=n.firstChild.nextSibling;return n.$$click=()=>xa(t()),R(n,()=>e.title,r),r.$$click=e=>{e.stopPropagation(),wa(t())},y(r=>{var i=`termtab`+(ma()===0&&ca()===t()?` active`:``)+(fa()&&ma()===1&&ua()===t()?` active`:``),a=`${e.title} — click to show in focused pane`;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),R(i,j(Ru,{icon:`+`,title:`new shell in this workspace`,onClick:Sa}),null),R(o,(()=>{var t=P(()=>!!ba());return()=>t()?e().find(e=>e.id===ba().agentId)?.workspace.split(`/`).filter(Boolean).pop():B()?.workspace})()),R(a,j(Ru,{icon:`◫`,get title(){return fa()?`single pane`:`split panes (50/50)`},onClick:Aa}),null),R(a,j(Ru,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:aa}),null);var l=ja(0);return typeof l==`function`&&Oe(l,c),c.$$pointerdown=()=>ha(0),R(c,j(N,{get when(){return ca()<0||ca()>=oa().length},get children(){return xh()}})),R(s,j(N,{get when(){return fa()},get children(){return[Sh(),(()=>{var e=wh(),t=ja(1);return typeof t==`function`&&Oe(t,e),e.$$pointerdown=()=>ha(1),R(e,j(N,{get when(){return ua()<0||ua()>=oa().length},get children(){return Ch()}})),y(()=>e.classList.toggle(`focused`,ma()===1)),e})()]}}),null),y(e=>{var n={height:`${ga()}px`},r=!!fa(),i=ma()===0;return e.e=Ee(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=Mh(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(e,j(N,{get when(){return P(()=>tn()>32)()&&!At()},get children(){var e=Eh();return e.firstChild,e.$$click=()=>{Ti(!0),sr()},R(e,(()=>{var e=P(()=>Gt()>0);return()=>e()?`${Gt()} new message${Gt()>1?`s`:``}`:`jump to present`})(),null),e}}),t),R(e,j(N,{get when(){return Ka().length>0},get children(){var e=Dh();return R(e,j(M,{get each(){return Ka()},children:(e,t)=>(()=>{var n=cg(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{k(e.insert),Ga(-1)},R(r,()=>e.insert.trim()),R(i,()=>e.title),y(r=>{var i=`cmdrow`+(t()===Wa()?` active`:``),a=e.title;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),R(e,j(N,{get when(){return za().length>0},get children(){var e=Dh();return R(e,j(M,{get each(){return za()},children:e=>(()=>{var t=lg(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{k(`@${e.key} `),Ga(-1)},R(n,()=>e.key,null),R(r,()=>e.label),y(()=>I(t,`title`,e.label)),t})()})),e}}),t),t.addEventListener(`submit`,co),R(t,j(N,{get when(){return io().length>0},get children(){var e=Oh(),t=e.firstChild,n=t.firstChild,r=n.nextSibling;return r.nextSibling,R(e,j(M,{get each(){return io()},children:(e,t)=>(()=>{var n=ug(),r=n.firstChild,i=r.nextSibling;return i.$$click=()=>ao(e=>e.filter((e,n)=>n!==t())),y(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&I(n,`title`,t.e=i),a!==t.t&&I(r,`src`,t.t=a),o!==t.a&&I(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),R(t,()=>io().length,n),R(t,()=>io().length>1?`s`:``,r),e}}),n),n.$$keydown=e=>{let t=Ka();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),Ga(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),Ga(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&Wa()>=0&&!h_?(e.preventDefault(),k(t[Wa()].insert),Ga(-1)):e.key===`Escape`&&t.length>0?Ga(-1):Mu({key:e.key,shiftKey:e.shiftKey,composing:h_,maximized:Tt()})&&(e.preventDefault(),co(e))},n.$$input=e=>{k(e.currentTarget.value),Ga(0),Za()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),oo(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{h_=!1}),k(qa?.value??``)}),n.addEventListener(`compositionstart`,()=>{h_=!0}),Oe(e=>{qa=e,e.value=O()},n),R(t,j(N,{get when(){return P(()=>!!O().startsWith(`@`))()&&O().includes(` `)},get children(){var e=kh(),t=e.firstChild;return t.addEventListener(`change`,e=>La(e.currentTarget.checked)),y(()=>t.checked=Ia()),e}}),r),r.$$click=()=>{let e=!Tt();Et(e),requestAnimationFrame(()=>Za())},R(r,()=>Tt()?`⤡`:`⤢`),R(t,j(Ru,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),R(t,j(N,{get when(){return io().length},get children(){var e=Ah();return e.firstChild,R(e,()=>io().length,null),e}}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&oo(e.currentTarget.files),e.currentTarget.value=``}),R(e,j(N,{get when(){return f_()},get children(){var e=jh();return R(e,f_),e}}),null),y(t=>{var i=`composer`+(Tt()?` maximized`:``),a=`message #${B().id} — / for commands · paste or 📎 to attach images`,o=Tt()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&L(e,t.e=i),a!==t.t&&I(n,`placeholder`,t.t=a),o!==t.a&&I(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),R(t,j(N,{get when(){return P(()=>!!me())()&&Ae()},get children(){var e=Nh();return e.$$click=()=>Me(!1),e}}),p),p.addEventListener(`scroll`,e=>{fo=e.currentTarget.scrollTop});var _=uo;return typeof _==`function`?Oe(_,p):uo=p,R(m,j(Ru,{icon:`✕`,title:`close details panel (esc)`,onClick:Pe}),null),R(p,j(N,{get when(){return B()?.id},keyed:!0,fallback:null,children:t=>[j(N,{get when(){return B().id},keyed:!0,fallback:null,children:e=>j(eh,{agentId:e,get workspace(){return B().workspace}})}),(()=>{var e=fg();return e.firstChild,R(e,j(N,{get when(){return ht().length},get children(){var e=dg(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>ht().length,t),e}}),null),e})(),(()=>{var t=hg(),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;wt=!0,ut(r),ft(an(ie().providers,r,e().find(e=>e.id===n()))),yt(r)}),R(r,j(M,{get each(){return _t()},children:e=>(()=>{var t=Fg();return t.value=e,R(t,e,null),R(t,()=>e===ie().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>ft(e.currentTarget.value),R(o,j(M,{get each(){return ht()},children:e=>(()=>{var t=Fg();return y(()=>t.value=e.id),t})()})),R(t,j(N,{get when(){return B().effortSupported},get children(){var e=pg(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>mt(e.currentTarget.value)),R(t,j(M,{get each(){return P(()=>!!B().effortOptions?.length)()?B().effortOptions:u_},children:e=>(()=>{var t=Fg();return t.value=e,R(t,e),t})()}),null),y(()=>t.value=pt()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await Q(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:lt(),model:dt().trim()||void 0,contextWindowTokens:ht().find(e=>e.id===(dt().trim()||void 0))?.contextLength,...B().effortSupported?{reasoningEffort:pt()}:{}})}),t.textContent=`✓ applied`,V()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},R(l,()=>B().model,null),R(t,j(N,{get when(){return St()},get children(){var e=mg();return R(e,St),e}}),null),y(()=>I(a,`placeholder`,on(ie().providers,lt(),B(),nn(B(),ie().providers,ie().defaultProvider)))),y(()=>r.value=lt()),y(()=>a.value=dt()),t})(),(()=>{var e=gg(),t=e.firstChild.firstChild;return t.addEventListener(`change`,e=>{n()&&Q(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(V)}),y(()=>t.checked=B().autoContinue??!0),e})(),(()=>{var e=vg();return e.firstChild,R(e,j(N,{get when(){return!!B().goal.text.trim()},get fallback(){return Ig()},get children(){var e=_g();return R(e,()=>B().goal.status),y(()=>L(e,`badge ${B().goal.status===`active`?`running`:B().goal.status}`)),e}}),null),e})(),(()=>{var e=yg();return e.firstChild,R(e,j(M,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=Lg();return t.$$click=()=>{n()&&Q(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(V)},I(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`),R(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),y(n=>{var r=`goalstate`+(B().goal.text.trim()&&B().goal.status===e?` on ${e}`:``),i=!!B().goal.text.trim()&&B().goal.status===e;return r!==n.e&&L(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),j(N,{get when(){return B().goal.text},get fallback(){return Rg()},get children(){return[(()=>{var e=bg(),t=e.firstChild;return Oe(wo,e),y(n=>{var r=Co(),i=Ie(String(B().goal.text));return n.e=Ee(e,r,n.e),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),e})(),j(N,{get when(){return B().goal.verify},get children(){return j(Dt,{title:`🔍️ verification contract`,tone:`tool`,get body(){return String(B().goal.verify)}})}}),j(N,{get when(){return B().goal.audit},children:e=>j(Dt,{get title(){return e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`},get meta(){return Ue(e().at)},get tone(){return e().verdict===`approved`?`ok`:`warn`},get body(){return P(()=>!!bt(e().feedback))()?`_the auditor returned a verdict with no detail_`:e().feedback}})})]}}),(()=>{var e=xg(),t=e.firstChild,n=t.nextSibling,r=n.nextSibling.firstChild.firstChild;return e.addEventListener(`submit`,Po),t.$$input=e=>{vo(e.currentTarget.value),Ao(!0)},Oe(Eo,t),n.$$input=e=>{Oo(e.currentTarget.value),Ao(!0)},r.addEventListener(`change`,e=>Mo(e.currentTarget.checked)),y(e=>Ee(t,{...To()??{}},e)),y(()=>t.value=_o()),y(()=>n.value=Do()),y(()=>r.checked=jo()),e})(),(()=>{var e=Cg();return e.firstChild,R(e,j(N,{get when(){return Lr().total>0},get children(){var e=Sg(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,R(e,()=>Lr().done,t),R(e,()=>Lr().total,n),y(t=>Ee(e,Lr().done===Lr().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),null),e})(),j(N,{get when(){return Lr().total>0},get children(){var e=wg(),t=e.firstChild;return y(e=>{var n=`barfill `+(Lr().done===Lr().total?``:`warn`),r=`${Math.round(Lr().done/Lr().total*100)}%`;return n!==e.e&&L(t,e.e=n),r!==e.t&&De(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),j(Fd,{get draft(){return kr()},get preview(){return jr()},onDraft:e=>{Ar(e),Pr(!0)}}),(()=>{var e=Tg(),t=e.firstChild,n=t.nextSibling;return R(e,j(Ru,{get icon(){return jr()?`✎`:`👁`},get title(){return jr()?`edit markdown`:`rendered checklist`},onClick:()=>Mr(!jr())}),t),n.$$click=Ir,e})(),Eg(),j(N,{get when(){return B().latestProgress},get fallback(){return zg()},children:e=>(()=>{var t=Wg(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return R(t,j(N,{get when(){return e().recent},get children(){var t=Bg(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=l_(e().recent)),t}}),i),R(t,j(N,{get when(){return e().problems},get children(){var t=Vg(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=l_(e().problems)),t}}),i),R(t,j(N,{get when(){return e().next},get children(){var t=Hg(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=l_(e().next)),t}}),i),R(t,j(N,{get when(){return e().goalStatus},get children(){var t=Ug(),n=t.firstChild.nextSibling;return R(n,()=>e().goalStatus),t}}),i),R(i,()=>Ue(e().ts)),y(()=>r.innerHTML=l_(e().doing)),t})()}),Dg(),(()=>{var e=Ag(),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 R(e,j(N,{get when(){return B().ctx},keyed:!0,get fallback(){return Gg()},children:e=>{let t=x(()=>{let t=e,n=ht().find(e=>e.id===B().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=Yg(),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 R(a,()=>Xd(r().usedTokens),o),R(t,j(N,{get when(){return r().effectiveWindow},get children(){var e=Kg(),t=e.firstChild;return R(e,()=>i(r().pct),t),R(e,()=>Xd(r().effectiveWindow),null),y(()=>L(e,`pill ${r().cls}`)),e}}),null),R(e,j(N,{get when(){return r().effectiveWindow},get children(){var e=qg(),t=e.firstChild;return y(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&L(t,e.e=n),i!==e.t&&De(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),R(c,()=>Xd(r().usingDerived?r().derivedBudget:r().compactAt),l),R(u,()=>r().usingDerived?`75% of window`:`manual`),R(e,j(N,{get when(){return bn()||r().compacting},get children(){var e=Jg(),t=e.firstChild.nextSibling.nextSibling;return R(t,()=>bn()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&Q(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(V)}),y(()=>f.checked=B().autoCompact!==!1),e})()}}),t),R(i,()=>Xd(B().stats.inputTokens)),R(o,()=>Xd(B().stats.outputTokens)),R(c,()=>B().stats.turns),R(u,()=>B().stats.toolCalls),R(f,()=>B().stats.compactions??0),R(t,j(N,{get when(){return(B().stats.costUsd??0)>0},get children(){var e=Og(),t=e.firstChild.nextSibling;return t.firstChild,R(t,()=>w_(B().stats.costUsd??0),null),y(()=>I(e,`title`,`≈ ${(B().stats.costUsd??0).toFixed(4)} this session, from the model's per-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),R(t,j(N,{get when(){return(B().stats.cachedInputTokens??0)>0},get children(){var e=kg(),t=e.firstChild.nextSibling,n=t.firstChild;return R(t,()=>Math.round(B().stats.cachedInputTokens/Math.max(1,B().stats.inputTokens)*100),n),y(()=>I(e,`title`,`${Xd(B().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),y(()=>I(d,`title`,`how many times old turns were summarized into notes to make room. ${B().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=Mg();return e.firstChild.nextSibling,R(e,j(N,{get when(){return ri()},get children(){var e=jg(),t=e.firstChild.nextSibling;return R(t,ri),e}}),null),e})(),j(M,{get each(){return ne()},children:e=>(()=>{var t=Xg(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=ri()===e.branch?null:e.branch,r=t!==ri();ii(t),n()&&(r&&(mi++,g([]),te(0),pi(!1)),bi(n()))},R(r,()=>e.branch,null),R(r,()=>e.branch===B().branch?` (current)`:``,null),R(i,()=>e.events,a),y(n=>{var r=`branch-row`+(e.branch===B().branch||e.branch===ri()?` cur`:``),i=e.branch===ri()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=Pg();return e.firstChild,R(e,j(N,{get when(){return Br().length>0},get children(){var e=Ng(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>Br().length,t),e}}),null),e})(),j(N,{get when(){return Br().length>0},get fallback(){return Zg()},get children(){return j(M,{get each(){return Br()},children:e=>(()=>{var t=$g(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>ji(e.agent),R(i,()=>e.id),R(a,()=>e.agent,null),R(r,j(N,{get when(){return e.forked},get children(){return Qg()}}),null),R(o,()=>e.schedule,s),R(o,(()=>{var t=P(()=>!!e.next);return()=>t()?Ue(e.next):`—`})(),null),R(o,(()=>{var t=P(()=>!!e.last);return()=>t()?` · last ${Ue(e.last)}`:` · never ran`})(),null),R(c,()=>Zd(e.prompt,90)),y(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${Zd(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&L(t,r.e=i),a!==r.t&&I(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),y(e=>{var n=`layout`+(Ae()?``:` right-hidden`)+(Fe()?` left-open`:``),i=`sidebar`+(Fe()?` open`:``),a=`iconbtn notifbtn`+(ar()>0?` has-unread`:``),s=ar()>0?`${ar()} unread notifications`:`notifications`,c=`conn`+(Mi()?` ok`:``),u=Mi()?`live (websocket)`:`reconnecting…`,d={"--termh":`${ga()}px`},m=`rightbar`+(Ae()?` open`:``);return n!==e.e&&L(t,e.e=n),i!==e.t&&L(r,e.t=i),a!==e.a&&L(o,e.a=a),s!==e.o&&I(o,`title`,e.o=s),c!==e.i&&L(l,e.i=c),u!==e.n&&I(l,`title`,e.n=u),e.s=Ee(f,d,e.s),m!==e.h&&L(p,e.h=m),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}),t})(),j(N,{get when(){return rr()},get children(){return[(()=>{var e=Fh();return e.$$click=()=>ir(!1),e})(),(()=>{var t=Rh(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return R(r,j(N,{get when(){return $n().length>0},get children(){var e=Ih();return e.$$click=()=>er([]),e}}),i),i.$$click=()=>ir(!1),R(t,j(N,{get when(){return $n().length>0},get fallback(){return e_()},get children(){var t=Lh();return R(t,j(M,{get each(){return $n()},children:t=>(()=>{var r=n_(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{er(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&ji(t.agentId),ir(!1),t.eventId&&setTimeout(()=>fr(t.eventId),n()===t.agentId?60:350)},R(i,(()=>{var e=P(()=>t.kind===`finish`);return()=>e()?`✅`:P(()=>t.kind===`question`)()?`❓️`:t.kind===`error`?`⚠️`:`📈`})()),R(a,()=>t.title),R(o,()=>Ue(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),er(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},R(s,()=>t.read?`✓`:`○`),R(r,j(N,{get when(){return t.body},get children(){var e=t_();return R(e,()=>C_(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&&L(r,e.e=n),i!==e.t&&I(r,`title`,e.t=i),a!==e.a&&I(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),j(N,{get when(){return oe()},get children(){return j(T_,{get providers(){return Object.keys(ie().providers??{})},onClose:()=>se(!1),onCreated:e=>{se(!1),V(),ji(e)}})}}),j(N,{get when(){return ue()},get children(){return j(jm,{get cfg(){return ie()},onClose:()=>A(!1),announcedOAuth:fe,get skills(){return Ba()},get hasSelection(){return!!n()},get agentId(){return n()},get features(){return Ha()},onSaved:()=>{Er(),Hr()},theme:{themes:Qe,activeId:ze,paintedId:le,auto:He,setAuto:e=>{qe(e),localStorage.setItem(`teapot.theme.auto`,e?`1`:`0`)},dark:it,setDark:at,light:Je,setLight:Ye,setThemes:rt,setActive:Be,preview:e=>Ze(e),commitAppearance:e=>{localStorage.setItem(`teapot.theme.auto`,e.auto?`1`:`0`),localStorage.setItem(`teapot.theme.dark`,e.dark),localStorage.setItem(`teapot.theme.light`,e.light),localStorage.setItem(`teapot.theme`,e.fixed)}}})}}),j(N,{get when(){return Gn()},fallback:null,children:e=>{let t=()=>h().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,h().length-t()-1);return j(Bu,{title:`edit prompt — forks the conversation`,onClose:()=>Kn(null),get children(){var t=i_(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await Q(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value})}),Kn(null),V();let t=n();t&&await ji(t)}catch(e){alert(`edit failed: ${e.message}`)}}),R(t,j(N,{get when(){return r()>0},get children(){var e=r_(),t=e.firstChild;return R(e,r,t),e}}),a),o.$$click=()=>Kn(null),y(()=>i.value=e().text),t}})}})]}function C_(e,t){return e.length>t?e.slice(0,t)+` …`:e}function w_(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 T_(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 Q(`/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 Q(`/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 j(Bu,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=o_(),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,te=C.firstChild.nextSibling,ne=C.nextSibling.firstChild.nextSibling,w=x.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),R(b,j(M,{get each(){return r()},children:e=>(()=>{var n=s_();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),R(n,e,null),n})()})),ee.$$input=e=>o(e.currentTarget.value),te.addEventListener(`change`,e=>c(e.currentTarget.value)),R(te,j(M,{get each(){return e.providers},children:e=>(()=>{var t=Fg();return R(t,e),t})()})),ne.$$input=e=>u(e.currentTarget.value),R(i,j(N,{get when(){return d()},get children(){var e=a_();return R(e,d),e}}),w),y(()=>h.value=t()),y(()=>ee.value=a()),y(()=>te.value=s()),y(()=>ne.value=l()),i}})}we([`click`,`input`,`keydown`,`pointerdown`,`dblclick`]),Ce(()=>j(S_,{}),document.getElementById(`root`));export{id as t};
36
- //# sourceMappingURL=index-BdfpD7xX.js.map
33
+ `)?`${e.value} `:e.value),Ja||(Ja=document.createElement(`div`),Ja.setAttribute(`aria-hidden`,`true`),Ja.style.cssText=`position:absolute;left:-9999px;top:0;pointer-events:none`,document.body.appendChild(Ja)),q.parentElement!==Ja&&Ja.appendChild(q),!Ya){let e=document.createElement(`style`);e.textContent=`[data-mirror]::after{content:attr(data-mirror-text);white-space:pre-wrap;display:block}`,document.head.appendChild(e),Ya=!0}return q.scrollHeight}let Za=()=>{if(!qa)return;let e=Tt();if(!qa.value&&!e){qa.style.height=``;return}let t=Xa(qa),n=e?-1:_n(t,360);qa.style.height=n===-1?``:`${n}px`},Qa,$a=null,eo,to=240,no=4,ro;b(()=>{let e=O();qa&&cn(p_)&&(ln(qa.value,e)&&(qa.value=e),Za())}),ee(()=>{let e=0,t=()=>{e||=requestAnimationFrame(()=>{e=0,Za()})};window.addEventListener(`resize`,t),C(()=>{window.removeEventListener(`resize`,t),e&&cancelAnimationFrame(e)})});let[io,ao]=v([]),oo=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){$(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{ao(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},so=async(t,r,i)=>{let a=r??n();if(!a)return;let o=io(),s=e().find(e=>e.id===a)?.session||a;try{let e=await Q(`/api/agents/${a}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:t,start:!0,...i?{source:i}:{},...o.length?{images:o}:{}})});Qn(s,[...Zn(s),{id:`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`,text:t,at:Date.now(),promptId:e.promptId,...o.length?{images:o.map(e=>e.url)}:{}}]),ao([]),Nu(Tt())&&Et(!1),Za(),At()&&requestAnimationFrame(()=>{At()&&wi()})}catch(e){k(t),console.error(`send failed:`,e)}},co=async t=>{t.preventDefault();let r=n(),i=O().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=Na().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){$(`usage: @${r} <task>`);return}$(`🧩 spawned ${(await Q(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:Ia()?`fork`:`none`})})).id}${Ia()?` (forked context)`:``}`),V(),k(``)}else if(s){if(!a){$(`usage: @${r} <message>`);return}await Q(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),$(`→ delivered to @${r}`),k(``)}else{$(`unknown @${r} — personas: ${Na().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){$(`@${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){k(`/goal `);return}if(t===`skill`&&!n){k(`/skill `);return}k(``);try{await lo(t,n)}catch(e){throw k(O()?`${i}\n${O()}`:i),e}}else k(``),await so(i)}},lo=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>Q(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(V);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await ji(r);else if(e===`compact`)$((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){$(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),$(`goal saved & notification queued`)}else if(e===`skill`){if(!t){$(`usage: /skill <name>`);return}await so(`[harness] Force-load and follow the skill "${t}" now: call load_skill("${t}") and execute its playbook for the current task.`,void 0,`harness`),$(`skill "${t}" dispatched`)}else $(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){$(`/${e} failed: ${t.message}`)}},uo,fo=0;b(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!uo)return;let e=Math.min(fo,uo.scrollHeight);Math.abs(uo.scrollTop-e)>1&&(uo.scrollTop=e)})})});let po=e=>()=>n()&&Q(`/api/agents/${n()}${e}`,{method:`POST`}).then(V),mo=async()=>{let i=n();if(!i)return;let a=new Set([i,...Lt(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 Q(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),m(!0);let s=ju(e(),a);s?ji(s.id):(r(null),g([]))},ho=async()=>{n()&&($(`stopped: ${((await Q(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),V())},go=()=>Q(`/api/agents/${B().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await m(!0),await ji(B().id)}),[_o,vo]=v(``),[yo,bo]=v(Kt(`goal`)),[xo,So]=v(Kt(`goalPreview`)),Co=()=>{let e={"max-height":`none`,"overflow-y":`auto`,resize:`vertical`};return xo()>0&&(e.height=`${xo()}px`),e},wo=e=>{C(Jt(e,e=>{So(t=>Math.abs(t-e)<1?t:(qt(`goalPreview`,e),e))}))},To=()=>yo()>0?{height:`${yo()}px`}:void 0,Eo=e=>{C(Jt(e,e=>{bo(t=>Math.abs(t-e)<1?t:(qt(`goal`,e),e))}))},[Do,Oo]=v(``),[ko,Ao]=v(!1),[jo,Mo]=v(!0),No=``;b(()=>{let e=n();e&&(B()?.goal,e!==No&&(No=e,Ao(!1),vo(``),Oo(``)))});let Po=async e=>{if(e.preventDefault(),n()&&_o().trim())try{await Q(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:_o(),notify:jo(),...Do().trim()?{verify:Do()}:{}})}),vo(``),Oo(``),Ao(!1),V()}catch(e){$(`goal save failed: ${e.message}`)}};return[j(N,{get when(){return Dr()},get children(){var e=$m();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}}),j(N,{get when(){return ce()},children:e=>(()=>{var t=Lh(),n=t.firstChild;return y(t=>{var r=Mt(e(),kt[kt.length-1]),i=jt(e());return r!==t.e&&I(n,`src`,t.e=r),i!==t.t&&I(n,`srcset`,t.t=i),t},{e:void 0,t:void 0}),t})()}),(()=>{var t=Mh(),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,m=p.firstChild;m.firstChild,R(t,j(N,{get when(){return P(()=>!!me())()&&Fe()},get children(){var e=eh();return e.$$click=Re,e}}),r),R(r,j(N,{get when(){return me()},get children(){var e=th(),t=e.firstChild.nextSibling;return t.$$click=Re,e}}),i),R(i,j(M,{get each(){return ni()},children:t=>[j(N,{get when(){return P(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=zh(),n=e.firstChild;return e.$$click=()=>$r(`ws:${t.wsHeader}`,ei(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),R(n,()=>t.wsCollapsedGroup?`▸`:`▾`),R(e,()=>ei(t.wsHeader),null),R(e,j(N,{get when(){return(ti().get(t.wsHeader)??0)>1||t.wsCollapsedGroup},get children(){var e=Rh();return R(e,()=>ti().get(t.wsHeader)??0),e}}),null),y(()=>I(e,`title`,t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${W(t.wsHeader)} hidden). Click to show.`:(ti().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${W(t.wsHeader)} in this directory`:t.wsHeader||``)),e}}),j(N,{get when(){return P(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=Wh(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>ji(t.a.id),R(r,j(N,{get when(){return Ft({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return Gh()},get children(){return(()=>{let e=!t.a.parent,n=e&&U().has(`chat:${t.a.id}`)||Jr(t.a.id);return(()=>{var r=Kh();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!Wr().has(t.a.id)){let e=new Set(Wr());e.add(t.a.id),Gr(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(Kr().has(t.a.id)){let e=new Set(Kr());e.delete(t.a.id),qr(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(Wr().has(t.a.id)){let e=new Set(Wr());e.delete(t.a.id),Gr(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}$r(`chat:${t.a.id}`,t.a.id,n)}else Yr(t.a.id)},R(r,n?`▸`:`▾`),y(()=>I(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),R(a,()=>vn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)})),R(r,(()=>{var e=P(()=>!!t.a.workspaceMissing);return()=>e()?qh():null})(),null),R(r,j(N,{get when(){return cr(t.a.id)>0},get children(){var e=Bh();return e.firstChild,R(e,()=>cr(t.a.id),null),y(()=>I(e,`title`,`${cr(t.a.id)} unread notification${cr(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),R(r,j(N,{get when(){return Jr(t.a.id)||t.chatCollapsedGroup===!0&&U().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=Lt(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=Jh();return e.firstChild,L(e,`subcount`+(r>0?` live`:``)),R(e,()=>n.length,null),R(e,r>0?` · ▶${r}`:``,null),y(()=>I(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),R(r,j(N,{get when(){return t.a.parent},get children(){return Vh()}}),null),R(r,j(N,{get when(){return Ur(t.a.id).length>0},get children(){var e=Hh();return y(()=>I(e,`title`,Ur(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
34
+ `))),e}}),null),R(r,j(N,{get when(){return t.a.goal.status===`done`},get children(){return Uh()}}),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=It(t.a.id,Na().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`:yn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)});return o!==e.e&&L(r,e.e=o),e.t=Ee(r,s,e.t),c!==e.a&&I(r,`title`,e.a=c),l!==e.o&&L(i,e.o=l),d!==e.i&&I(i,`title`,e.i=d),f!==e.n&&L(a,e.n=f),p!==e.s&&I(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(),ir(!rr()),rr()||er(e=>e.map(e=>({...e,read:!0})))},R(o,j(N,{get when(){return ar()>0},get children(){var e=nh();return R(e,ar),e}}),null),R(a,j(Ru,{icon:`👻`,get active(){return tr()},get title(){return tr()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!tr();if(nr(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&B()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&ji(t.id)}}}),null),R(a,j(Ru,{icon:`+`,title:`new agent`,onClick:()=>{Er(),se(!0)}}),null),R(a,j(Ru,{icon:`⚙️`,title:`settings`,onClick:()=>{Er(),A(!0)}}),null),R(c,`0.37.73`,null),R(d,j(N,{get when(){return T()},get children(){return[`master rss `,P(()=>T().rssMb),`MB · heap `,P(()=>T().heapUsedMb),`MB`,j(N,{get when(){return T().heapTotalMb!==void 0},get children(){return[` · total `,P(()=>T().heapTotalMb),`MB`]}}),j(N,{get when(){return T().externalMb!==void 0},get children(){return[` · ext `,P(()=>T().externalMb),`MB`]}}),rh(),`load1 `,P(()=>T().loadavg1),` · up `,P(()=>Math.floor(T().uptimeSec/60)),`m`]}})),R(f,j(N,{get when(){return B()?.id},keyed:!0,get fallback(){return Yh()},get children(){return[(()=>{var t=uh(),r=t.firstChild,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 R(t,j(N,{get when(){return me()},get children(){var e=ih();return e.$$click=()=>Le(!Fe()),y(()=>I(e,`aria-expanded`,Fe())),e}}),r),r.$$click=()=>ra(),R(t,j(N,{get when(){return $i()},get fallback(){return(()=>{var e=Xh();return e.$$click=()=>ra(),R(e,()=>vn(B())),y(()=>I(e,`title`,`${yn(B(),B().session)} — click to rename`)),e})()},get children(){var e=ah();return e.addEventListener(`blur`,()=>void ia()),e.$$keydown=e=>{e.key===`Enter`?(e.preventDefault(),ia()):e.key===`Escape`&&(e.preventDefault(),ea(!1))},e.$$input=e=>na(e.currentTarget.value),Oe(e=>{requestAnimationFrame(()=>{e.focus(),e.select()})},e),I(e,`spellcheck`,!1),y(()=>e.value=ta()),e}}),i),R(i,()=>B().status),R(t,j(N,{get when(){return Hn()>0},get children(){var e=oh(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return n.nextSibling,R(e,Hn,t),R(e,()=>Hn()===1?`message`:`messages`,n),R(e,()=>B().status===`stopped`?` (stopped)`:``,null),y(()=>I(e,`title`,(()=>{let e=B().pendingPromptQueue??[],t=e.length||B().pendingPromptIds?.length||B().pendingPrompts||0,n=e.length?e.filter(e=>(e.source??`user`)===`user`).length:t,r=t-n;return`${`${t} message${t>1?`s`:``} queued${r?` — ${n} from you, ${r} from the harness`:` from you`}`}. ${B().status===`stopped`?`This agent is STOPPED, so nothing will run until you press start (or it is resumed).`:`They are handed to the model at its next turn boundary — the timeline shows them as queued… until then.`}`+(n?` Yours can be withdrawn with ✕ cancel while still queued.`:``)})())),e}}),a),R(t,j(N,{get when(){return Ji().length>0},get children(){var e=sh();return e.firstChild,e.$$click=()=>{Zi(!Xi()),Xi()&&Qi()},R(e,()=>Ji().filter(e=>e.running).length||Ji().length,null),R(e,()=>Ji().some(e=>e.running)?` running`:` done`,null),y(t=>{var n=Xi(),r=`background shells — ${Ji().filter(e=>e.running).length} running, ${Ji().length} total (click to inspect)`;return n!==t.e&&I(e,`aria-expanded`,t.e=n),r!==t.t&&I(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),a),R(t,j(N,{get when(){return Ur(B().id).length>0},get children(){var e=ch();return e.firstChild,R(e,()=>Ur(B().id).length,null),y(()=>I(e,`title`,`scheduled tasks:\n${Ur(B().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
35
+ `)}`)),e}}),a),R(a,()=>B().model,o),R(a,()=>B().session,s),R(a,()=>B().branch,c),R(a,()=>B().stats.turns,l),R(a,()=>B().stats.toolCalls,u),f.$$click=()=>(Un()?po(`/stop`):po(`/start`))(),R(f,()=>Un()?`■ stop`:`▶ start`),R(d,j(N,{get when(){return e().some(e=>e.parent===n())},get children(){return j(Ru,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ho})}}),p),R(d,j(Ru,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙️ settings → archive)`,onClick:mo}),null),R(d,j(Ru,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:go}),null),R(d,j(Ru,{icon:`⌨`,title:`terminal (t)`,onClick:aa}),null),R(d,j(Ru,{icon:`▤`,title:`toggle details panel (d)`,get active(){return Ae()},onClick:Ne}),null),R(t,j(N,{get when(){return Xi()},get children(){var e=lh(),t=e.firstChild.firstChild.nextSibling;return t.$$click=()=>Zi(!1),R(e,j(N,{get when(){return Ji().length>0},get fallback(){return Zh()},get children(){return j(M,{get each(){return Ji()},children:e=>(()=>{var t=$h(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(r,()=>Zd(e.cmd,80)),R(i,(()=>{var t=P(()=>!!e.detached);return()=>t()?`detached · pid ${e.pid??`?`}`:P(()=>!!e.running)()?Ve(Date.now()-e.startedAt):`exit ${e.code??`?`}`})(),null),R(i,()=>e.truncated?` · truncated`:``,null),a.$$click=async()=>{await Q(`/api/agents/${encodeURIComponent(B().id)}/bg-jobs/${encodeURIComponent(e.id)}`,{method:`DELETE`}).catch(()=>{}),await Qi()},R(a,(()=>{var t=P(()=>!!e.detached);return()=>t()?`forget`:e.running?`kill`:`clear`})()),R(t,j(N,{get when(){return e.tail.trim()},get fallback(){return j(N,{get when(){return e.detached},get children(){var t=eg(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.pid??`?`,n),t}})},get children(){var t=Qh();return R(t,()=>e.tail),t}}),null),y(t=>{var i=`bgjob-dot `+(e.running?`running`:`done`),o=e.running?`running`:`finished`,s=e.cmd,c=e.detached?`this job survived a harness restart (pid ${e.pid??`?`}) — its output can no longer be read here; stop it yourself if needed`:e.running?`kill this job (whole process group)`:`forget this finished job`;return i!==t.e&&L(n,t.e=i),o!==t.t&&I(n,`title`,t.t=o),s!==t.a&&I(r,`title`,t.a=s),c!==t.o&&I(a,`title`,t.o=c),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()})}}),null),e}}),null),y(e=>{var t=`badge ${B().status}`,n=B().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(B().statusReason)?`${B().status} — ${B().statusReason}`:void 0,r=`${B().model} · ${B().session}/${B().branch} · turns ${B().stats.turns} · tools ${B().stats.toolCalls}`,o=`runbtn`+(Un()?` danger`:``),s=Un()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&L(i,e.e=t),n!==e.t&&I(i,`title`,e.t=n),r!==e.a&&I(a,`title`,e.a=r),o!==e.o&&L(f,e.o=o),s!==e.i&&I(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=vh();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=pn(r,$a,eo,ro);i===`layout`&&!At()&&no>0&&Math.abs(r.height-(eo??r.height))>1&&(no--,F(t,_e)),$a=null,eo=r.height,ro=r.viewport,un(r);let a=At(),o=performance.now();o-ve>100&&(ve=o,_e=ke(t));let s=hn(a,i,r);s!==a&&Pt(s),i===`reader`&&(no=4),s&&i!==`reader`?(Gt()&&Yt(0),sr(),mn(s,r)&&dn(r)>0&&wi()):s&&fn(r)&&(Gt()&&Yt(0),sr()),r.top<=4&&n()&&!ci()&&!fi()&&h().length>0&&_i()}),Oe(e=>Te(e),e),R(e,j(N,{get when(){return bn()},children:e=>(()=>{var t=tg();return t.firstChild,R(t,(()=>{var t=P(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?Xd(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),R(e,j(N,{get when(){return P(()=>!!fi())()&&br().length>0},get children(){return dh()}}),null),R(e,j(N,{get when(){return ci()},get children(){return fh()}}),null),R(e,j(N,{get when(){return br().length>0},get fallback(){return P(()=>!!ui())()?ng():rg()},get children(){return[j(M,{get each(){return br()},children:e=>j(bp,{e,prev:()=>Cr(e,-1),next:()=>Cr(e,1),get showBranch(){return ne().length>1},res:()=>pr().resFor.get(e.id),get orphan(){return pr().orphanCalls.has(e.id)},onOption:e=>void so(e),answeredIds:vr,onAnswered:gr,get agentActive(){return P(()=>!!Wn())()&&$e(e)},onResize:()=>{At()&&wi()},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.promptId&&e.data?.sent!==!0?()=>{let t=String(e.data.promptId);Q(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:t})}).then(e=>{let n=String(e.text??``);k(O()?`${n}\n\n${O()}`:n),Qn(Xn(),Jn().filter(e=>e.promptId!==t)),$(`message withdrawn — draft restored`)}).catch(()=>$(`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?async()=>{Un()&&(await Q(`/api/agents/${n()}/stop`,{method:`POST`}).catch(()=>{}),await V()),Kn({eventId:e.id,text:String(e.data?.text??``)})}:void 0}})}),j(N,{get when(){return ui()},get children(){return ph()}}),j(N,{get when(){return P(()=>!!Wn())()&&Dn()},get children(){var e=_h(),t=e.firstChild.nextSibling;return t.firstChild,R(t,j(N,{get when(){return z().trim()!==``},get children(){var e=mh(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return R(t,j(pd,{get startedAt(){return zn()}}),null),Oe(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),b(()=>{z(),t&&(e.scrollTop=e.scrollHeight)})},n),R(n,z),e}}),null),R(t,j(N,{get when(){return Pn()},get fallback(){return ig()},get children(){return j(N,{get when(){return Cn()},get fallback(){return(()=>{var e=gh();return y(()=>e.innerHTML=Ie(Pn()+`▍`)),e})()},get children(){return[hh(),(()=>{var e=gh();return y(()=>e.innerHTML=Ie(wn()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),j(N,{get when(){return Ki()},get children(){var t=Ch(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{_a(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(ga()))},n.$$pointerdown=ka,R(i,j(M,{get each(){return oa()},children:(e,t)=>(()=>{var n=ag(),r=n.firstChild.nextSibling;return n.$$click=()=>xa(t()),R(n,()=>e.title,r),r.$$click=e=>{e.stopPropagation(),wa(t())},y(r=>{var i=`termtab`+(ma()===0&&ca()===t()?` active`:``)+(fa()&&ma()===1&&ua()===t()?` active`:``),a=`${e.title} — click to show in focused pane`;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),R(i,j(Ru,{icon:`+`,title:`new shell in this workspace`,onClick:Sa}),null),R(o,(()=>{var t=P(()=>!!ba());return()=>t()?e().find(e=>e.id===ba().agentId)?.workspace.split(`/`).filter(Boolean).pop():B()?.workspace})()),R(a,j(Ru,{icon:`◫`,get title(){return fa()?`single pane`:`split panes (50/50)`},onClick:Aa}),null),R(a,j(Ru,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:aa}),null);var l=ja(0);return typeof l==`function`&&Oe(l,c),c.$$pointerdown=()=>ha(0),R(c,j(N,{get when(){return ca()<0||ca()>=oa().length},get children(){return yh()}})),R(s,j(N,{get when(){return fa()},get children(){return[bh(),(()=>{var e=Sh(),t=ja(1);return typeof t==`function`&&Oe(t,e),e.$$pointerdown=()=>ha(1),R(e,j(N,{get when(){return ua()<0||ua()>=oa().length},get children(){return xh()}})),y(()=>e.classList.toggle(`focused`,ma()===1)),e})()]}}),null),y(e=>{var n={height:`${ga()}px`},r=!!fa(),i=ma()===0;return e.e=Ee(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=Ah(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(e,j(N,{get when(){return P(()=>tn()>32)()&&!At()},get children(){var e=wh();return e.firstChild,e.$$click=()=>{Ti(!0),sr()},R(e,(()=>{var e=P(()=>Gt()>0);return()=>e()?`${Gt()} new message${Gt()>1?`s`:``}`:`jump to present`})(),null),e}}),t),R(e,j(N,{get when(){return Ka().length>0},get children(){var e=Th();return R(e,j(M,{get each(){return Ka()},children:(e,t)=>(()=>{var n=og(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{k(e.insert),Ga(-1)},R(r,()=>e.insert.trim()),R(i,()=>e.title),y(r=>{var i=`cmdrow`+(t()===Wa()?` active`:``),a=e.title;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),R(e,j(N,{get when(){return za().length>0},get children(){var e=Th();return R(e,j(M,{get each(){return za()},children:e=>(()=>{var t=sg(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{k(`@${e.key} `),Ga(-1)},R(n,()=>e.key,null),R(r,()=>e.label),y(()=>I(t,`title`,e.label)),t})()})),e}}),t),t.addEventListener(`submit`,co),R(t,j(N,{get when(){return io().length>0},get children(){var e=Eh(),t=e.firstChild,n=t.firstChild,r=n.nextSibling;return r.nextSibling,R(e,j(M,{get each(){return io()},children:(e,t)=>(()=>{var n=cg(),r=n.firstChild,i=r.nextSibling;return i.$$click=()=>ao(e=>e.filter((e,n)=>n!==t())),y(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&I(n,`title`,t.e=i),a!==t.t&&I(r,`src`,t.t=a),o!==t.a&&I(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),R(t,()=>io().length,n),R(t,()=>io().length>1?`s`:``,r),e}}),n),n.$$keydown=e=>{let t=Ka();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),Ga(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),Ga(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&Wa()>=0&&!p_?(e.preventDefault(),k(t[Wa()].insert),Ga(-1)):e.key===`Escape`&&t.length>0?Ga(-1):Mu({key:e.key,shiftKey:e.shiftKey,composing:p_,maximized:Tt()})&&(e.preventDefault(),co(e))},n.$$input=e=>{k(e.currentTarget.value),Ga(0),Za()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),oo(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{p_=!1}),k(qa?.value??``)}),n.addEventListener(`compositionstart`,()=>{p_=!0}),Oe(e=>{qa=e,e.value=O()},n),R(t,j(N,{get when(){return P(()=>!!O().startsWith(`@`))()&&O().includes(` `)},get children(){var e=Dh(),t=e.firstChild;return t.addEventListener(`change`,e=>La(e.currentTarget.checked)),y(()=>t.checked=Ia()),e}}),r),r.$$click=()=>{let e=!Tt();Et(e),requestAnimationFrame(()=>Za())},R(r,()=>Tt()?`⤡`:`⤢`),R(t,j(Ru,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),R(t,j(N,{get when(){return io().length},get children(){var e=Oh();return e.firstChild,R(e,()=>io().length,null),e}}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&oo(e.currentTarget.files),e.currentTarget.value=``}),R(e,j(N,{get when(){return u_()},get children(){var e=kh();return R(e,u_),e}}),null),y(t=>{var i=`composer`+(Tt()?` maximized`:``),a=`message #${B().id} — / for commands · paste or 📎 to attach images`,o=Tt()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&L(e,t.e=i),a!==t.t&&I(n,`placeholder`,t.t=a),o!==t.a&&I(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),R(t,j(N,{get when(){return P(()=>!!me())()&&Ae()},get children(){var e=jh();return e.$$click=()=>Me(!1),e}}),p),p.addEventListener(`scroll`,e=>{fo=e.currentTarget.scrollTop});var _=uo;return typeof _==`function`?Oe(_,p):uo=p,R(m,j(Ru,{icon:`✕`,title:`close details panel (esc)`,onClick:Pe}),null),R(p,j(N,{get when(){return B()?.id},keyed:!0,fallback:null,children:t=>[j(N,{get when(){return B().id},keyed:!0,fallback:null,children:e=>j(Qm,{agentId:e,get workspace(){return B().workspace}})}),(()=>{var e=ug();return e.firstChild,R(e,j(N,{get when(){return ht().length},get children(){var e=lg(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>ht().length,t),e}}),null),e})(),(()=>{var t=pg(),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;wt=!0,ut(r),ft(an(ie().providers,r,e().find(e=>e.id===n()))),yt(r)}),R(r,j(M,{get each(){return _t()},children:e=>(()=>{var t=Ng();return t.value=e,R(t,e,null),R(t,()=>e===ie().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>ft(e.currentTarget.value),R(o,j(M,{get each(){return ht()},children:e=>(()=>{var t=Ng();return y(()=>t.value=e.id),t})()})),R(t,j(N,{get when(){return B().effortSupported},get children(){var e=dg(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>mt(e.currentTarget.value)),R(t,j(M,{get each(){return P(()=>!!B().effortOptions?.length)()?B().effortOptions:c_},children:e=>(()=>{var t=Ng();return t.value=e,R(t,e),t})()}),null),y(()=>t.value=pt()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await Q(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:lt(),model:dt().trim()||void 0,contextWindowTokens:ht().find(e=>e.id===(dt().trim()||void 0))?.contextLength,...B().effortSupported?{reasoningEffort:pt()}:{}})}),t.textContent=`✓ applied`,V()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},R(l,()=>B().model,null),R(t,j(N,{get when(){return St()},get children(){var e=fg();return R(e,St),e}}),null),y(()=>I(a,`placeholder`,on(ie().providers,lt(),B(),nn(B(),ie().providers,ie().defaultProvider)))),y(()=>r.value=lt()),y(()=>a.value=dt()),t})(),(()=>{var e=mg(),t=e.firstChild.firstChild;return t.addEventListener(`change`,e=>{n()&&Q(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(V)}),y(()=>t.checked=B().autoContinue??!0),e})(),(()=>{var e=gg();return e.firstChild,R(e,j(N,{get when(){return!!B().goal.text.trim()},get fallback(){return Pg()},get children(){var e=hg();return R(e,()=>B().goal.status),y(()=>L(e,`badge ${B().goal.status===`active`?`running`:B().goal.status}`)),e}}),null),e})(),(()=>{var e=_g();return e.firstChild,R(e,j(M,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=Fg();return t.$$click=()=>{n()&&Q(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(V)},I(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`),R(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),y(n=>{var r=`goalstate`+(B().goal.text.trim()&&B().goal.status===e?` on ${e}`:``),i=!!B().goal.text.trim()&&B().goal.status===e;return r!==n.e&&L(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),j(N,{get when(){return B().goal.text},get fallback(){return Ig()},get children(){return[(()=>{var e=vg(),t=e.firstChild;return Oe(wo,e),y(n=>{var r=Co(),i=Ie(String(B().goal.text));return n.e=Ee(e,r,n.e),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),e})(),j(N,{get when(){return B().goal.verify},get children(){return j(Dt,{title:`🔍️ verification contract`,tone:`tool`,get body(){return String(B().goal.verify)}})}}),j(N,{get when(){return B().goal.audit},children:e=>j(Dt,{get title(){return e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`},get meta(){return Ue(e().at)},get tone(){return e().verdict===`approved`?`ok`:`warn`},get body(){return P(()=>!!bt(e().feedback))()?`_the auditor returned a verdict with no detail_`:e().feedback}})})]}}),(()=>{var e=yg(),t=e.firstChild,n=t.nextSibling,r=n.nextSibling.firstChild.firstChild;return e.addEventListener(`submit`,Po),t.$$input=e=>{vo(e.currentTarget.value),Ao(!0)},Oe(Eo,t),n.$$input=e=>{Oo(e.currentTarget.value),Ao(!0)},r.addEventListener(`change`,e=>Mo(e.currentTarget.checked)),y(e=>Ee(t,{...To()??{}},e)),y(()=>t.value=_o()),y(()=>n.value=Do()),y(()=>r.checked=jo()),e})(),(()=>{var e=xg();return e.firstChild,R(e,j(N,{get when(){return Lr().total>0},get children(){var e=bg(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,R(e,()=>Lr().done,t),R(e,()=>Lr().total,n),y(t=>Ee(e,Lr().done===Lr().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),null),e})(),j(N,{get when(){return Lr().total>0},get children(){var e=Sg(),t=e.firstChild;return y(e=>{var n=`barfill `+(Lr().done===Lr().total?``:`warn`),r=`${Math.round(Lr().done/Lr().total*100)}%`;return n!==e.e&&L(t,e.e=n),r!==e.t&&De(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),j(Fd,{get draft(){return kr()},get preview(){return jr()},onDraft:e=>{Ar(e),Pr(!0)}}),(()=>{var e=Cg(),t=e.firstChild,n=t.nextSibling;return R(e,j(Ru,{get icon(){return jr()?`✎`:`👁`},get title(){return jr()?`edit markdown`:`rendered checklist`},onClick:()=>Mr(!jr())}),t),n.$$click=Ir,e})(),wg(),j(N,{get when(){return B().latestProgress},get fallback(){return Lg()},children:e=>(()=>{var t=Hg(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return R(t,j(N,{get when(){return e().recent},get children(){var t=Rg(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=s_(e().recent)),t}}),i),R(t,j(N,{get when(){return e().problems},get children(){var t=zg(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=s_(e().problems)),t}}),i),R(t,j(N,{get when(){return e().next},get children(){var t=Bg(),n=t.firstChild.nextSibling;return y(()=>n.innerHTML=s_(e().next)),t}}),i),R(t,j(N,{get when(){return e().goalStatus},get children(){var t=Vg(),n=t.firstChild.nextSibling;return R(n,()=>e().goalStatus),t}}),i),R(i,()=>Ue(e().ts)),y(()=>r.innerHTML=s_(e().doing)),t})()}),Tg(),(()=>{var e=Og(),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 R(e,j(N,{get when(){return B().ctx},keyed:!0,get fallback(){return Ug()},children:e=>{let t=x(()=>{let t=e,n=ht().find(e=>e.id===B().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=qg(),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 R(a,()=>Xd(r().usedTokens),o),R(t,j(N,{get when(){return r().effectiveWindow},get children(){var e=Wg(),t=e.firstChild;return R(e,()=>i(r().pct),t),R(e,()=>Xd(r().effectiveWindow),null),y(()=>L(e,`pill ${r().cls}`)),e}}),null),R(e,j(N,{get when(){return r().effectiveWindow},get children(){var e=Gg(),t=e.firstChild;return y(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&L(t,e.e=n),i!==e.t&&De(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),R(c,()=>Xd(r().usingDerived?r().derivedBudget:r().compactAt),l),R(u,()=>r().usingDerived?`75% of window`:`manual`),R(e,j(N,{get when(){return bn()||r().compacting},get children(){var e=Kg(),t=e.firstChild.nextSibling.nextSibling;return R(t,()=>bn()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&Q(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(V)}),y(()=>f.checked=B().autoCompact!==!1),e})()}}),t),R(i,()=>Xd(B().stats.inputTokens)),R(o,()=>Xd(B().stats.outputTokens)),R(c,()=>B().stats.turns),R(u,()=>B().stats.toolCalls),R(f,()=>B().stats.compactions??0),R(t,j(N,{get when(){return(B().stats.costUsd??0)>0},get children(){var e=Eg(),t=e.firstChild.nextSibling;return t.firstChild,R(t,()=>S_(B().stats.costUsd??0),null),y(()=>I(e,`title`,`≈ ${(B().stats.costUsd??0).toFixed(4)} this session, from the model's per-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),R(t,j(N,{get when(){return(B().stats.cachedInputTokens??0)>0},get children(){var e=Dg(),t=e.firstChild.nextSibling,n=t.firstChild;return R(t,()=>Math.round(B().stats.cachedInputTokens/Math.max(1,B().stats.inputTokens)*100),n),y(()=>I(e,`title`,`${Xd(B().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),y(()=>I(d,`title`,`how many times old turns were summarized into notes to make room. ${B().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=Ag();return e.firstChild.nextSibling,R(e,j(N,{get when(){return ri()},get children(){var e=kg(),t=e.firstChild.nextSibling;return R(t,ri),e}}),null),e})(),j(M,{get each(){return ne()},children:e=>(()=>{var t=Jg(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=ri()===e.branch?null:e.branch,r=t!==ri();ii(t),n()&&(r&&(mi++,g([]),te(0),pi(!1)),bi(n()))},R(r,()=>e.branch,null),R(r,()=>e.branch===B().branch?` (current)`:``,null),R(i,()=>e.events,a),y(n=>{var r=`branch-row`+(e.branch===B().branch||e.branch===ri()?` cur`:``),i=e.branch===ri()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=Mg();return e.firstChild,R(e,j(N,{get when(){return Br().length>0},get children(){var e=jg(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>Br().length,t),e}}),null),e})(),j(N,{get when(){return Br().length>0},get fallback(){return Yg()},get children(){return j(M,{get each(){return Br()},children:e=>(()=>{var t=Zg(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>ji(e.agent),R(i,()=>e.id),R(a,()=>e.agent,null),R(r,j(N,{get when(){return e.forked},get children(){return Xg()}}),null),R(o,()=>e.schedule,s),R(o,(()=>{var t=P(()=>!!e.next);return()=>t()?Ue(e.next):`—`})(),null),R(o,(()=>{var t=P(()=>!!e.last);return()=>t()?` · last ${Ue(e.last)}`:` · never ran`})(),null),R(c,()=>Zd(e.prompt,90)),y(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${Zd(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&L(t,r.e=i),a!==r.t&&I(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),y(e=>{var n=`layout`+(Ae()?``:` right-hidden`)+(Fe()?` left-open`:``),i=`sidebar`+(Fe()?` open`:``),a=`iconbtn notifbtn`+(ar()>0?` has-unread`:``),s=ar()>0?`${ar()} unread notifications`:`notifications`,c=`conn`+(Mi()?` ok`:``),u=Mi()?`live (websocket)`:`reconnecting…`,d={"--termh":`${ga()}px`},m=`rightbar`+(Ae()?` open`:``);return n!==e.e&&L(t,e.e=n),i!==e.t&&L(r,e.t=i),a!==e.a&&L(o,e.a=a),s!==e.o&&I(o,`title`,e.o=s),c!==e.i&&L(l,e.i=c),u!==e.n&&I(l,`title`,e.n=u),e.s=Ee(f,d,e.s),m!==e.h&&L(p,e.h=m),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}),t})(),j(N,{get when(){return rr()},get children(){return[(()=>{var e=Nh();return e.$$click=()=>ir(!1),e})(),(()=>{var t=Ih(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return R(r,j(N,{get when(){return $n().length>0},get children(){var e=Ph();return e.$$click=()=>er([]),e}}),i),i.$$click=()=>ir(!1),R(t,j(N,{get when(){return $n().length>0},get fallback(){return Qg()},get children(){var t=Fh();return R(t,j(M,{get each(){return $n()},children:t=>(()=>{var r=e_(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{er(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&ji(t.agentId),ir(!1),t.eventId&&setTimeout(()=>fr(t.eventId),n()===t.agentId?60:350)},R(i,(()=>{var e=P(()=>t.kind===`finish`);return()=>e()?`✅`:P(()=>t.kind===`question`)()?`❓️`:t.kind===`error`?`⚠️`:`📈`})()),R(a,()=>t.title),R(o,()=>Ue(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),er(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},R(s,()=>t.read?`✓`:`○`),R(r,j(N,{get when(){return t.body},get children(){var e=$g();return R(e,()=>x_(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&&L(r,e.e=n),i!==e.t&&I(r,`title`,e.t=i),a!==e.a&&I(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),j(N,{get when(){return oe()},get children(){return j(C_,{get providers(){return Object.keys(ie().providers??{})},onClose:()=>se(!1),onCreated:e=>{se(!1),V(),ji(e)}})}}),j(N,{get when(){return ue()},get children(){return j(km,{get cfg(){return ie()},onClose:()=>A(!1),announcedOAuth:fe,get skills(){return Ba()},get hasSelection(){return!!n()},get agentId(){return n()},get features(){return Ha()},onSaved:()=>{Er(),Hr()},theme:{themes:Qe,activeId:ze,paintedId:le,auto:He,setAuto:e=>{qe(e),localStorage.setItem(`teapot.theme.auto`,e?`1`:`0`)},dark:it,setDark:at,light:Je,setLight:Ye,setThemes:rt,setActive:Be,preview:e=>Ze(e),commitAppearance:e=>{localStorage.setItem(`teapot.theme.auto`,e.auto?`1`:`0`),localStorage.setItem(`teapot.theme.dark`,e.dark),localStorage.setItem(`teapot.theme.light`,e.light),localStorage.setItem(`teapot.theme`,e.fixed)}}})}}),j(N,{get when(){return Gn()},fallback:null,children:e=>{let t=()=>h().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,h().length-t()-1);return j(Bu,{title:`edit prompt — forks the conversation`,onClose:()=>Kn(null),get children(){var t=n_(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await Q(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value})}),Kn(null),V();let t=n();t&&await ji(t)}catch(e){alert(`edit failed: ${e.message}`)}}),R(t,j(N,{get when(){return r()>0},get children(){var e=t_(),t=e.firstChild;return R(e,r,t),e}}),a),o.$$click=()=>Kn(null),y(()=>i.value=e().text),t}})}})]}function x_(e,t){return e.length>t?e.slice(0,t)+` …`:e}function S_(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 C_(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 Q(`/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 Q(`/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 j(Bu,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=i_(),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,te=C.firstChild.nextSibling,ne=C.nextSibling.firstChild.nextSibling,w=x.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),R(b,j(M,{get each(){return r()},children:e=>(()=>{var n=a_();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),R(n,e,null),n})()})),ee.$$input=e=>o(e.currentTarget.value),te.addEventListener(`change`,e=>c(e.currentTarget.value)),R(te,j(M,{get each(){return e.providers},children:e=>(()=>{var t=Ng();return R(t,e),t})()})),ne.$$input=e=>u(e.currentTarget.value),R(i,j(N,{get when(){return d()},get children(){var e=r_();return R(e,d),e}}),w),y(()=>h.value=t()),y(()=>ee.value=a()),y(()=>te.value=s()),y(()=>ne.value=l()),i}})}we([`click`,`input`,`keydown`,`pointerdown`,`dblclick`]),Ce(()=>j(b_,{}),document.getElementById(`root`));export{id as t};
36
+ //# sourceMappingURL=index-DtLfOFz4.js.map