@code-yeongyu/senpi 2026.10.11 → 2026.10.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/bundle/chunks/anthropic-messages-GYG6YZY5.js +10 -0
- package/dist/bundle/chunks/{app-server-command-NHDOL4HQ.js → app-server-command-OL6PPUOA.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-EJF2XJ7Q.js → azure-openai-responses-GU6FOSJR.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZABLYCHT.js → chunk-46JEQXD7.js} +1 -1
- package/dist/bundle/chunks/{chunk-VE3D74HN.js → chunk-55VKYA5V.js} +1 -1
- package/dist/bundle/chunks/{chunk-7UNN3YHW.js → chunk-5AVFHHDF.js} +230 -221
- package/dist/bundle/chunks/{chunk-2JE2DOIF.js → chunk-5DPTM5E2.js} +1 -1
- package/dist/bundle/chunks/chunk-5UPUSGP5.js +2 -0
- package/dist/bundle/chunks/chunk-5VMRMY6N.js +16 -0
- package/dist/bundle/chunks/{chunk-7X3VRAM3.js → chunk-7P3QPVTF.js} +1 -1
- package/dist/bundle/chunks/{chunk-T6IYKWIH.js → chunk-BUGZZVQW.js} +1 -1
- package/dist/bundle/chunks/chunk-DL7EFVT2.js +12 -0
- package/dist/bundle/chunks/chunk-E5YUVGLQ.js +11 -0
- package/dist/bundle/chunks/{chunk-RLFQICEY.js → chunk-EQJY2B5F.js} +1 -1
- package/dist/bundle/chunks/{chunk-VYKBN4MR.js → chunk-GC2RU5TS.js} +1 -1
- package/dist/bundle/chunks/chunk-GPKEJOTQ.js +202 -0
- package/dist/bundle/chunks/{chunk-KCVSSFOV.js → chunk-GQ5PWY6P.js} +4 -3
- package/dist/bundle/chunks/{chunk-4GPJOGXZ.js → chunk-I4AEC6MH.js} +1 -1
- package/dist/bundle/chunks/chunk-JXSFGRBE.js +8 -0
- package/dist/bundle/chunks/{chunk-YGCMN2CX.js → chunk-NAY5LB53.js} +1 -1
- package/dist/bundle/chunks/{chunk-EBOD66AS.js → chunk-PBN2CATL.js} +2 -2
- package/dist/bundle/chunks/chunk-PFNBY43W.js +2 -0
- package/dist/bundle/chunks/{chunk-CY2B4QRR.js → chunk-PUWEQK2W.js} +1 -1
- package/dist/bundle/chunks/{chunk-5DBPUQSX.js → chunk-SF6AUNQZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-G2XAU4BX.js → chunk-TMTT5CLA.js} +1 -1
- package/dist/bundle/chunks/{chunk-2JKDZXIY.js → chunk-VWFKLW73.js} +2 -2
- package/dist/bundle/chunks/chunk-WZMSBRTW.js +2 -0
- package/dist/bundle/chunks/{chunk-55HLKZSB.js → chunk-XVJRRLGN.js} +1 -1
- package/dist/bundle/chunks/chunk-Z2PWWBBD.js +31 -0
- package/dist/bundle/chunks/cli-main-RSIYAR4J.js +3 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-SWVU2AXJ.js → cloudflare-workers-ai-system-one-LVWRKOUD.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-XG4YX6FQ.js → google-generative-ai-JMGYPTXL.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-BBOZ6OUB.js → google-vertex-CI4FPIU7.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-EZ3KEW6V.js → help-fast-path-M7KMBM6K.js} +1 -1
- package/dist/bundle/chunks/host-command-6UR3DSFR.js +2 -0
- package/dist/bundle/chunks/host-lifecycle-2BKCCK5X.js +3 -0
- package/dist/bundle/chunks/host-lifecycle.js +10 -7
- package/dist/bundle/chunks/host-session-command-A2MZHEBP.js +19 -0
- package/dist/bundle/chunks/interactive-mode-EJBMTJOH.js +2 -0
- package/dist/bundle/chunks/{list-tips-WE2YGQM6.js → list-tips-BEQAOA4N.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-RB3ZBCGE.js → mistral-conversations-5OD7662T.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-V4CUQLV7.js → multi-session-host-YYMLHCUA.js} +4 -4
- package/dist/bundle/chunks/{openai-codex-responses-DBTPUXRW.js → openai-codex-responses-FN3UPAFI.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-QAJQC4BY.js → openai-completions-KMUQ3T4M.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-UBJWCEHG.js → openai-responses-V4Q5GVLO.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-WTRDT4ZH.js → package-manager-cli-6A5ZP26E.js} +1 -1
- package/dist/bundle/chunks/rotation-stream-PT6LLBMJ.js +2 -0
- package/dist/bundle/chunks/rpc-mode-XNYJPYUM.js +2 -0
- package/dist/bundle/chunks/runtime-session-ZBHFMT65.js +2 -0
- package/dist/bundle/chunks/{schedule-command-PJVRKAKD.js → schedule-command-FYQG2MFX.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-7TX4XHN4.js +3 -0
- package/dist/bundle/chunks/session-picker-4RNB27SM.js +2 -0
- package/dist/bundle/chunks/session-worker.js +418 -412
- package/dist/bundle/chunks/{typesafe-system-one-B5TW3FHM.js → typesafe-system-one-WUHW7HR4.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session.d.ts +11 -2
- package/dist/core/agent-session.js +152 -43
- package/dist/core/compaction/compaction.js +2 -0
- package/dist/core/extensions/builtin/anthropic-web-search/index.js +22 -14
- package/dist/core/extensions/builtin/cache-keepalive/index.js +8 -4
- package/dist/core/extensions/builtin/cache-keepalive/session-prewarm.d.ts +2 -1
- package/dist/core/extensions/builtin/cache-keepalive/session-prewarm.js +55 -7
- package/dist/core/extensions/builtin/cache-keepalive/startup-activity-gate.d.ts +8 -0
- package/dist/core/extensions/builtin/cache-keepalive/startup-activity-gate.js +25 -0
- package/dist/core/extensions/builtin/compaction/index.js +13 -5
- package/dist/core/extensions/builtin/compaction/speculative.d.ts +1 -0
- package/dist/core/extensions/builtin/compaction/speculative.js +8 -4
- package/dist/core/extensions/builtin/moved-path-guard/tool-classes.js +1 -0
- package/dist/core/extensions/builtin/openai-web-search/index.d.ts +4 -1
- package/dist/core/extensions/builtin/openai-web-search/index.js +54 -17
- package/dist/core/extensions/builtin/server-search-fallback.d.ts +12 -0
- package/dist/core/extensions/builtin/server-search-fallback.js +50 -0
- package/dist/core/extensions/builtin/terminal/runtime-session.d.ts +10 -1
- package/dist/core/extensions/builtin/terminal/runtime-session.js +48 -4
- package/dist/core/extensions/builtin/websearch/index.d.ts +1 -1
- package/dist/core/extensions/builtin/websearch/index.js +119 -18
- package/dist/core/extensions/builtin/websearch/server-search.d.ts +11 -0
- package/dist/core/extensions/builtin/websearch/server-search.js +230 -0
- package/dist/core/extensions/builtin/websearch/websearch/native.d.ts +2 -0
- package/dist/core/extensions/builtin/websearch/websearch/search-model.js +15 -0
- package/dist/core/extensions/runner.d.ts +8 -1
- package/dist/core/extensions/runner.js +56 -7
- package/dist/core/extensions/types.d.ts +12 -2
- package/dist/core/extensions/user-activity.d.ts +10 -0
- package/dist/core/extensions/user-activity.js +20 -0
- package/dist/core/model-config-schema.d.ts +34 -0
- package/dist/core/model-config-schema.js +2 -0
- package/dist/core/model-config.js +1 -0
- package/dist/core/reserved-keywords.d.ts +28 -0
- package/dist/core/reserved-keywords.js +81 -0
- package/dist/core/retry-fallback/candidates.d.ts +1 -1
- package/dist/core/retry-fallback/candidates.js +1 -12
- package/dist/core/retry-fallback/controller.d.ts +3 -1
- package/dist/core/retry-fallback/controller.js +11 -5
- package/dist/core/retry-fallback/cooldown.d.ts +2 -1
- package/dist/core/retry-fallback/cooldown.js +21 -12
- package/dist/core/retry-fallback/unusable.d.ts +2 -0
- package/dist/core/retry-fallback/unusable.js +14 -2
- package/dist/core/retry-fallback/usage-limit.d.ts +10 -1
- package/dist/core/retry-fallback/usage-limit.js +39 -2
- package/dist/core/session-title-generator.js +2 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/modes/index.d.ts +1 -1
- package/dist/modes/interactive/components/assistant-render-descriptors.js +7 -1
- package/dist/modes/interactive/composer-user-activity.d.ts +6 -0
- package/dist/modes/interactive/composer-user-activity.js +30 -0
- package/dist/modes/interactive/grok/chrome.js +2 -1
- package/dist/modes/interactive/interactive-mode.js +15 -6
- package/dist/modes/interactive/session-control-registry.js +8 -1
- package/dist/modes/interactive/theme/reserved-keyword-rainbow.d.ts +11 -0
- package/dist/modes/interactive/theme/reserved-keyword-rainbow.js +50 -0
- package/dist/modes/interactive/theme/theme.d.ts +3 -1
- package/dist/modes/interactive/theme/theme.js +9 -0
- package/dist/modes/print-mode.js +7 -2
- package/dist/modes/rpc/connection-handler.js +43 -11
- package/dist/modes/rpc/custom-capability.d.ts +2 -0
- package/dist/modes/rpc/custom-capability.js +2 -0
- package/dist/modes/rpc/host-admission-proxy.d.ts +9 -0
- package/dist/modes/rpc/host-admission-proxy.js +211 -0
- package/dist/modes/rpc/host-admission.d.ts +21 -0
- package/dist/modes/rpc/host-admission.js +59 -0
- package/dist/modes/rpc/host-capabilities.js +2 -1
- package/dist/modes/rpc/host-client-occupancy.d.ts +2 -1
- package/dist/modes/rpc/host-client-occupancy.js +7 -0
- package/dist/modes/rpc/host-decision.d.ts +2 -2
- package/dist/modes/rpc/host-decision.js +4 -0
- package/dist/modes/rpc/host-ensure-types.d.ts +2 -0
- package/dist/modes/rpc/host-ensure.js +31 -3
- package/dist/modes/rpc/host-lifecycle-drain.d.ts +2 -1
- package/dist/modes/rpc/host-lifecycle-drain.js +3 -1
- package/dist/modes/rpc/host-lifecycle-proxy.d.ts +3 -2
- package/dist/modes/rpc/host-lifecycle-proxy.js +10 -19
- package/dist/modes/rpc/host-lifecycle-shutdown.d.ts +2 -0
- package/dist/modes/rpc/host-lifecycle-shutdown.js +3 -1
- package/dist/modes/rpc/host-lifecycle-ticker.d.ts +11 -0
- package/dist/modes/rpc/host-lifecycle-ticker.js +27 -0
- package/dist/modes/rpc/host-lifecycle.js +15 -23
- package/dist/modes/rpc/host-outcome.js +1 -0
- package/dist/modes/rpc/host-protocol-info.d.ts +2 -0
- package/dist/modes/rpc/host-protocol-info.js +1 -0
- package/dist/modes/rpc/host-session-runner.js +22 -1
- package/dist/modes/rpc/host-status-all.js +1 -0
- package/dist/modes/rpc/host-status.d.ts +1 -0
- package/dist/modes/rpc/host-status.js +5 -1
- package/dist/modes/rpc/rpc-client.d.ts +7 -1
- package/dist/modes/rpc/rpc-client.js +12 -0
- package/dist/modes/rpc/rpc-types.d.ts +49 -1
- package/dist/modes/rpc/rpc-types.js +5 -0
- package/dist/modes/rpc/session-command-activity.js +2 -0
- package/dist/modes/rpc/session-held.js +3 -0
- package/docs/extensions.md +13 -1
- package/docs/providers.md +88 -0
- package/docs/rpc.md +150 -5
- package/docs/web-search.md +3 -1
- package/package.json +7 -7
- package/dist/bundle/chunks/anthropic-messages-5QQJVQPZ.js +0 -9
- package/dist/bundle/chunks/chunk-2A3MS2Z7.js +0 -8
- package/dist/bundle/chunks/chunk-6SBY4ZWC.js +0 -2
- package/dist/bundle/chunks/chunk-6WCOSBI7.js +0 -2
- package/dist/bundle/chunks/chunk-E75RO54O.js +0 -14
- package/dist/bundle/chunks/chunk-JMYO34RK.js +0 -2
- package/dist/bundle/chunks/chunk-KRNXUTZJ.js +0 -2
- package/dist/bundle/chunks/chunk-L4HVJWIF.js +0 -11
- package/dist/bundle/chunks/chunk-N5WLLHUE.js +0 -2
- package/dist/bundle/chunks/chunk-NEFNNQSV.js +0 -9
- package/dist/bundle/chunks/chunk-PWIYVLIA.js +0 -9
- package/dist/bundle/chunks/chunk-Q3R44CGT.js +0 -5
- package/dist/bundle/chunks/chunk-QIARZN7G.js +0 -31
- package/dist/bundle/chunks/chunk-QKU6JOA4.js +0 -2
- package/dist/bundle/chunks/chunk-QYWXDE47.js +0 -2
- package/dist/bundle/chunks/chunk-XHELSLN3.js +0 -188
- package/dist/bundle/chunks/chunk-YDJ4HGWO.js +0 -16
- package/dist/bundle/chunks/chunk-ZJHRDQCH.js +0 -2
- package/dist/bundle/chunks/cli-main-TUBNBZNK.js +0 -3
- package/dist/bundle/chunks/host-command-WO7VKJBJ.js +0 -2
- package/dist/bundle/chunks/host-lifecycle-X2J5FTJL.js +0 -3
- package/dist/bundle/chunks/host-session-command-ICBOH5RP.js +0 -19
- package/dist/bundle/chunks/interactive-mode-UGDNCGQ5.js +0 -2
- package/dist/bundle/chunks/rotation-stream-OODURUGZ.js +0 -2
- package/dist/bundle/chunks/rpc-mode-22MCT32O.js +0 -2
- package/dist/bundle/chunks/runtime-session-I4NDNGC5.js +0 -2
- package/dist/bundle/chunks/session-control-endpoint-SFPRQBDO.js +0 -3
- package/dist/bundle/chunks/session-picker-3ZQPV7Z3.js +0 -2
|
@@ -20,7 +20,7 @@ import{__export}from"./chunk-IKOFCODM.js";function parseTmuxKittyTerminalOverrid
|
|
|
20
20
|
`);let line=newLines[i],isImage=isImageLine(line),imageReservedRows=isImage?this.getKittyImageReservedRows(newLines,i,renderEnd):1;if(imageReservedRows>1){let imageStartScreenRow=i-viewportTop;if(imageStartScreenRow<0||imageStartScreenRow+imageReservedRows>height){logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`),fullRender(!0,!preserveMuxScrollback);return}buffer+=`\x1B[2K${TUI.SEGMENT_RESET}`;for(let row=1;row<imageReservedRows;row++)buffer+=`\r
|
|
21
21
|
\x1B[2K${TUI.SEGMENT_RESET}`;buffer+=`\x1B[${imageReservedRows-1}A`,buffer+=line,buffer+=`\x1B[${imageReservedRows-1}B`,i+=imageReservedRows-1;continue}buffer+=`\x1B[2K${TUI.SEGMENT_RESET}`;let lineWidth=visibleWidth(line);if(!isImage&&lineWidth>width){let crashLogPath=path.join(os.homedir(),".senpi","agent","senpi-crash.log"),strictRender=process.env.PI_TUI_STRICT_RENDER==="1";if(strictRender||!this.overWideCrashDumpWritten){let crashData=formatOverWideRenderDiagnostic(newLines,width,i,lineWidth);if(!strictRender)writeRenderDiagnosticBestEffort(crashLogPath,crashData),this.overWideCrashDumpWritten=!0;else{let crashDumpWritten=writeRenderDiagnosticBestEffort(crashLogPath,crashData);this.stop();let errorMsg=[`Rendered line ${i} exceeds terminal width (${lineWidth} > ${width}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",crashDumpWritten?`Debug log written to: ${crashLogPath}`:`Debug log could not be written to: ${crashLogPath}`].join(`
|
|
22
22
|
`);throw new Error(errorMsg)}}let truncatedLine=sliceByColumn(line,0,width,!0)+TUI.SEGMENT_RESET;newLines[i]=truncatedLine,buffer+=truncatedLine;continue}buffer+=line}let finalCursorRow=renderEnd;if(this.previousLines.length>newLines.length){if(renderEnd<newLines.length-1){let moveDown=newLines.length-1-renderEnd;buffer+=`\x1B[${moveDown}B`,finalCursorRow=newLines.length-1}let extraLines=this.previousLines.length-newLines.length;for(let i=newLines.length;i<this.previousLines.length;i++)buffer+=`\r
|
|
23
|
-
\x1B[2K${TUI.SEGMENT_RESET}`;buffer+=`\x1B[${extraLines}A`}if(buffer=this.finishFrame(buffer,cursorPos,newLines.length,finalCursorRow),process.env.PI_TUI_DEBUG==="1"){let debugDir="
|
|
23
|
+
\x1B[2K${TUI.SEGMENT_RESET}`;buffer+=`\x1B[${extraLines}A`}if(buffer=this.finishFrame(buffer,cursorPos,newLines.length,finalCursorRow),process.env.PI_TUI_DEBUG==="1"){let debugDir=path.join(os.tmpdir(),"tui");fs.mkdirSync(debugDir,{recursive:!0});let debugPath=path.join(debugDir,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),debugData=[`firstChanged: ${firstChanged}`,`viewportTop: ${viewportTop}`,`cursorRow: ${this.cursorRow}`,`height: ${height}`,`lineDiff: ${lineDiff}`,`hardwareCursorRow: ${hardwareCursorRow}`,`renderEnd: ${renderEnd}`,`finalCursorRow: ${finalCursorRow}`,`cursorPos: ${JSON.stringify(cursorPos)}`,`newLines.length: ${newLines.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(newLines,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(buffer)].join(`
|
|
24
24
|
`);fs.writeFileSync(debugPath,debugData,{encoding:"utf8",mode:DIAGNOSTIC_LOG_MODE}),chmodDiagnosticLogBestEffort(debugPath)}writeBounded(this.terminal,buffer),this.cursorRow=Math.max(0,newLines.length-1),this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.setPreviousLines(newLines,rawLines),needsKittyImageExpansion&&(this.previousKittyImageIds=this.collectKittyImageIds(newLines)),this.previousWidth=width,this.previousHeight=height}buildHardwareCursorSequence(cursorPos,totalLines){let buffer="";if(!cursorPos||totalLines<=0)this.#lastCursorVisibility!==!1&&(buffer+="\x1B[?25l",this.#lastCursorVisibility=!1);else{let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow;rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,this.hardwareCursorRow=targetRow,this.#lastCursorVisibility!==this.showHardwareCursor&&(buffer+=this.showHardwareCursor?"\x1B[?25h":"\x1B[?25l",this.#lastCursorVisibility=this.showHardwareCursor)}return buffer}finishFrame(buffer,cursorPos,totalLines,hardwareCursorRow){return this.hardwareCursorRow=hardwareCursorRow,buffer+this.buildHardwareCursorSequence(cursorPos,totalLines)+TUI.FRAME_END}positionHardwareCursor(cursorPos,totalLines){let buffer=this.buildHardwareCursorSequence(cursorPos,totalLines);buffer&&this.terminal.write(TUI.FRAME_BEGIN+buffer+TUI.FRAME_END)}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};function isTerminalReport(data){return data.startsWith("\x1B[<")||data.startsWith("\x1B[M")||data.length>2&&(data.startsWith("\x1B]")||data.startsWith("\x1BP")||data.startsWith("\x1B_"))||data.startsWith("\x1B[?")||/^\x1b\[\d+(;\d+)*t$/.test(data)}var TUI=class extends TuiBase{constructor(){super(...arguments),this.mode="regular"}};function isAsciiLetter(char){if(!char)return!1;let code=char.charCodeAt(0);return code>=97&&code<=122}function isAsciiDigit(char){if(!char)return!1;let code=char.charCodeAt(0);return code>=48&&code<=57}function isWordBoundaryPrefix(char){switch(char){case" ":case" ":case`
|
|
25
25
|
`:case"\r":case"-":case"_":case".":case"/":case":":return!0;default:return!1}}function scoreMatch(queryLower,textLower){if(queryLower.length===0)return{matches:!0,score:0};if(queryLower.length>textLower.length)return{matches:!1,score:0};let queryIndex=0,score=0,lastMatchIndex=-1,consecutiveMatches=0;for(;queryIndex<queryLower.length;){let i=textLower.indexOf(queryLower[queryIndex],lastMatchIndex+1);if(i===-1)break;let isWordBoundary=i===0||isWordBoundaryPrefix(textLower[i-1]);lastMatchIndex===i-1?(consecutiveMatches++,score-=consecutiveMatches*5):(consecutiveMatches=0,lastMatchIndex>=0&&(score+=(i-lastMatchIndex-1)*2)),isWordBoundary&&(score-=10),score+=i*.1,lastMatchIndex=i,queryIndex++}return queryIndex<queryLower.length?{matches:!1,score:0}:(queryLower===textLower&&(score-=100),{matches:!0,score})}function addWholeTokenSwap(variants,queryLower){let splitIndex=0;for(;splitIndex<queryLower.length&&isAsciiLetter(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let digitEnd=splitIndex;for(;digitEnd<queryLower.length&&isAsciiDigit(queryLower[digitEnd]);)digitEnd++;digitEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}for(splitIndex=0;splitIndex<queryLower.length&&isAsciiDigit(queryLower[splitIndex]);)splitIndex++;if(splitIndex>0&&splitIndex<queryLower.length){let letterEnd=splitIndex;for(;letterEnd<queryLower.length&&isAsciiLetter(queryLower[letterEnd]);)letterEnd++;letterEnd===queryLower.length&&variants.add(queryLower.slice(splitIndex)+queryLower.slice(0,splitIndex))}}function buildAlphanumericSwapQueries(queryLower){let variants=new Set;addWholeTokenSwap(variants,queryLower);for(let i=0;i<queryLower.length-1;i++){let current=queryLower[i],next=queryLower[i+1];(isAsciiLetter(current)&&isAsciiDigit(next)||isAsciiDigit(current)&&isAsciiLetter(next))&&variants.add(queryLower.slice(0,i)+next+current+queryLower.slice(i+2))}return[...variants]}function fuzzyMatch(query,text){return fuzzyMatchLower(query.toLowerCase(),text.toLowerCase())}function fuzzyMatchLower(queryLower,textLower){let direct=scoreMatch(queryLower,textLower);if(direct.matches)return direct;let bestSwap=null;for(let variant of buildAlphanumericSwapQueries(queryLower)){let match=scoreMatch(variant,textLower);if(!match.matches)continue;let score=match.score+5;(!bestSwap||score<bestSwap.score)&&(bestSwap={matches:!0,score})}return bestSwap??direct}function fuzzyFilter(items,query,getText){if(!query.trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a,b2)=>a.totalScore-b2.totalScore),results.map(r=>r.item)}import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir as homedir3}from"os";import{basename,dirname as dirname2,join as join2}from"path";var SKILL_COMMAND_PREFIX="skill:",DOLLAR_QUERY_PATTERN=/^\$([a-zA-Z0-9:_-]*)$/,DOLLAR_MENTION_PATTERN=/(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g,COMMON_SHELL_VARIABLES=new Set(["CI","EDITOR","HOME","LANG","LC_ALL","NODE_ENV","OLDPWD","PATH","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","VISUAL"]);function isDollarQueryCompletable(query){return query===""?!0:query.startsWith("-")||query.startsWith("_")||/^\d/.test(query)?!1:!COMMON_SHELL_VARIABLES.has(query)}function commandName(command){return"name"in command?command.name:command.value}function skillName(name){return name.startsWith(SKILL_COMMAND_PREFIX)&&name.slice(SKILL_COMMAND_PREFIX.length)||null}function commandDescription(command){let hint="argumentHint"in command&&command.argumentHint?command.argumentHint:void 0,description=command.description??"";return hint?description?`${hint} \u2014 ${description}`:hint:description||void 0}function findDollarSkillMentions(line,knownSkills){if(knownSkills.size===0)return[];let mentions=[];for(let match of line.matchAll(DOLLAR_MENTION_PATTERN)){let token=match[2]??"",name=token.startsWith(SKILL_COMMAND_PREFIX)?token.slice(SKILL_COMMAND_PREFIX.length):token;if(!knownSkills.has(name))continue;let start=match.index+(match[1]??"").length;mentions.push({start,end:start+token.length+1,name})}return mentions}function knownSkillNames(commands){return new Set(commands.flatMap(command=>{let name=skillName(commandName(command));return name?[name]:[]}))}function getDollarInvocationContext(textBeforeCursor,_cursorLine,commands){let tokenStart=textBeforeCursor.search(/\S+$/),token=tokenStart===-1?"":textBeforeCursor.slice(tokenStart),match=DOLLAR_QUERY_PATTERN.exec(token);if(!match)return null;let rawQuery=match[1]??"";if(!isDollarQueryCompletable(rawQuery))return null;let explicitSkillNamespace=rawQuery.startsWith(SKILL_COMMAND_PREFIX),query=explicitSkillNamespace?rawQuery.slice(SKILL_COMMAND_PREFIX.length):rawQuery;if(knownSkillNames(commands).has(query))return null;let isFirstToken=textBeforeCursor.slice(0,tokenStart).trim()==="";return{prefix:`$${rawQuery}`,query,skillsOnly:explicitSkillNamespace||!isFirstToken}}function getDollarInvocationSuggestions(commands,query,skillsOnly){let items=commands.flatMap(command=>{let name=commandName(command),skill=skillName(name);return skill?[{kind:"skill",value:`$${skill}`,label:`$${skill}`,searchText:skill,description:commandDescription(command)}]:skillsOnly?[]:[{kind:"command",value:`/${name}`,label:`/${name}`,searchText:name,description:commandDescription(command)}]});return fuzzyFilter(items,query,item=>item.searchText).map((item,index)=>({...item,index})).sort((left,right)=>left.kind!==right.kind?left.kind==="command"?-1:1:left.index-right.index).map(({index:_index,kind:_kind,searchText:_searchText,...item})=>item)}var SKILL_COMMAND_PREFIX2="skill:";function isSlashNamespaceItem(value){return value.endsWith(":")}function compareSlashCommandSuggestion(prefix,left,right){let leftExact=left.value===prefix,rightExact=right.value===prefix;if(leftExact!==rightExact)return leftExact?-1:1;let leftPrefix=left.value.startsWith(prefix),rightPrefix=right.value.startsWith(prefix);return leftPrefix!==rightPrefix?leftPrefix?-1:1:leftPrefix&&rightPrefix&&left.value.length!==right.value.length?right.value.length-left.value.length:left.index-right.index}function getSlashCommandSuggestions(commands,prefix){let normalizedPrefix=prefix.toLowerCase(),explicitSkillNamespace=normalizedPrefix.startsWith(SKILL_COMMAND_PREFIX2),hasSkillCommands=commands.some(cmd=>("name"in cmd?cmd.name:cmd.value).startsWith(SKILL_COMMAND_PREFIX2)),commandItems=commands.flatMap(cmd=>{let name="name"in cmd?cmd.name:cmd.value,isSkill=name.startsWith(SKILL_COMMAND_PREFIX2),skillName2=isSkill?name.slice(SKILL_COMMAND_PREFIX2.length):"";if(isSkill&&!explicitSkillNamespace&&(normalizedPrefix.length===0||!skillName2.toLowerCase().startsWith(normalizedPrefix)))return[];let hint="argumentHint"in cmd&&cmd.argumentHint?cmd.argumentHint:void 0,requiresArguments=("requiresArguments"in cmd?cmd.requiresArguments:void 0)??hint!==void 0,desc=cmd.description??"",fullDesc=hint?desc?`${hint} \u2014 ${desc}`:hint:desc;return[{name,label:name,description:fullDesc||void 0,searchText:isSkill&&!explicitSkillNamespace?skillName2:name,awaitsArguments:requiresArguments||"awaitsArguments"in cmd&&cmd.awaitsArguments===!0}]});return hasSkillCommands&&!explicitSkillNamespace&&normalizedPrefix.length>0&&SKILL_COMMAND_PREFIX2.startsWith(normalizedPrefix)&&commandItems.push({name:SKILL_COMMAND_PREFIX2,label:SKILL_COMMAND_PREFIX2,description:"Browse available skills",searchText:SKILL_COMMAND_PREFIX2,awaitsArguments:!1}),fuzzyFilter(commandItems,prefix,item=>item.searchText).map((item,index)=>({value:item.name,label:item.label,...item.description&&{description:item.description},...item.awaitsArguments&&{awaitsArguments:!0},index})).sort((left,right)=>compareSlashCommandSuggestion(normalizedPrefix,left,right)).map(({index:_index,...item})=>item)}var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return normalized;let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",segments=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment));if(segments.length===0)return normalized;let pattern=segments.join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&(lastDelimiter=index-1);return lastDelimiter}function stripLeadingWrappers(token){let result=token;for(;result.length>0;){let closer=PATH_WRAPPERS[result[0]];if(!closer||result.includes(closer,1))break;result=result.slice(1)}return result}function findUnclosedQuoteStart(text){let inQuotes=!1,quoteStart=-1;for(let i=0;i<text.length;i+=1)text[i]==='"'&&(inQuotes=!inQuotes,inQuotes&&(quoteStart=i));return inQuotes?quoteStart:null}function isTokenStart(text,index){let start=index;for(;start>0&&PATH_WRAPPERS[text[start-1]];)start-=1;return PATH_DELIMITERS.has(text[start-1]??"")||tokenStartRegex.test(text.slice(0,start))}function extractQuotedPrefix(text){let quoteStart=findUnclosedQuoteStart(text);return quoteStart===null?null:quoteStart>0&&text[quoteStart-1]==="@"?isTokenStart(text,quoteStart-1)?text.slice(quoteStart-1):null:isTokenStart(text,quoteStart)?text.slice(quoteStart):null}function parsePathPrefix(prefix){return prefix.startsWith('@"')?{rawPrefix:prefix.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:prefix.startsWith('"')?{rawPrefix:prefix.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path4,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path4),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path4}"`:`${prefix}${path4}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){let args=["--base-directory",baseDir,"--max-results",String(maxResults),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return maxDepth!==void 0&&args.push("--max-depth",String(maxDepth)),toDisplayPath(query).includes("/")&&args.push("--full-path"),query&&args.push(buildFdPathQuery(query)),await new Promise(resolve=>{if(signal.aborted){resolve([]);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),stdout="",resolved=!1,finish=results=>{resolved||(resolved=!0,signal.removeEventListener("abort",onAbort),resolve(results))},onAbort=()=>{child.exitCode===null&&child.kill("SIGKILL")};signal.addEventListener("abort",onAbort,{once:!0}),child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk}),child.on("error",()=>{finish([])}),child.on("close",code=>{if(signal.aborted||code!==0||!stdout){finish([]);return}let lines=stdout.trim().split(`
|
|
26
26
|
`).filter(Boolean),results=[];for(let line of lines){let displayLine=toDisplayPath(line),hasTrailingSeparator=displayLine.endsWith("/"),normalizedPath=hasTrailingSeparator?displayLine.slice(0,-1):displayLine;normalizedPath===".git"||normalizedPath.startsWith(".git/")||normalizedPath.includes("/.git/")||results.push({path:displayLine,isDirectory:hasTrailingSeparator})}finish(results)})})}var CombinedAutocompleteProvider=class{constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}getMentionRanges(line){return findDollarSkillMentions(line,knownSkillNames(this.commands)).map(({start,end})=>({start,end}))}async getSuggestions(lines,cursorLine,cursorCol,options){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol),atPrefix=this.extractAtPrefix(textBeforeCursor);if(atPrefix){let{rawPrefix,isQuotedPrefix}=parsePathPrefix(atPrefix),suggestions2=await this.getFuzzyFileSuggestions(rawPrefix,{isQuotedPrefix,signal:options.signal});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let dollarContext=getDollarInvocationContext(textBeforeCursor,cursorLine,this.commands);if(dollarContext){let suggestions2=getDollarInvocationSuggestions(this.commands,dollarContext.query,dollarContext.skillsOnly);return suggestions2.length===0?null:{items:suggestions2,prefix:dollarContext.prefix}}let commandText=textBeforeCursor.trimStart();if(!options.force&&commandText.startsWith("/")){let spaceIndex=commandText.indexOf(" ");if(spaceIndex===-1){let prefix=commandText.slice(1),filtered=getSlashCommandSuggestions(this.commands,prefix);return filtered.length===0?null:{items:filtered,prefix:commandText}}let tokenStart=textBeforeCursor.search(/\S+$/),currentToken=tokenStart===-1?"":textBeforeCursor.slice(tokenStart);if(currentToken.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(textBeforeCursor.slice(0,tokenStart))){let skillCommands=this.commands.filter(command2=>("name"in command2?command2.name:command2.value).startsWith("skill:")),filtered=getSlashCommandSuggestions(skillCommands,currentToken.slice(1));return filtered.length===0?null:{items:filtered,prefix:currentToken}}let commandName2=commandText.slice(1,spaceIndex),argumentText=commandText.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName2);if(!command||!("getArgumentCompletions"in command)||!command.getArgumentCompletions)return null;let argumentSuggestions=await command.getArgumentCompletions(argumentText);return!Array.isArray(argumentSuggestions)||argumentSuggestions.length===0?null:{items:argumentSuggestions,prefix:argumentText}}let pathMatch=this.extractPathPrefix(textBeforeCursor,options.force??!1);if(pathMatch===null)return null;let suggestions=this.getFileSuggestions(pathMatch);return suggestions.length===0?null:{items:suggestions,prefix:pathMatch}}applyCompletion(lines,cursorLine,cursorCol,item,prefix){let currentLine=lines[cursorLine]||"",beforePrefix=currentLine.slice(0,cursorCol-prefix.length),afterCursor=currentLine.slice(cursorCol),isQuotedPrefix=prefix.startsWith('"')||prefix.startsWith('@"'),hasLeadingQuoteAfterCursor=afterCursor.startsWith('"'),hasTrailingQuoteInItem=item.value.endsWith('"'),adjustedAfterCursor=isQuotedPrefix&&hasTrailingQuoteInItem&&hasLeadingQuoteAfterCursor?afterCursor.slice(1):afterCursor;if(prefix.startsWith("$")&&(item.value.startsWith("/")||item.value.startsWith("$"))){let newLine2=`${beforePrefix}${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+1}}if(prefix.startsWith("/")&&!prefix.slice(1).includes("/")&&(beforePrefix.trim()===""||prefix.startsWith("/skill:")&&this.isLeadingKnownSkillCommandRun(beforePrefix))){let separator=isSlashNamespaceItem(item.value)?"":" ",newLine2=`${beforePrefix}/${item.value}${separator}${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+1+item.value.length+separator.length}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.value}${suffix}${adjustedAfterCursor}`,newLines2=[...lines];newLines2[cursorLine]=newLine2;let hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2+suffix.length}}let textBeforeCursor=currentLine.slice(0,cursorCol);if(textBeforeCursor.includes("/")&&textBeforeCursor.includes(" ")){let newLine2=beforePrefix+item.value+adjustedAfterCursor,newLines2=[...lines];newLines2[cursorLine]=newLine2;let isDirectory2=item.label.endsWith("/"),hasTrailingQuote2=item.value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2}}let newLine=beforePrefix+item.value+adjustedAfterCursor,newLines=[...lines];newLines[cursorLine]=newLine;let isDirectory=item.label.endsWith("/"),hasTrailingQuote=item.value.endsWith('"'),cursorOffset=isDirectory&&hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+cursorOffset}}isLeadingKnownSkillCommandRun(text){let tokens=text.trim().split(/\s+/);return tokens.length>0&&tokens.every(token=>{if(!token.startsWith("/skill:"))return!1;let commandName2=token.slice(1);return this.commands.some(command=>("name"in command?command.name:command.value)===commandName2)})}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),token=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return token.startsWith("@")?token:null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path4){if(path4.startsWith("~/")){let expandedPath=join2(homedir3(),path4.slice(2));return path4.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path4==="~")return homedir3();return path4}resolveScopedFuzzyQuery(rawQuery){let normalizedQuery=toDisplayPath(rawQuery),slashIndex=normalizedQuery.lastIndexOf("/");if(slashIndex===-1)return null;let displayBase=normalizedQuery.slice(0,slashIndex+1),query=normalizedQuery.slice(slashIndex+1),baseDir;displayBase.startsWith("~/")?baseDir=this.expandHomePath(displayBase):displayBase.startsWith("/")?baseDir=displayBase:baseDir=join2(this.basePath,displayBase);try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{baseDir,query,displayBase}}scopedPathForDisplay(displayBase,relativePath){let normalizedRelativePath=toDisplayPath(relativePath);return displayBase==="/"?`/${normalizedRelativePath}`:`${toDisplayPath(displayBase)}${normalizedRelativePath}`}getFileSuggestions(prefix){try{let searchDir,searchPrefix,{rawPrefix,isAtPrefix,isQuotedPrefix}=parsePathPrefix(prefix),expandedPrefix=rawPrefix;if(expandedPrefix.startsWith("~")&&(expandedPrefix=this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="/"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join2(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname2(expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=join2(this.basePath,dir),searchPrefix=file}let entries=readdirSync(searchDir,{withFileTypes:!0}),suggestions=[];for(let entry of entries){if(!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase()))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{let fullPath=join2(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}let relativePath,name=entry.name,displayPrefix=rawPrefix;if(displayPrefix.endsWith("/"))relativePath=displayPrefix+name;else if(displayPrefix.includes("/")||displayPrefix.includes("\\"))if(displayPrefix.startsWith("~/")){let homeRelativeDir=displayPrefix.slice(2),dir=dirname2(homeRelativeDir);relativePath=`~/${dir==="."?name:join2(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname2(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join2(dirname2(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a,b2)=>{let aIsDir=a.label.endsWith("/"),bIsDir=b2.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b2.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options){if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,baseDirEntries=await this.getBaseDirSuggestions(fdBaseDir,fdQuery,options.signal),recursiveEntries=await walkDirectoryWithFd(fdBaseDir,this.fdPath,fdQuery,100,options.signal),seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),entries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))];if(options.signal.aborted)return[];let scoredEntries=entries.map(entry=>({...entry,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b2)=>{let scoreDiff=b2.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b2.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b2.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b2.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,pathWithoutSlash):pathWithoutSlash,entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}catch{return[]}}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};var Text=class _Text{constructor(text="",paddingX=1,paddingY=1,customBgFn){this.revision=nextRenderRevision(),this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){text!==this.text&&this.markRevision(),this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.markRevision(),this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,this.markRevision()}markRevision(){this.revision=this.getRenderRevision()===void 0?this.revision+1:nextRenderRevision()}getRenderRevision(){return Object.getPrototypeOf(this)===_Text.prototype?this.revision:void 0}textRenderRevision(){return this.revision}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};var DEFAULT_PRIMARY_COLUMN_WIDTH=32,PRIMARY_COLUMN_GAP=2,MIN_DESCRIPTION_WIDTH=10,normalizeToSingleLine=text=>text.replace(/[\r\n]+/g," ").trim(),clamp=(value,min,max)=>Math.max(min,Math.min(value,max)),SelectList=class{constructor(items,maxVisible,theme,layout={}){this.items=[],this.filteredItems=[],this.selectedIndex=0,this.maxVisible=5,this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.layout=layout}setFilter(filter){this.filteredItems=this.items.filter(item=>item.value.toLowerCase().startsWith(filter.toLowerCase())),this.selectedIndex=0}setSelectedIndex(index){this.selectedIndex=Math.max(0,Math.min(index,this.filteredItems.length-1))}invalidate(){}render(width){let lines=[];if(this.filteredItems.length===0)return lines.push(this.theme.noMatch(" No matching commands")),lines;let primaryColumnWidth=this.getPrimaryColumnWidth(),{startIndex,endIndex}=this.getVisibleRange();for(let i=startIndex;i<endIndex;i++){let item=this.filteredItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,descriptionSingleLine=item.description?normalizeToSingleLine(item.description):void 0;lines.push(this.renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth))}if(startIndex>0||endIndex<this.filteredItems.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredItems.length})`;lines.push(this.theme.scrollInfo(truncateToWidth(scrollText,width-2,"")))}return lines}handleMouse(event){if(this.filteredItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+delta)),this.selectedIndex!==previousIndex&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let{startIndex,endIndex}=this.getVisibleRange(),itemIndex=startIndex+event.y;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex!==itemIndex&&(this.selectedIndex=itemIndex,this.notifySelectionChange()),{handled:!0,focus:!0};if(event.type==="click"){let clickedIndex=this.mousePressedIndex??itemIndex;this.mousePressedIndex=void 0;let changed=this.selectedIndex!==clickedIndex;this.selectedIndex=clickedIndex,changed&&this.notifySelectionChange();let selectedItem=this.filteredItems[this.selectedIndex];return selectedItem&&this.onSelect?.(selectedItem),{handled:!0}}}}handleInput(keyData){let kb=getKeybindings();if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,this.filteredItems.length)}}renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth){let prefix=isSelected?"\u2192 ":" ",prefixWidth=visibleWidth(prefix);if(descriptionSingleLine&&width>40){let effectivePrimaryColumnWidth=Math.max(1,Math.min(primaryColumnWidth,width-prefixWidth-4)),maxPrimaryWidth=Math.max(1,effectivePrimaryColumnWidth-PRIMARY_COLUMN_GAP),truncatedValue2=this.truncatePrimary(item,isSelected,maxPrimaryWidth,effectivePrimaryColumnWidth),truncatedValueWidth=visibleWidth(truncatedValue2),spacing=" ".repeat(Math.max(1,effectivePrimaryColumnWidth-truncatedValueWidth)),descriptionStart=prefixWidth+truncatedValueWidth+spacing.length,remainingWidth=width-descriptionStart-2;if(remainingWidth>MIN_DESCRIPTION_WIDTH){let truncatedDesc=truncateToWidth(descriptionSingleLine,remainingWidth,"");return this.composeRow(prefix,truncatedValue2,spacing+truncatedDesc,isSelected)}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return this.composeRow(prefix,truncatedValue,void 0,isSelected)}composeRow(prefix,primary,description,isSelected){return this.theme.renderRow?this.theme.renderRow({prefix:isSelected?this.theme.selectedPrefix(prefix):prefix,primary,description,isSelected}):isSelected?this.theme.selectedText(`${prefix}${primary}${description??""}`):prefix+primary+(description!==void 0?this.theme.description(description):"")}getPrimaryColumnWidth(){let{min,max}=this.getPrimaryColumnBounds(),widestPrimary=this.filteredItems.reduce((widest,item)=>Math.max(widest,visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(widestPrimary,min,max)}getPrimaryColumnBounds(){let rawMin=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH,rawMax=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH;return{min:Math.max(1,Math.min(rawMin,rawMax)),max:Math.max(1,Math.max(rawMin,rawMax))}}truncatePrimary(item,isSelected,maxWidth,columnWidth){let displayValue=this.getDisplayValue(item),truncatedValue=this.layout.truncatePrimary?this.layout.truncatePrimary({text:displayValue,maxWidth,columnWidth,item,isSelected}):truncateToWidth(displayValue,maxWidth,"");return truncateToWidth(truncatedValue,maxWidth,"")}getDisplayValue(item){return item.label||item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};function A(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=A();function U(l3){T=l3}var E={exec:()=>null};function I(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=l3(n),e[n]=i),i}}function d(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(m.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}var we=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l3=>new RegExp(`^ {0,${l3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}(?:</?(?:${H})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:I(l3=>new RegExp(`^ {0,${l3}}>`))},ye=/^(?:[ \t]*(?:\n|$))+/,Pe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Se=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,_e=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,K=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,le=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ue=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),$e=d(le).replace(/bull/g,K).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),W=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Le=/^[^\n]+/,X=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ze=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",X).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,K).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",J=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Me=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",J).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),pe=l3=>d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Ae=pe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ie=pe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ce=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ie).getRegex(),V={blockquote:Ce,code:Pe,def:ze,fences:Se,heading:_e,hr:v,html:Me,lheading:ue,list:Ee,newline:ye,paragraph:Ae,table:E,text:Le},ie=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),Be={...V,lheading:$e,table:ie,paragraph:d(W).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ie).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},De={...V,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",J).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(W).replace("hr",v).replace("heading",` *#{1,6} *[^
|
|
@@ -106,10 +106,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
|
|
|
106
106
|
\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteAltScreenKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){return decodeMouseButton(button)}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result,applyFocus=!0){let focusTarget=applyFocus&&result.focus?this.resolveMouseFocusTarget(result.focusTarget??result.target.component):null,focusChanged=focusTarget!==null&&this.getFocusedComponent()!==focusTarget;return focusTarget&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),focusBeforeClick=this.getFocusedComponent(),clickResult=this.dispatchMouseToTarget(clickEvent,target);if(clickResult){let keepHandlerFocus=this.getFocusedComponent()!==focusBeforeClick;render=this.applyMouseDispatchResult(clickEvent,clickResult,!keepHandlerFocus)||render}}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){return parseWheelEvent(data)}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){return parseSgrMouseEvent(data)}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter3.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
|
|
107
107
|
`);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b2)=>b2.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return isMouseSequence(data)}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,""));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imagesNeedRedraw=screen.some((line,row)=>line!==this.previousScreen[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteAltScreenKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));buffer+=preparedKittyScreen.evictedImageDeletion;let clearRowsBeforeKittyImages=redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&(!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm");if(clearRowsBeforeKittyImages)for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H${clearRowsBeforeKittyImages?"":"\x1B[2K"}${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};var TuiMainScreen=class extends TuiBase{constructor(...args){super(...args),this.mode="regular",this.trackingEnabled=!1,this.clicks=new MouseClickSynthesizer,this.addInputListener(data=>this.handleMouseInput(data))}applyMouseTracking(enabled){let supported=!!process.stdout.isTTY&&!process.env.TERMUX_VERSION&&(process.platform!=="win32"||!!process.env.WT_SESSION),next=enabled&&supported&&!this.stopped;this.clicks.cancel(),this.mousePress=void 0,this.trackingEnabled!==next&&(this.trackingEnabled=next,this.terminal.write(next?MOUSE_TRACKING.inline:MOUSE_TRACKING.disable))}beforeTerminalStop(){this.terminal.write(MOUSE_TRACKING.disable),this.trackingEnabled=!1,this.clicks.cancel(),this.mousePress=void 0}doRender(){this.stopped||(this.mouseExternalWritePending&&(this.mouseExternalWritePending=!1,this.terminal.write(`\r
|
|
108
108
|
`),this.restoreRenderState({previousLines:[],previousWidth:0,previousHeight:0,cursorRow:0,hardwareCursorRow:0,maxLinesRendered:0,previousViewportTop:0})),super.doRender(),this.noteCommittedMouseFrame(),this.calibrateMouseAnchor())}collectMouseComponents(){let components=[],visit=component=>{if(components.push(component),component instanceof Container)for(let child of component.children)visit(child)};for(let root of this.getMouseLayoutRoots())visit(root);return components}pressLayoutUnchanged(press){let lines=this.previousLines;if(press.frame!==lines){if(press.frame.length!==lines.length)return!1;for(let index=0;index<lines.length;index++)if(press.frame[index]!==lines[index])return!1}let components=this.collectMouseComponents();return components.length===press.components.length&&components.every((component,index)=>component===press.components[index])}applyMouseResult(result){if(!result?.focus)return;let target=this.resolveMouseFocusTarget(result.focusTarget??result.target.component);target&&this.setFocus(target)}handleMouseInput(data){if(!isMouseSequence(data))return{consume:!1};let raw=parseSgrMouseEvent(data);if(!this.trackingEnabled||!raw||raw.button!==0)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let frameLine=this.resolveFrameLine(raw.y+1);if(frameLine===void 0||raw.x>=this.terminal.columns)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let event=toTuiMouseEvent(raw.release?"release":"press",raw,this.terminal);if(raw.release){let press=this.mousePress;if(this.mousePress=void 0,!press||press.epoch!==this.placementEpoch||!this.pressLayoutUnchanged(press)||press.x!==raw.x||press.y!==raw.y)return this.clicks.cancel(),{consume:!0};let count=this.clicks.release(raw,press.target.component,this.placementEpoch);if(count!==void 0){let click={...event,type:"click",clickCount:count},focusBeforeClick=this.getFocusedComponent(),clickResult=dispatchMouseEvent(press.target.component,retargetMouseEvent(click,press.target));this.getFocusedComponent()===focusBeforeClick&&this.applyMouseResult(clickResult),this.requestRender()}}else{let overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:dispatchMouseEvent(this,{...event,y:frameLine,height:this.previousLines.length}));this.mousePress=void 0,result?(this.applyMouseResult(result),this.mousePress={target:result.target,epoch:this.placementEpoch,frame:this.previousLines,components:this.collectMouseComponents(),x:raw.x,y:raw.y},this.clicks.press(raw,result.target.component,this.placementEpoch)):this.clicks.cancel(),this.requestRender()}return{consume:!0}}captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}};var dist_exports={};__export(dist_exports,{AltScreenSearchComponent:()=>AltScreenSearchComponent,Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,CompositeRevision:()=>CompositeRevision,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,IMAGE_MARKER_REGEX:()=>IMAGE_MARKER_REGEX,IMAGE_MARKER_SINGLE:()=>IMAGE_MARKER_SINGLE,Image:()=>Image,ImageMarkerRegistry:()=>ImageMarkerRegistry,Input:()=>Input,KITTY_PLACEHOLDER_MAX:()=>KITTY_PLACEHOLDER_MAX,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,MOUSE_TRACKING:()=>MOUSE_TRACKING,Markdown:()=>Markdown,Marked:()=>Q,MouseClickSynthesizer:()=>MouseClickSynthesizer,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI:()=>TUI,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,buildKittyPlaceholderRow:()=>buildKittyPlaceholderRow,calculateImageRows:()=>calculateImageRows,claimFrameRow:()=>claimFrameRow,clearRenderCache:()=>clearRenderCache,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,currentRenderRevision:()=>currentRenderRevision,decodeKittyPrintable:()=>decodeKittyPrintable,decodeMouseButton:()=>decodeMouseButton,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,dispatchMouseEvent:()=>dispatchMouseEvent,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,expandPasteMarkers:()=>expandPasteMarkers,findAltScreenSearchMatches:()=>findAltScreenSearchMatches,foregroundAnsi:()=>foregroundAnsi,formatImageMarker:()=>formatImageMarker,frameLineBytesTotals:()=>frameLineBytesTotals,frameMode:()=>frameMode,frameScrollbackRows:()=>frameScrollbackRows,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,fuzzyMatchLower:()=>fuzzyMatchLower,getAltScreenSearchMatchKey:()=>getAltScreenSearchMatchKey,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getGraphemeSegmenter:()=>getGraphemeSegmenter,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getMarkdownHighlightCallCount:()=>getMarkdownHighlightCallCount,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,getWordSegmenter:()=>getWordSegmenter,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,imageMarkerId:()=>imageMarkerId,indexedColor:()=>indexedColor,isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,isImageMarker:()=>isImageMarker,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isMouseSequence:()=>isMouseSequence,isViewportTUI:()=>isViewportTUI,isWarpWslSession:()=>isWarpWslSession,joinLineArrays:()=>joinLineArrays,mainScreenHistoryLines:()=>mainScreenHistoryLines,matchesKey:()=>matchesKey,mixColors:()=>mixColors,nextRenderRevision:()=>nextRenderRevision,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,outerKittyGraphicsMode:()=>outerKittyGraphicsMode,parseColor:()=>parseColor,parseKey:()=>parseKey,parseSgrMouseEvent:()=>parseSgrMouseEvent,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,parseWheelEvent:()=>parseWheelEvent,renderAtFrameRow:()=>renderAtFrameRow,renderImage:()=>renderImage,resetCapabilitiesCache:()=>resetCapabilitiesCache,resetMainScreenHistoryLines:()=>resetMainScreenHistoryLines,resetMarkdownHighlightCallCount:()=>resetMarkdownHighlightCallCount,rgbColor:()=>rgbColor,sanitizeTerminalLabel:()=>sanitizeTerminalLabel,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,shortenImagePath:()=>shortenImagePath,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,toTuiMouseEvent:()=>toTuiMouseEvent,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi,wrapTmuxPassthrough:()=>wrapTmuxPassthrough});var multiply=(m2,[x2,y2,z])=>m2.map(row=>row[0]*x2+row[1]*y2+row[2]*z),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],LMS_TO_LINEAR_SRGB=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],SATURATION_FIT=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,.00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x2=>.5*(K3*x2-K1+Math.sqrt((K3*x2-K1)**2+4*K2*K3*x2)),okhslToOklabLightness=x2=>(x2*x2+K1*x2)/(K3*(x2+K2)),linearToSrgb=value=>value>.0031308?1.055*value**(1/2.4)-.055:12.92*value,srgbToLinear=value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4;function oklabToLinearSrgb(lab){return multiply(LMS_TO_LINEAR_SRGB,multiply(LAB_TO_LMS,lab).map(value=>value**3))}function linearSrgbToOklab(rgb){return multiply(LMS_TO_LAB,multiply(LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b:b2}){return linearSrgbToOklab([r/255,g/255,b2/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b2]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b:b2}}function lmsSlopes(a,b2){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a+row[2]*b2)}function maxSaturation(a,b2){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a+y2*b2>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a+k2*b2+k3*a*a+k4*a*b2,slopes=lmsSlopes(a,b2),base=slopes.map(k=>1+saturation*k),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f2=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f22=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f2*f1/(f1*f1-.5*f2*f22)}function cusp(a,b2){let saturation=maxSaturation(a,b2),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb([1,saturation*a,saturation*b2])));return[lightness,lightness*saturation]}function maxChroma(a,b2,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a,b2),lms=slopes.map(k=>lightness+t*k),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(row=>{let f2=dot(row,cubes)-1,f1=dot(row,first),f22=dot(row,second),u=f1/(f1*f1-.5*f2*f22);return u>=0?-f2*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a,b2){let peak=cusp(a,b2),cMax=maxChroma(a,b2,L2,peak),k=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b2+a*(-2.19557347+1.75198401*b2+a*(-2.13704948-10.02301043*b2+a*(-4.24894561+5.38770819*b2+4.69891013*a)))),midT=.11239642+1/(1.6132032-.68124379*b2+a*(.40370612+.90148123*b2+a*(-.27087943+.6122399*b2+a*(.00299215-.45399568*b2-.14661872*a)))),cMid=.9*k*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a=Math.cos(angle),b2=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a,b2),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*c0;chroma=t*k1/(1-(1-k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a,chroma*b2]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/chroma),saturation;if(chroma<cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b2){for(let[name,value]of[["r",r],["g",g],["b",b2]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.freeze({kind:"rgb",r,g,b:b2})}function oklchColor(l3,c,h){if(requireFinite(l3,"l"),requireFinite(c,"c"),requireFinite(h,"h"),l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);if(c<0)throw new Error(`c must not be negative: ${c}`);return Object.freeze({kind:"oklch",l:l3,c,h:(h%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)$`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(h,s,l3){if(requireFinite(h,"h"),requireFinite(s,"s"),requireFinite(l3,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);let{r,g,b:b2}=okhslToRgb(h,s,l3);return rgbColor(r,g,b2)}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){if(typeof value=="number")return indexedColor(value);let hex=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(value);if(hex){let digits=hex[1].length===3?[...hex[1]].map(digit=>digit+digit).join(""):hex[1];return rgbColor(Number.parseInt(digits.slice(0,2),16),Number.parseInt(digits.slice(2,4),16),Number.parseInt(digits.slice(4,6),16))}let oklch=OKLCH_PATTERN.exec(value);if(oklch){let lightness=Number.parseFloat(oklch[1])/(oklch[2]?100:1);return oklchColor(lightness,Number.parseFloat(oklch[3]),Number.parseFloat(oklch[4]))}let okhsl=OKHSL_PATTERN.exec(value);if(okhsl){let saturation=Number.parseFloat(okhsl[2])/(okhsl[3]?100:1),lightness=Number.parseFloat(okhsl[4])/(okhsl[5]?100:1);return okhslColor(Number.parseFloat(okhsl[1]),saturation,lightness)}throw new Error(`Invalid color value: ${value}`)}var BASIC_COLORS=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],CUBE_VALUES=[0,95,135,175,215,255],GRAY_VALUES=Array.from({length:24},(_2,index)=>8+index*10);function indexedToRgb(index){if(index<16)return{...BASIC_COLORS[index]};if(index<232){let cubeIndex=index-16;return{r:CUBE_VALUES[Math.floor(cubeIndex/36)],g:CUBE_VALUES[Math.floor(cubeIndex%36/6)],b:CUBE_VALUES[cubeIndex%6]}}let gray=8+(index-232)*10;return{r:gray,g:gray,b:gray}}function isInSrgbGamut(linear){return linear.every(channel=>channel>=-1e-7&&channel<=1+1e-7)}function oklchToRgb({l:l3,c,h}){let radians=h*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l3,chroma*cos,chroma*sin]),direct=atChroma(c);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(linear)}function colorToRgb(color){switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l3,a,b2]=rgbToOklab(colorToRgb(color));return{l:l3,c:Math.hypot(a,b2),h:(Math.atan2(b2,a)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b:b2}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(2,"0");return`#${channel(r)}${channel(g)}${channel(b2)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a2=colorToRgb(first),b3=colorToRgb(second);return rgbColor(a2.r+(b3.r-a2.r)*amount,a2.g+(b3.g-a2.g)*amount,a2.b+(b3.b-a2.b)*amount)}let a=colorToOklch(first),b2=colorToOklch(second),firstHue=a.c<1e-7?b2.h:a.h,hueDelta=((b2.c<1e-7?firstHue:b2.h)-firstHue+540)%360-180;return oklchColor(a.l+(b2.l-a.l)*amount,a.c+(b2.c-a.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}function rgbToAnsi256(color){let rIndex=findClosest(CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,{r:grayValue,g:grayValue,b:grayValue})<colorDistance(color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){return colorAnsi(color,mode,!0)}function styleText(text,options,mode){return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),options.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options.underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var Box=class _Box{constructor(paddingX=1,paddingY=1,bgFn){this.children=[],this.disposed=!1,this.composite=new CompositeRevision,this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache(),component.dispose?.())}clear(){for(let child of this.children)child.dispose?.();this.children=[],this.invalidateCache()}detachAll(){this.children=[],this.invalidateCache()}dispose(){if(!this.disposed){this.disposed=!0;for(let child of this.children)child.dispose?.();this.invalidateCache()}}setBgFn(bgFn){this.bgFn=bgFn,this.composite.bump()}invalidateCache(){this.cache=void 0,this.composite.bump()}matchCache(width,childLines,bgSample){let cache=this.cache;return!!cache&&cache.width===width&&cache.bgSample===bgSample&&cache.childLines.length===childLines.length&&cache.childLines.every((line,i)=>line===childLines[i])}invalidate(){this.invalidateCache(),this.composite.bump();for(let child of this.children)child.invalidate?.()}getRenderRevision(){return Object.getPrototypeOf(this)===_Box.prototype?this.childRenderRevision():void 0}childRenderRevision(){return this.composite.read(this.children)}bumpRenderRevision(){this.composite.bump()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth);mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(line)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(width,childLines,bgSample))return this.cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));for(let line of childLines)result.push(this.applyBg(leftPad+line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));return flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?applyBackgroundToLine(padded,width,this.bgFn):padded}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.frames=[...DEFAULT_FRAMES],this.intervalMs=DEFAULT_INTERVAL_MS,this.currentFrame=0,this.indicatorIntervalId=null,this.messageIntervalId=null,this.indicatorFormatter=void 0,this.messageFormatter=void 0,this.messageIntervalMs=DEFAULT_INTERVAL_MS,this.messageAnimationStartedAt=0,this.ui=null,this.renderIndicatorVerbatim=!1,this.message="Loading...",this.lastDisplayedText=void 0,this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.messageFormatter&&(this.messageAnimationStartedAt=Date.now()),this.updateDisplay(),this.restartAnimation()}stop(){this.indicatorIntervalId&&(clearInterval(this.indicatorIntervalId),this.indicatorIntervalId=null),this.messageIntervalId&&(clearInterval(this.messageIntervalId),this.messageIntervalId=null)}dispose(){this.stop()}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.indicatorFormatter=indicator?.indicatorFormatter,this.messageFormatter=indicator?.messageFormatter,this.messageIntervalMs=indicator?.messageIntervalMs&&indicator.messageIntervalMs>0?indicator.messageIntervalMs:this.intervalMs,this.currentFrame=0,this.messageAnimationStartedAt=Date.now(),this.start()}restartAnimation(){this.stop(),this.frames.length>1&&(this.indicatorIntervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs),this.indicatorIntervalId.unref?.()),(this.indicatorFormatter||this.messageFormatter)&&(this.messageAnimationStartedAt=Date.now(),this.messageIntervalId=setInterval(()=>{this.updateDisplay()},this.messageIntervalMs),this.messageIntervalId.unref?.())}getRenderedIndicator(animationElapsedMs=this.getAnimationElapsedMs()){let frame=this.frames[this.currentFrame]??"";return frame.length===0?"":this.indicatorFormatter?this.indicatorFormatter(frame,animationElapsedMs):this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}getAnimationElapsedMs(){return Math.max(0,Date.now()-this.messageAnimationStartedAt)}updateDisplay(){let animationElapsedMs=this.getAnimationElapsedMs(),renderedFrame=this.getRenderedIndicator(animationElapsedMs),indicator=renderedFrame.length>0?`${renderedFrame} `:"",renderedMessage=this.messageFormatter?this.messageFormatter(this.message,animationElapsedMs):this.messageColorFn(this.message),displayedText=`${indicator}${renderedMessage}`;displayedText!==this.lastDisplayedText&&(this.lastDisplayedText=displayedText,this.setText(displayedText),this.ui&&this.ui.requestRender())}};var CancellableLoader=class extends Loader{constructor(){super(...arguments),this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var IMAGE_MARKER_REGEX=/\[Image #([1-9]\d*)\]/g,IMAGE_MARKER_SINGLE=/^\[Image #([1-9]\d*)\]$/;function formatImageMarker(id){return`[Image #${id}]`}function isImageMarker(segment){return segment.length>=10&&IMAGE_MARKER_SINGLE.test(segment)}function imageMarkerId(segment){let match=segment.length>=10?IMAGE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function countOccurrences(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}var ImageMarkerRegistry=class{constructor(){this.entries=new Set,this.imageCounter=0}add(){let id=++this.imageCounter;return this.entries.add(id),formatImageMarker(id)}authorizedMarkers(text){let markers=new Set;for(let id of this.entries){let marker=formatImageMarker(id);countOccurrences(text,marker)===1&&markers.add(marker)}return markers}canonicalize(text){let order=this.ids(text);if(order.length===0)return{text,order};let renumbered=new Map;for(let[index,id]of order.entries())renumbered.set(id,index+1);let updatedText=text.replace(IMAGE_MARKER_REGEX,marker=>{let id=imageMarkerId(marker),newId=id===void 0?void 0:renumbered.get(id);return newId===void 0?marker:formatImageMarker(newId)});return this.entries=new Set(order.map((_2,index)=>index+1)),this.imageCounter=this.entries.size,{text:updatedText,order}}clear(){this.entries.clear(),this.imageCounter=0}ids(text){let authorized=this.authorizedMarkers(text),ordered=[];for(let match of text.matchAll(IMAGE_MARKER_REGEX))authorized.has(match[0])&&ordered.push(Number.parseInt(match[1],10));return ordered}install(state,text){this.restore(state),this.prune(text)}prune(text,previousText){for(let id of[...this.entries]){let marker=formatImageMarker(id);(!(previousText===void 0||countOccurrences(previousText,marker)===1)||countOccurrences(text,marker)!==1)&&this.entries.delete(id)}this.imageCounter=Math.max(...this.entries,0)}remove(id,text){if(!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence(text,formatImageMarker(id),""),higherIds=[...this.entries].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){this.entries.delete(oldId);let marker=formatImageMarker(oldId);if(countOccurrences(updatedText,marker)!==1)continue;let newId=oldId-1;updatedText=replaceSingleOccurrence(updatedText,marker,formatImageMarker(newId)),this.entries.add(newId)}return this.imageCounter=Math.max(...this.entries,0),{text:updatedText,removed:!0}}restore(state){this.entries=new Set(state.ids),this.imageCounter=Math.max(state.imageCounter,...this.entries,0)}snapshot(){return{ids:[...this.entries].sort((a,b2)=>a-b2),imageCounter:this.imageCounter}}};var PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function formatPasteMarker(id,lineCount,charCount){return lineCount>10?`[paste #${id} +${lineCount} lines]`:`[paste #${id} ${charCount} chars]`}function countLines(content){let lineCount=1;for(let index=0;index<content.length;index++)content.charCodeAt(index)===10&&lineCount++;return lineCount}function createEntry(id,content,marker){let charCount=content.length,lineMatch=marker?.match(PASTE_MARKER_SINGLE)?.[3]?.match(/^\+(\d+) lines$/),lineCount=lineMatch?Number.parseInt(lineMatch[1],10):countLines(content),canonical=formatPasteMarker(id,lineCount,charCount);return{content,marker:marker===canonical?marker:canonical,lineCount,charCount}}function countOccurrences2(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence2(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}function entriesFromState(state){let entries=new Map;for(let[id,content]of state.pastes)entries.set(id,createEntry(id,content,state.markers?.get(id)));return entries}function expandPasteMarkers(text,state){let entries=entriesFromState(state),byMarker=new Map;for(let entry of entries.values())byMarker.set(entry.marker,entry);let matches=[],counts=new Map;for(let match of text.matchAll(PASTE_MARKER_REGEX)){let marker=match[0];byMarker.has(marker)&&(matches.push({start:match.index,end:match.index+marker.length,marker}),counts.set(marker,(counts.get(marker)??0)+1))}if(matches.length===0)return text;let chunks=[],offset=0;for(let match of matches){chunks.push(text.slice(offset,match.start));let entry=byMarker.get(match.marker);chunks.push(counts.get(match.marker)===1?entry.content:match.marker),offset=match.end}return chunks.push(text.slice(offset)),chunks.join("")}function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function pasteMarkerId(segment){let match=segment.length>=10?PASTE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function segmentWithMarkers(text,baseSegmenter,validMarkers){if(validMarkers.size===0)return baseSegmenter.segment(text);let found=[];for(let marker2 of validMarkers){let start=text.indexOf(marker2);start!==-1&&found.push({start,end:start+marker2.length})}if(found.length===0)return baseSegmenter.segment(text);found.sort((a,b2)=>a.start-b2.start||b2.end-a.end);let markers=[];for(let range of found){let previous=markers[markers.length-1];previous&&range.start<previous.end||markers.push(range)}let result=[],markerIndex=0,marker=markers[0];for(let segment of baseSegmenter.segment(text)){for(;marker&&segment.index>=marker.end;)marker=markers[++markerIndex];!marker||segment.index<marker.start?result.push(segment):segment.index===marker.start&&result.push({segment:text.slice(marker.start,marker.end),index:marker.start,input:text})}return result}var PasteMarkerRegistry=class{constructor(){this.entries=new Map,this.pasteCounter=0,this.metadataBuilds=0}add(content,lineCount,charCount){let id=++this.pasteCounter,marker=formatPasteMarker(id,lineCount,charCount);return this.entries.set(id,{content,marker,lineCount,charCount}),this.metadataBuilds++,marker}authorizedMarkers(text){let markers=new Set;for(let entry of this.entries.values())countOccurrences2(text,entry.marker)===1&&markers.add(entry.marker);return markers}clear(){this.entries.clear(),this.pasteCounter=0}expand(text){return expandPasteMarkers(text,this.snapshot())}get metadataBuildCount(){return this.metadataBuilds}install(state,text){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0),this.prune(text)}prune(text,previousText){for(let[id,entry]of this.entries)(!(previousText===void 0||countOccurrences2(previousText,entry.marker)===1)||countOccurrences2(text,entry.marker)!==1)&&this.entries.delete(id);this.pasteCounter=Math.max(...this.entries.keys(),0)}remove(id,text){let removedEntry=this.entries.get(id);if(!removedEntry||!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence2(text,removedEntry.marker,""),higherIds=[...this.entries.keys()].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){let entry=this.entries.get(oldId);if(this.entries.delete(oldId),countOccurrences2(updatedText,entry.marker)!==1)continue;let newId=oldId-1,renamed=formatPasteMarker(newId,entry.lineCount,entry.charCount);updatedText=replaceSingleOccurrence2(updatedText,entry.marker,renamed),this.entries.set(newId,{...entry,marker:renamed})}return this.pasteCounter=Math.max(...this.entries.keys(),0),{text:updatedText,removed:!0}}snapshot(){let pastes=new Map,markers=new Map;for(let[id,entry]of this.entries)pastes.set(id,entry.content),markers.set(id,entry.marker);return{pastes,markers,pasteCounter:this.pasteCounter}}restore(state){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0)}};import*as fs2 from"node:fs";import*as path3 from"node:path";import{createRequire as createRequire2}from"node:module";import*as path2 from"node:path";import{createRequire}from"node:module";import{dirname as dirname3,isAbsolute as isAbsolute2,join as join3}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function resolvePackageEntry(resolveOverride){if(resolveOverride)return resolveOverride(TUI_PACKAGE_NAME);try{return fileURLToPath(import.meta.resolve(TUI_PACKAGE_NAME))}catch{}return moduleRequire.resolve(TUI_PACKAGE_NAME)}function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname3(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=resolvePackageEntry(options.resolvePackage);packageEntry&&isAbsolute2(packageEntry)&&candidates.push(join3(dirname3(packageEntry),"..",nativePath))}catch{}return candidates.push(join3(moduleDir,"..",nativePath),join3(moduleDir,nativePath),join3(dirname3(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path2.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}function observeProcessStderrWrites(listener){let original=process.stderr.write,observed=function(...args){return listener(),Reflect.apply(original,this,args)};return process.stderr.write=observed,()=>{process.stderr.write===observed&&(process.stderr.write=original)}}import{StringDecoder}from"node:string_decoder";import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,DEFAULT_BURST_WINDOW_MS=20,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",LINE_BREAK=/\r\n|\r|\n/g,TRAILING_LINE_BREAK_RUN=/(\r\n|\r|\n)+$/,LINE_BREAK_BEFORE_TEXT=/[\r\n][^\r\n]/;function countLineBreaks(text){let matches=text.match(LINE_BREAK);return matches===null?0:matches.length}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let seqEnd=1;for(;seqEnd<=remaining.length;){let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else{let codepoint=remaining.codePointAt(0),character=String.fromCodePoint(codepoint);sequences.push(character),pos+=character.length}}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{constructor(options={}){super(),this.buffer="",this.timeout=null,this.discardingMouseFragment=!1,this.pasteMode=!1,this.pasteBuffer="",this.decoder=new StringDecoder("utf8"),this.heldNewline="",this.heldNewlineEndsPaste=!1,this.burstTimer=null,this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS,this.burstWindowMs=options.burstWindowMs??DEFAULT_BURST_WINDOW_MS,this.clock=options.now??Date.now}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str,decodedFromBuffer=!1;if(Buffer.isBuffer(data))if(!((this.decoder.lastNeed??0)>0)&&data.length===1&&data[0]>=128&&data[0]<194){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=this.decoder.write(data),decodedFromBuffer=!0;else str=data;if(str.length===0&&this.buffer.length===0){decodedFromBuffer||this.emitDataSequence("");return}if(this.discardingMouseFragment){let terminator=str.search(/[\x40-\x7e]/),escapeIndex=str.indexOf(ESC);if(escapeIndex!==-1&&(terminator===-1||escapeIndex<terminator))str=str.slice(escapeIndex);else{if(terminator===-1)return;str=str.slice(terminator+1)}this.discardingMouseFragment=!1}this.burstTimer&&(clearTimeout(this.burstTimer),this.burstTimer=null),this.buffer+=str;let chunkAt=str.length>0?this.clock():void 0,burstGap=chunkAt!==void 0&&this.lastInputAt!==void 0?chunkAt-this.lastInputAt:void 0;if(chunkAt!==void 0&&(this.lastInputAt=chunkAt),this.heldNewline.length>0&&(burstGap!==void 0&&burstGap>=this.burstWindowMs?this.releaseHeldNewline():(this.buffer=this.heldNewline+this.buffer,this.heldNewline="",this.heldNewlineEndsPaste=!1)),this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}if(this.consumeUnbracketedBurst(burstGap))return;let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder,this.buffer.startsWith("\x1B[<")?(this.mouseFragmentStartedAt??=Date.now(),this.buffer.length>64&&(this.buffer="",this.discardingMouseFragment=!0)):this.mouseFragmentStartedAt=void 0;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)this.emitDataSequence(sequence)},timeoutMs)}}consumeUnbracketedBurst(burstGap){let text=this.buffer;if(text.length===0||text.includes(ESC)||text.includes(BRACKETED_PASTE_START))return!1;let breaks=countLineBreaks(text);if(breaks===0)return!1;if((breaks>=2||LINE_BREAK_BEFORE_TEXT.test(text))&&/[^\r\n]/.test(text))return this.buffer="",this.lastBurstPasteAt=this.lastInputAt,this.emit("paste",text),!0;let trailing=text.match(TRAILING_LINE_BREAK_RUN)?.[0];if(trailing===void 0||burstGap===void 0||burstGap>=this.burstWindowMs)return!1;let head=text.slice(0,text.length-trailing.length),endsPaste=this.lastBurstPasteAt!==void 0&&this.lastInputAt!==void 0&&this.lastInputAt-this.lastBurstPasteAt<this.burstWindowMs;if(head.length===0&&!endsPaste)return!1;for(let chunk of head)this.emitDataSequence(chunk);return this.buffer="",this.holdTrailingNewline(trailing,endsPaste),!0}holdTrailingNewline(run,endsPaste){this.heldNewline=run,this.heldNewlineEndsPaste=endsPaste,this.burstTimer&&clearTimeout(this.burstTimer),this.burstTimer=setTimeout(()=>{this.burstTimer=null,this.releaseHeldNewline()},this.burstWindowMs)}releaseHeldNewline(){if(this.heldNewline.length===0)return;let held=this.heldNewline,endsPaste=this.heldNewlineEndsPaste;if(this.heldNewline="",this.heldNewlineEndsPaste=!1,endsPaste){this.emit("paste",held);return}for(let chunk of held)this.emitDataSequence(chunk)}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.burstTimer&&(clearTimeout(this.burstTimer),this.burstTimer=null),this.releaseHeldNewline(),this.buffer.length===0)return[];if(this.buffer.startsWith("\x1B[<")){let remaining=750-(Date.now()-(this.mouseFragmentStartedAt??Date.now()));return remaining>0&&this.buffer.length<=64?this.timeout=setTimeout(()=>this.flush(),remaining):(this.buffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!0),[]}let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.burstTimer&&(clearTimeout(this.burstTimer),this.burstTimer=null),this.heldNewline="",this.heldNewlineEndsPaste=!1,this.lastBurstPasteAt=void 0,this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!1,this.pendingKittyPrintableCodepoint=void 0,this.decoder=new StringDecoder("utf8")}getBuffer(){return this.buffer}destroy(){this.clear()}};import{execFileSync as execFileSync2}from"node:child_process";function queryTmuxCursorPosition(pane,deadline,execFile2){let read=()=>{let remaining=deadline-Date.now();if(!(remaining<=0))try{let args=["display-message","-p","-t",pane,"#{cursor_y} #{cursor_x}"],output=execFile2?execFile2("tmux",args):execFileSync2("tmux",args,{encoding:"utf8",timeout:remaining,stdio:["ignore","pipe","ignore"]}),match=/^(\d+) (\d+)$/.exec(output.trim());if(!match||Date.now()>=deadline)return;let row=Number(match[1])+1,column=Number(match[2])+1;return Number.isSafeInteger(row)&&Number.isSafeInteger(column)?{row,column}:void 0}catch{return}},first=read();return!first||deadline-Date.now()<=10?Promise.resolve(void 0):new Promise(resolve=>{setTimeout(()=>{let second=read();resolve(second?.row===first.row&&second.column===first.column?second:void 0)},10)})}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,DEAD_TERMINAL_ERROR_CODES=new Set(["EIO","EPIPE","ENOTCONN"]),EIO_ERRNO=5,EPIPE_ERRNO=32,DEAD_TERMINAL_ERRNOS=new Set([EIO_ERRNO,EPIPE_ERRNO]),ERRNO_IN_MESSAGE_PATTERN=/errno:\s*(\d+)/,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u\x1B[c`;function parseCursorPositionResponse(sequence){let match=/^\x1b\[\?(\d+);(\d+)(?:;(\d+))?R$/.exec(sequence);return match?{row:Number(match[1]),column:Number(match[2]),...match[3]===void 0?{}:{page:Number(match[3])}}:void 0}function parseKeyboardProtocolNegotiationSequence(sequence){let cursorPosition=parseCursorPositionResponse(sequence);if(cursorPosition)return{type:"cursor-position",...cursorPosition};let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}function isWarpWslSession(env=process.env,platform=process.platform,socketExists=socketPath=>{try{return fs2.statSync(socketPath).isSocket()}catch{return!1}}){if(platform!=="linux"||isMultiplexerSession(env)||env.SSH_CONNECTION?.trim()||env.SSH_CLIENT?.trim()||env.SSH_TTY?.trim())return!1;let isWarp=!!(env.WARP_SESSION_ID?.trim()||env.WARP_TERMINAL_SESSION_UUID?.trim()),interopPath=env.WSL_INTEROP?.trim(),isWsl=isWarp&&interopPath!==void 0&&/^\/run\/WSL\/\d+_interop$/.test(interopPath)&&socketExists(interopPath);return isWarp&&isWsl}function normalizeWarpWslShiftEnterInput(data,env=process.env,platform=process.platform,socketExists){return data===`
|
|
109
|
-
`&&isWarpWslSession(env,platform,socketExists)?NATIVE_SHIFT_ENTER_SEQUENCE:data}function keyboardEnhancementEnabled(){let value=process.env.PI_TUI_KEYBOARD_PROTOCOL;return value===void 0?!0:!["0","false","no","off"].includes(value.toLowerCase())}function isDeadTerminalError(error){if(!(error instanceof Error))return!1;if("code"in error&&typeof error.code=="string")return DEAD_TERMINAL_ERROR_CODES.has(error.code);if("errno"in error&&error.errno===EIO_ERRNO)return!0;let messageErrno=ERRNO_IN_MESSAGE_PATTERN.exec(error.message);return messageErrno?DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1],10)):!1}var STDIN_ERROR_HANDLER_GRACE_MS=250,stdinErrorSubscribers=new Set;function isTerminalDetachStdinError(err){if(err.code==="EIO")return!0;let errno=err.errno;return errno===EIO_ERRNO||errno===-EIO_ERRNO}var dispatchStdinError=err=>{if(!isTerminalDetachStdinError(err)){if(!process.stdin.listeners("error").some(listener=>listener!==dispatchStdinError))throw err;return}for(let subscriber of stdinErrorSubscribers)subscriber(err)};function subscribeToStdinErrors(subscriber){stdinErrorSubscribers.size===0&&process.stdin.on("error",dispatchStdinError),stdinErrorSubscribers.add(subscriber)}function unsubscribeFromStdinErrors(subscriber){stdinErrorSubscribers.delete(subscriber),stdinErrorSubscribers.size===0&&process.stdin.removeListener("error",dispatchStdinError)}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100,DEFAULT_BURST_WINDOW_MS2=20,DEFAULT_SSH_BURST_WINDOW_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}function resolveBurstWindowMs(env=process.env){let raw=env.PI_TUI_BURST_WINDOW_MS?.trim();if(raw!==void 0&&raw.length>0){let configured=Number(raw);if(Number.isFinite(configured)&&configured>=0)return configured}return env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_BURST_WINDOW_MS:DEFAULT_BURST_WINDOW_MS2}var ProcessTerminal=class{constructor(options){this.wasRaw=!1,this.externalWriteObservers=new Set,this.keyboardNegotiationSettled=!1,this.cursorQueryTimedOut=!1,this.forwardingExternalWrite=!1,this._kittyProtocolActive=!1,this._modifyOtherKeysActive=!1,this.keyboardProtocolPushed=!1,this.pendingKeyboardProtocolDeviceAttributes=0,this.keyboardProtocolNegotiationBuffer="",this.discardingPrivateResponse=!1,this.writeLogPath=(()=>{let env=process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs2.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path3.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})(),this.onExternalStdoutWrite=options?.onExternalStdoutWrite,this.observeExternalStderrWrites=options?.observeExternalStderrWrites??observeProcessStderrWrites,this.tmuxExecFile=options?.tmuxExecFile}get kittyProtocolActive(){return this._kittyProtocolActive}queryCursorPosition(){if(this.cursorQuery)return this.cursorQuery.promise;if(!this.inputHandler||this.cursorQueryTimedOut)return Promise.resolve(void 0);let resolve,promise=new Promise(settle=>{resolve=settle}),timer=setTimeout(()=>{this.cursorQueryTimedOut=!0,this.settleCursorQuery(void 0)},750);return this.cursorQuery={promise,resolve,timer,issued:!1,tmuxPane:process.env.TMUX_PANE,deadline:Date.now()+750},this.issueCursorQuery(),promise}issueCursorQuery(){if(!this.keyboardNegotiationSettled||!this.cursorQuery||this.cursorQuery.issued)return;this.cursorQuery.issued=!0,this.rawWrite("\x1B[?6n");let pending=this.cursorQuery;pending?.tmuxPane!==void 0&&queryTmuxCursorPosition(pending.tmuxPane,pending.deadline,this.tmuxExecFile).then(position=>{this.cursorQuery===pending&&(Date.now()>=pending.deadline&&(this.cursorQueryTimedOut=!0),this.settleCursorQuery(this.cursorQueryTimedOut?void 0:position))})}settleCursorQuery(position){let pending=this.cursorQuery;pending&&(this.cursorQuery=void 0,clearTimeout(pending.timer),pending.resolve(position))}observeExternalWrites(listener){return this.externalWriteObservers.add(listener),this.inputHandler&&(this.installExternalStdoutGuard(),this.installExternalStderrObserver()),()=>{this.externalWriteObservers.delete(listener)}}noteExternalWrite(){for(let listener of this.externalWriteObservers)listener()}installExternalStderrObserver(){this.stopExternalStderrObservation||this.externalWriteObservers.size===0||(this.stopExternalStderrObservation=this.observeExternalStderrWrites(()=>this.noteExternalWrite()))}rawWrite(data){if(this.rawStdoutWrite){this.rawStdoutWrite(data);return}process.stdout.write(data)}installExternalStdoutGuard(){let handler=this.onExternalStdoutWrite;if(!handler&&this.externalWriteObservers.size===0||this.originalStdoutWrite)return;this.originalStdoutWrite=process.stdout.write;let rawWrite=process.stdout.write.bind(process.stdout);this.rawStdoutWrite=rawWrite,process.stdout.write=((chunk,encodingOrCallback,callback)=>{let cb=typeof encodingOrCallback=="function"?encodingOrCallback:callback,encoding=typeof encodingOrCallback=="string"?encodingOrCallback:void 0,text=typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding);if(!handler||this.forwardingExternalWrite)return this.noteExternalWrite(),rawWrite(text),cb?.(null),!0;this.forwardingExternalWrite=!0;try{handler(text)}catch{this.noteExternalWrite(),rawWrite(text)}finally{this.forwardingExternalWrite=!1}return cb?.(null),!0})}removeExternalStdoutGuard(){this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite,this.originalStdoutWrite=void 0,this.rawStdoutWrite=void 0)}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.installExternalStdoutGuard(),this.installExternalStderrObserver(),this.keyboardNegotiationSettled=!keyboardEnhancementEnabled(),this.cursorQueryTimedOut=!1,this.discardingPrivateResponse=!1,this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),this.stdinErrorHandlerCleanupTimer&&(clearTimeout(this.stdinErrorHandlerCleanupTimer),this.stdinErrorHandlerCleanupTimer=void 0),this.stdinErrorHandler||(this.stdinErrorHandler=()=>{},subscribeToStdinErrors(this.stdinErrorHandler)),this.rawWrite("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs(),burstWindowMs:resolveBurstWindowMs()}),this.stdinBuffer.on("data",sequence=>{if(this.discardingPrivateResponse)if(sequence.startsWith("\x1B"))this.discardingPrivateResponse=!1;else{/[\x40-\x7e]/.test(sequence)&&(this.discardingPrivateResponse=!1);return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),keyboardEnhancementEnabled()&&((process.env.TMUX!==void 0||process.env.TMUX_PANE!==void 0)&&this.enableModifyOtherKeys(),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer(),this.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY))}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="cursor-position"){if(this.cursorQuery?.issued&&this.cursorQuery.tmuxPane===void 0){let{type:_type,...position}=negotiationSequence;this.settleCursorQuery(position)}return!0}if(negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1}return this.keyboardNegotiationSettled=!0,this.issueCursorQuery(),negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(discardTail=!1){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;if(this.clearKeyboardProtocolNegotiationBuffer(),/^\x1b\[\?[\d;]*$/.test(sequence)){this.discardingPrivateResponse=discardTail;return}this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput(!0)},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(this.rawWrite("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(this.rawWrite("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.settleCursorQuery(void 0),this.stopExternalStderrObservation?.(),this.stopExternalStderrObservation=void 0,this.clearProgressInterval()&&this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.rawWrite("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;if(this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode)try{process.stdin.setRawMode(this.wasRaw)}catch(error){if(!isDeadTerminalError(error))throw error}this.removeExternalStdoutGuard(),this.scheduleStdinErrorHandlerCleanup()}scheduleStdinErrorHandlerCleanup(){if(!this.stdinErrorHandler||this.stdinErrorHandlerCleanupTimer)return;let handler=this.stdinErrorHandler;this.stdinErrorHandlerCleanupTimer=setTimeout(()=>{this.stdinErrorHandlerCleanupTimer=void 0,this.stdinErrorHandler===handler&&(this.stdinErrorHandler=void 0,unsubscribeFromStdinErrors(handler))},STDIN_ERROR_HANDLER_GRACE_MS),this.stdinErrorHandlerCleanupTimer.unref()}write(data){if(this.rawWrite(data),this.writeLogPath)try{fs2.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?this.rawWrite(`\x1B[${lines}B`):lines<0&&this.rawWrite(`\x1B[${-lines}A`)}hideCursor(){this.rawWrite("\x1B[?25l")}showCursor(){this.rawWrite("\x1B[?25h")}clearLine(){this.rawWrite("\x1B[K")}clearFromCursor(){this.rawWrite("\x1B[J")}clearScreen(){this.rawWrite("\x1B[2J\x1B[H")}setTitle(title){let sanitizedTitle=title.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");this.rawWrite(`\x1B]0;${sanitizedTitle}\x07`)}setProgress(active){active?(this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var FAKE_CURSOR_END2="\x1B[7m \x1B[0m";function clampMentions(mentions,length){return mentions.map(range=>({start:Math.max(0,range.start),end:Math.min(length,range.end)})).filter(range=>range.start<range.end)}function cutPoints(length,mentions,cursorGlyph){let cuts=new Set([0,length]);for(let range of mentions)cuts.add(range.start),cuts.add(range.end);return cursorGlyph&&(cuts.add(cursorGlyph.start),cuts.add(cursorGlyph.end)),[...cuts].sort((left,right)=>left-right)}function renderEditorLine(input){let{text,cursor}=input,mentions=clampMentions(input.mentions,text.length),cursorInText=cursor!==void 0&&cursor.pos<text.length,cursorGlyph=cursorInText&&cursor.drawFakeCursor?{start:cursor.pos,end:cursor.pos+input.firstGrapheme(text.slice(cursor.pos)).length}:void 0,points=cutPoints(text.length,mentions,cursorGlyph),out="";for(let index=0;index<points.length-1;index++){let from=points[index]??0,to=points[index+1]??from;cursorInText&&from===cursor.pos&&(out+=cursor.marker);let segment=text.slice(from,to);cursorGlyph&&from===cursorGlyph.start?out+=`\x1B[7m${segment}\x1B[0m`:mentions.some(range=>from>=range.start&&to<=range.end)?out+=input.mentionStyle(segment):out+=segment}return cursor!==void 0&&!cursorInText&&(out+=cursor.marker,cursor.drawFakeCursor)?{text:out+FAKE_CURSOR_END2,cursorAppended:!0}:{text:out,cursorAppended:!1}}var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter4=getWordSegmenter();function isAtomicMarker(segment){return isPasteMarker(segment)||isImageMarker(segment)}function markerKind(segment){if(isPasteMarker(segment))return"paste";if(isImageMarker(segment))return"image"}function containsMarkerPrefix(text){return text.includes("[paste #")||text.includes("[Image #")}function isPrintableAsciiText(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code<32||code>126)return!1}return!0}function wordWrapAsciiLine(line,maxWidth){if(line.length<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],chunkStart=0;for(;chunkStart<line.length;){let chunkEnd=Math.min(line.length,chunkStart+maxWidth);if(chunkEnd<line.length){let breakAt=-1;for(let i=chunkEnd;i>chunkStart;i--){let code=line.charCodeAt(i-1);if(code===32||code===9){breakAt=i-1;break}}breakAt>chunkStart&&(chunkEnd=breakAt)}let raw=line.slice(chunkStart,chunkEnd),text=raw.trimEnd();for((text||chunks.length===0)&&chunks.push({text,startIndex:chunkStart,endIndex:chunkStart+raw.length}),chunkStart=chunkEnd;chunkStart<line.length;){let code=line.charCodeAt(chunkStart);if(code!==32&&code!==9)break;chunkStart++}}return chunks.length>0?chunks:[{text:"",startIndex:0,endIndex:0}]}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(preSegmented===void 0&&!/\s/.test(line)&&!containsMarkerPrefix(line)&&isPrintableAsciiText(line))return wordWrapAsciiLine(line,maxWidth);if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isAtomicMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&¤tWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isAtomicMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isAtomicMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isAtomicMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#","$"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{constructor(tui,theme,options={}){this.state={lines:[""],cursorLine:0,cursorCol:0},this.focused=!1,this.paddingX=0,this.lastWidth=80,this.renderedVisibleLineCount=1,this.renderedAutocompleteHeight=0,this.scrollOffset=0,this.autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS],this.autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters),this.autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters),this.autocompleteState=null,this.autocompletePrefix="",this.autocompleteItems=[],this.autocompleteMaxVisible=5,this.autocompleteRequestTask=Promise.resolve(),this.autocompleteStartToken=0,this.autocompleteRequestId=0,this.pasteMarkers=new PasteMarkerRegistry,this.imageMarkers=new ImageMarkerRegistry,this.pasteBuffer="",this.isInPaste=!1,this.history=[],this.historyIndex=-1,this.historyDraft=null,this.killRing=new KillRing,this.lastAction=null,this.jumpMode=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.undoStack=new UndoStack,this.wrappedLineCache=[],this.disableSubmit=!1,this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0,this.terminalEnvironment=options.terminalEnvironment,this.terminalPlatform=options.terminalPlatform,this.terminalSocketExists=options.terminalSocketExists;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter4:graphemeSegmenter2,this.authorizedMarkers(text))}authorizedMarkers(text){let imageMarkers=this.imageMarkers.authorizedMarkers(text);if(imageMarkers.size===0)return this.pasteMarkers.authorizedMarkers(text);let merged=new Set(this.pasteMarkers.authorizedMarkers(text));for(let marker of imageMarkers)merged.add(marker);return merged}removePasteMarker(id){let removal=this.pasteMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
|
|
109
|
+
`&&isWarpWslSession(env,platform,socketExists)?NATIVE_SHIFT_ENTER_SEQUENCE:data}function keyboardEnhancementEnabled(){let value=process.env.PI_TUI_KEYBOARD_PROTOCOL;return value===void 0?!0:!["0","false","no","off"].includes(value.toLowerCase())}function isDeadTerminalError(error){if(!(error instanceof Error))return!1;if("code"in error&&typeof error.code=="string")return DEAD_TERMINAL_ERROR_CODES.has(error.code);if("errno"in error&&error.errno===EIO_ERRNO)return!0;let messageErrno=ERRNO_IN_MESSAGE_PATTERN.exec(error.message);return messageErrno?DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1],10)):!1}var STDIN_ERROR_HANDLER_GRACE_MS=250,stdinErrorSubscribers=new Set;function isTerminalDetachStdinError(err){if(err.code==="EIO")return!0;let errno=err.errno;return errno===EIO_ERRNO||errno===-EIO_ERRNO}var dispatchStdinError=err=>{if(!isTerminalDetachStdinError(err)){if(!process.stdin.listeners("error").some(listener=>listener!==dispatchStdinError))throw err;return}for(let subscriber of stdinErrorSubscribers)subscriber(err)};function subscribeToStdinErrors(subscriber){stdinErrorSubscribers.size===0&&process.stdin.on("error",dispatchStdinError),stdinErrorSubscribers.add(subscriber)}function unsubscribeFromStdinErrors(subscriber){stdinErrorSubscribers.delete(subscriber),stdinErrorSubscribers.size===0&&process.stdin.removeListener("error",dispatchStdinError)}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100,DEFAULT_BURST_WINDOW_MS2=20,DEFAULT_SSH_BURST_WINDOW_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}function resolveBurstWindowMs(env=process.env){let raw=env.PI_TUI_BURST_WINDOW_MS?.trim();if(raw!==void 0&&raw.length>0){let configured=Number(raw);if(Number.isFinite(configured)&&configured>=0)return configured}return env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_BURST_WINDOW_MS:DEFAULT_BURST_WINDOW_MS2}var ProcessTerminal=class{constructor(options){this.wasRaw=!1,this.externalWriteObservers=new Set,this.keyboardNegotiationSettled=!1,this.cursorQueryTimedOut=!1,this.forwardingExternalWrite=!1,this._kittyProtocolActive=!1,this._modifyOtherKeysActive=!1,this.keyboardProtocolPushed=!1,this.pendingKeyboardProtocolDeviceAttributes=0,this.keyboardProtocolNegotiationBuffer="",this.discardingPrivateResponse=!1,this.writeLogPath=(()=>{let env=process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs2.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path3.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})(),this.onExternalStdoutWrite=options?.onExternalStdoutWrite,this.observeExternalStderrWrites=options?.observeExternalStderrWrites??observeProcessStderrWrites,this.tmuxExecFile=options?.tmuxExecFile}get kittyProtocolActive(){return this._kittyProtocolActive}queryCursorPosition(){if(this.cursorQuery)return this.cursorQuery.promise;if(!this.inputHandler||this.cursorQueryTimedOut)return Promise.resolve(void 0);let resolve,promise=new Promise(settle=>{resolve=settle}),timer=setTimeout(()=>{this.cursorQueryTimedOut=!0,this.settleCursorQuery(void 0)},750);return this.cursorQuery={promise,resolve,timer,issued:!1,tmuxPane:process.env.TMUX_PANE,deadline:Date.now()+750},this.issueCursorQuery(),promise}issueCursorQuery(){if(!this.keyboardNegotiationSettled||!this.cursorQuery||this.cursorQuery.issued)return;this.cursorQuery.issued=!0,this.rawWrite("\x1B[?6n");let pending=this.cursorQuery;pending?.tmuxPane!==void 0&&queryTmuxCursorPosition(pending.tmuxPane,pending.deadline,this.tmuxExecFile).then(position=>{this.cursorQuery===pending&&(Date.now()>=pending.deadline&&(this.cursorQueryTimedOut=!0),this.settleCursorQuery(this.cursorQueryTimedOut?void 0:position))})}settleCursorQuery(position){let pending=this.cursorQuery;pending&&(this.cursorQuery=void 0,clearTimeout(pending.timer),pending.resolve(position))}observeExternalWrites(listener){return this.externalWriteObservers.add(listener),this.inputHandler&&(this.installExternalStdoutGuard(),this.installExternalStderrObserver()),()=>{this.externalWriteObservers.delete(listener)}}noteExternalWrite(){for(let listener of this.externalWriteObservers)listener()}installExternalStderrObserver(){this.stopExternalStderrObservation||this.externalWriteObservers.size===0||(this.stopExternalStderrObservation=this.observeExternalStderrWrites(()=>this.noteExternalWrite()))}rawWrite(data){if(this.rawStdoutWrite){this.rawStdoutWrite(data);return}process.stdout.write(data)}installExternalStdoutGuard(){let handler=this.onExternalStdoutWrite;if(!handler&&this.externalWriteObservers.size===0||this.originalStdoutWrite)return;this.originalStdoutWrite=process.stdout.write;let rawWrite=process.stdout.write.bind(process.stdout);this.rawStdoutWrite=rawWrite,process.stdout.write=((chunk,encodingOrCallback,callback)=>{let cb=typeof encodingOrCallback=="function"?encodingOrCallback:callback,encoding=typeof encodingOrCallback=="string"?encodingOrCallback:void 0,text=typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding);if(!handler||this.forwardingExternalWrite)return this.noteExternalWrite(),rawWrite(text),cb?.(null),!0;this.forwardingExternalWrite=!0;try{handler(text)}catch{this.noteExternalWrite(),rawWrite(text)}finally{this.forwardingExternalWrite=!1}return cb?.(null),!0})}removeExternalStdoutGuard(){this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite,this.originalStdoutWrite=void 0,this.rawStdoutWrite=void 0)}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.installExternalStdoutGuard(),this.installExternalStderrObserver(),this.keyboardNegotiationSettled=!keyboardEnhancementEnabled(),this.cursorQueryTimedOut=!1,this.discardingPrivateResponse=!1,this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),this.stdinErrorHandlerCleanupTimer&&(clearTimeout(this.stdinErrorHandlerCleanupTimer),this.stdinErrorHandlerCleanupTimer=void 0),this.stdinErrorHandler||(this.stdinErrorHandler=()=>{},subscribeToStdinErrors(this.stdinErrorHandler)),this.rawWrite("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs(),burstWindowMs:resolveBurstWindowMs()}),this.stdinBuffer.on("data",sequence=>{if(this.discardingPrivateResponse)if(sequence.startsWith("\x1B"))this.discardingPrivateResponse=!1;else{/[\x40-\x7e]/.test(sequence)&&(this.discardingPrivateResponse=!1);return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),keyboardEnhancementEnabled()&&((process.env.TMUX!==void 0||process.env.TMUX_PANE!==void 0)&&this.enableModifyOtherKeys(),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer(),this.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY))}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="cursor-position"){if(this.cursorQuery?.issued&&this.cursorQuery.tmuxPane===void 0){let{type:_type,...position}=negotiationSequence;this.settleCursorQuery(position)}return!0}if(negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1}return this.keyboardNegotiationSettled=!0,this.issueCursorQuery(),negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(discardTail=!1){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;if(this.clearKeyboardProtocolNegotiationBuffer(),/^\x1b\[\?[\d;]*$/.test(sequence)){this.discardingPrivateResponse=discardTail;return}this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput(!0)},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(this.rawWrite("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(this.rawWrite("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.settleCursorQuery(void 0),this.stopExternalStderrObservation?.(),this.stopExternalStderrObservation=void 0,this.clearProgressInterval()&&this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.rawWrite("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;if(this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode)try{process.stdin.setRawMode(this.wasRaw)}catch(error){if(!isDeadTerminalError(error))throw error}this.removeExternalStdoutGuard(),this.scheduleStdinErrorHandlerCleanup()}scheduleStdinErrorHandlerCleanup(){if(!this.stdinErrorHandler||this.stdinErrorHandlerCleanupTimer)return;let handler=this.stdinErrorHandler;this.stdinErrorHandlerCleanupTimer=setTimeout(()=>{this.stdinErrorHandlerCleanupTimer=void 0,this.stdinErrorHandler===handler&&(this.stdinErrorHandler=void 0,unsubscribeFromStdinErrors(handler))},STDIN_ERROR_HANDLER_GRACE_MS),this.stdinErrorHandlerCleanupTimer.unref()}write(data){if(this.rawWrite(data),this.writeLogPath)try{fs2.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?this.rawWrite(`\x1B[${lines}B`):lines<0&&this.rawWrite(`\x1B[${-lines}A`)}hideCursor(){this.rawWrite("\x1B[?25l")}showCursor(){this.rawWrite("\x1B[?25h")}clearLine(){this.rawWrite("\x1B[K")}clearFromCursor(){this.rawWrite("\x1B[J")}clearScreen(){this.rawWrite("\x1B[2J\x1B[H")}setTitle(title){let sanitizedTitle=title.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");this.rawWrite(`\x1B]0;${sanitizedTitle}\x07`)}setProgress(active){active?(this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var FAKE_CURSOR_END2="\x1B[7m \x1B[0m";function clampMentions(mentions,length){return mentions.map(range=>({start:Math.max(0,range.start),end:Math.min(length,range.end)})).filter(range=>range.start<range.end)}function keywordRangesByLine(lines,runs){let byLine=new Map,lineStart=0;for(let line=0;line<lines.length;line++){let lineEnd=lineStart+(lines[line]?.length??0);for(let run of runs){let start=Math.max(run.start,lineStart),end=Math.min(run.end,lineEnd);if(start>=end)continue;let pieces=byLine.get(line)??[];pieces.push({start:start-lineStart,end:end-lineStart,runStart:run.start-lineStart,runLength:run.end-run.start}),byLine.set(line,pieces)}lineStart=lineEnd+1}return byLine}function styleKeywordSegment(segment,from,range,style){let out="",offset=from;for(let char of segment)out+=style(char,offset-range.runStart,range.runLength),offset+=char.length;return out}function cutPoints(length,mentions,cursorGlyph){let cuts=new Set([0,length]);for(let range of mentions)cuts.add(range.start),cuts.add(range.end);return cursorGlyph&&(cuts.add(cursorGlyph.start),cuts.add(cursorGlyph.end)),[...cuts].sort((left,right)=>left-right)}function renderEditorLine(input){let{text,cursor}=input,mentions=clampMentions(input.mentions,text.length),keywordStyle=input.keywordStyle,keywords=keywordStyle?(input.keywords??[]).filter(range=>Math.max(0,range.start)<Math.min(text.length,range.end)&&!mentions.some(mention=>range.start<mention.end&&mention.start<range.end)):[],cursorInText=cursor!==void 0&&cursor.pos<text.length,cursorGlyph=cursorInText&&cursor.drawFakeCursor?{start:cursor.pos,end:cursor.pos+input.firstGrapheme(text.slice(cursor.pos)).length}:void 0,points=cutPoints(text.length,[...mentions,...clampMentions(keywords,text.length)],cursorGlyph),out="";for(let index=0;index<points.length-1;index++){let from=points[index]??0,to=points[index+1]??from;cursorInText&&from===cursor.pos&&(out+=cursor.marker);let segment=text.slice(from,to);if(cursorGlyph&&from===cursorGlyph.start)out+=`\x1B[7m${segment}\x1B[0m`;else if(mentions.some(range=>from>=range.start&&to<=range.end))out+=input.mentionStyle(segment);else if(keywordStyle){let keyword=keywords.find(range=>from>=range.start&&to<=range.end);out+=keyword?styleKeywordSegment(segment,from,keyword,keywordStyle):segment}else out+=segment}return cursor!==void 0&&!cursorInText&&(out+=cursor.marker,cursor.drawFakeCursor)?{text:out+FAKE_CURSOR_END2,cursorAppended:!0}:{text:out,cursorAppended:!1}}var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter4=getWordSegmenter();function isAtomicMarker(segment){return isPasteMarker(segment)||isImageMarker(segment)}function markerKind(segment){if(isPasteMarker(segment))return"paste";if(isImageMarker(segment))return"image"}function containsMarkerPrefix(text){return text.includes("[paste #")||text.includes("[Image #")}function isPrintableAsciiText(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code<32||code>126)return!1}return!0}function wordWrapAsciiLine(line,maxWidth){if(line.length<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],chunkStart=0;for(;chunkStart<line.length;){let chunkEnd=Math.min(line.length,chunkStart+maxWidth);if(chunkEnd<line.length){let breakAt=-1;for(let i=chunkEnd;i>chunkStart;i--){let code=line.charCodeAt(i-1);if(code===32||code===9){breakAt=i-1;break}}breakAt>chunkStart&&(chunkEnd=breakAt)}let raw=line.slice(chunkStart,chunkEnd),text=raw.trimEnd();for((text||chunks.length===0)&&chunks.push({text,startIndex:chunkStart,endIndex:chunkStart+raw.length}),chunkStart=chunkEnd;chunkStart<line.length;){let code=line.charCodeAt(chunkStart);if(code!==32&&code!==9)break;chunkStart++}}return chunks.length>0?chunks:[{text:"",startIndex:0,endIndex:0}]}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(preSegmented===void 0&&!/\s/.test(line)&&!containsMarkerPrefix(line)&&isPrintableAsciiText(line))return wordWrapAsciiLine(line,maxWidth);if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isAtomicMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&¤tWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isAtomicMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isAtomicMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isAtomicMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#","$"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}(?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{constructor(tui,theme,options={}){this.state={lines:[""],cursorLine:0,cursorCol:0},this.focused=!1,this.paddingX=0,this.lastWidth=80,this.renderedVisibleLineCount=1,this.renderedAutocompleteHeight=0,this.scrollOffset=0,this.autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS],this.autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters),this.autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters),this.autocompleteState=null,this.autocompletePrefix="",this.autocompleteItems=[],this.autocompleteMaxVisible=5,this.autocompleteRequestTask=Promise.resolve(),this.autocompleteStartToken=0,this.autocompleteRequestId=0,this.pasteMarkers=new PasteMarkerRegistry,this.imageMarkers=new ImageMarkerRegistry,this.pasteBuffer="",this.isInPaste=!1,this.history=[],this.historyIndex=-1,this.historyDraft=null,this.killRing=new KillRing,this.lastAction=null,this.jumpMode=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.undoStack=new UndoStack,this.wrappedLineCache=[],this.disableSubmit=!1,this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0,this.terminalEnvironment=options.terminalEnvironment,this.terminalPlatform=options.terminalPlatform,this.terminalSocketExists=options.terminalSocketExists;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter4:graphemeSegmenter2,this.authorizedMarkers(text))}authorizedMarkers(text){let imageMarkers=this.imageMarkers.authorizedMarkers(text);if(imageMarkers.size===0)return this.pasteMarkers.authorizedMarkers(text);let merged=new Set(this.pasteMarkers.authorizedMarkers(text));for(let marker of imageMarkers)merged.add(marker);return merged}removePasteMarker(id){let removal=this.pasteMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
|
|
110
110
|
`),!0):!1}removeImageMarker(id){let survivors=this.imageMarkers.ids(this.getText()).filter(entryId=>entryId!==id),removal=this.imageMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
|
|
111
111
|
`),this.onImageMarkersChanged?.(survivors),!0):!1}removeMarkerSegment(segment){switch(markerKind(segment)){case"paste":{let id=pasteMarkerId(segment);return id!==void 0&&this.removePasteMarker(id)}case"image":{let id=imageMarkerId(segment);return id!==void 0&&this.removeImageMarker(id)}default:return!1}}notifyImageMarkersChanged(){this.onImageMarkersChanged?.(this.imageMarkers.ids(this.getText()))}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
|
|
112
|
-
`);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){this.wrappedLineCache.length=0}getWrappedLine(lineIndex,contentWidth){let line=this.state.lines[lineIndex]||"",cached=this.wrappedLineCache[lineIndex];if(cached&&cached.lineRef===line&&cached.contentWidth===contentWidth)return cached;let width=isPrintableAsciiText(line)?line.length:visibleWidth(line);if(containsMarkerPrefix(line))return{width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")])};let wrapped={lineRef:line,contentWidth,width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth)};return this.wrappedLineCache[lineIndex]=wrapped,wrapped}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let layoutLines=this.layoutText(layoutWidth),terminalRows=this.tui.terminal.rows,maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused,drawFakeCursor=!this.tui.getShowHardwareCursor(),mentionStyle=this.theme.mention,mentionRangesByLine=new Map,mentionRangesFor=layoutLine=>{if(!mentionStyle||!this.autocompleteProvider?.getMentionRanges)return[];let ranges=mentionRangesByLine.get(layoutLine.logicalLine);return ranges===void 0&&(ranges=this.autocompleteProvider.getMentionRanges(this.state.lines[layoutLine.logicalLine]??""),mentionRangesByLine.set(layoutLine.logicalLine,ranges)),ranges.map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex}))};for(let layoutLine of visibleLines){let lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1,cursor=layoutLine.hasCursor&&layoutLine.cursorPos!==void 0?{pos:layoutLine.cursorPos,marker:emitCursorMarker?CURSOR_MARKER:"",drawFakeCursor}:void 0,rendered=renderEditorLine({text:layoutLine.text,mentions:mentionRangesFor(layoutLine),mentionStyle:mentionStyle??(text=>text),cursor,firstGrapheme:text=>[...this.segment(text,"grapheme")][0]?.segment??""}),displayText=rendered.text;rendered.cursorAppended&&(lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0));let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){let lineWidth=visibleWidth(line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.max(1,event.width-paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(data){data=normalizeWarpWslShiftEnterInput(data,this.terminalEnvironment,this.terminalPlatform,this.terminalSocketExists);let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){if(this.isAutocompleteListStale()){this.acceptRefreshedAutocomplete();return}let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),drillsIntoNamespace&&this.tryTriggerAutocomplete()}return}if(kb.matches(data,"tui.select.confirm")){if(!this.autocompletePrefix.startsWith("/")&&this.isAutocompleteListStale()){this.acceptRefreshedAutocomplete();return}let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),drillsIntoNamespace){this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),this.tryTriggerAutocomplete();return}if(this.autocompletePrefix.startsWith("/")){let awaitsArguments=this.autocompleteItems.some(item=>item===selected&&item.awaitsArguments===!0);if(this.cancelAutocomplete(),awaitsArguments){this.onChange&&this.onChange(this.getText());return}}else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&¤tLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
|
|
112
|
+
`);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){this.wrappedLineCache.length=0}getWrappedLine(lineIndex,contentWidth){let line=this.state.lines[lineIndex]||"",cached=this.wrappedLineCache[lineIndex];if(cached&&cached.lineRef===line&&cached.contentWidth===contentWidth)return cached;let width=isPrintableAsciiText(line)?line.length:visibleWidth(line);if(containsMarkerPrefix(line))return{width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")])};let wrapped={lineRef:line,contentWidth,width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth)};return this.wrappedLineCache[lineIndex]=wrapped,wrapped}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}keywordRangesByLine(highlight){let text=this.state.lines.join(`
|
|
113
|
+
`);return this.keywordRunsCache?.text!==text&&(this.keywordRunsCache={text,byLine:keywordRangesByLine(this.state.lines,highlight.find(text))}),this.keywordRunsCache.byLine}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let layoutLines=this.layoutText(layoutWidth),terminalRows=this.tui.terminal.rows,maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused,drawFakeCursor=!this.tui.getShowHardwareCursor(),mentionStyle=this.theme.mention,mentionRangesByLine=new Map,mentionRangesFor=layoutLine=>{if(!mentionStyle||!this.autocompleteProvider?.getMentionRanges)return[];let ranges=mentionRangesByLine.get(layoutLine.logicalLine);return ranges===void 0&&(ranges=this.autocompleteProvider.getMentionRanges(this.state.lines[layoutLine.logicalLine]??""),mentionRangesByLine.set(layoutLine.logicalLine,ranges)),ranges.map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex}))},keywordHighlight=this.theme.keywordHighlight,keywordRangesByLine2=keywordHighlight?this.keywordRangesByLine(keywordHighlight):void 0,keywordRangesFor=layoutLine=>(keywordRangesByLine2?.get(layoutLine.logicalLine)??[]).map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex,runStart:range.runStart-layoutLine.startIndex,runLength:range.runLength}));for(let layoutLine of visibleLines){let lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1,cursor=layoutLine.hasCursor&&layoutLine.cursorPos!==void 0?{pos:layoutLine.cursorPos,marker:emitCursorMarker?CURSOR_MARKER:"",drawFakeCursor}:void 0,rendered=renderEditorLine({text:layoutLine.text,mentions:mentionRangesFor(layoutLine),mentionStyle:mentionStyle??(text=>text),keywords:keywordRangesFor(layoutLine),keywordStyle:keywordHighlight?.style,cursor,firstGrapheme:text=>[...this.segment(text,"grapheme")][0]?.segment??""}),displayText=rendered.text;rendered.cursorAppended&&(lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0));let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){let lineWidth=visibleWidth(line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.max(1,event.width-paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(data){data=normalizeWarpWslShiftEnterInput(data,this.terminalEnvironment,this.terminalPlatform,this.terminalSocketExists);let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){if(this.isAutocompleteListStale()){this.acceptRefreshedAutocomplete();return}let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),drillsIntoNamespace&&this.tryTriggerAutocomplete()}return}if(kb.matches(data,"tui.select.confirm")){if(!this.autocompletePrefix.startsWith("/")&&this.isAutocompleteListStale()){this.acceptRefreshedAutocomplete();return}let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){let drillsIntoNamespace=this.isSlashNamespaceSelection(selected.value);this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),drillsIntoNamespace){this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText()),this.tryTriggerAutocomplete();return}if(this.autocompletePrefix.startsWith("/")){let awaitsArguments=this.autocompleteItems.some(item=>item===selected&&item.awaitsArguments===!0);if(this.cancelAutocomplete(),awaitsArguments){this.onChange&&this.onChange(this.getText());return}}else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&¤tLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
|
|
113
114
|
`&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(kb.matches(data,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(kb.matches(data,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(kb.matches(data,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(kb.matches(data,"tui.editor.pageUp")){this.pageScroll(-1);return}if(kb.matches(data,"tui.editor.pageDown")){this.pageScroll(1);return}if(kb.matches(data,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(matchesKey(data,"shift+space")){this.insertCharacter(" ");return}let printable=decodePrintableKey(data);if(printable!==void 0){this.insertCharacter(printable);return}data.charCodeAt(0)>=32&&this.insertCharacter(data)}layoutText(contentWidth){let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return this.wrappedLineCache.length=this.state.lines.length,layoutLines.push({text:"",hasCursor:!0,cursorPos:0,logicalLine:0,startIndex:0}),layoutLines;for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine,wrappedLine=this.getWrappedLine(i,contentWidth);if(wrappedLine.width<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol,logicalLine:i,startIndex:0}):layoutLines.push({text:line,hasCursor:!1,logicalLine:i,startIndex:0});else{let chunks=wrappedLine.chunks;for(let chunkIndex=0;chunkIndex<chunks.length;chunkIndex++){let chunk=chunks[chunkIndex];if(!chunk)continue;let cursorPos=this.state.cursorCol,isLastChunk=chunkIndex===chunks.length-1,hasCursorInChunk=!1,adjustedCursorPos=0;isCurrentLine&&(isLastChunk?(hasCursorInChunk=cursorPos>=chunk.startIndex,adjustedCursorPos=cursorPos-chunk.startIndex):(hasCursorInChunk=cursorPos>=chunk.startIndex&&cursorPos<chunk.endIndex,hasCursorInChunk&&(adjustedCursorPos=cursorPos-chunk.startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos,logicalLine:i,startIndex:chunk.startIndex}):layoutLines.push({text:chunk.text,hasCursor:!1,logicalLine:i,startIndex:chunk.startIndex})}}}return this.wrappedLineCache.length=this.state.lines.length,layoutLines}getText(){return this.state.lines.join(`
|
|
114
115
|
`)}getExpandedText(){return this.pasteMarkers.expand(this.state.lines.join(`
|
|
115
116
|
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(text){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let normalized=this.normalizeText(text),previousText=this.getText();previousText!==normalized&&this.pushUndoSnapshot(),this.pasteMarkers.prune(normalized,previousText);let previousImageOrder=this.imageMarkers.ids(previousText);this.imageMarkers.prune(normalized,previousText),this.setTextInternal(normalized);let canonicalization=this.imageMarkers.canonicalize(normalized);this.applyCanonicalizedText(canonicalization);let imageOrder=canonicalization.order;(previousImageOrder.length!==imageOrder.length||previousImageOrder.some((id,i)=>id!==imageOrder[i]))&&this.onImageMarkersChanged?.(imageOrder)}getPasteState(){return this.pasteMarkers.snapshot()}setPasteState(state){this.pasteMarkers.install(state,this.getText())}getImageMarkerState(){return this.imageMarkers.snapshot()}setImageMarkerState(state){this.imageMarkers.install(state,this.getText())}insertImageMarker(){this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing();let marker=this.imageMarkers.add();this.insertTextAtCursorInternal(marker);let canonicalization=this.imageMarkers.canonicalize(this.getText());this.applyCanonicalizedText(canonicalization);let insertionId=imageMarkerId(marker),finalId=canonicalization.order.includes(insertionId)?canonicalization.order.indexOf(insertionId)+1:insertionId;return this.onImageMarkersChanged?.(canonicalization.order),finalId}applyCanonicalizedText(canonicalization){if(canonicalization.text===this.getText())return;let oldLine=this.state.lines[this.state.cursorLine]??"",cursorCol=this.state.cursorCol,renumbered=new Map;for(let[index,id]of canonicalization.order.entries())renumbered.set(id,index+1);let delta=0;for(let match of oldLine.matchAll(IMAGE_MARKER_REGEX)){if((match.index??0)+match[0].length>cursorCol)break;let newId=renumbered.get(Number.parseInt(match[1]??"0",10));newId!==void 0&&(delta+=formatImageMarker(newId).length-match[0].length)}this.state.lines=canonicalization.text.split(`
|