@hydra-acp/cli 0.1.148 → 0.1.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,6 +25,8 @@
25
25
 
26
26
  > **Status: experimental.** One daemon owns your coding agents, so a session isn't tied to the window that started it. Built on the [Agent Client Protocol (ACP)](https://agentclientprotocol.com/).
27
27
 
28
+ ![Starting a session in the hydra-acp TUI, then switching between two live sessions from the picker](assets/demo.svg)
29
+
28
30
  ## What it is
29
31
 
30
32
  `hydra-acp` is a **session manager, multiplexer, and TUI** for AI coding agents. Many clients — a terminal TUI, your editor, a browser, Slack — attach to the same live session at once and see it update in real time. Start a session at your desk, follow it from your phone, hand it off to a teammate.
package/dist/cli.js CHANGED
@@ -224,7 +224,7 @@ uncaught: ${e.stack??e.message}
224
224
  `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=L0(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=L0(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n=Ha,s=fc;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
225
225
  `);this.pasteBuffer="";let a=kC(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=YB(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.contentWidth()}termWidth(){return this.term.width||0}sidebarReserved(){if(!this.sidebarVisible)return 0;let e=this.term.width||0;if(e<LB)return 0;let n=this.sidebarConfiguredWidth??Math.min(FB,Math.max(M0,Math.floor(e*.28))),s=e-BB-Mc-my;return Math.min(n,Math.max(M0,s))+Mc+my}sidebarOverlay(){let e=this.sidebarReserved();return e>0&&e*2>(this.term.width||0)}sidebarColumnStart(){let e=this.sidebarReserved();return e===0?0:(this.term.width||0)-e+1}contentWidth(){let e=this.term.width||0;return this.sidebarOverlay()?e:Math.max(0,e-this.sidebarReserved())}transcriptVisibleWidth(){let e=this.sidebarColumnStart();return e===0?this.contentWidth():e-1}sidebarBodyWidth(){let e=this.sidebarReserved();return e===0?0:e-Mc-my}isSidebarVisible(){return this.sidebarVisible}isSidebarSuppressed(){return this.sidebarVisible&&this.sidebarReserved()===0}isSidebarOverlay(){return this.sidebarOverlay()}setSidebarVisible(e){this.sidebarVisible!==e&&(this.sidebarVisible=e,this.lastSidebarClick=null,this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear(),this.sidebarPages={},this.sidebarScrollOffset=0,this.sidebarOverflowRows=0,this.sidebarRenderer.invalidate(),this.painter.clearCache())}toggleSidebar(){return this.setSidebarVisible(!this.sidebarVisible),this.sidebarVisible}setSidebarGadgets(e){this.sidebarRenderer.setGadgets(e),this.scheduleRepaint()}isSidebarGadgetConfigured(e){return this.sidebarRenderer.isConfigured(e)}isSidebarGadgetActive(e){return this.sidebarRenderer.isConfigured(e)&&!this.sidebarCollapsed.has(e)}toggleSidebarGadgetCollapsed(e){let n=!this.sidebarCollapsed.has(e);return n?this.sidebarCollapsed.add(e):this.sidebarCollapsed.delete(e),this.sidebarRenderer.invalidate(),this.onSidebarCollapseChange?.(e,n),n}setSidebarCollapsed(e){this.sidebarCollapsed=new Set(e),this.sidebarRenderer.invalidate()}sidebarCollapsedIds(){return[...this.sidebarCollapsed]}setSidebarBorder(e){this.sidebarBorder!==e&&(this.sidebarBorder=e,this.sidebarRenderer.invalidate(),this.painter.clearCache(),this.scheduleRepaint())}setSidebarWidth(e){this.sidebarConfiguredWidth=e,this.painter.clearCache()}setSidebarSnapshot(e){this.sidebarSnapshot={...this.sidebarSnapshot,...e},this.sidebarVisible&&this.scheduleRepaint()}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.cancelSlide(!0),this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.contentWidth();return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),d=n.length-s.count,c=this.lines.slice(s.start,o),l=new Array(n.length),f=[];for(let u=0;u<n.length;u++){let p=c[u],h=n[u];p!==void 0&&ZB(p,h)?l[u]=p:(p!==void 0&&f.push(p),l[u]=h)}for(let u=n.length;u<c.length;u++)f.push(c[u]);this.lines.splice(s.start,s.count,...l);for(let u of f)this.forgetLine(u);for(let u of l)this.lineIds.has(u)||this.trackLine(u);if(this.invalidateSelectionIfTouches(f),s.count=n.length,d!==0)for(let[u,p]of this.keyedBlocks)u!==e&&p.start>s.start&&(p.start+=d);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
226
226
  `),[o,...a]=i,d=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",d+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),d+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),d+=this.wrappedRowsOf(l)}let c=" ".repeat(n.length);for(let l of a){let f={prefix:c,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),d+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(d),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setBarConfig(e){this.barConfig=DC(e),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.syncReportedCwd(),r0({sessionId:this.sessionbar.sessionId,agent:this.sessionbar.agent,title:this.sessionbar.title,model:this.sessionbar.model,costAmount:this.sessionbar.usage?.costAmount,cwd:this.sessionbar.cwd}),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=yN(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}syncReportedCwd(){let e=this.sessionbar.cwd?.trim();e&&e!==this.lastReportedCwd&&(this.lastReportedCwd=e,sy(e))}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),i0({status:this.banner.status,queued:this.banner.queued}),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Ge(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}sessionTitle(){return this.sessionbar.title}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),pe({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let d={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},c=this.selection;c&&c.startLineId===d.startLineId&&c.startOffset===d.startOffset&&c.endLineId===d.endLineId&&c.endOffset===d.endOffset||(this.selection=d,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}farEndpointFrom(e){if(this.selection===null)return null;let n=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.startLineId),i=this.lineIndexById(n.endLineId);if(s<0||r<0||i<0)return null;let o=(f,u,p,h)=>f!==p?f-p:u-h,a=o(s,e.offset,r,n.startOffset),d=o(s,e.offset,i,n.endOffset);if(a<=0)return{sourceLineId:n.endLineId,offset:n.endOffset};if(d>=0)return{sourceLineId:n.startLineId,offset:n.startOffset};let c=Math.abs(s-r)*1e6+Math.abs(e.offset-n.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-n.endOffset)>=c?{sourceLineId:n.endLineId,offset:n.endOffset}:{sourceLineId:n.startLineId,offset:n.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let d=(r.body??"").slice(o.start,o.end);(_c(r.bodyStyle)||r.ansi)&&(d=Wf(d)),n.push(d)}return n.join(`
227
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let d=new Map;for(let c=r;c<=i;c++){let l=this.lines[c];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=c===r?Math.max(0,Math.min(u,o)):0,h=c===i?Math.max(0,Math.min(u,a)):u;d.set(f,{start:p,end:h,toEnd:c<i})}return{loIdx:r,hiIdx:i,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=s.bodyDisplayShift??0,a=s.sourceColEnd??i+e.body.length-o,d=Math.max(r.start,i),c=Math.min(r.end,a);if(c<=d)return null;let l,f;if(s.sourceColEnd!==void 0){let u=this.sourceBodyForId(s.sourceLineId);if(u===null)return null;let p=Sy(u,i,d),h=Sy(u,d,c);l=ky(e.body,o,p),f=ky(e.body,l,h)}else l=d-i+o,f=c-i+o;return{start:l,end:f,toEndOfLine:r.toEnd||r.end>a}}sourceBodyForId(e){let n=this.lineIndexById(e);return n===-1?null:this.lines[n]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>n.start&&(d.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let i=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=d&&f.start<c)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(d=>d.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(o=Math.max(o,d.start+d.count))}for(let a=i.start+i.count;a<o;a++){let d=this.lines[a];d&&(d.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(dg),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&(this.clearSelection(),this.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),o0(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(n=>({...n}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&this.clearSelection(),this.compactionPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,n){if(process.env.HYDRA_TUI_KEY_TRACE&&pe({tag:"key",name:e,isChar:!!n.isCharacter}),n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.scrollToNextTurn();return}let s=zf(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let f=e==="MOUSE_WHEEL_UP"?3:-3,u=this.mouseCell(n);if(u!==null&&this.isFormCell(u.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(u!==null&&this.isSidebarCell(u.x,u.y)&&this.scrollSidebarBy(f))return;this.scrollBy(f);return}let r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(n),a=XB(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&o!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:o.x,y:o.y,name:e});let c=o!==null?this.barHitAt(o.x,o.y):null;if(d==="move"){let f=c?.id??null;if(f!==this.hoveredBarHit&&(this.hoveredBarHit=f,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),o!==null&&this.isPermissionCell(o.y)){let u=this.permissionHitAt(o.x,o.y);this.setPointerShape(u!==null?"pointer":"default"),u!==null&&u.kind==="option"&&this.permissionPrompt!==null&&u.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:u.index,select:!0})}if(o!==null&&this.isFormCell(o.y)){let u=this.formHitAt(o.x,o.y);this.setPointerShape(u!==null?"pointer":"default"),u!==null&&u.kind==="row"&&this.formPrompt!==null&&u.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:u.row,select:!0})}}let l=o!==null&&c===null&&this.barHits.get(o.y)===void 0&&o.x>=1&&o.x<=this.transcriptVisibleWidth();if(o!==null&&l&&d!=="release"){let f=this.keyAndSubAtRow(o.y),u=f!==null&&f.key.startsWith("agent:")?null:f;if(u===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(o.y),h=this.nearestKeyBelowRow(o.y);p!==null&&h!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(h)&&(u={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(u!==null?"pointer":"default"),d==="move"){let p=u?.key??null,h=u?.sub??null;(p!==this.hoveredBlockKey||h!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=h,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(o!==null&&!l&&this.setPointerShape("default"),(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback())));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let f=this.lastLeftClick;if(f!==null&&o!==null&&Math.abs(o.x-f.x)<=Hf&&Math.abs(o.y-f.y)<=Hf&&Date.now()-f.t<=Pc||this.flushPendingBlockClick(),o!==null&&this.handleBarPress(o)){this.pressCell=null;return}if(o!==null&&this.handlePermissionPress(o)){this.pressCell=null;return}if(o!==null&&this.handleFormPress(o)){this.pressCell=null;return}if(this.handleSidebarPress(o)){this.pressCell=null,this.clearSelection();return}this.pressCell=o,this.handleSelectionPress(o,QB(n,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){if(this.handleBarRelease(o)){this.pressCell=null;return}if(this.handlePermissionRelease(o)){this.pressCell=null;return}if(this.handleFormRelease(o)){this.pressCell=null;return}let f=this.pressCell;this.pressCell=null;let u=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(f!==null&&o!==null&&o.x===f.x&&o.y===f.y&&!u&&this.onBlockClick){let p=this.keyAndSubAtRow(o.y),h=p?.key??null;if(h!==null){let m=o.y;for(;m>1&&this.keyAtRow(m-1)===h;)m-=1;this.schedulePendingBlockClick(h,o.y-m,p?.sub??null)}}(o===null||!this.isSidebarCell(o.x,o.y))&&this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(n&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=Pc&&Math.abs(e.x-i.x)<=Hf&&Math.abs(e.y-i.y)<=Hf&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(s,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(s);c!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:c.start},{sourceLineId:s.sourceLineId,offset:c.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let n=this.lineById(e);if(n===null)return;let s=(n.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let n=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=n&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let n=this.scrollbackVisibleRows();if(n<=0||this.lines.length===0)return null;let s=this.contentWidth(),{rows:r}=this.wrapTail(s,n+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-n),a=r.slice(o,i),d=Math.max(0,n-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=c<d;if(c===0&&l||u){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(c>=n-1&&f){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,n){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let i=1;i<s;i++){let o=n-i;if(o>=1){let d=this.resolveCellToSource(r,o);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=n+i;if(a<=s){let d=this.resolveCellToSource(r,a);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let n=this.farEndpointFrom(e);return n===null?!1:(this.selectionAnchor=n,this.selectionDragStarted=!0,this.setSelection(n,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,n){if(this.autoscrollTimer!==null&&this.autoscrollDir===n){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=n,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},t.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=jf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Uf.test(r[a])&&!py.test(r[a]))return null;let d=a;for(;d>0&&py.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&py.test(r[c]);)c++;for(;c>d+1&&_B.test(r[c-1]);)c--;if(r.slice(d,c).includes("://")){let p=d,h=c;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!Uf.test(r[a]))return null;let f=a;for(;f>0&&Uf.test(r[f-1]);)f--;let u=a+1;for(;u<r.length&&Uf.test(r[u]);)u++;for(;u>f+1&&E0.test(r[u-1]);)u--;for(;f<u-1&&E0.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,f,u)}projectCleanRangeToRaw(e,n,s,r){let i=n,o=n;for(let a=0;a<e.length;a++)if(e[a]===s&&i===n&&(i=a),e[a]===r&&o===n){o=a;break}return{start:i,end:o}}pathTokenAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=jf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!fy.test(r[a]))return null;let d=a;for(;d>0&&fy.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&fy.test(r[c]);)c++;let l=r.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=r.slice(c).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let n=this.lineById(e.sourceLineId);if(n===null||!n.links||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=jf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of n.links)if(o>=a.start&&o<a.end)return a.url;return null}osc8UrlFor(e){if(P0.test(e))return null;if(e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;let n=e.indexOf("#"),s=n===-1?e:e.slice(0,n),r=n===-1?"":e.slice(n);if(s.length===0)return null;let i=s;return s==="~"||s.startsWith("~/")?i=s==="~"?Df():`${Df()}/${s.slice(2)}`:uy(s)||(i=T0(this.sessionbar.cwd,s)),Hm(i+r)}linkSpansForWindow(e,n,s,r,i){let o=rN(e),a=[];for(let d of n){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=o[d.start]??e.length,f=o[d.end]??e.length,u=Math.max(l,s),p=Math.min(f,r);p>u&&a.push({start:u-s+i,end:p-s+i,url:c})}return a.length>0?a:null}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Df():`${Df()}/${n.slice(2)}`);let s=uy(n)||e.startsWith("~"),r=uy(n)?n:T0(this.sessionbar.cwd,n);if(s)return r;try{if(R0(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.raw;if(!$B.test(s))return!1;let r=s.startsWith(en)?[s]:[en+s,s],i=null;for(let o of r)try{if(R0(B.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}dispatchLinkUrl(e){let n=e.match(P0);if(n){let i=n[1]??null;return i!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(i):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let s=e;if(s.startsWith("file://")){let i=s.slice(7),o=i.indexOf("/");s=o===-1?"":i.slice(o);try{s=decodeURIComponent(s)}catch{}}if(s.length===0)return!1;let r=s.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return r?this.tryOpenPathString(`${r[1]}:${r[2]}`):this.tryOpenPathString(s)}tryOpenLinkAt(e,n){let s=this.findLinkUrlAt(e);if(s!==null)return this.dispatchLinkUrl(s);let i=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(i!==void 0)return this.dispatchLinkUrl(i);if(n!==null){let o=this.blockLinkUrlAt(n);if(o!==null)return this.dispatchLinkUrl(o)}return!1}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...d]=this.openFileCommand;if(!a)return!1;let c=!1,l=[];for(let f of d)f.includes("%f")&&(c=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));c||l.push(i);try{let f=TB(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.message}`)}return!0}schedulePendingBlockClick(e,n,s){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n,s);return}this.cancelPendingBlockClick();let r=this.onBlockClick,i=setTimeout(()=>{this.pendingBlockClick=null,r(e,n,s)},Pc);typeof i.unref=="function"&&i.unref(),this.pendingBlockClick={timer:i,key:e,rowOffset:n,subKey:s}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset,e.subKey))}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Bg(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?aI:of))}blockLinkUrlAt(e){let n=this.keyAtRow(e);if(n===null)return null;let s=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return null;let{rows:i}=this.wrapTail(s,r+this.scrollOffset);for(let o of i)if(o.blockKey===n&&o.linkSpans!==void 0&&o.linkSpans.length>0)return o.linkSpans[0]?.url??null;return null}keyAtRow(e){let n=this.contentWidth(),s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}nearestKeyAboveRow(e){for(let n=e-1;n>=1;n--){let s=this.keyAtRow(n);if(s!==null)return s}return null}nearestKeyBelowRow(e){let s=this.scrollbackVisibleRows();for(let r=e+1;r<=s;r++){let i=this.keyAtRow(r);if(i!==null)return i}return null}keyAndSubAtRow(e){let n=this.contentWidth(),s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;if(f<0||f>=c.length)return null;let u=c[f];return u?.blockKey?{key:u.blockKey,sub:u.hoverSubKey??null}:null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.contentWidth(),r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-i),l=a.slice(c,d),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=ut(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let S=w,x=_c(p.bodyStyle)||p.ansi===!0?m0(Cy(p.body),S):h0(p.body,S);if(h.sourceColEnd!==void 0){let R=this.sourceBodyForId(h.sourceLineId);if(R!==null){let A=Sy(p.body,y,x),M=ky(R,h.sourceColOffset,A);return{sourceLineId:h.sourceLineId,offset:M}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+x-y}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){let e=this.turnStops(),n=this.settledScrollOffset(),s=e.find(r=>r>n);this.stepToTurnStop(s??this.maxScrollOffset())}scrollToNextTurn(){let e=this.turnStops(),n=this.settledScrollOffset(),s=0;for(let r of e){if(r>=n)break;s=r}this.stepToTurnStop(s)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),n=this.scrollPageSize(),s=[0,...this.turnScrollOffsets(),e].filter(i=>i>=0&&i<=e).sort((i,o)=>i-o),r=[];for(let i=0;i<s.length;i++){let o=s[i];r.at(-1)!==o&&r.push(o);let a=s[i+1];if(a===void 0||n<=0)continue;let d=[];for(let c=a-n;c>o;c-=n)d.push(c);d.reverse(),r.push(...d)}return r}notifyTurnPosition(e){let n=this.turnScrollOffsets();if(n.length===0)return;let s=n.findIndex(i=>i>=e),r=s===-1?1:n.length-s;this.notify(`turn ${r}/${n.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),n=this.scrollbackVisibleRows();if(n<=0)return[];let s=[],r=0,i=null;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines[o];if(!(!a||this.isHiddenLine(a))){if(r+=this.wrapOne(a,e).length,a.bodyStyle==="user"){i={offset:Math.max(0,r-n),lineIndex:o};continue}i!==null&&(s.push(i),i=null)}}return i!==null&&s.push(i),s}slideScrollTo(e){this.cancelSlide();let n=Math.min(this.maxScrollOffset(),Math.max(0,e)),s=Math.abs(n-this.scrollOffset);if(s!==0){if(s<=VB||!this.slideEnabled){this.setScrollOffset(n);return}this.slideTarget=n,this.slideTimer=setInterval(()=>{let r=this.slideTarget-this.scrollOffset,i=Math.sign(r)*Math.max(1,Math.round(Math.abs(r)*GB)),o=Math.abs(r)<=Math.abs(i)?this.slideTarget:this.scrollOffset+i;this.scrollOffset=o,this.syncedPartialRepaint(()=>this.drawScrollback()),o===this.slideTarget&&this.cancelSlide()},KB)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=Math.min(this.maxScrollOffset(),Math.max(0,e));n!==this.scrollOffset&&(this.scrollOffset=n,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=N0(i.body,n);for(let a=o.length-1;a>=0;a--)s.push({lineIdx:r,col:o[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=s.bodyDisplayShift??0,i=n.col-s.sourceColOffset+r;return i<r||i>=e.body.length?null:i}scrollToMatch(e){let n=this.contentWidth(),s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let h=p.body.length;if(e.col<f+h){o=l.length-1-u;break}f+=h}}let a=r+o,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-bt-Mt-Pt-OB-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,n,s,r){return this.started?this.painter.paintRow(e,n,s,r):!1}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),this.barHits.clear(),Ge(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Pt-Mt-bt;this.drawBar("composerTop",r),this.drawPrompt(),this.drawBar("composerBottom",n-bt),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null}}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:"",queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null}}drawBar(e,n){let s=NC[e],r=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,i=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top,o=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?OC(o):null,d=a!==null?[a]:zg(e,i.right,o),c=$C(r,zg(e,i.left,o),d,s),l=this.terminalFocused?this.hoveredBarHit:null,f=`${e}|${r}|${l??""}|${c.signature}`;this.paintRow(n,f,()=>{for(let u of c.chunks){let p=u.id!==void 0&&u.id===l?"hint-hover":u.token;$(this.term,p,u.text)}}),this.barHits.set(n,c.hits)}barHitAt(e,n){let s=this.barHits.get(n);return s===void 0?null:s.find(r=>e>=r.start&&e<=r.end)??null}bannerHitAt(e,n){let s=this.barHitAt(e,n);if(s===null)return null;let r=s.id.slice(s.id.indexOf(":")+1);return r==="mode"||r==="pick"||r==="guide"||r==="detach"?r:null}stepFormCursor(e){let n=this.formPrompt;if(n===null||n.rows.length===0)return;let s=Math.max(0,Math.min(n.rows.length-1,n.selectedIndex+e));s!==n.selectedIndex&&this.onFormClick?.({kind:"row",row:s,select:!0})}isFormCell(e){let n=this.formRegion;return this.formPrompt!==null&&n!==null&&e>=n.top&&e<=n.bottom}formHitAt(e,n){if(!this.isFormCell(n))return null;for(let r of this.formHintHits)if(r.row===n&&e>=r.start&&e<=r.end)return{kind:"hint",action:r.action};let s=this.formRowHits.get(n);if(s===void 0)return null;if(s.field!==void 0&&e>=s.field.startCol){let{slice:r,sliceStart:i,startCol:o}=s.field,a=i,d=o;for(let c of r){let l=d+ut(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:s.row,caretOffset:a}}return{kind:"row",row:s.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let n=this.formPressHit;if(this.formPressHit=null,n===null||e===null||!this.isFormCell(e.y))return n!==null;let s=this.formHitAt(e.x,e.y);return s===null||s.kind!==n.kind||s.kind==="row"&&n.kind==="row"&&s.row!==n.row||s.kind==="hint"&&n.kind==="hint"&&s.action!==n.action||this.onFormClick?.(s),!0}handleBarPress(e){let n=this.barHitAt(e.x,e.y);if(n===null)return this.barPressHit=null,!1;let s=Date.now(),r=this.lastBarClick;return r!==null&&r.id===n.id&&s-r.t<=Pc&&n.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(n.doubleAction,n.value),!0):(this.lastBarClick={id:n.id,t:s},this.barPressHit=n,!0)}handleBarRelease(e){let n=this.barPressHit;if(this.barPressHit=null,n===null||e===null)return!1;let s=this.barHitAt(e.x,e.y);return s===null||s.id!==n.id?!1:(s.action==="none"||this.dispatchBarAction(s.action,s.value),!0)}dispatchBarAction(e,n){if(e!=="none"){if(e==="copy"){Bg(n,{target:this.selectionClipboard}).then(s=>{this.notify(s.ok?`copied ${n}`:`clipboard copy failed: ${s.reason}`)},s=>{this.notify(`clipboard copy failed: ${s.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(n);return}if(e==="open"){this.tryOpenPathString(n)||this.notify(this.hasOpenFileCommand()?`can't open ${n}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,n)}}drawScrollback(){let e=this.contentWidth(),n=this.sidebarReserved()>0&&!this.sidebarOverlay(),s=this.sidebarBodyWidth()>0,r=1,i=this.scrollbackVisibleRows();if(i<=0)return;let{rows:o,exhausted:a}=this.wrapTail(e,i+this.scrollOffset);if(a){let y=Math.max(0,o.length-i);this.scrollOffset>y&&(this.scrollOffset=y)}let d=o.length-this.scrollOffset,c=Math.max(0,d-i),l=o.slice(c,d),f=Math.max(0,i-l.length),u=this.currentMatchInfo(),p=u?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let h=-1,m=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let y=0;y<l.length;y++){let w=l[y]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(h===-1&&(h=y),m=y)}for(let y=0;y<i;y++){let w=r+y,S=y-f,v=S>=0?l[S]:void 0,x=this.activeMatchCol(v,u),R=v?this.selectionRangeForChunk(v):null,A=v!==void 0&&v.blockKey!==void 0&&(v.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(v.blockKey)),M=v!==void 0&&v.blockKey===void 0&&h!==-1&&S>=h&&S<=m,N=A||M,E=this.terminalFocused&&N&&(this.hoveredSubKey===null||(v.hoverSubKey??null)===this.hoveredSubKey),_=vy("sb",e,v,this.scrollbackHighlight,x,R)+(E?"|H":"");this.paintRow(w,_,()=>{v?this.writeFormattedLine(v,e,x,p,R,E,n,v.linkSpans??null):n&&this.term(" ".repeat(e))},n?{erase:!1}:void 0)&&s&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let y=new Set;for(let S of l)S.blockKey!==void 0&&y.add(S.blockKey);let w=[];for(let S of this.pendingVisibleKeys)y.has(S)&&w.push(S);for(let S of w)this.pendingVisibleKeys.delete(S),this.onBlockVisible(S)}}drawSidebar(e,n){let s=this.sidebarBodyWidth();if(s<=0||n<=0){this.sidebarOverflowRows=0;return}let r=this.sidebarColumnStart(),i={metrics:{cellWidth:ut,truncate:zt},width:s,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:n},o={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(o,i);this.sidebarOverflowRows=Math.max(0,a.length-n),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear();let c=r+Mc;for(let l=0;l<n;l++){let f=e+l,u=l+d,p=a[u];p?.openPath!==void 0&&this.sidebarRowPaths.set(f,p.openPath),p?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(f,p.doubleAction),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(f,p.actions.map(w=>({start:c+w.start-1,end:c+w.end-1,..."page"in w?{gadget:w.page.gadget,index:w.page.index}:{gadget:w.collapse.gadget,collapse:!0}})));let h=l===0&&d>0?"\u25B2":l===n-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",m=p?.openPath===void 0||!p.openPath.startsWith("/")||p.openSpan===void 0?null:[{...p.openSpan,url:Hm(p.openPath)}],y=vy("sbar",s,p,null,null,null)+`|${h}|${m===null?"":m.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(f,y,()=>{this.term(" ".repeat(Math.max(0,Mc-1))),h===" "?this.term(" "):er(this.term,h,"sidebar-rule",!1),p?this.writeFormattedLine(p,s,null,0,null,!1,!0,m):this.term(" ".repeat(s))},{region:"sidebar",column:r})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let n=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return n===this.sidebarScrollOffset||(this.sidebarScrollOffset=n,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,n){let s=this.sidebarColumnStart();return s===0?!1:e>=s&&e<=(this.term.width||0)&&n>=1&&n<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let i of this.sidebarRowActions.get(e.y)??[])if(!(e.x<i.start||e.x>i.end))return i.collapse===!0?this.toggleSidebarGadgetCollapsed(i.gadget):this.sidebarPages={...this.sidebarPages,[i.gadget]:i.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let n=Date.now(),s=this.lastSidebarClick;if(s!==null&&n-s.t<=Pc&&e.y===s.y){this.lastSidebarClick=null;let i=this.sidebarRowDoubleActions.get(e.y);if(i!==void 0)return this.dispatchBarAction(i.action,i.value),!0;let o=this.sidebarRowPaths.get(e.y);return o!==void 0&&!this.dispatchLinkUrl(o)&&this.notify(this.hasOpenFileCommand()?`can't open ${o}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t:n},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(gy,this.queuedTexts.length)}chipRows(){return Math.min(wy,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(yy,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-bt-Mt-Pt,i=this.queuedRows(),o=this.chipRows(),d=r-1-i-o-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>yy,h=this.completions.length-yy+1,m=u?p?`comp|${n}|overflow|${h}`:`comp|${n}|${c}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,m,()=>{if(!u)return;if(p){$(this.term,"modal-hint",` + ${h} more match(es)`);return}let y=u.name.padEnd(c),w=u.description??"",S=n-y.length-4,v=S>0?zt(w,S):"";this.term.noFormat(" "),$(this.term,"completion-name",y),v.length>0&&(this.term.noFormat(" "),$(this.term,"completion-desc",v))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-bt-Mt-Pt-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=o+d,l=d===e-1&&this.attachments.length>wy,f=this.attachments.length-wy,u=this.attachments[d],p=u?`${u.name??"image"} \xB7 ${es(u.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(c,h,()=>{if(l){$(this.term,"modal-hint",` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term.noFormat(" "),$(this.term,"attachment",`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(oN(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-bt-Mt-Pt,i=this.chipRows(),a=r-1-i-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>gy,p=this.queuedTexts.length-gy,h=f===void 0?"":u?`+ ${p+1} more queued`:zt(gN(f),n-4),m=!u&&c===d,y=f===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":u?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(f===void 0)return;let w=`\u23F3 ${h}`,S=w+" ".repeat(Math.max(0,n-1-w.length));m?$(this.term,"queue-cursor","\u25B8"):$(this.term,"queue-blank"," "),$(this.term,"queue-row",S)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=tr(s.buffer,n),i=Cr(r,s,hy),o=this.term.height-i.rendered-Pt-Mt-bt+1,a=!1;for(let d=0;d<i.rendered;d++){let c=r[i.windowStart+d],l=o+d,f="wrap",u="";c&&(c.bufferIdx===0&&c.startCol===0?f="first":c.startCol===0&&(f="newline"),u=(s.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(f==="first"?a?$(this.term,"composer-inactive","> "):$(this.term,"composer-gutter","> "):f==="newline"?$(this.term,"composer-continuation","\xB7 "):this.term(" "),a?$(this.term,"composer-inactive",u):$(this.term,"content",u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-by-Pt-Mt-bt+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{$(this.term,"prompt-text",` ? ${zt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{$(this.term,"modal-hint",` ${zt(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-Pt-Mt-bt+1,i=r,o=(a,d)=>{i>=r+s||(this.paintRow(i,a,d),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{$(this.term,"prompt-text",` ${zt(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{$(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let d=e.options[a];if(!d)continue;let c=a===e.selectedIndex,f=` ${c?"\u276F":" "} ${a+1}. ${zt(d.label,n-8)}`;o(`cpct|o|${n}|${a}|${c?"1":"0"}|${d.label}`,()=>{c?$(this.term,"modal-option-selected",f):$(this.term,"modal-option",f)})}o(`cpct|hint|${n}`,()=>{$(this.term,"modal-hint"," \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Pt-Mt-bt+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`help|t|${n}|${e.title}`,()=>{$(this.term,"prompt-text",` \u2753 ${zt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(i>=r+s-1)break;if(d===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);o(`help|e|${n}|${c}|${l}`,()=>{this.term(" "),$(this.term,"modal-key",f),$(this.term,"content",` ${zt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{$(this.term,"modal-hint",` ${zt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(WB,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Pt-Mt-bt+1,i=r;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:r,bottom:r+s-1};let o=(l,f)=>{i>=r+s||(this.paintRow(i,l,f),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{$(this.term,"prompt-text",` \u{1F512} ${zt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{$(this.term,"modal-hint",` ${zt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{$(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(i>=r+s-1);l++){let f=e.options[l];if(!f)continue;let u=l===e.selectedIndex,h=` ${u?"\u276F":" "} ${l+1}. ${zt(f.label,n-8)}`;this.permissionRowHits.set(i,l),o(`perm|o|${n}|${l}|${u?"1":"0"}|${f.label}`,()=>{u?$(this.term,"modal-option-selected",h):$(this.term,"modal-option",h)})}let d=O0(UB,n),c=i;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});o(`perm|hint|${n}|${d.text}`,()=>{$(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let n=this.permissionRegion;return this.permissionPrompt!==null&&n!==null&&e>=n.top&&e<=n.bottom}permissionHitAt(e,n){if(!this.isPermissionCell(n))return null;for(let r of this.permissionHintHits)if(r.row===n&&e>=r.start&&e<=r.end)return{kind:"hint",action:r.action};let s=this.permissionRowHits.get(n);return s===void 0?null:{kind:"option",index:s}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let n=this.permissionPressHit;if(this.permissionPressHit=null,n===null||e===null||!this.isPermissionCell(e.y))return n!==null;let s=this.permissionHitAt(e.x,e.y);return s===null||s.kind!==n.kind||s.kind==="option"&&n.kind==="option"&&s.index!==n.index||s.kind==="hint"&&n.kind==="hint"&&s.action!==n.action?!0:Date.now()-this.permissionArmedAt<HB?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(s),!0)}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}drawBanner(){let e=this.term.height,n=this.promptRows(),s=e-n-Pt-Mt-bt;this.drawBar("composerTop",s),this.drawBar("composerBottom",e-bt)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Pt-Mt-bt+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Pt-Mt-bt;this.term.moveTo(2,Math.min(u,p));return}if(this.formPrompt){let l=this.formPrompt,f=this.formWindowSize(),u=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-u),h=this.term.height-Pt-Mt-bt,m=Math.min(p,h),w=F0(l,this.term.width,u,f).find(S=>S.selected);if(w?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(w.caretCol,this.term.width),m);return}if(this.confirmPrompt){let l=this.term.height-by-Pt-Mt-bt+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-Pt-Mt-bt+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Pt-Mt-bt;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Pt-Mt-bt+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=tr(s.buffer,n),i=Cr(r,s,hy),a=this.term.height-i.rendered-Pt-Mt-bt+1+Math.max(0,i.cursorVisualRow-i.windowStart),d=i.cursorVisualCol+3,c=this.term.height-Pt-Mt-bt;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return by;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=tr(s.buffer,n);return Math.min(hy,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(NB,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(jB,this.formPrompt.maxRows??DB),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Pt-Mt-bt+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let n=this.term.width,s=this.formRows(),r=this.formTop(),i=this.formWindowSize(),o=`${e.title}|${e.rows.length}|${i}`;o!==this.formWindowKey?(this.formWindowKey=o,this.formWindowTop=uN(e.rows.length,e.selectedIndex,i)):this.formWindowTop=fN(this.formWindowTop,e.rows.length,e.selectedIndex,i);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:r,bottom:r+s-1};let d=r,c=(m,y)=>{d>=r+s||(this.paintRow(d,m,y),d+=1)},l=e.rows.length>i?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${n}|${e.title}|${l}`,()=>{$(this.term,"prompt-text",` \u2699 ${zt(`${e.title}${l}`,n-5)}`)});let f=F0(e,n,a,i);for(let m of f){if(d>=r+s-1)break;this.formRowHits.set(d,{row:m.index,...m.kind==="text"?{field:{startCol:1+ut(m.prefix),slice:m.field,sliceStart:m.fieldStart}}:{}}),c(m.sig,()=>{if(m.kind==="text"){$(this.term,m.selected?"modal-option-selected":"modal-option",m.prefix),$(this.term,"content",m.field);return}$(this.term,m.selected?"modal-option-selected":"modal-option",m.body)})}let u=e.hints??pN,p=d,h=O0(u,n);for(let m of h.spans)this.formHintHits.push({row:p,...m});c(`form|hint|${n}|${h.text}`,()=>{$(this.term,"modal-hint",` ${h.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],d=this.wrapOne(a,e);if(s.push(d),r+=d.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Pt-Mt-bt,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,d=e-1,c=a;this.drawBar("btw",c);let l=this.wrapBtwTail(n,d);for(let f=0;f<d;f++){let u=c+1+f,p=l.length-d+f,h=p>=0?l[p]:void 0,m=vy(`btw|c${f}`,n,h);this.paintRow(u,m,()=>{h?this.writeFormattedLine(h,n):this.term.noFormat(" ".repeat(n))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,n){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(n,d.length);return{rows:d.slice(d.length-c),exhausted:n>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let s=[],r=0,i=0,o=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(o=!0);continue}let l=this.wrapOne(c,e);if(s.push(l),r+=l.length,i=d,r>=n)break}let a=[];for(let d=s.length-1;d>=0;d--)a.push(...s[d]);return{rows:a,exhausted:i===0||o}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let y=this.wrapCache.get(s);if(y)return y}let r=e.prefix??"",i=ut(r),o=Math.max(1,n-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),d=Math.max(1,o-a),c=_c(e.bodyStyle),l=e.ansi?tN(e.body,a>0?d:o):aN(e.body,a>0?d:o,{escapeAware:c}),f=e.ansi?0:e.maxWrapRows??0,u=f>0&&l.length>f;u&&(l.length=f);let p=[],h=0,m=0;for(let y=0;y<l.length;y++){let w=l[y]??"",S=y===0||a===0?w:" ".repeat(a)+w;u&&y===l.length-1&&(S=zt(`${S}\u2026`,o,{escapeAware:c}));let v={prefix:y===0?e.prefix:" ".repeat(i),body:S};if(e.prefixStyle!==void 0&&(v.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(v.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(v.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(v.hoverSubKey=e.hoverSubKey),e.fillRow&&(v.fillRow=!0),e.ansi&&(v.ansi=!0),y===0&&e.iterm2Image&&(v.iterm2Image=e.iterm2Image),s!==void 0&&w.length>0)if(e.ansi){let x=h,R=0;for(let E=0;E<w.length;){let _=ts(w,E);if(_){E+=_.text.length,_.width>0&&(R+=1);continue}R+=1,E+=1}let A=R;for(;A>0&&h<e.body.length;){let E=ts(e.body,h);if(E){h+=E.text.length,E.width>0&&(A-=1);continue}h+=1,A-=1}let M=h;if(y===l.length-1){for(;M<e.body.length;){let E=ts(e.body,M);if(!E)break;M+=E.text.length}h=M}let N={sourceLineId:s,sourceColOffset:x,sourceColEnd:M};if(y>0&&a>0&&(N.bodyDisplayShift=a),this.wrapOrigin.set(v,N),e.links!==void 0){let E=this.linkSpansForWindow(e.body,e.links,x,M,y===0||a===0?0:a);E!==null&&(v.linkSpans=E)}}else{let x=e.body.indexOf(w,m),R=x===-1?m:x,A={sourceLineId:s,sourceColOffset:R};if(y>0&&a>0&&(A.bodyDisplayShift=a),this.wrapOrigin.set(v,A),e.links!==void 0){let M=this.linkSpansForWindow(e.body,e.links,R,R+w.length,y===0||a===0?0:a);M!==null&&(v.linkSpans=M)}m=R+w.length}p.push(v)}return s!==void 0&&this.wrapCache.set(s,p),p}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1,a=!1,d=null){e.prefix&&er(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let c=Math.max(0,n-ut(e.prefix??"")),l=_c(e.bodyStyle),f=e.ansi?e.body:zt(e.body,c,{escapeAware:l}),u=d===null||d.length===0?null:d.map(m=>({start:Math.max(0,Math.min(f.length,m.start)),end:Math.max(0,Math.min(f.length,m.end)),url:m.url})).filter(m=>m.end>m.start).sort((m,y)=>m.start-y.start),p=(m,y,w)=>{if(u===null){w(m,y);return}let S=y+m.length,v=y;for(let x of u){if(x.end<=v||x.start>=S)continue;let R=Math.max(x.start,v),A=Math.min(x.end,S);R>v&&w(m.slice(v-y,R-y),v),process.stdout.write(`\x1B]8;;${x.url}\x1B\\`),w(m.slice(R-y,A-y),R),process.stdout.write("\x1B]8;;\x1B\\"),v=A}v<S&&w(m.slice(v-y),v)},h=(m,y)=>{m.length!==0&&p(m,y,(w,S)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let v=s!==null&&s>=S?s-S:null;eN(this.term,w,e.bodyStyle,this.scrollbackHighlight,v,r,o)}else er(this.term,w,e.bodyStyle,o)})};if(i!==null){let m=Math.max(0,Math.min(f.length,i.start)),y=Math.max(m,Math.min(f.length,i.end)),w=_c(e.bodyStyle)||e.ansi===!0;if(h(f.slice(0,m),0),y>m){let v=f.slice(m,y);w&&(v=Wf(v)),w?er(this.term,v,"selection-highlight",o):p(v,m,x=>{er(this.term,x,"selection-highlight",o)})}let S=f.slice(y);if(w&&y>m){let v=iN(f.slice(0,y));v.length>0&&(S=v+S)}h(S,y)}else h(f,0);if(e.fillRow||o||a){let m=e.ansi?B0(f):ut(l?Wf(f):f),y=c-m;if(y>0){let w=i!==null&&i.toEndOfLine?"selection-highlight":e.fillRow||o?e.bodyStyle:void 0;er(this.term," ".repeat(y),w,o)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};D0=/[^\x20-\x7e]/,Iy=new Intl.Segmenter(void 0,{granularity:"grapheme"}),H0=!1;pN=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}];yN=tt});function wN(t,e,n=Kf){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function z0(t,e){bs();let n=tt(e.sessionId),s=e.importedFromMachine??"another machine",r=yt(e.cwd),i=Kf.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let d=7+Kf.length*2+2,c=Fn(t,{contentHeight:d,title:"Imported session"}),l=c.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(c.contentX,c.contentY+u),$(t,"modal-label",` ${p.label}`),$(t,"content",ht(p.value,l-p.label.length-2)),u++;return u++,K0(t,c,u,{intro:"What do you want to do?",choices:Kf,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),c};return Qs({term:t,render:o,onKey:(a,d,c,l)=>{let f=bN(a,c);if(!f)return;let u=wN(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function K0(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),$(t,"content",` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let c=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?$(t,"list-selected",gc(c,r)):$(t,"content",c),i++,t.moveTo(e.contentX,e.contentY+i),$(t,"list-description",` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),$(t,"modal-hint",` ${s.footer}`)}function bN(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function G0(t,e,n){let s=tt(e.sessionId),r=e.title??yt(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=Fn(t,{contentHeight:11,title:"Open session",overlay:!0}),c=d.contentW,l=0;t.moveTo(d.contentX,d.contentY+l),$(t,"modal-label"," session: "),$(t,"content",ht(s,c-10)),l++,t.moveTo(d.contentX,d.contentY+l),$(t,"content"," "+ht(r,c-2)),l++,l++,K0(t,d,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(d=>{let c=!1,l=()=>{c=!0},f=p=>{l(),n.pop(),d(p)},u=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){f("launch");return}if(y==="v"){f("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,h,m)=>{c||u(p,h,m)},onResize:()=>{c||a()}})})}var Kf,Ry=K(()=>{"use strict";Ae();Yn();no();Qt();Kf=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Oc(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function V0(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",d=i.startsWith(" ")?"":" ";return a+d+i}let o=Oc(e);return o.length<=r.length?null:o+i}var Gf=K(()=>{"use strict"});import*as J0 from"os";async function co(t,e,n={}){let s=n.defaultCwd??(e?await qI(e.cwd):void 0)??J0.homedir();bs();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:tt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:yt(e.cwd)}]:[],a=new oi(s),d=null,c=!1,l=null,f=null,u=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),S=h.indexOf(y),v=()=>{let E=o.length+6;l=Fn(t,{contentHeight:E,title:r,overlay:n.overlay===!0});let _=l.contentW,H=0;for(let q of o)t.moveTo(l.contentX,l.contentY+H),$(t,"modal-label",` ${q.label}`),$(t,"content",ht(q.value,_-q.label.length-2)),H++;H++,t.moveTo(l.contentX,l.contentY+H),$(t,"content",` ${i}`),H+=2,A(H),H+=2;let W=l.contentY+H;d!==null?(t.moveTo(l.contentX,W),$(t,"input-error",` ${ht(d,_-2)}`),f=null,u=null,p=null):(t.moveTo(l.contentX,W),$(t,"modal-hint",h),f=W,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+S,end:l.contentX+S+y.length-1})},x=()=>o.length+3,R=0,A=E=>{if(!l)return;let _=E??x();t.moveTo(l.contentX,l.contentY+_).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+_),$(t,"box-border","\u2502"),t.moveTo(l.contentX,l.contentY+_),t.noFormat(" ");let W=Math.max(1,l.contentW-1-2),q=a.text,Q=a.cursor;Q<R&&(R=Q),Q-R>=W&&(R=Q-W+1),R<0&&(R=0);let re=q.slice(R,R+W);R>0&&re.length>0&&(re="\u2026"+re.slice(1));let Se=Q-R;if(c){$(t,"content",re);return}Se>=re.length?($(t,"content",re),$(t,"input-cursor"," ")):($(t,"content",re.slice(0,Se)),$(t,"input-cursor",re[Se]??" "),$(t,"content",re.slice(Se+1)))},M=()=>{if(A(),!l)return;let E=x()+2;t.moveTo(l.contentX,l.contentY+E).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+E),$(t,"box-border","\u2502");let _=l.contentY+E;t.moveTo(l.contentX,_),d!==null?($(t,"input-error",` ${ht(d,l.contentW-2)}`),f=null,u=null,p=null):($(t,"modal-hint",h),f=_,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+S,end:l.contentX+S+y.length-1})},N=E=>{if(c)return;let _=a.text;c=!0,d=null,M(),Sc(_).then(H=>{if(c=!1,H.ok){E({kind:"ok",path:H.path});return}d=H.reason,M()})};return Qs({term:t,render:v,overlay:n.overlay===!0,onKey:(E,_,H,W)=>{if(!c){if(E==="ENTER"||E==="KP_ENTER"){N(W);return}if(E==="ESCAPE"){W({kind:"back"});return}if(E==="CTRL_C"||E==="CTRL_D"){W({kind:"cancel"});return}if(E==="TAB"){c=!0,zI(a.text).then(q=>{if(c=!1,q.matches.length===0)return;let Q;if(q.matches.length===1)Q=q.prefix+q.matches[0];else{let re=Oc(q.matches);if(re.length<=q.basePrefix.length)return;Q=q.prefix+re}Q!==a.text&&(a.setText(Q,{recordUndo:!0}),d=null,M())});return}if(a.handleKey(E,H?.isCharacter===!0)){d=null,M();return}}},onMouse:(E,_,H)=>{if(c||E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let W=_?.x,q=_?.y;if(!(typeof W!="number"||typeof q!="number")){if(l!==null&&(W<l.x||W>=l.x+l.w||q<l.y||q>=l.y+l.h)){H({kind:"back"});return}if(f!==null&&q===f){if(u!==null&&W>=u.start&&W<=u.end){N(H);return}if(p!==null&&W>=p.start&&W<=p.end){H({kind:"back"});return}}}}})}var Ty=K(()=>{"use strict";Ae();Yn();wg();Gf();no();gf();Qt()});import*as Q0 from"fs";import*as X0 from"os";import*as Vf from"path";function Jf(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function vN(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function SN(t){return t.replace(/\\ /g," ")}function Y0(t){return t.replace(/ /g,"\\ ")}function kN(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function xN(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=X0.homedir()+n.slice(1)),Vf.isAbsolute(n)?n:Vf.resolve(e,n)}function IN(t){let e;try{e=Q0.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Yf(t,e,n=IN){let s=SN(t),{dirPrefix:r,base:i}=kN(s);if(r.length===0&&!vN(t)&&i.length===0)return null;let o=xN(r,e),a=n(o);if(a===null)return null;let d=i.startsWith("."),c=a.filter(u=>u.name.startsWith(i)&&(d||!u.name.startsWith(".")));if(c.length===0)return null;let l=c.map(u=>u.isDir?u.name+"/":u.name);if(c.length===1){let u=c[0],p=u.isDir?u.name+"/":u.name;return{replacement:Y0(r+p),candidates:l}}let f=Oc(c.map(u=>u.name));return{replacement:Y0(r+f),candidates:l}}var Ey=K(()=>{"use strict";Gf()});function CN(t){process.stdout.write(`\x1B]9;4;${t}\x1B\\`)}function AN(t,e,n){let s=`${n.agentId}@${n.version}`;if(n.source==="npm")return n.phase==="install_start"||n.phase==="download_start"?`${t} installing ${s} via npm\u2026`:n.phase==="installed"?`${t} ${s} installed`:`${t} installing ${s} via npm\u2026`;if(n.phase==="download_start"||n.phase==="download_progress"){let r=n.receivedBytes??0,i=n.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),d=Math.min(100,Math.floor(r/i*100));return`${t} downloading ${s} ${o}/${a} MB (${d}%)`}return`${t} downloading ${s} ${o} MB`}return n.phase==="download_done"?`${t} downloaded ${s}, verifying\u2026`:n.phase==="extract"?`${t} extracting ${s}\u2026`:n.phase==="installed"?`${t} ${s} installed`:e||t}function Qf(t,e){let n=!1,s="",r=!1,i=t,o=a=>{n||a===3&&r||a===0&&!r||(r=a===3,CN(a))};return{write(a){n||(i=a,s=a,e.write(a))},applyProgress(a){if(n)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let c=AN(i,s,a);s=c,e.write(c)},finalize(){n||(n=!0,o(0),e.finalize())}}}function Z0(t){let e=!1;return{write(n){e||(process.stdout.write("\r"),t.eraseLineAfter(),$(t,"status-active",n))},finalize(){e||(e=!0,process.stdout.write(`
227
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let d=new Map;for(let c=r;c<=i;c++){let l=this.lines[c];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=c===r?Math.max(0,Math.min(u,o)):0,h=c===i?Math.max(0,Math.min(u,a)):u;d.set(f,{start:p,end:h,toEnd:c<i})}return{loIdx:r,hiIdx:i,byId:d}}selectionRangeForChunk(e){if(this.selection===null)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=s.bodyDisplayShift??0,a=s.sourceColEnd??i+e.body.length-o,d=Math.max(r.start,i),c=Math.min(r.end,a);if(c<=d)return null;let l,f;if(s.sourceColEnd!==void 0){let u=this.sourceBodyForId(s.sourceLineId);if(u===null)return null;let p=Sy(u,i,d),h=Sy(u,d,c);l=ky(e.body,o,p),f=ky(e.body,l,h)}else l=d-i+o,f=c-i+o;return{start:l,end:f,toEndOfLine:r.toEnd||r.end>a}}sourceBodyForId(e){let n=this.lineIndexById(e);return n===-1?null:this.lines[n]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,d]of this.keyedBlocks)a!==e&&d.start>n.start&&(d.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(d=>{let c=this.keyedBlocks.get(d);return c?{key:d,start:c.start,count:c.count}:null}).filter(d=>d!==null).sort((d,c)=>d.start-c.start),r=s.findIndex(d=>d.key===e);if(r<0)return[];let i=(d,c)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=d&&f.start<c)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(d=>d.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let d=this.keyedBlocks.get(a);d&&(o=Math.max(o,d.start+d.count))}for(let a=i.start+i.count;a<o;a++){let d=this.lines[a];d&&(d.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(dg),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&(this.clearSelection(),this.permissionArmedAt=Date.now()),this.permissionPrompt=e?{...e}:null,e===null&&(this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion=null,this.permissionPressHit=null),o0(this.permissionPrompt!==null),this.repaint()}setFormPrompt(e){e!==null&&this.formPrompt===null&&this.clearSelection(),this.formPrompt=e?{...e,rows:e.rows.map(n=>({...n}))}:null,e===null&&(this.clearFormHits(),this.formWindowKey=null,this.formWindowTop=0),this.repaint()}clearFormHits(){this.formRowHits.clear(),this.formHintHits=[],this.formRegion=null,this.formPressHit=null}isFormPromptActive(){return this.formPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&this.clearSelection(),this.compactionPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,n){if(process.env.HYDRA_TUI_KEY_TRACE&&pe({tag:"key",name:e,isChar:!!n.isCharacter}),n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}if(e==="ALT_PAGE_UP"){this.scrollToPrevTurn();return}if(e==="ALT_PAGE_DOWN"){this.scrollToNextTurn();return}let s=zf(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"||e==="MOUSE_WHEEL_DOWN"){let f=e==="MOUSE_WHEEL_UP"?3:-3,u=this.mouseCell(n);if(u!==null&&this.isFormCell(u.y)){this.stepFormCursor(e==="MOUSE_WHEEL_UP"?-3:3);return}if(u!==null&&this.isSidebarCell(u.x,u.y)&&this.scrollSidebarBy(f))return;this.scrollBy(f);return}let r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(n),a=XB(e),d=null;e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?d="move":e.endsWith("_PRESSED")?d="press":e.endsWith("_RELEASED")&&(d="release"),d!==null&&o!==null&&this.onMouse&&this.onMouse({kind:d,button:a,x:o.x,y:o.y,name:e});let c=o!==null?this.barHitAt(o.x,o.y):null;if(d==="move"){let f=c?.id??null;if(f!==this.hoveredBarHit&&(this.hoveredBarHit=f,this.syncedPartialRepaint(()=>this.drawBars())),c!==null&&this.setPointerShape(c.action!=="none"||c.doubleAction!=="none"?"pointer":"default"),o!==null&&this.isPermissionCell(o.y)){let u=this.permissionHitAt(o.x,o.y);this.setPointerShape(u!==null?"pointer":"default"),u!==null&&u.kind==="option"&&this.permissionPrompt!==null&&u.index!==this.permissionPrompt.selectedIndex&&this.onPermissionClick?.({kind:"option",index:u.index,select:!0})}if(o!==null&&this.isFormCell(o.y)){let u=this.formHitAt(o.x,o.y);this.setPointerShape(u!==null?"pointer":"default"),u!==null&&u.kind==="row"&&this.formPrompt!==null&&u.row!==this.formPrompt.selectedIndex&&this.onFormClick?.({kind:"row",row:u.row,select:!0})}}let l=o!==null&&c===null&&this.barHits.get(o.y)===void 0&&o.x>=1&&o.x<=this.transcriptVisibleWidth();if(o!==null&&l&&d!=="release"){let f=this.keyAndSubAtRow(o.y),u=f!==null&&f.key.startsWith("agent:")?null:f;if(u===null&&d==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let p=this.nearestKeyAboveRow(o.y),h=this.nearestKeyBelowRow(o.y);p!==null&&h!==null&&this.hoveredRunKeys.has(p)&&this.hoveredRunKeys.has(h)&&(u={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(u!==null?"pointer":"default"),d==="move"){let p=u?.key??null,h=u?.sub??null;(p!==this.hoveredBlockKey||h!==this.hoveredSubKey)&&(this.hoveredBlockKey=p,this.hoveredSubKey=h,this.hoveredRunKeys=p!==null&&this.onHoverRun?this.onHoverRun(p)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else d==="move"&&(o!==null&&!l&&this.setPointerShape("default"),(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback())));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let f=this.lastLeftClick;if(f!==null&&o!==null&&Math.abs(o.x-f.x)<=Hf&&Math.abs(o.y-f.y)<=Hf&&Date.now()-f.t<=Pc||this.flushPendingBlockClick(),o!==null&&this.handleBarPress(o)){this.pressCell=null;return}if(o!==null&&this.handlePermissionPress(o)){this.pressCell=null;return}if(o!==null&&this.handleFormPress(o)){this.pressCell=null;return}if(this.handleSidebarPress(o)){this.pressCell=null,this.clearSelection();return}this.pressCell=o,this.handleSelectionPress(o,QB(n,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){if(this.handleBarRelease(o)){this.pressCell=null;return}if(this.handlePermissionRelease(o)){this.pressCell=null;return}if(this.handleFormRelease(o)){this.pressCell=null;return}let f=this.pressCell;this.pressCell=null;let u=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(f!==null&&o!==null&&o.x===f.x&&o.y===f.y&&!u&&this.onBlockClick){let p=this.keyAndSubAtRow(o.y),h=p?.key??null;if(h!==null){let m=o.y;for(;m>1&&this.keyAtRow(m-1)===h;)m-=1;this.schedulePendingBlockClick(h,o.y-m,p?.sub??null)}}(o===null||!this.isSidebarCell(o.x,o.y))&&this.handleSelectionRelease(o)}}}handleSelectionPress(e,n=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(n&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=Pc&&Math.abs(e.x-i.x)<=Hf&&Math.abs(e.y-i.y)<=Hf&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.tryOpenLinkAt(s,e?.y??null)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let c=this.wordBoundsAt(s);c!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:c.start},{sourceLineId:s.sourceLineId,offset:c.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let n=this.lineById(e);if(n===null)return;let s=(n.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let n=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=n&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let n=this.scrollbackVisibleRows();if(n<=0||this.lines.length===0)return null;let s=this.contentWidth(),{rows:r}=this.wrapTail(s,n+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-n),a=r.slice(o,i),d=Math.max(0,n-a.length),c=e-1,l=this.scrollOffset<this.maxScrollOffset(),f=this.scrollOffset>0,u=c<d;if(c===0&&l||u){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(c>=n-1&&f){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,n){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=Math.max(1,Math.min(this.transcriptVisibleWidth(),e));for(let i=1;i<s;i++){let o=n-i;if(o>=1){let d=this.resolveCellToSource(r,o);if(d!==null){let c=this.lineById(d.sourceLineId);return c?{sourceLineId:d.sourceLineId,offset:(c.body??"").length}:d}}let a=n+i;if(a<=s){let d=this.resolveCellToSource(r,a);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let n=this.farEndpointFrom(e);return n===null?!1:(this.selectionAnchor=n,this.selectionDragStarted=!0,this.setSelection(n,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,n){if(this.autoscrollTimer!==null&&this.autoscrollDir===n){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=n,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},t.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=jf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Uf.test(r[a])&&!py.test(r[a]))return null;let d=a;for(;d>0&&py.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&py.test(r[c]);)c++;for(;c>d+1&&_B.test(r[c-1]);)c--;if(r.slice(d,c).includes("://")){let p=d,h=c;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!Uf.test(r[a]))return null;let f=a;for(;f>0&&Uf.test(r[f-1]);)f--;let u=a+1;for(;u<r.length&&Uf.test(r[u]);)u++;for(;u>f+1&&E0.test(r[u-1]);)u--;for(;f<u-1&&E0.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,f,u)}projectCleanRangeToRaw(e,n,s,r){let i=n,o=n;for(let a=0;a<e.length;a++)if(e[a]===s&&i===n&&(i=a),e[a]===r&&o===n){o=a;break}return{start:i,end:o}}pathTokenAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=jf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!fy.test(r[a]))return null;let d=a;for(;d>0&&fy.test(r[d-1]);)d--;let c=a+1;for(;c<r.length&&fy.test(r[c]);)c++;let l=r.slice(d,c);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let f=null,u=r.slice(c).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}findLinkUrlAt(e){let n=this.lineById(e.sourceLineId);if(n===null||!n.links||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=jf(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of n.links)if(o>=a.start&&o<a.end)return a.url;return null}osc8UrlFor(e){if(P0.test(e))return null;if(e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return e;let n=e.indexOf("#"),s=n===-1?e:e.slice(0,n),r=n===-1?"":e.slice(n);if(s.length===0)return null;let i=s;return s==="~"||s.startsWith("~/")?i=s==="~"?Df():`${Df()}/${s.slice(2)}`:uy(s)||(i=T0(this.sessionbar.cwd,s)),Hm(i+r)}linkSpansForWindow(e,n,s,r,i){let o=rN(e),a=[];for(let d of n){let c=this.osc8UrlFor(d.url);if(c===null)continue;let l=o[d.start]??e.length,f=o[d.end]??e.length,u=Math.max(l,s),p=Math.min(f,r);p>u&&a.push({start:u-s+i,end:p-s+i,url:c})}return a.length>0?a:null}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Df():`${Df()}/${n.slice(2)}`);let s=uy(n)||e.startsWith("~"),r=uy(n)?n:T0(this.sessionbar.cwd,n);if(s)return r;try{if(R0(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.raw;if(!$B.test(s))return!1;let r=s.startsWith(en)?[s]:[en+s,s],i=null;for(let o of r)try{if(R0(B.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}dispatchLinkUrl(e){let n=e.match(P0);if(n){let i=n[1]??null;return i!==null&&this.onHydraLinkClick!==void 0?this.onHydraLinkClick(i):!1}if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e)&&!e.startsWith("file://"))return!1;let s=e;if(s.startsWith("file://")){let i=s.slice(7),o=i.indexOf("/");s=o===-1?"":i.slice(o);try{s=decodeURIComponent(s)}catch{}}if(s.length===0)return!1;let r=s.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return r?this.tryOpenPathString(`${r[1]}:${r[2]}`):this.tryOpenPathString(s)}tryOpenLinkAt(e,n){let s=this.findLinkUrlAt(e);if(s!==null)return this.dispatchLinkUrl(s);let i=this.lineById(e.sourceLineId)?.links?.[0]?.url;if(i!==void 0)return this.dispatchLinkUrl(i);if(n!==null){let o=this.blockLinkUrlAt(n);if(o!==null)return this.dispatchLinkUrl(o)}return!1}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...d]=this.openFileCommand;if(!a)return!1;let c=!1,l=[];for(let f of d)f.includes("%f")&&(c=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));c||l.push(i);try{let f=TB(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.message}`)}return!0}schedulePendingBlockClick(e,n,s){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n,s);return}this.cancelPendingBlockClick();let r=this.onBlockClick,i=setTimeout(()=>{this.pendingBlockClick=null,r(e,n,s)},Pc);typeof i.unref=="function"&&i.unref(),this.pendingBlockClick={timer:i,key:e,rowOffset:n,subKey:s}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset,e.subKey))}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Bg(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?aI:of))}blockLinkUrlAt(e){let n=this.keyAtRow(e);if(n===null)return null;let s=this.contentWidth(),r=this.scrollbackVisibleRows();if(r<=0)return null;let{rows:i}=this.wrapTail(s,r+this.scrollOffset);for(let o of i)if(o.blockKey===n&&o.linkSpans!==void 0&&o.linkSpans.length>0)return o.linkSpans[0]?.url??null;return null}keyAtRow(e){let n=this.contentWidth(),s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;return f<0||f>=c.length?null:c[f]?.blockKey??null}nearestKeyAboveRow(e){for(let n=e-1;n>=1;n--){let s=this.keyAtRow(n);if(s!==null)return s}return null}nearestKeyBelowRow(e){let s=this.scrollbackVisibleRows();for(let r=e+1;r<=s;r++){let i=this.keyAtRow(r);if(i!==null)return i}return null}keyAndSubAtRow(e){let n=this.contentWidth(),s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,d=Math.max(0,a-r),c=o.slice(d,a),l=Math.max(0,r-c.length),f=i-l;if(f<0||f>=c.length)return null;let u=c[f];return u?.blockKey?{key:u.blockKey,sub:u.hoverSubKey??null}:null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.contentWidth(),r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>this.transcriptVisibleWidth())return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),d=a.length-this.scrollOffset,c=Math.max(0,d-i),l=a.slice(c,d),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=ut(p.prefix??""),y=h.bodyDisplayShift??0,w=e-1-m;if(w<y)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let S=w,x=_c(p.bodyStyle)||p.ansi===!0?m0(Cy(p.body),S):h0(p.body,S);if(h.sourceColEnd!==void 0){let R=this.sourceBodyForId(h.sourceLineId);if(R!==null){let A=Sy(p.body,y,x),M=ky(R,h.sourceColOffset,A);return{sourceLineId:h.sourceLineId,offset:M}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+x-y}}scrollBy(e){if(e===0)return;this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}scrollToPrevTurn(){if(this.pageWhenNoTurns(1))return;let e=this.turnStops(),n=this.settledScrollOffset(),s=e.find(r=>r>n);this.stepToTurnStop(s??this.maxScrollOffset())}scrollToNextTurn(){if(this.pageWhenNoTurns(-1))return;let e=this.turnStops(),n=this.settledScrollOffset(),s=0;for(let r of e){if(r>=n)break;s=r}this.stepToTurnStop(s)}pageWhenNoTurns(e){return this.turnScrollOffsets().length>0?!1:(this.scrollBy(e*this.scrollPageSize()),!0)}settledScrollOffset(){return this.slideTimer!==null?this.slideTarget:this.scrollOffset}stepToTurnStop(e){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.slideScrollTo(e),this.notifyTurnPosition(e)}turnStops(){let e=this.maxScrollOffset(),n=[0,...this.turnScrollOffsets(),e].filter(s=>s>=0&&s<=e).sort((s,r)=>s-r);return n.filter((s,r)=>r===0||s!==n[r-1])}notifyTurnPosition(e){let n=this.turnScrollOffsets();if(n.length===0)return;let s=n.findIndex(i=>i>=e),r=s===-1?1:n.length-s;this.notify(`turn ${r}/${n.length}`,1500)}turnScrollOffsets(){return this.turnAnchors().map(e=>e.offset)}turnAnchors(){let e=this.contentWidth(),n=this.scrollbackVisibleRows();if(n<=0)return[];let s=[],r=0,i=null;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines[o];if(!(!a||this.isHiddenLine(a))){if(r+=this.wrapOne(a,e).length,a.bodyStyle==="user"){i={offset:Math.max(0,r-n),lineIndex:o};continue}i!==null&&(s.push(i),i=null)}}return i!==null&&s.push(i),s}slideScrollTo(e){this.cancelSlide();let n=Math.min(this.maxScrollOffset(),Math.max(0,e)),s=Math.abs(n-this.scrollOffset);if(s!==0){if(s<=VB||!this.slideEnabled){this.setScrollOffset(n);return}this.slideTarget=n,this.slideTimer=setInterval(()=>{let r=this.slideTarget-this.scrollOffset,i=Math.sign(r)*Math.max(1,Math.round(Math.abs(r)*GB)),o=Math.abs(r)<=Math.abs(i)?this.slideTarget:this.scrollOffset+i;this.scrollOffset=o,this.syncedPartialRepaint(()=>this.drawScrollback()),o===this.slideTarget&&this.cancelSlide()},KB)}}cancelSlide(e=!1){this.slideTimer!==null&&(clearInterval(this.slideTimer),this.slideTimer=null,e&&this.scrollOffset!==this.slideTarget&&(this.scrollOffset=Math.min(this.maxScrollOffset(),Math.max(0,this.slideTarget)),this.syncedPartialRepaint(()=>this.drawScrollback())))}setScrollOffset(e){this.cancelSlide(),this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=Math.min(this.maxScrollOffset(),Math.max(0,e));n!==this.scrollOffset&&(this.scrollOffset=n,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=N0(i.body,n);for(let a=o.length-1;a>=0;a--)s.push({lineIdx:r,col:o[a].start})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=s.bodyDisplayShift??0,i=n.col-s.sourceColOffset+r;return i<r||i>=e.body.length?null:i}scrollToMatch(e){let n=this.contentWidth(),s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let h=p.body.length;if(e.col<f+h){o=l.length-1-u;break}f+=h}}let a=r+o,d=Math.max(0,a-Math.floor(s/2)),c=this.maxScrollOffset();this.scrollOffset=Math.min(c,d)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-bt-Mt-Pt-OB-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.contentWidth(),Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,n,s,r){return this.started?this.painter.paintRow(e,n,s,r):!1}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),this.barHits.clear(),Ge(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawSidebar(1,this.scrollbackVisibleRows()),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Pt-Mt-bt;this.drawBar("composerTop",r),this.drawPrompt(),this.drawBar("composerBottom",n-bt),this.drawBar("sessionbar",this.term.height),this.placeCursor(),(this.permissionPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}barContext(){return{scope:"session",session:this.sessionbar,banner:this.banner,scrollOffset:this.scrollOffset,transient:this.bannerRightContent(),hovered:this.terminalFocused?this.hoveredBarHit:null}}btwContext(){let e=this.btwOverlayStatus==="busy"?"busy":this.btwOverlayStatus==="done"?"ready":"disconnected";return{scope:"btw",statusLabel:"By the way",session:{...this.sessionbar,sessionId:this.btwOverlaySessionId??"",...this.btwOverlayUsage!==void 0?{usage:this.btwOverlayUsage}:{usage:void 0}},banner:{status:e,currentMode:void 0,hint:"",queued:0},scrollOffset:0,transient:null,hovered:this.terminalFocused?this.hoveredBarHit:null}}drawBar(e,n){let s=NC[e],r=e==="sessionbar"?Math.max(1,this.term.width-1):this.term.width,i=e==="sessionbar"?this.barConfig.sessionbar:e==="composerBottom"?this.barConfig.composer.bottom:this.barConfig.composer.top,o=e==="btw"?this.btwContext():this.barContext(),a=e==="composerBottom"?OC(o):null,d=a!==null?[a]:zg(e,i.right,o),c=$C(r,zg(e,i.left,o),d,s),l=this.terminalFocused?this.hoveredBarHit:null,f=`${e}|${r}|${l??""}|${c.signature}`;this.paintRow(n,f,()=>{for(let u of c.chunks){let p=u.id!==void 0&&u.id===l?"hint-hover":u.token;$(this.term,p,u.text)}}),this.barHits.set(n,c.hits)}barHitAt(e,n){let s=this.barHits.get(n);return s===void 0?null:s.find(r=>e>=r.start&&e<=r.end)??null}bannerHitAt(e,n){let s=this.barHitAt(e,n);if(s===null)return null;let r=s.id.slice(s.id.indexOf(":")+1);return r==="mode"||r==="pick"||r==="guide"||r==="detach"?r:null}stepFormCursor(e){let n=this.formPrompt;if(n===null||n.rows.length===0)return;let s=Math.max(0,Math.min(n.rows.length-1,n.selectedIndex+e));s!==n.selectedIndex&&this.onFormClick?.({kind:"row",row:s,select:!0})}isFormCell(e){let n=this.formRegion;return this.formPrompt!==null&&n!==null&&e>=n.top&&e<=n.bottom}formHitAt(e,n){if(!this.isFormCell(n))return null;for(let r of this.formHintHits)if(r.row===n&&e>=r.start&&e<=r.end)return{kind:"hint",action:r.action};let s=this.formRowHits.get(n);if(s===void 0)return null;if(s.field!==void 0&&e>=s.field.startCol){let{slice:r,sliceStart:i,startCol:o}=s.field,a=i,d=o;for(let c of r){let l=d+ut(c);if(e<l)break;d=l,a+=c.length}return{kind:"row",row:s.row,caretOffset:a}}return{kind:"row",row:s.row}}handleFormPress(e){return this.isFormCell(e.y)?(this.formPressHit=this.formHitAt(e.x,e.y),!0):(this.formPressHit=null,!1)}handleFormRelease(e){let n=this.formPressHit;if(this.formPressHit=null,n===null||e===null||!this.isFormCell(e.y))return n!==null;let s=this.formHitAt(e.x,e.y);return s===null||s.kind!==n.kind||s.kind==="row"&&n.kind==="row"&&s.row!==n.row||s.kind==="hint"&&n.kind==="hint"&&s.action!==n.action||this.onFormClick?.(s),!0}handleBarPress(e){let n=this.barHitAt(e.x,e.y);if(n===null)return this.barPressHit=null,!1;let s=Date.now(),r=this.lastBarClick;return r!==null&&r.id===n.id&&s-r.t<=Pc&&n.doubleAction!=="none"?(this.lastBarClick=null,this.barPressHit=null,this.dispatchBarAction(n.doubleAction,n.value),!0):(this.lastBarClick={id:n.id,t:s},this.barPressHit=n,!0)}handleBarRelease(e){let n=this.barPressHit;if(this.barPressHit=null,n===null||e===null)return!1;let s=this.barHitAt(e.x,e.y);return s===null||s.id!==n.id?!1:(s.action==="none"||this.dispatchBarAction(s.action,s.value),!0)}dispatchBarAction(e,n){if(e!=="none"){if(e==="copy"){Bg(n,{target:this.selectionClipboard}).then(s=>{this.notify(s.ok?`copied ${n}`:`clipboard copy failed: ${s.reason}`)},s=>{this.notify(`clipboard copy failed: ${s.message}`)});return}if(e==="open-session"){this.onHydraLinkClick?.(n);return}if(e==="open"){this.tryOpenPathString(n)||this.notify(this.hasOpenFileCommand()?`can't open ${n}`:"no tui.openFileCommand configured");return}this.onBarAction?.(e,n)}}drawScrollback(){let e=this.contentWidth(),n=this.sidebarReserved()>0&&!this.sidebarOverlay(),s=this.sidebarBodyWidth()>0,r=1,i=this.scrollbackVisibleRows();if(i<=0)return;let{rows:o,exhausted:a}=this.wrapTail(e,i+this.scrollOffset);if(a){let y=Math.max(0,o.length-i);this.scrollOffset>y&&(this.scrollOffset=y)}let d=o.length-this.scrollOffset,c=Math.max(0,d-i),l=o.slice(c,d),f=Math.max(0,i-l.length),u=this.currentMatchInfo(),p=u?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let h=-1,m=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let y=0;y<l.length;y++){let w=l[y]?.blockKey;w===void 0||!(w===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w))||(h===-1&&(h=y),m=y)}for(let y=0;y<i;y++){let w=r+y,S=y-f,v=S>=0?l[S]:void 0,x=this.activeMatchCol(v,u),R=v?this.selectionRangeForChunk(v):null,A=v!==void 0&&v.blockKey!==void 0&&(v.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(v.blockKey)),M=v!==void 0&&v.blockKey===void 0&&h!==-1&&S>=h&&S<=m,N=A||M,E=this.terminalFocused&&N&&(this.hoveredSubKey===null||(v.hoverSubKey??null)===this.hoveredSubKey),_=vy("sb",e,v,this.scrollbackHighlight,x,R)+(E?"|H":"");this.paintRow(w,_,()=>{v?this.writeFormattedLine(v,e,x,p,R,E,n,v.linkSpans??null):n&&this.term(" ".repeat(e))},n?{erase:!1}:void 0)&&s&&this.painter.invalidate("sidebar",w)}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let y=new Set;for(let S of l)S.blockKey!==void 0&&y.add(S.blockKey);let w=[];for(let S of this.pendingVisibleKeys)y.has(S)&&w.push(S);for(let S of w)this.pendingVisibleKeys.delete(S),this.onBlockVisible(S)}}drawSidebar(e,n){let s=this.sidebarBodyWidth();if(s<=0||n<=0){this.sidebarOverflowRows=0;return}let r=this.sidebarColumnStart(),i={metrics:{cellWidth:ut,truncate:zt},width:s,border:this.sidebarBorder,pages:this.sidebarPages,collapsed:this.sidebarCollapsed,maxRows:n},o={...this.sidebarSnapshot,now:Date.now()},a=this.sidebarRenderer.render(o,i);this.sidebarOverflowRows=Math.max(0,a.length-n),this.sidebarScrollOffset>this.sidebarOverflowRows&&(this.sidebarScrollOffset=this.sidebarOverflowRows);let d=this.sidebarScrollOffset;this.sidebarRowPaths.clear(),this.sidebarRowDoubleActions.clear(),this.sidebarRowActions.clear();let c=r+Mc;for(let l=0;l<n;l++){let f=e+l,u=l+d,p=a[u];p?.openPath!==void 0&&this.sidebarRowPaths.set(f,p.openPath),p?.doubleAction!==void 0&&this.sidebarRowDoubleActions.set(f,p.doubleAction),p?.actions!==void 0&&p.actions.length>0&&this.sidebarRowActions.set(f,p.actions.map(w=>({start:c+w.start-1,end:c+w.end-1,..."page"in w?{gadget:w.page.gadget,index:w.page.index}:{gadget:w.collapse.gadget,collapse:!0}})));let h=l===0&&d>0?"\u25B2":l===n-1&&d<this.sidebarOverflowRows?"\u25BC":p?.gutter??" ",m=p?.openPath===void 0||!p.openPath.startsWith("/")||p.openSpan===void 0?null:[{...p.openSpan,url:Hm(p.openPath)}],y=vy("sbar",s,p,null,null,null)+`|${h}|${m===null?"":m.map(w=>`${w.start}:${w.end}:${w.url}`).join(",")}`;this.paintRow(f,y,()=>{this.term(" ".repeat(Math.max(0,Mc-1))),h===" "?this.term(" "):er(this.term,h,"sidebar-rule",!1),p?this.writeFormattedLine(p,s,null,0,null,!1,!0,m):this.term(" ".repeat(s))},{region:"sidebar",column:r})}}scrollSidebarBy(e){if(this.sidebarOverflowRows<=0)return!1;let n=Math.max(0,Math.min(this.sidebarOverflowRows,this.sidebarScrollOffset-e));return n===this.sidebarScrollOffset||(this.sidebarScrollOffset=n,this.repaintNow()),!0}sidebarPageState(){return this.sidebarPages}sidebarScrollState(){return{offset:this.sidebarScrollOffset,overflow:this.sidebarOverflowRows}}isSidebarCell(e,n){let s=this.sidebarColumnStart();return s===0?!1:e>=s&&e<=(this.term.width||0)&&n>=1&&n<=this.scrollbackVisibleRows()}handleSidebarPress(e){if(e===null||!this.isSidebarCell(e.x,e.y))return!1;for(let i of this.sidebarRowActions.get(e.y)??[])if(!(e.x<i.start||e.x>i.end))return i.collapse===!0?this.toggleSidebarGadgetCollapsed(i.gadget):this.sidebarPages={...this.sidebarPages,[i.gadget]:i.index??0},this.lastSidebarClick=null,this.repaintNow(),!0;let n=Date.now(),s=this.lastSidebarClick;if(s!==null&&n-s.t<=Pc&&e.y===s.y){this.lastSidebarClick=null;let i=this.sidebarRowDoubleActions.get(e.y);if(i!==void 0)return this.dispatchBarAction(i.action,i.value),!0;let o=this.sidebarRowPaths.get(e.y);return o!==void 0&&!this.dispatchLinkUrl(o)&&this.notify(this.hasOpenFileCommand()?`can't open ${o}`:"no tui.openFileCommand configured"),!0}return this.lastSidebarClick={x:e.x,y:e.y,t:n},!0}hasOpenFileCommand(){return this.openFileCommand!==null}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(gy,this.queuedTexts.length)}chipRows(){return Math.min(wy,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.formPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(yy,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-bt-Mt-Pt,i=this.queuedRows(),o=this.chipRows(),d=r-1-i-o-e+1,c=0;for(let l of this.completions.slice(0,e))l.name.length>c&&(c=l.name.length);for(let l=0;l<e;l++){let f=d+l,u=this.completions[l],p=l===e-1&&this.completions.length>yy,h=this.completions.length-yy+1,m=u?p?`comp|${n}|overflow|${h}`:`comp|${n}|${c}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,m,()=>{if(!u)return;if(p){$(this.term,"modal-hint",` + ${h} more match(es)`);return}let y=u.name.padEnd(c),w=u.description??"",S=n-y.length-4,v=S>0?zt(w,S):"";this.term.noFormat(" "),$(this.term,"completion-name",y),v.length>0&&(this.term.noFormat(" "),$(this.term,"completion-desc",v))})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-bt-Mt-Pt-1-e+1,a=this.isIterm2();for(let d=0;d<e;d++){let c=o+d,l=d===e-1&&this.attachments.length>wy,f=this.attachments.length-wy,u=this.attachments[d],p=u?`${u.name??"image"} \xB7 ${es(u.sizeBytes)}`:"",h=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(c,h,()=>{if(l){$(this.term,"modal-hint",` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term.noFormat(" "),$(this.term,"attachment",`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(oN(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-bt-Mt-Pt,i=this.chipRows(),a=r-1-i-e+1,d=this.dispatcher.state().queueIndex;for(let c=0;c<e;c++){let l=a+c,f=this.queuedTexts[c],u=c===e-1&&this.queuedTexts.length>gy,p=this.queuedTexts.length-gy,h=f===void 0?"":u?`+ ${p+1} more queued`:zt(gN(f),n-4),m=!u&&c===d,y=f===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":u?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(f===void 0)return;let w=`\u23F3 ${h}`,S=w+" ".repeat(Math.max(0,n-1-w.length));m?$(this.term,"queue-cursor","\u25B8"):$(this.term,"queue-blank"," "),$(this.term,"queue-row",S)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.formPrompt){this.drawFormPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=tr(s.buffer,n),i=Cr(r,s,hy),o=this.term.height-i.rendered-Pt-Mt-bt+1,a=!1;for(let d=0;d<i.rendered;d++){let c=r[i.windowStart+d],l=o+d,f="wrap",u="";c&&(c.bufferIdx===0&&c.startCol===0?f="first":c.startCol===0&&(f="newline"),u=(s.buffer[c.bufferIdx]??"").slice(c.startCol,c.endCol));let p=c?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{c&&(f==="first"?a?$(this.term,"composer-inactive","> "):$(this.term,"composer-gutter","> "):f==="newline"?$(this.term,"composer-continuation","\xB7 "):this.term(" "),a?$(this.term,"composer-inactive",u):$(this.term,"content",u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-by-Pt-Mt-bt+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{$(this.term,"prompt-text",` ? ${zt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{$(this.term,"modal-hint",` ${zt(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-Pt-Mt-bt+1,i=r,o=(a,d)=>{i>=r+s||(this.paintRow(i,a,d),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{$(this.term,"prompt-text",` ${zt(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{$(this.term,"content"," Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let d=e.options[a];if(!d)continue;let c=a===e.selectedIndex,f=` ${c?"\u276F":" "} ${a+1}. ${zt(d.label,n-8)}`;o(`cpct|o|${n}|${a}|${c?"1":"0"}|${d.label}`,()=>{c?$(this.term,"modal-option-selected",f):$(this.term,"modal-option",f)})}o(`cpct|hint|${n}`,()=>{$(this.term,"modal-hint"," \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Pt-Mt-bt+1,i=r,o=(d,c)=>{i>=r+s||(this.paintRow(i,d,c),i+=1)};o(`help|t|${n}|${e.title}`,()=>{$(this.term,"prompt-text",` \u2753 ${zt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(d=>d===null?0:d[0].length),4));for(let d of e.entries){if(i>=r+s-1)break;if(d===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[c,l]=d,f=c.padEnd(a);o(`help|e|${n}|${c}|${l}`,()=>{this.term(" "),$(this.term,"modal-key",f),$(this.term,"content",` ${zt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{$(this.term,"modal-hint",` ${zt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(WB,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Pt-Mt-bt+1,i=r;this.permissionRowHits.clear(),this.permissionHintHits=[],this.permissionRegion={top:r,bottom:r+s-1};let o=(l,f)=>{i>=r+s||(this.paintRow(i,l,f),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{$(this.term,"prompt-text",` \u{1F512} ${zt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{$(this.term,"modal-hint",` ${zt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{$(this.term,"content"," Do you want to proceed?")});for(let l=0;l<e.options.length&&!(i>=r+s-1);l++){let f=e.options[l];if(!f)continue;let u=l===e.selectedIndex,h=` ${u?"\u276F":" "} ${l+1}. ${zt(f.label,n-8)}`;this.permissionRowHits.set(i,l),o(`perm|o|${n}|${l}|${u?"1":"0"}|${f.label}`,()=>{u?$(this.term,"modal-option-selected",h):$(this.term,"modal-option",h)})}let d=O0(UB,n),c=i;for(let l of d.spans)(l.action==="commit"||l.action==="cancel")&&this.permissionHintHits.push({row:c,start:l.start,end:l.end,action:l.action});o(`perm|hint|${n}|${d.text}`,()=>{$(this.term,"modal-hint",` ${d.text}`)})}isPermissionCell(e){let n=this.permissionRegion;return this.permissionPrompt!==null&&n!==null&&e>=n.top&&e<=n.bottom}permissionHitAt(e,n){if(!this.isPermissionCell(n))return null;for(let r of this.permissionHintHits)if(r.row===n&&e>=r.start&&e<=r.end)return{kind:"hint",action:r.action};let s=this.permissionRowHits.get(n);return s===void 0?null:{kind:"option",index:s}}handlePermissionPress(e){return this.isPermissionCell(e.y)?(this.permissionPressHit=this.permissionHitAt(e.x,e.y),!0):(this.permissionPressHit=null,!1)}handlePermissionRelease(e){let n=this.permissionPressHit;if(this.permissionPressHit=null,n===null||e===null||!this.isPermissionCell(e.y))return n!==null;let s=this.permissionHitAt(e.x,e.y);return s===null||s.kind!==n.kind||s.kind==="option"&&n.kind==="option"&&s.index!==n.index||s.kind==="hint"&&n.kind==="hint"&&s.action!==n.action?!0:Date.now()-this.permissionArmedAt<HB?(this.notify("permission prompt just appeared, click again to confirm"),!0):(this.onPermissionClick?.(s),!0)}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}drawBanner(){let e=this.term.height,n=this.promptRows(),s=e-n-Pt-Mt-bt;this.drawBar("composerTop",s),this.drawBar("composerBottom",e-bt)}drawBars(){this.drawBanner(),this.drawBar("sessionbar",this.term.height)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Pt-Mt-bt+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Pt-Mt-bt;this.term.moveTo(2,Math.min(u,p));return}if(this.formPrompt){let l=this.formPrompt,f=this.formWindowSize(),u=this.formWindowTop,p=this.formTop()+1+(l.selectedIndex-u),h=this.term.height-Pt-Mt-bt,m=Math.min(p,h),w=F0(l,this.term.width,u,f).find(S=>S.selected);if(w?.kind!=="text"){this.term.hideCursor(!0);return}this.term.hideCursor(!1),this.term.moveTo(Math.min(w.caretCol,this.term.width),m);return}if(this.confirmPrompt){let l=this.term.height-by-Pt-Mt-bt+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-Pt-Mt-bt+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Pt-Mt-bt;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Pt-Mt-bt+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=tr(s.buffer,n),i=Cr(r,s,hy),a=this.term.height-i.rendered-Pt-Mt-bt+1+Math.max(0,i.cursorVisualRow-i.windowStart),d=i.cursorVisualCol+3,c=this.term.height-Pt-Mt-bt;this.term.moveTo(Math.min(d,this.term.width),Math.min(a,c))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.formPrompt)return this.formRows();if(this.confirmPrompt)return by;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=tr(s.buffer,n);return Math.min(hy,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(NB,4+this.permissionPrompt.options.length):0}formRows(){return this.formPrompt?Math.min(Math.max(jB,this.formPrompt.maxRows??DB),2+this.formPrompt.rows.length):0}formWindowSize(){return Math.max(1,this.formRows()-2)}formTop(){return this.term.height-this.formRows()-Pt-Mt-bt+1}drawFormPrompt(){let e=this.formPrompt;if(!e)return;let n=this.term.width,s=this.formRows(),r=this.formTop(),i=this.formWindowSize(),o=`${e.title}|${e.rows.length}|${i}`;o!==this.formWindowKey?(this.formWindowKey=o,this.formWindowTop=uN(e.rows.length,e.selectedIndex,i)):this.formWindowTop=fN(this.formWindowTop,e.rows.length,e.selectedIndex,i);let a=this.formWindowTop;this.clearFormHits(),this.formRegion={top:r,bottom:r+s-1};let d=r,c=(m,y)=>{d>=r+s||(this.paintRow(d,m,y),d+=1)},l=e.rows.length>i?` (${e.selectedIndex+1}/${e.rows.length})`:"";c(`form|t|${n}|${e.title}|${l}`,()=>{$(this.term,"prompt-text",` \u2699 ${zt(`${e.title}${l}`,n-5)}`)});let f=F0(e,n,a,i);for(let m of f){if(d>=r+s-1)break;this.formRowHits.set(d,{row:m.index,...m.kind==="text"?{field:{startCol:1+ut(m.prefix),slice:m.field,sliceStart:m.fieldStart}}:{}}),c(m.sig,()=>{if(m.kind==="text"){$(this.term,m.selected?"modal-option-selected":"modal-option",m.prefix),$(this.term,"content",m.field);return}$(this.term,m.selected?"modal-option-selected":"modal-option",m.body)})}let u=e.hints??pN,p=d,h=O0(u,n);for(let m of h.spans)this.formHintHits.push({row:p,...m});c(`form|hint|${n}|${h.text}`,()=>{$(this.term,"modal-hint",` ${h.text}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],d=this.wrapOne(a,e);if(s.push(d),r+=d.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Pt-Mt-bt,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,d=e-1,c=a;this.drawBar("btw",c);let l=this.wrapBtwTail(n,d);for(let f=0;f<d;f++){let u=c+1+f,p=l.length-d+f,h=p>=0?l[p]:void 0,m=vy(`btw|c${f}`,n,h);this.paintRow(u,m,()=>{h?this.writeFormattedLine(h,n):this.term.noFormat(" ".repeat(n))})}}isHiddenLine(e){return e.collapsed===!0||this.hideThoughts&&e.bodyStyle==="thought"}wrapTail(e,n){if(e<=4){let d=[];for(let l of this.lines)this.isHiddenLine(l)||d.push(l);let c=Math.min(n,d.length);return{rows:d.slice(d.length-c),exhausted:n>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let s=[],r=0,i=0,o=!1;for(let d=this.lines.length-1;d>=0;d--){let c=this.lines[d];if(this.isHiddenLine(c)){d===0&&(o=!0);continue}let l=this.wrapOne(c,e);if(s.push(l),r+=l.length,i=d,r>=n)break}let a=[];for(let d=s.length-1;d>=0;d--)a.push(...s[d]);return{rows:a,exhausted:i===0||o}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let y=this.wrapCache.get(s);if(y)return y}let r=e.prefix??"",i=ut(r),o=Math.max(1,n-i-1),a=Math.max(0,Math.min(e.hangingIndent??0,o-1)),d=Math.max(1,o-a),c=_c(e.bodyStyle),l=e.ansi?tN(e.body,a>0?d:o):aN(e.body,a>0?d:o,{escapeAware:c}),f=e.ansi?0:e.maxWrapRows??0,u=f>0&&l.length>f;u&&(l.length=f);let p=[],h=0,m=0;for(let y=0;y<l.length;y++){let w=l[y]??"",S=y===0||a===0?w:" ".repeat(a)+w;u&&y===l.length-1&&(S=zt(`${S}\u2026`,o,{escapeAware:c}));let v={prefix:y===0?e.prefix:" ".repeat(i),body:S};if(e.prefixStyle!==void 0&&(v.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(v.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(v.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(v.hoverSubKey=e.hoverSubKey),e.fillRow&&(v.fillRow=!0),e.ansi&&(v.ansi=!0),y===0&&e.iterm2Image&&(v.iterm2Image=e.iterm2Image),s!==void 0&&w.length>0)if(e.ansi){let x=h,R=0;for(let E=0;E<w.length;){let _=ts(w,E);if(_){E+=_.text.length,_.width>0&&(R+=1);continue}R+=1,E+=1}let A=R;for(;A>0&&h<e.body.length;){let E=ts(e.body,h);if(E){h+=E.text.length,E.width>0&&(A-=1);continue}h+=1,A-=1}let M=h;if(y===l.length-1){for(;M<e.body.length;){let E=ts(e.body,M);if(!E)break;M+=E.text.length}h=M}let N={sourceLineId:s,sourceColOffset:x,sourceColEnd:M};if(y>0&&a>0&&(N.bodyDisplayShift=a),this.wrapOrigin.set(v,N),e.links!==void 0){let E=this.linkSpansForWindow(e.body,e.links,x,M,y===0||a===0?0:a);E!==null&&(v.linkSpans=E)}}else{let x=e.body.indexOf(w,m),R=x===-1?m:x,A={sourceLineId:s,sourceColOffset:R};if(y>0&&a>0&&(A.bodyDisplayShift=a),this.wrapOrigin.set(v,A),e.links!==void 0){let M=this.linkSpansForWindow(e.body,e.links,R,R+w.length,y===0||a===0?0:a);M!==null&&(v.linkSpans=M)}m=R+w.length}p.push(v)}return s!==void 0&&this.wrapCache.set(s,p),p}writeFormattedLine(e,n,s=null,r=0,i=null,o=!1,a=!1,d=null){e.prefix&&er(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let c=Math.max(0,n-ut(e.prefix??"")),l=_c(e.bodyStyle),f=e.ansi?e.body:zt(e.body,c,{escapeAware:l}),u=d===null||d.length===0?null:d.map(m=>({start:Math.max(0,Math.min(f.length,m.start)),end:Math.max(0,Math.min(f.length,m.end)),url:m.url})).filter(m=>m.end>m.start).sort((m,y)=>m.start-y.start),p=(m,y,w)=>{if(u===null){w(m,y);return}let S=y+m.length,v=y;for(let x of u){if(x.end<=v||x.start>=S)continue;let R=Math.max(x.start,v),A=Math.min(x.end,S);R>v&&w(m.slice(v-y,R-y),v),process.stdout.write(`\x1B]8;;${x.url}\x1B\\`),w(m.slice(R-y,A-y),R),process.stdout.write("\x1B]8;;\x1B\\"),v=A}v<S&&w(m.slice(v-y),v)},h=(m,y)=>{m.length!==0&&p(m,y,(w,S)=>{if(this.scrollbackHighlight!==null&&!e.ansi){let v=s!==null&&s>=S?s-S:null;eN(this.term,w,e.bodyStyle,this.scrollbackHighlight,v,r,o)}else er(this.term,w,e.bodyStyle,o)})};if(i!==null){let m=Math.max(0,Math.min(f.length,i.start)),y=Math.max(m,Math.min(f.length,i.end)),w=_c(e.bodyStyle)||e.ansi===!0;if(h(f.slice(0,m),0),y>m){let v=f.slice(m,y);w&&(v=Wf(v)),w?er(this.term,v,"selection-highlight",o):p(v,m,x=>{er(this.term,x,"selection-highlight",o)})}let S=f.slice(y);if(w&&y>m){let v=iN(f.slice(0,y));v.length>0&&(S=v+S)}h(S,y)}else h(f,0);if(e.fillRow||o||a){let m=e.ansi?B0(f):ut(l?Wf(f):f),y=c-m;if(y>0){let w=i!==null&&i.toEndOfLine?"selection-highlight":e.fillRow||o?e.bodyStyle:void 0;er(this.term," ".repeat(y),w,o)}}(e.ansi||e.body.includes("\x1B"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};D0=/[^\x20-\x7e]/,Iy=new Intl.Segmenter(void 0,{granularity:"grapheme"}),H0=!1;pN=[{label:"\u2191/\u2193 choose"},{label:"\u23CE this session",action:"commit"},{label:"s save default",action:"save"},{label:"Esc close",action:"close"}];yN=tt});function wN(t,e,n=Kf){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function z0(t,e){bs();let n=tt(e.sessionId),s=e.importedFromMachine??"another machine",r=yt(e.cwd),i=Kf.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let d=7+Kf.length*2+2,c=Fn(t,{contentHeight:d,title:"Imported session"}),l=c.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(c.contentX,c.contentY+u),$(t,"modal-label",` ${p.label}`),$(t,"content",ht(p.value,l-p.label.length-2)),u++;return u++,K0(t,c,u,{intro:"What do you want to do?",choices:Kf,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),c};return Qs({term:t,render:o,onKey:(a,d,c,l)=>{let f=bN(a,c);if(!f)return;let u=wN(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function K0(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),$(t,"content",` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let c=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?$(t,"list-selected",gc(c,r)):$(t,"content",c),i++,t.moveTo(e.contentX,e.contentY+i),$(t,"list-description",` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),$(t,"modal-hint",` ${s.footer}`)}function bN(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function G0(t,e,n){let s=tt(e.sessionId),r=e.title??yt(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let d=Fn(t,{contentHeight:11,title:"Open session",overlay:!0}),c=d.contentW,l=0;t.moveTo(d.contentX,d.contentY+l),$(t,"modal-label"," session: "),$(t,"content",ht(s,c-10)),l++,t.moveTo(d.contentX,d.contentY+l),$(t,"content"," "+ht(r,c-2)),l++,l++,K0(t,d,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(d=>{let c=!1,l=()=>{c=!0},f=p=>{l(),n.pop(),d(p)},u=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){f("launch");return}if(y==="v"){f("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,h,m)=>{c||u(p,h,m)},onResize:()=>{c||a()}})})}var Kf,Ry=K(()=>{"use strict";Ae();Yn();no();Qt();Kf=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Oc(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function V0(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",d=i.startsWith(" ")?"":" ";return a+d+i}let o=Oc(e);return o.length<=r.length?null:o+i}var Gf=K(()=>{"use strict"});import*as J0 from"os";async function co(t,e,n={}){let s=n.defaultCwd??(e?await qI(e.cwd):void 0)??J0.homedir();bs();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:tt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:yt(e.cwd)}]:[],a=new oi(s),d=null,c=!1,l=null,f=null,u=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),S=h.indexOf(y),v=()=>{let E=o.length+6;l=Fn(t,{contentHeight:E,title:r,overlay:n.overlay===!0});let _=l.contentW,H=0;for(let q of o)t.moveTo(l.contentX,l.contentY+H),$(t,"modal-label",` ${q.label}`),$(t,"content",ht(q.value,_-q.label.length-2)),H++;H++,t.moveTo(l.contentX,l.contentY+H),$(t,"content",` ${i}`),H+=2,A(H),H+=2;let W=l.contentY+H;d!==null?(t.moveTo(l.contentX,W),$(t,"input-error",` ${ht(d,_-2)}`),f=null,u=null,p=null):(t.moveTo(l.contentX,W),$(t,"modal-hint",h),f=W,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+S,end:l.contentX+S+y.length-1})},x=()=>o.length+3,R=0,A=E=>{if(!l)return;let _=E??x();t.moveTo(l.contentX,l.contentY+_).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+_),$(t,"box-border","\u2502"),t.moveTo(l.contentX,l.contentY+_),t.noFormat(" ");let W=Math.max(1,l.contentW-1-2),q=a.text,Q=a.cursor;Q<R&&(R=Q),Q-R>=W&&(R=Q-W+1),R<0&&(R=0);let re=q.slice(R,R+W);R>0&&re.length>0&&(re="\u2026"+re.slice(1));let Se=Q-R;if(c){$(t,"content",re);return}Se>=re.length?($(t,"content",re),$(t,"input-cursor"," ")):($(t,"content",re.slice(0,Se)),$(t,"input-cursor",re[Se]??" "),$(t,"content",re.slice(Se+1)))},M=()=>{if(A(),!l)return;let E=x()+2;t.moveTo(l.contentX,l.contentY+E).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+E),$(t,"box-border","\u2502");let _=l.contentY+E;t.moveTo(l.contentX,_),d!==null?($(t,"input-error",` ${ht(d,l.contentW-2)}`),f=null,u=null,p=null):($(t,"modal-hint",h),f=_,u={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+S,end:l.contentX+S+y.length-1})},N=E=>{if(c)return;let _=a.text;c=!0,d=null,M(),Sc(_).then(H=>{if(c=!1,H.ok){E({kind:"ok",path:H.path});return}d=H.reason,M()})};return Qs({term:t,render:v,overlay:n.overlay===!0,onKey:(E,_,H,W)=>{if(!c){if(E==="ENTER"||E==="KP_ENTER"){N(W);return}if(E==="ESCAPE"){W({kind:"back"});return}if(E==="CTRL_C"||E==="CTRL_D"){W({kind:"cancel"});return}if(E==="TAB"){c=!0,zI(a.text).then(q=>{if(c=!1,q.matches.length===0)return;let Q;if(q.matches.length===1)Q=q.prefix+q.matches[0];else{let re=Oc(q.matches);if(re.length<=q.basePrefix.length)return;Q=q.prefix+re}Q!==a.text&&(a.setText(Q,{recordUndo:!0}),d=null,M())});return}if(a.handleKey(E,H?.isCharacter===!0)){d=null,M();return}}},onMouse:(E,_,H)=>{if(c||E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let W=_?.x,q=_?.y;if(!(typeof W!="number"||typeof q!="number")){if(l!==null&&(W<l.x||W>=l.x+l.w||q<l.y||q>=l.y+l.h)){H({kind:"back"});return}if(f!==null&&q===f){if(u!==null&&W>=u.start&&W<=u.end){N(H);return}if(p!==null&&W>=p.start&&W<=p.end){H({kind:"back"});return}}}}})}var Ty=K(()=>{"use strict";Ae();Yn();wg();Gf();no();gf();Qt()});import*as Q0 from"fs";import*as X0 from"os";import*as Vf from"path";function Jf(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function vN(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function SN(t){return t.replace(/\\ /g," ")}function Y0(t){return t.replace(/ /g,"\\ ")}function kN(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function xN(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=X0.homedir()+n.slice(1)),Vf.isAbsolute(n)?n:Vf.resolve(e,n)}function IN(t){let e;try{e=Q0.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Yf(t,e,n=IN){let s=SN(t),{dirPrefix:r,base:i}=kN(s);if(r.length===0&&!vN(t)&&i.length===0)return null;let o=xN(r,e),a=n(o);if(a===null)return null;let d=i.startsWith("."),c=a.filter(u=>u.name.startsWith(i)&&(d||!u.name.startsWith(".")));if(c.length===0)return null;let l=c.map(u=>u.isDir?u.name+"/":u.name);if(c.length===1){let u=c[0],p=u.isDir?u.name+"/":u.name;return{replacement:Y0(r+p),candidates:l}}let f=Oc(c.map(u=>u.name));return{replacement:Y0(r+f),candidates:l}}var Ey=K(()=>{"use strict";Gf()});function CN(t){process.stdout.write(`\x1B]9;4;${t}\x1B\\`)}function AN(t,e,n){let s=`${n.agentId}@${n.version}`;if(n.source==="npm")return n.phase==="install_start"||n.phase==="download_start"?`${t} installing ${s} via npm\u2026`:n.phase==="installed"?`${t} ${s} installed`:`${t} installing ${s} via npm\u2026`;if(n.phase==="download_start"||n.phase==="download_progress"){let r=n.receivedBytes??0,i=n.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),d=Math.min(100,Math.floor(r/i*100));return`${t} downloading ${s} ${o}/${a} MB (${d}%)`}return`${t} downloading ${s} ${o} MB`}return n.phase==="download_done"?`${t} downloaded ${s}, verifying\u2026`:n.phase==="extract"?`${t} extracting ${s}\u2026`:n.phase==="installed"?`${t} ${s} installed`:e||t}function Qf(t,e){let n=!1,s="",r=!1,i=t,o=a=>{n||a===3&&r||a===0&&!r||(r=a===3,CN(a))};return{write(a){n||(i=a,s=a,e.write(a))},applyProgress(a){if(n)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let c=AN(i,s,a);s=c,e.write(c)},finalize(){n||(n=!0,o(0),e.finalize())}}}function Z0(t){let e=!1;return{write(n){e||(process.stdout.write("\r"),t.eraseLineAfter(),$(t,"status-active",n))},finalize(){e||(e=!0,process.stdout.write(`
228
228
  `))}}}var Py=K(()=>{"use strict";Qt()});function My(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}function Lc(){return pn()?.id??"terminal"}function EN(){if(!If())return tA;let t=[];for(let e of tA)t.push(e),e?.[0]==="*"&&t.push(["^t","new tab: selected session, or send the composer to a new one"]);return t}async function _y(t,e){let n=()=>{process.stdout.write(ms),process.stdout.write(Zi),process.stdout.write(vr),process.stdout.write(eo),process.stdout.write(to),process.stdout.write(Ua),process.stdout.write(ja),process.stdout.write(Wa),process.stdout.write(Xi),process.stdout.write("\x1B>")};n();let s=e.prefs??My();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(O=>O.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=Zf(e.sessions,r),o=T=>{let O=T;return s.filters.cwdOnly&&(O=O.filter(z=>z.cwd===r)),s.filters.includeNonInteractive||(O=O.filter(z=>z.interactive===!0)),O=_N(O,s.filters.hostFilter),O},a=o(i),d={columns:e.config.tui.sessionColumns??Ba,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},c=a.map(T=>Vi(T,Date.now())),l=ti(c,d),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let T=a.findIndex(O=>O.sessionId===e.currentSessionId);T>=0&&(u=T+1)}let h=!1,m="",y=120,w=!1,S=0,v="normal",x=null,R=!1,A="input",M=new Sr({history:[],collapsePastes:!1}),N=[],E=!1,_=0,H=0,W=null,q=!1,Q=new Map,re=ti([],d),Se="",De=T=>Q.get(T)??null,Ft=()=>{let T=Date.now(),O=new Map(a.map(ae=>[ae.sessionId,ae])),z=[];Q=new Map;for(let ae of N){let oe=O.get(ae.sessionId);if(!oe)continue;let Ee=Vi(oe,T);Q.set(ae.sessionId,Ee),z.push(Ee)}re=ti(z,d);let ee=Math.max(20,Gt(t)-Xf);Se=Js(Gi,re,ee,d).padEnd(ee)},St=null,ze=null,nt=null,ie=null,X=()=>{if(ie!==null){let T=ie;return{plain:T,render:()=>{$(t,"status-active",` ${T}`)}}}if(h){let T=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${T} \xB7 ^c clears`,render:()=>{$(t,"prompt-text",` /${m}`),$(t,"prompt-cursor"," "),$(t,"modal-hint",` ${T} \xB7 ^c clears`)}}}return nt!==null?{plain:nt,render:()=>{$(t,"modal-hint",` ${nt}`)}}:null},Ie=!1,Te=new Sr({history:[]});if(e.initialPrompt&&Te.setBuffer(e.initialPrompt),e.initialAttachments)for(let T of e.initialAttachments)Te.addAttachment(T);let sn=e.config.tui.promptHistoryMaxEntries;Ud(B.globalTuiHistoryFile()).then(T=>{let O=T.length>sn?T.slice(T.length-sn):T;Te.setHistory(O)}).catch(()=>{});let ke=new Ya(t),Be=Ys(t),ft=Gt(t),dt=0,nr="",Ar=0,Bn=[],jt=1,Rr=0,Tr=0,sr=0,fo="",Qa=[],rs=1,Wc=0,Er=[],Vt=1,li=0,He=0,Xa=0,qc=()=>{Be=Ys(t),ft=Gt(t);let T=Math.max(10,ft-Xf-1);Ar=Math.max(10,ft-eA);let O=Math.max(10,ft-8),z=Te.state().attachments.length,ee=z>0?` \xB7 \u{1F4CE}\xD7${z}`:"",ae=Math.max(10,O-ee.length);nr=PN(r,ae)+ee;let oe=Te.state();Bn=tr(oe.buffer,Ar);let Ee=Cr(Bn,oe,Fc);jt=Ee.rendered,Rr=Ee.windowStart,Tr=Ee.cursorVisualRow,sr=Ee.cursorVisualCol;let st=6+jt,ot=Math.max(3,Be-st);dt=Math.min(a.length,ot),fo=Js(Gi,l,T,d).padEnd(T),Qa=c.map(Ht=>Js(Ht,l,T,d).padEnd(T))},po=()=>{c=a.map(T=>Vi(T,Date.now())),l=ti(c,d),f=1+a.length,qc()},Dt=()=>{let T=o(i);h&&m.length>0?a=T.filter(O=>$N(O,m)):a=T,po(),h?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+dt>a.length&&(p=Math.max(0,a.length-dt)),kn()},is=T=>{if(T!==void 0){let O=a.findIndex(z=>z.sessionId===T);if(O>=0){u=O+1,kn();return}}u=a.length>0?1:0,p=0,kn()},kn=()=>{if(u===0)return;let T=u-1;T<p?p=T:T>=p+dt?p=T-dt+1:p+dt>a.length&&(p=Math.max(0,a.length-dt))},xs=()=>Math.max(2,ft-3),Lt=!1,ue=!0,ct=!1,$t=[],os=e.composerAgentId,Nn=e.composerModel,ui=()=>{let T=os;if(!T)return"";let O=Nn;return O?`${T}\u2022${O}`:T},Is=null,rr=null,xn=null,ho=()=>{let T=xs(),O=`\u2500 ${nr} `,z=ui(),ee="";if(z.length>0){let kt=`\u2500 ${z} `;kt.length+O.length+1<=T&&(ee=kt)}let ae=Math.max(1,T-O.length-ee.length),oe="\u2500".repeat(ae),Ee=(u===0||Lt)&&ue;if(Is=O.length>0?{start:2,end:1+O.length}:null,ee.length>0){let kt=1+O.length+ae+1;rr={start:kt,end:kt+ee.length-1}}else rr=null;let st=Ee?"box-border-focused":"box-border",ot=Ee?"box-border-focused-hover":"box-border-hover",Ht=(kt,$r)=>{$(t,$r?ot:st,kt)};$(t,st,"\u256D"),Ht(O,xn==="cwd"),$(t,st,oe),ee&&Ht(ee,xn==="agent"),$(t,st,"\u256E")},Pr=()=>{let T=xs(),O="\u2500".repeat(T);(u===0||Lt)&&ue?$(t,"box-border-focused",`\u2570${O}\u256F`):$(t,"box-border",`\u2570${O}\u256F`)},mo=()=>{let T=X();if(T===null)return;let O=Math.max(0,Gt(t)-2);if(T.plain.length>O){let z=T.plain.slice(0,Math.max(0,O-1))+"\u2026";$(t,"modal-hint",` ${z}`);return}T.render()},as=T=>{let O=Bn[T];return O?(Te.state().buffer[O.bufferIdx]??"").slice(O.startCol,O.endCol):""},go=T=>{let O=xs(),z=as(T),ee=Math.max(0,O-1-z.length),ae=" ".repeat(ee);(u===0||Lt)&&ue?($(t,"box-border-focused","\u2502"),$(t,"content",` ${z}${ae}`),$(t,"box-border-focused","\u2502")):($(t,"box-border","\u2502"),$(t,"content",` ${z}${ae}`),$(t,"box-border","\u2502"))},Cs=T=>{let O=Qa[T]??"",z=a[T],ee=z&&z.priority&&z.priority>0?"* ":" ";u===T+1&&!Lt&&ue?$(t,"list-selected",`${ee}${O}`):$(t,"content",`${ee}${O}`)},Za=()=>{let T=p,O=Math.max(0,a.length-p-dt),z=[];if(s.filters.cwdOnly&&z.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let ee=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;z.push({kind:"host",text:ee})}return s.filters.includeNonInteractive&&z.push({kind:"plain",text:"+non-interactive"}),T>0&&z.push({kind:"plain",text:`\u2191 ${T} above`}),O>0&&z.push({kind:"plain",text:`\u2193 ${O} below`}),z},hn=()=>{let T=Za();return T.length===0?"":` ${T.map(O=>O.text).join(" \xB7 ")}`},rn=T=>tt(T),ir=()=>{let T=x?`${x.sessionId}|${x.status}`:"";return["ind",v,T,St?`${St.text}${St.cursor}`:"",ze??"",h?`1|${m}|${a.length}`:"0",hn(),rd?"h1":"h0",Ao?"ho1":"ho0"].join("")},he=()=>{Ge(()=>{ke.paintRow(Dn(),ir(),()=>{let T=()=>{fs=null,Rn=null};if(v==="confirm-kill"&&x)T(),$(t,"prompt-text",` kill ${rn(x.sessionId)}? [y/N]`);else if(v==="confirm-delete"&&x)T(),x.status==="warm"?$(t,"prompt-destructive",` kill + delete ${rn(x.sessionId)}? [y/N]`):$(t,"prompt-destructive",` delete ${rn(x.sessionId)}? [y/N]`);else if(v==="busy"&&x)T(),$(t,"modal-status",` working on ${rn(x.sessionId)}\u2026`);else if(v==="rename"&&x&&St){T();let O=St.text,z=St.cursor;$(t,"prompt-text"," title: "),$(t,"prompt-text",O.slice(0,z)),z<O.length?($(t,"prompt-cursor",O[z]??" "),$(t,"prompt-text",O.slice(z+1))):$(t,"prompt-cursor"," "),$(t,"modal-hint"," Enter saves \xB7 Esc cancels")}else if(ze!==null)T(),$(t,"modal-status",` ${ze}`);else{let O=Za(),z=hn(),ee="Esc \xB7 Go Back",ae=ee.length,oe=5,Ee=z.length,st=Math.max(1,ft-Ee-ae-oe);if(Rn=null,O.length>0){$(t,"modal-hint"," ");let ot=3;for(let Ht=0;Ht<O.length;Ht++){let kt=O[Ht];Ht>0&&($(t,"modal-hint"," \xB7 "),ot+=3),kt.kind==="host"?(Rn={start:ot,end:ot+kt.text.length-1},Ao?$(t,"content",kt.text):$(t,"modal-hint",kt.text)):$(t,"modal-hint",kt.text),ot+=kt.text.length}}$(t,"modal-hint"," ".repeat(st)),rd?$(t,"content",ee):$(t,"modal-hint",ee),fs={start:ft-oe-ae+1,end:ft-oe}}})})},fi=T=>rs+1+T,ds=()=>rs+jt+1,Bt=()=>rs+jt+3,yo=T=>Bt()+1+(T-p),Dn=()=>Bt()+1+dt,I=()=>{let T=Tr-Rr;if(T<0||T>=jt)return;let O=3+sr;t.moveTo(O,fi(T))},wo=()=>ue?u===0?"f":Lt?"h":"u":"x",zc=()=>`ct|${wo()}|${xs()}|${nr}|${ui()}|${xn??""}`,ed=()=>`cb|${wo()}|${xs()}`,pi=()=>ie!==null?`cs|i|${ie}`:h?`cs|s|${m}|${a.length}`:nt!==null?`cs|h|${nt}`:"blank",As=T=>`cbb|${wo()}|${xs()}|${as(T)}`,cs=()=>`h|${fo}`,bo=T=>{let O=a[T],z=O&&O.priority&&O.priority>0?"* ":" ",ee=Qa[T]??"";return`sr|${u===T+1&&!Lt&&ue?"1":"0"}|${z}${ee}`},lt=()=>{Ge(()=>{t.hideCursor(),qc(),kn(),rs=1,ke.ensureSize(ft,Be),ke.paintRow(rs,zc(),()=>{ho()});for(let T=0;T<jt;T++){let O=Rr+T;ke.paintRow(fi(T),As(O),()=>{go(O)})}ke.paintRow(ds(),ed(),()=>{Pr()}),ke.paintRow(ds()+1,pi(),()=>mo()),ke.paintRow(Bt(),cs(),()=>{$(t,"list-header",` ${fo}`)});for(let T=0;T<dt;T++){let O=p+T,z=Bt()+1+T;O<a.length?ke.paintRow(z,bo(O),()=>{Cs(O)}):ke.paintRow(z,"blank",()=>{})}he();for(let T=Dn()+1;T<=Be;T++)ke.paintRow(T,"blank",()=>{});u===0&&(I(),t.hideCursor(!1))})},or=()=>{ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),lt()},td=()=>{Ge(()=>{t.hideCursor(),ke.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),$(t,"modal-title"," Picker hotkeys"),t.noFormat(`
229
229
 
230
230
  `);for(let T of EN()){if(T===null){t(`
@@ -265,7 +265,7 @@ connection lost: ${g.message}
265
265
  `),To(g?1:0)}),process.on("SIGINT",nd),np.length>0&&(I.appendLines(np.map(g=>({prefix:" ",body:`theme: ${g}`,bodyStyle:"notice-error"}))),np=[]),Bc.length>0&&(I.notify(Bc.join(" \xB7 "),1e4),Bc=[]),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&dd(s.initialPrompt??"",s.initialAttachments??[]),await Mr}async function GD(t,e,n,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),s.resolved!==void 0&&(a.resolved=s.resolved),a}if(s.forceNew)return await jA(t,n,s,i)!=="ok"?null:UA(s,o,e);if(s.resume){let a=p0();if(a){let f=(await Qn(n,{all:!0,includeNonInteractive:!0})).find(u=>u.sessionId===a);if(f)return{sessionId:f.sessionId,agentId:f.agentId??"",cwd:f.cwd??o,resolved:f}}let d=await Qn(n,{cwd:o,all:!0}),c=Du(d,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o,resolved:c}:($(t,"cli-warn",`No sessions found for ${o}.
266
266
  `),null)}for(;;){let a=await Qn(n,{includeNonInteractive:!0}),d=i.lastChosenAgent??s.agentId??e.defaultAgent,c=d?i.lastChosenModel??e.defaultModels?.[d]:void 0,l=[];try{l=await Ki(n)}catch{}let f=await _y(t,{cwd:o,sessions:a,config:e,target:n,prefs:r,...d?{composerAgentId:d}:{},...c?{composerModel:c}:{},...l.length>0?{availableAgents:l}:{},onComposerAgentChange:(w,S)=>{Nc(i,w,S)},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(f.kind==="abort"||f.kind==="exit")return null;if(f.kind==="new"){f.agentId!==void 0&&(s.agentId=f.agentId,Nc(i,f.agentId,f.model)),f.model!==void 0&&(s.model=f.model),f.prompt!==void 0&&(s.initialPrompt=f.prompt),f.attachments&&f.attachments.length>0&&(s.initialAttachments=f.attachments),f.cwd!==void 0&&(o=f.cwd,s.cwd=f.cwd);let w=f.installStatus,S=await jA(t,n,s,i,()=>{w&&(w.finalize(),w=void 0)});if(S==="cancel")return w&&w.finalize(),null;if(S==="back"){w&&w.finalize();continue}let v=UA(s,o,e);return w&&(v.installStatus=w),v}if(f.kind==="fork"){let w=await ZA(t,n,f,a);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}s.readonly=f.readonly===!0;let u=f.installStatus,p=()=>{u&&(u.finalize(),u=void 0)},h=a.find(w=>w.sessionId===f.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let w=await QA(t,n,h,f,s);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}if(n.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await Sc(h.cwd)).ok){p();let S=await co(t,h,{defaultCwd:wt(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(S.kind==="cancel")return null;if(S.kind==="back")continue;let v=f.agentId??h.agentId??"";return{sessionId:f.sessionId,agentId:v,cwd:S.path,resumeHint:{agentId:v,cwd:S.path,upstreamSessionId:""}}}let y={sessionId:f.sessionId,agentId:f.agentId??"",cwd:o};return u&&(y.installStatus=u),h!==void 0&&(y.resolved=h),y}}async function QA(t,e,n,s,r){for(;;){let i=await z0(t,n);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let c=s.agentId??n.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:n.cwd}}}let o=await XA(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await co(t,n);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let d=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:a.path,resumeHint:{agentId:d,cwd:a.path,upstreamSessionId:""}}}}}async function XA(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await Ki(e)}catch{return{kind:"ok",agentId:n,changed:!1}}if(s.length===0||s.some(i=>i.id===n))return{kind:"ok",agentId:n,changed:!1};let r=await Cc(t,s,n,{title:"Agent not available here",intro:`Source agent "${n}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function ZA(t,e,n,s){let r=s.find(f=>f.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await XA(t,e,n.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let d=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let f=await co(t,r);if(f.kind==="cancel")return{kind:"cancel"};if(f.kind==="back")return{kind:"back"};o=f.path}let c=d??n.sourceAgentId??"",l;try{l=await Nu(e,n.sourceSessionId,{...i?{cwd:o}:{},...d?{agentId:d}:{}})}catch(f){return $(t,"notice-error",`
267
267
  fork failed: ${f.message}
268
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:c,cwd:o,upstreamSessionId:""}}:{}}}}function UA(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}function Nc(t,e,n){if(t.lastChosenAgent=e,n===void 0){delete t.lastChosenModel;return}t.lastChosenModel=n}async function jA(t,e,n,s,r){if(n.agentId||await Rw())return"ok";let i;try{i=await Ki(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await Le(),a=s.lastChosenAgent??o.defaultAgent,d=await Cc(t,i,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";if(n.agentId=d.agentId,Nc(s,d.agentId,o.defaultModels?.[d.agentId]),d.persist)try{await Ii(d.agentId)}catch{}return"ok"}function VD(t,e){pe({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}var np,Bc,sp,uo,ss,WA,qA,zA,KA,jy,ND,DD,UD,HA,qD,eR=K(()=>{"use strict";Li();Zt();fg();at();wg();Ti();qi();Xd();wd();JI();Yn();Ae();Ei();_n();uf();gg();Xl();ac();XI();nC();rC();iC();sA();Py();nf();Ty();Ry();$g();ug();iA();Ay();vm();Hg();Cf();Tf();aA();iy();Va();ty();Gf();Ey();uA();Yr();wr();Qt();Go();IA();Fy();Mi();ly();dy();AA();EA();Gg();MA();LA();np=[],Bc=[],sp=[],uo="terminal",qA=null,KA=null;jy="dismiss";ND=12e4,DD=12e3;UD=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next warm session"],["Alt+P","previous warm session"],["^T","show / hide thoughts"],["^S","show / hide sidebar (with an empty draft; amends otherwise)"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter \xB7 sidebar)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Alt+PgUp / Alt+PgDn","step by turn (prompt to top row; long turns page)"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["Double-click","open file under cursor / sidebar file row (tui.openFileCommand, else $VISUAL/$EDITOR)"],["Double-click bar","cwd opens \xB7 title renames \xB7 agent/model/mode pick \xB7 else copy"],["Click in a modal","row picks / cycles it \xB7 hint words act \xB7 wheel walks the list"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];HA=!1;qD=2});var tR={};Ep(tR,{runTui:()=>YA});var nR=K(()=>{"use strict";eR()});import{readFileSync as JD}from"fs";import{fileURLToPath as YD}from"url";import{dirname as QD,resolve as XD}from"path";var mw=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-from-note","no-pager","no-wait","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),OR=new Set(["agent","args","columns","command","cwd","drip-speed","env","from","from-label","from-session","host","last","model","name","out","prompt","session","since","stream-bytes","stream-threshold","tail","timeout","to"]);function gw(t){for(let e of Object.keys(t))if(!mw.has(e)&&!OR.has(e))return e}function Pp(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let d=r.slice(2,i);n[d]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(mw.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function FR(t,e){let n=t[e];if(typeof n=="string")return n}function Fo(t,e){return t[e]===!0||t[e]==="true"}var LR="HYDRA_ACP_";function BR(t){return LR+t.toUpperCase().replace(/-/g,"_")}function Ct(t,e){let n=FR(t,e);return n!==void 0?n:process.env[BR(e)]}at();Ti();async function qw(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=Bp(n);return{target:await jw(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Le();return{target:await ln(s),sessionId:n,fromUrl:!1}}function Vp(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_TARGET_SESSION;if(typeof n=="string"&&n.length>0)return n}Ei();Ae();at();hr();import*as Gw from"fs/promises";async function Vw(t){if(await Gw.mkdir(B.home(),{recursive:!0}),await fl(),!await No()){let n=Bo();await Do(n),process.stdout.write(`Initialized ${B.authToken()}
268
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:c,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:c,cwd:o,upstreamSessionId:""}}:{}}}}function UA(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}function Nc(t,e,n){if(t.lastChosenAgent=e,n===void 0){delete t.lastChosenModel;return}t.lastChosenModel=n}async function jA(t,e,n,s,r){if(n.agentId||await Rw())return"ok";let i;try{i=await Ki(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await Le(),a=s.lastChosenAgent??o.defaultAgent,d=await Cc(t,i,a);if(d.kind==="cancel")return"cancel";if(d.kind==="back")return"back";if(n.agentId=d.agentId,Nc(s,d.agentId,o.defaultModels?.[d.agentId]),d.persist)try{await Ii(d.agentId)}catch{}return"ok"}function VD(t,e){pe({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}var np,Bc,sp,uo,ss,WA,qA,zA,KA,jy,ND,DD,UD,HA,qD,eR=K(()=>{"use strict";Li();Zt();fg();at();wg();Ti();qi();Xd();wd();JI();Yn();Ae();Ei();_n();uf();gg();Xl();ac();XI();nC();rC();iC();sA();Py();nf();Ty();Ry();$g();ug();iA();Ay();vm();Hg();Cf();Tf();aA();iy();Va();ty();Gf();Ey();uA();Yr();wr();Qt();Go();IA();Fy();Mi();ly();dy();AA();EA();Gg();MA();LA();np=[],Bc=[],sp=[],uo="terminal",qA=null,KA=null;jy="dismiss";ND=12e4,DD=12e3;UD=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next warm session"],["Alt+P","previous warm session"],["^T","show / hide thoughts"],["^S","show / hide sidebar (with an empty draft; amends otherwise)"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter \xB7 sidebar)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Alt+PgUp / Alt+PgDn","jump to previous / next prompt"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["Double-click","open file under cursor / sidebar file row (tui.openFileCommand, else $VISUAL/$EDITOR)"],["Double-click bar","cwd opens \xB7 title renames \xB7 agent/model/mode pick \xB7 else copy"],["Click in a modal","row picks / cycles it \xB7 hint words act \xB7 wheel walks the list"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];HA=!1;qD=2});var tR={};Ep(tR,{runTui:()=>YA});var nR=K(()=>{"use strict";eR()});import{readFileSync as JD}from"fs";import{fileURLToPath as YD}from"url";import{dirname as QD,resolve as XD}from"path";var mw=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-from-note","no-pager","no-wait","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),OR=new Set(["agent","args","columns","command","cwd","drip-speed","env","from","from-label","from-session","host","last","model","name","out","prompt","session","since","stream-bytes","stream-threshold","tail","timeout","to"]);function gw(t){for(let e of Object.keys(t))if(!mw.has(e)&&!OR.has(e))return e}function Pp(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let d=r.slice(2,i);n[d]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(mw.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function FR(t,e){let n=t[e];if(typeof n=="string")return n}function Fo(t,e){return t[e]===!0||t[e]==="true"}var LR="HYDRA_ACP_";function BR(t){return LR+t.toUpperCase().replace(/-/g,"_")}function Ct(t,e){let n=FR(t,e);return n!==void 0?n:process.env[BR(e)]}at();Ti();async function qw(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=Bp(n);return{target:await jw(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await Le();return{target:await ln(s),sessionId:n,fromUrl:!1}}function Vp(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_TARGET_SESSION;if(typeof n=="string"&&n.length>0)return n}Ei();Ae();at();hr();import*as Gw from"fs/promises";async function Vw(t){if(await Gw.mkdir(B.home(),{recursive:!0}),await fl(),!await No()){let n=Bo();await Do(n),process.stdout.write(`Initialized ${B.authToken()}
269
269
  Service token: ${n}
270
270
  `);return}if(Fo(t,"rotate-token")){let n=Bo();await Do(n),process.stdout.write(`Rotated token in ${B.authToken()}
271
271
  New token: ${n}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydra-acp/cli",
3
- "version": "0.1.148",
3
+ "version": "0.1.149",
4
4
  "description": "Multi-client ACP session daemon: spawn agents, attach over WSS, multiplex sessions across editors.",
5
5
  "license": "MIT",
6
6
  "type": "module",