@sourcegraph/amp 0.0.1759852911-g557057 → 0.0.1759858678-g356ccd

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.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -5826,7 +5826,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||lO}function l76(J,Q){let
5826
5826
  `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),W;if(d76()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await u76({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}F0();pI();M2();import{homedir as P79}from"node:os";import Nu from"node:path";Sw();u4();ON();I2();O3();r6();k0();function i76(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}F0();ON();import ae8 from"node:fs";import a76 from"node:path";function n76(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!a76.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function r76(J){try{let Q=a76.extname(J).toLowerCase(),Z=vs1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=ae8.readFileSync(J);return ne8(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function ne8(J,Q){if(J.length>YR)return l.warn(`Image file too large: ${J.length} bytes (max: ${YR})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as F56}from"node:child_process";import{rmdir as b19}from"node:fs/promises";import{tmpdir as x19}from"node:os";import H56 from"node:path";ZR();F0();import{spawn as re8}from"node:child_process";import{promises as se8}from"node:fs";function s76(J){return J.kind==="executable"}function o76(J){return J.kind==="markdown"}var WH=50000,t76=300000;async function Tb1(J,Q,Z,X={}){let{timeoutMs:Y=t76,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),o76(q))return await oe8(q,Q);else if(s76(q))return await te8(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function oe8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await se8.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>WH?Z.slice(0,WH)+`
5827
5827
  ... (output truncated at ${WH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function te8(J,Q,Z=t76,X){return new Promise((Y)=>{let[K,q]=ee8(J,Q);l.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=Ps1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),l.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=re8(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=WH)F.push(V);else{let N=WH-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=WH)H.push(V);else{let N=WH-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
5828
5828
  ${L}`:L;if(B>WH)A+=`
5829
- ... (output truncated at ${WH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function ee8(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Q19(Z,X?[...X]:null,Y,Q);else return J19(Z,X?[...X]:null,Y,Q)}function J19(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Q19(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}F0();pI();M2();Sw();u4();aV();iK();lB();r6();k0();import{mkdtemp as y19,readFile as f19,unlink as h19,writeFile as bq2}from"fs/promises";var T41={};L6(T41,{scrollUp:()=>j19,scrollDown:()=>R19,link:()=>T19,image:()=>C19,iTerm:()=>S19,exitAlternativeScreen:()=>$19,eraseUp:()=>O19,eraseStartLine:()=>L19,eraseScreen:()=>Cb1,eraseLines:()=>V19,eraseLine:()=>Z56,eraseEndLine:()=>N19,eraseDown:()=>A19,enterAlternativeScreen:()=>E19,cursorUp:()=>J56,cursorTo:()=>Y19,cursorShow:()=>M19,cursorSavePosition:()=>U19,cursorRestorePosition:()=>W19,cursorPrevLine:()=>B19,cursorNextLine:()=>H19,cursorMove:()=>K19,cursorLeft:()=>Q56,cursorHide:()=>D19,cursorGetPosition:()=>F19,cursorForward:()=>G19,cursorDown:()=>q19,cursorBackward:()=>z19,clearTerminal:()=>I19,clearScreen:()=>w19,beep:()=>P19});import Sb1 from"node:process";var P41=globalThis.window?.document!==void 0,mK2=globalThis.process?.versions?.node!==void 0,uK2=globalThis.process?.versions?.bun!==void 0,pK2=globalThis.Deno?.version?.deno!==void 0,dK2=globalThis.process?.versions?.electron!==void 0,cK2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,lK2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,iK2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,aK2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,nK2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,wm=globalThis.navigator?.userAgentData?.platform,rK2=wm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",sK2=wm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",oK2=wm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",tK2=wm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),eK2=wm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var G2="\x1B[",Em="\x1B]",VT="\x07",Im=";",e76=!P41&&Sb1.env.TERM_PROGRAM==="Apple_Terminal",Z19=!P41&&Sb1.platform==="win32",X19=P41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Sb1.cwd,Y19=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return G2+(J+1)+"G";return G2+(Q+1)+Im+(J+1)+"H"},K19=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=G2+-J+"D";else if(J>0)Z+=G2+J+"C";if(Q<0)Z+=G2+-Q+"A";else if(Q>0)Z+=G2+Q+"B";return Z},J56=(J=1)=>G2+J+"A",q19=(J=1)=>G2+J+"B",G19=(J=1)=>G2+J+"C",z19=(J=1)=>G2+J+"D",Q56=G2+"G",U19=e76?"\x1B7":G2+"s",W19=e76?"\x1B8":G2+"u",F19=G2+"6n",H19=G2+"E",B19=G2+"F",D19=G2+"?25l",M19=G2+"?25h",V19=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=Z56+(Z<J-1?J56():"");if(J)Q+=Q56;return Q},N19=G2+"K",L19=G2+"1K",Z56=G2+"2K",A19=G2+"J",O19=G2+"1J",Cb1=G2+"2J",j19=G2+"S",R19=G2+"T",w19="\x1Bc",I19=Z19?`${Cb1}${G2}0f`:`${Cb1}${G2}3J${G2}H`,E19=G2+"?1049h",$19=G2+"?1049l",P19=VT,T19=(J,Q)=>[Em,"8",Im,Im,Q,VT,J,Em,"8",Im,Im,VT].join(""),C19=(J,Q={})=>{let Z=`${Em}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+VT},S19={setCwd:(J=X19())=>`${Em}50;CurrentDir=${J}${VT}`,annotation(J,Q={}){let Z=`${Em}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+VT}};var C41=n6(U56(),1);function zV(J,Q,{target:Z="stdout",...X}={}){if(!C41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return T41.link(J,Q)}zV.isSupported=C41.default.stdout;zV.stderr=(J,Q,Z={})=>zV(J,Q,{target:"stderr",...Z});zV.stderr.isSupported=C41.default.stderr;F0();iK();class xb1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759852911-g557057"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Pe1(Q)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}F0();class S41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class sZ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function W56(J){if(J instanceof S41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof sZ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var g19={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (r_1(),i26));return(await K({worker:J.worker},{clientId:J.clientId,onUserDisconnect:()=>{Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}})).promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((G)=>{Z.sendStatus({connected:!1,errorMessage:G.message})}),new sZ(`Started connecting to Amp web interface
5829
+ ... (output truncated at ${WH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function ee8(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Q19(Z,X?[...X]:null,Y,Q);else return J19(Z,X?[...X]:null,Y,Q)}function J19(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Q19(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}F0();pI();M2();Sw();u4();aV();iK();lB();r6();k0();import{mkdtemp as y19,readFile as f19,unlink as h19,writeFile as bq2}from"fs/promises";var T41={};L6(T41,{scrollUp:()=>j19,scrollDown:()=>R19,link:()=>T19,image:()=>C19,iTerm:()=>S19,exitAlternativeScreen:()=>$19,eraseUp:()=>O19,eraseStartLine:()=>L19,eraseScreen:()=>Cb1,eraseLines:()=>V19,eraseLine:()=>Z56,eraseEndLine:()=>N19,eraseDown:()=>A19,enterAlternativeScreen:()=>E19,cursorUp:()=>J56,cursorTo:()=>Y19,cursorShow:()=>M19,cursorSavePosition:()=>U19,cursorRestorePosition:()=>W19,cursorPrevLine:()=>B19,cursorNextLine:()=>H19,cursorMove:()=>K19,cursorLeft:()=>Q56,cursorHide:()=>D19,cursorGetPosition:()=>F19,cursorForward:()=>G19,cursorDown:()=>q19,cursorBackward:()=>z19,clearTerminal:()=>I19,clearScreen:()=>w19,beep:()=>P19});import Sb1 from"node:process";var P41=globalThis.window?.document!==void 0,mK2=globalThis.process?.versions?.node!==void 0,uK2=globalThis.process?.versions?.bun!==void 0,pK2=globalThis.Deno?.version?.deno!==void 0,dK2=globalThis.process?.versions?.electron!==void 0,cK2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,lK2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,iK2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,aK2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,nK2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,wm=globalThis.navigator?.userAgentData?.platform,rK2=wm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",sK2=wm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",oK2=wm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",tK2=wm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),eK2=wm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var G2="\x1B[",Em="\x1B]",VT="\x07",Im=";",e76=!P41&&Sb1.env.TERM_PROGRAM==="Apple_Terminal",Z19=!P41&&Sb1.platform==="win32",X19=P41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Sb1.cwd,Y19=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return G2+(J+1)+"G";return G2+(Q+1)+Im+(J+1)+"H"},K19=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=G2+-J+"D";else if(J>0)Z+=G2+J+"C";if(Q<0)Z+=G2+-Q+"A";else if(Q>0)Z+=G2+Q+"B";return Z},J56=(J=1)=>G2+J+"A",q19=(J=1)=>G2+J+"B",G19=(J=1)=>G2+J+"C",z19=(J=1)=>G2+J+"D",Q56=G2+"G",U19=e76?"\x1B7":G2+"s",W19=e76?"\x1B8":G2+"u",F19=G2+"6n",H19=G2+"E",B19=G2+"F",D19=G2+"?25l",M19=G2+"?25h",V19=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=Z56+(Z<J-1?J56():"");if(J)Q+=Q56;return Q},N19=G2+"K",L19=G2+"1K",Z56=G2+"2K",A19=G2+"J",O19=G2+"1J",Cb1=G2+"2J",j19=G2+"S",R19=G2+"T",w19="\x1Bc",I19=Z19?`${Cb1}${G2}0f`:`${Cb1}${G2}3J${G2}H`,E19=G2+"?1049h",$19=G2+"?1049l",P19=VT,T19=(J,Q)=>[Em,"8",Im,Im,Q,VT,J,Em,"8",Im,Im,VT].join(""),C19=(J,Q={})=>{let Z=`${Em}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+VT},S19={setCwd:(J=X19())=>`${Em}50;CurrentDir=${J}${VT}`,annotation(J,Q={}){let Z=`${Em}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+VT}};var C41=n6(U56(),1);function zV(J,Q,{target:Z="stdout",...X}={}){if(!C41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return T41.link(J,Q)}zV.isSupported=C41.default.stdout;zV.stderr=(J,Q,Z={})=>zV(J,Q,{target:"stderr",...Z});zV.stderr.isSupported=C41.default.stderr;F0();iK();class xb1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759858678-g356ccd"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Pe1(Q)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}F0();class S41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class sZ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function W56(J){if(J instanceof S41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof sZ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var g19={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (r_1(),i26));return(await K({worker:J.worker},{clientId:J.clientId,onUserDisconnect:()=>{Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}})).promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((G)=>{Z.sendStatus({connected:!1,errorMessage:G.message})}),new sZ(`Started connecting to Amp web interface
5830
5830
  Client ID: ${Y}
5831
5831
  You can now send messages from the web interface to this thread`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}}};class yb1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=lT()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new xb1(async()=>{try{return(await n8()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),U9.pipe(S0((Q)=>Q.settings["internal.modes"]),$8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...m19},process.env.AMP_CONNECT==="1")Object.assign(this.commands,g19);if(J)Object.assign(this.commands,u19)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{l.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Tb1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var m19={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${ZJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:kX0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new S41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await y19(H56.join(x19(),"amp-edit-")),Y=H56.join(X,"message.amp.md");F56(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await f19(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return l.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await h19(Y),await b19(X)}catch(K){l.warn("Failed to clean up temporary file",K)}return}catch(Z){return l.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return _U("dangerouslyAllowAll",!1),new sZ("Amp is now following permissions rules for this session")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return _U("dangerouslyAllowAll",!0),new sZ("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await DT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw l.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:DT};await I41(Y);return}catch(Y){l.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return l.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new sZ(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return l.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5832
5832
  `).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=Cv(new URL(Y),Z.id).toString(),G=`Thread URL: ${zV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new sZ(`${G}
@@ -5837,7 +5837,7 @@ This thread's visibility has been updated to: ${z}`)}catch(W){let F=W instanceof
5837
5837
  ${Y}`)}catch(Q){return l.error("Failed to get guidance files",Q),Error("Failed to retrieve guidance files")}}},ide:{name:"ide",description:"Connect to an IDE or switch to a different IDE",execute:async(J,Q)=>{if(!J.openIdePicker)return Error("IDE picker is not available in this context");J.openIdePicker();return}},quit:{name:"quit",description:"Exit Amp",execute:async(J,Q)=>{J.exitApp()}}},u19={mode:{name:"mode",description:"Set agent mode - `/mode` shows current, `/mode <mode>` sets mode",requiresArgs:!1,execute:async(J,Q)=>{try{let Z=await n8(),X=Oz(Z.settings),Y=J.getInMemoryAgentModeOverride(),K=Y??X;if(!Q||Q.length===0){let W=KQ1(K),F=Y!==null,H=RC.map((B)=>B.mode).join(", ");return new sZ(`Current mode: ${K}${W?` - ${W}`:""}${F?" (session override)":" (from settings)"}
5838
5838
  Available modes: ${H}`)}let q=Q[0]?.trim();if(!q)return Error("Mode value cannot be empty");let G=q,z=RC.map((W)=>W.mode);if(!ZN.includes(G))return Error(`Invalid mode: ${G}. Valid modes: ${z.join(", ")}`);J.setInMemoryAgentModeOverride(G);let U=KQ1(G);return new sZ(`Mode set to: ${G}${U?` - ${U}`:""} (session override)`)}catch(Z){return l.error("Failed to access agent mode setting",Z),Error("Failed to access agent mode setting")}}}};F0();import p19 from"node:http";class fb1{enabled;interval;server=null;latestSnapshot=null;timer=null;rootElement=null;port=9876;objectToId=new WeakMap;nextId=0;renderObjectToElementMap=new Map;constructor(J=!1,Q=1000){this.enabled=J;this.interval=Q}start(J){if(!this.enabled)return;this.rootElement=J,this.startServer(),this.startPeriodicScan()}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;if(this.server)this.server.close(),this.server=null}startServer(){this.server=p19.createServer((J,Q)=>{if(Q.setHeader("Access-Control-Allow-Origin","*"),Q.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),Q.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),J.method==="OPTIONS"){Q.writeHead(200),Q.end();return}if(J.url==="/widget-tree"&&J.method==="GET"){Q.setHeader("Content-Type","application/json"),Q.writeHead(200),Q.end(JSON.stringify(this.latestSnapshot||{timestamp:Date.now(),rootWidget:null}));return}if(J.url==="/health"&&J.method==="GET"){Q.setHeader("Content-Type","application/json"),Q.writeHead(200),Q.end(JSON.stringify({status:"ok",enabled:this.enabled}));return}Q.writeHead(404),Q.end("Not Found")}),this.server.listen(this.port,"localhost",()=>{l.info(`Widget Tree Debugger running on http://localhost:${this.port}`),l.info(`Widget Tree Data: http://localhost:${this.port}/widget-tree`)}),this.server.on("error",(J)=>{l.error("Widget Tree Debugger server error:",J)})}startPeriodicScan(){this.scanTree(),this.timer=setInterval(()=>{this.scanTree()},this.interval)}scanTree(){if(!this.rootElement)return;try{this.renderObjectToElementMap.clear(),this.buildRenderObjectElementMap(this.rootElement);let J=this.elementToDebugInfo(this.rootElement),Q=this.elementToElementDebugInfo(this.rootElement),Z=this.rootElement.renderObject?this.renderObjectToRenderTreeDebugInfo(this.rootElement.renderObject,this.rootElement):null;this.latestSnapshot={timestamp:Date.now(),rootWidget:J,rootElement:Q,rootRenderObject:Z}}catch(J){l.error("Error scanning trees:",J)}}elementToDebugInfo(J){let Q=this.toId(J),Z=J.widget.constructor.name,X=J.widget.key?String(J.widget.key):void 0,Y=J.depth,K;if(J.renderObject)K=this.renderObjectToDebugInfo(J.renderObject);let q=J.children.map((G)=>this.elementToDebugInfo(G));return{id:Q,type:Z,key:X,depth:Y,renderObject:K,children:q}}elementToElementDebugInfo(J){let Q=this.toId(J),Z=J.constructor.name,X=J.depth,Y=J.dirty,K=J.mounted,q=this.elementToDebugInfo(J),G;if(J.renderObject)G=this.renderObjectToDebugInfo(J.renderObject);let z=J.children.map((U)=>this.elementToElementDebugInfo(U));return{id:Q,type:Z,depth:X,dirty:Y,mounted:K,widget:q,renderObject:G,children:z}}renderObjectToRenderTreeDebugInfo(J,Q){let Z=this.toId(J),X=this.renderObjectToElementMap.get(J),Y=X?this.toId(X):void 0,K=J.constructor.name,q={},G=!1,z=!1,U=void 0,W=void 0,F=void 0,H=void 0;if(Q)H=this.getDebugData(Q,J);else{let M=this.renderObjectToElementMap.get(J);if(M)H=this.getDebugData(M,J);else if("debugData"in J){let V=J.debugData;if(V&&Object.keys(V).length>0)H=V}}try{if("needsLayout"in J)G=J.needsLayout;if("needsPaint"in J)z=J.needsPaint;if("size"in J)W=J.size;if("_lastConstraints"in J)U=J._lastConstraints;if("offset"in J){let V=J.offset;if(V&&typeof V==="object"&&"x"in V&&"y"in V)F={x:V.x,y:V.y}}let M=Object.getOwnPropertyNames(J);for(let V of M)if(!V.startsWith("_")&&V!=="constructor"&&!["needsLayout","needsPaint","size","constraints","offset"].includes(V))try{let N=J[V];if(typeof N!=="function"&&typeof N!=="object")q[V]=N}catch{}}catch(M){q.error=`Failed to extract properties: ${M}`}let B=[];try{if("children"in J&&Array.isArray(J.children)){let M=J.children;for(let V of M)B.push(this.renderObjectToRenderTreeDebugInfo(V))}}catch{}return{id:Z,type:K,constraints:U,size:W,offset:F,needsLayout:G,needsPaint:z,properties:q,debugData:H,elementId:Y,children:B}}renderObjectToDebugInfo(J){let Q=J.constructor.name,Z={};try{if("size"in J)Z.size=J.size;if("constraints"in J)Z.constraints=J.constraints;if("offset"in J)Z.offset=J.offset;let X=Object.getOwnPropertyNames(J);for(let Y of X)if(!Y.startsWith("_")&&Y!=="constructor")try{let K=J[Y];if(typeof K!=="function")Z[Y]=K}catch{}}catch(X){Z.error=`Failed to extract properties: ${X}`}return{type:Q,properties:Z}}getLatestSnapshot(){return this.latestSnapshot}forceScan(){this.scanTree()}buildRenderObjectElementMap(J){if(J.renderObject)this.renderObjectToElementMap.set(J.renderObject,J);for(let Q of J.children)this.buildRenderObjectElementMap(Q)}toId(J){let Q=this.objectToId.get(J);if(Q===void 0)Q=`inspector-${this.nextId++}`,this.objectToId.set(J,Q);return Q}getDebugData(J,Q){let Z={};if("debugData"in J.widget){let Y=J.widget.debugData;if(Y&&Object.keys(Y).length>0)Z={...Z,...Y}}let X=Q||J.renderObject;if(X&&"debugData"in X){let Y=X.debugData;if(Y&&Object.keys(Y).length>0)Z={...Z,...Y}}return Object.keys(Z).length>0?Z:void 0}}F0();function hb1(){let J=d19();if(J)return J;let Q=c19();if(Q)return{...Q,pixelWidth:0,pixelHeight:0};return null}function d19(){try{let J=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Q=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),X=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Q)({ws_row:Q.types.ushort,ws_col:Q.types.ushort,ws_xpixel:Q.types.ushort,ws_ypixel:Q.types.ushort}),Y=J.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),K=process.platform==="darwin"?1074295912:21523,q=new X;if(Y.ioctl(process.stdout.fd,K,q.ref())===0)return{rows:q.ws_row,columns:q.ws_col,pixelWidth:q.ws_xpixel,pixelHeight:q.ws_ypixel};return null}catch(J){return null}}function c19(){try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows)return{columns:process.stdout.columns,rows:process.stdout.rows};let J=process.stdin;if(process.stdin.isTTY&&J.columns&&J.rows)return{columns:J.columns,rows:J.rows};let Q=process.stdout;if(typeof Q.getWindowSize==="function"){let Z=Q.getWindowSize();if(Z[0]>0&&Z[1]>0)return{columns:Z[0],rows:Z[1]}}return null}catch(J){return null}}function $m(J){return{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,scrollStep:()=>3,...J}}var B56=[{sequence:"\x1B[?2026$p",description:"Query synchronized output support"},{sequence:"\x1B[?2027$p",description:"Query emoji width mode support"},{sequence:"\x1B[?1016$p",description:"Query pixel mouse mode support"},{sequence:"\x1B[?u",description:"Query Kitty keyboard protocol support"},{sequence:"\x1B[>0q",description:"Query terminal version (XTVERSION)"},{sequence:"\x1BP+q4d73\x1B\\",description:"Query OSC 52 clipboard support (XTGETTCAP Ms)"},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}];class v41{capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,scrollStep:()=>this.getScrollStep()};complete=!1;inbandPixelData=null;processDecrqss(J,Q){if(J==="?2026")this.capabilities.syncOutput=Q==="1"||Q==="2";if(J==="?2027")this.capabilities.emojiWidth=Q==="1"||Q==="2";if(J==="?1016")this.capabilities.pixelMouse=Q==="1"||Q==="2";if(J==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(J,Q){if(this.checkPixelDimensions(),this.detectJetBrains())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(J){return this.capabilities.xtversion=J,!1}processXtgettcap(J,Q){if(J.toLowerCase()==="4d73")this.capabilities.osc52=Q.length>0;return!1}updateInbandPixelData(J,Q,Z,X){if(Z&&X&&Z>0&&X>0)this.inbandPixelData={pixelWidth:Z,pixelHeight:X,columns:J,rows:Q},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let J=hb1();this.capabilities.pixelDimensions=!!(J&&J.pixelWidth>0&&J.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let J=hb1();if(J&&J.pixelWidth>0&&J.pixelHeight>0)return{pixelWidth:J.pixelWidth,pixelHeight:J.pixelHeight,columns:J.columns,rows:J.rows};return null}getPendingQueries(){return this.complete?[]:["\x1B[c"]}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.detectEmacs())return"disabled";if(this.detectSSH()||this.detectJetBrains())return"slow";return"fast"}detectEmacs(){return!!process.env.INSIDE_EMACS}detectJetBrains(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}detectSSH(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if(UG())return 1;return 3}}F0();import{execFile as _41}from"node:child_process";import{platform as gb1}from"node:os";import{promisify as l19}from"node:util";var k41=l19(_41),i19=(J)=>`\x1B]52;c;${J}\x1B\\`,a19="\x1B]52;c;?\x1B\\",n19="\x1B]52;p;?\x1B\\";class D56{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await k41("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=_41("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=_41("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=_41("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(a19)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await k41("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await k41("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await k41("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(n19)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(gb1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(gb1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=i19(Z);process.stdout.write(X);return}if(gb1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var WG=new D56;function r19(J){let Q=(J&4)!==0,Z=(J&8)!==0,X=(J&16)!==0,Y=(J&32)!==0,K=J&-61,q="unknown";switch(K){case 0:q="left";break;case 1:q="middle";break;case 2:q="right";break;case 64:q="wheel_up";break;case 65:q="wheel_down";break;default:q="unknown";break}return{button:q,modifiers:{shift:Q,ctrl:X,alt:Z,meta:!1},motion:Y}}function Pm(J,Q,Z,X){let Y=r19(J.button),K;if(Y.button==="wheel_up"||Y.button==="wheel_down")K="scroll";else if(Y.motion)K="move";else if(J.pressed)K="press";else K="release";let q,G;if(Q&&Z&&X)q=(J.x-1)/Z,G=(J.y-1)/X;else q=J.x-1,G=J.y-1;return{type:"mouse",action:K,button:Y.button,x:q,y:G,modifiers:Y.modifiers,drag:Y.motion&&J.pressed}}var D5={DEFAULT:"default",POINTER:"pointer",TEXT:"text",WAIT:"wait",CROSSHAIR:"crosshair",HELP:"help",MOVE:"move",NOT_ALLOWED:"not-allowed",PROGRESS:"progress",CELL:"cell",CONTEXT_MENU:"context-menu",COPY:"copy",ALIAS:"alias",ZOOM_IN:"zoom-in",ZOOM_OUT:"zoom-out",GRAB:"grab",GRABBING:"grabbing",N_RESIZE:"n-resize",S_RESIZE:"s-resize",E_RESIZE:"e-resize",W_RESIZE:"w-resize",NE_RESIZE:"ne-resize",NW_RESIZE:"nw-resize",SE_RESIZE:"se-resize",SW_RESIZE:"sw-resize",COL_RESIZE:"col-resize",ROW_RESIZE:"row-resize"};var Tm=4,b1={default(J){return J!==void 0?{type:"default",alpha:J}:{type:"default"}},index(J,Q){return Q!==void 0?{type:"index",value:J,alpha:Q}:{type:"index",value:J}},rgb(J,Q,Z,X){return X!==void 0?{type:"rgb",value:{r:J,g:Q,b:Z},alpha:X}:{type:"rgb",value:{r:J,g:Q,b:Z}}},transparent(){return{type:"default",alpha:0}},black:{type:"index",value:0},red:{type:"index",value:1},green:{type:"index",value:2},yellow:{type:"index",value:3},blue:{type:"index",value:4},magenta:{type:"index",value:5},cyan:{type:"index",value:6},white:{type:"index",value:7},brightWhite:{type:"index",value:15}};function N9(J=" ",Q={},Z=1,X){return{char:J,style:{...Q},width:Z,hyperlink:X}}var FH=N9(" ",{});function s19(J,Q){return J.char===Q.char&&J.width===Q.width&&o19(J.style,Q.style)&&b41(J.hyperlink,Q.hyperlink)}function o19(J,Q){return M56(J.fg,Q.fg)&&M56(J.bg,Q.bg)&&J.bold===Q.bold&&J.italic===Q.italic&&J.underline===Q.underline&&J.strikethrough===Q.strikethrough&&J.reverse===Q.reverse&&J.dim===Q.dim}function b41(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;return J.uri===Q.uri&&J.id===Q.id}function M56(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;if(J.type!==Q.type)return!1;if(J.alpha!==Q.alpha)return!1;switch(J.type){case"default":return!0;case"index":return Q.value===J.value;case"rgb":{let Z=Q.value;return Z.r===J.value.r&&Z.g===J.value.g&&Z.b===J.value.b}default:return!1}}function V56(J){switch(J.type){case"rgb":return J.value;case"index":return{0:{r:0,g:0,b:0},1:{r:128,g:0,b:0},2:{r:0,g:128,b:0},3:{r:128,g:128,b:0},4:{r:0,g:0,b:128},5:{r:128,g:0,b:128},6:{r:0,g:128,b:128},7:{r:192,g:192,b:192},8:{r:128,g:128,b:128},9:{r:255,g:0,b:0},10:{r:0,g:255,b:0},11:{r:255,g:255,b:0},12:{r:0,g:0,b:255},13:{r:255,g:0,b:255},14:{r:0,g:255,b:255},15:{r:255,g:255,b:255}}[J.value]||{r:128,g:128,b:128};case"default":return null;default:return null}}function N56(J,Q){let Z=J.alpha??1;if(Z>=1)return J;if(Z<=0)return Q;let X=V56(J),Y=V56(Q);if(!X||!Y)return Z>0.5?J:Q;let K=Math.round(X.r*Z+Y.r*(1-Z)),q=Math.round(X.g*Z+Y.g*(1-Z)),G=Math.round(X.b*Z+Y.b*(1-Z));return{type:"rgb",value:{r:Math.max(0,Math.min(255,K)),g:Math.max(0,Math.min(255,q)),b:Math.max(0,Math.min(255,G))}}}function t19(J,Q){let Z={...Q};if(J.fg)if(Q.fg)Z.fg=N56(J.fg,Q.fg);else Z.fg=J.fg;if(J.bg)if(J.bg.alpha===0){if(Q.bg)Z.bg=Q.bg}else if(Q.bg)Z.bg=N56(J.bg,Q.bg);else Z.bg=J.bg;if(J.bold!==void 0)Z.bold=J.bold;if(J.italic!==void 0)Z.italic=J.italic;if(J.underline!==void 0)Z.underline=J.underline;if(J.strikethrough!==void 0)Z.strikethrough=J.strikethrough;if(J.reverse!==void 0)Z.reverse=J.reverse;if(J.dim!==void 0)Z.dim=J.dim;return Z}class mb1{cells;width;height;constructor(J,Q){this.width=J,this.height=Q,this.cells=[],this.resize(J,Q)}getSize(){return{width:this.width,height:this.height}}resize(J,Q){this.width=J,this.height=Q,this.cells=Array(Q).fill(null).map(()=>Array(J).fill(null).map(()=>FH))}getCell(J,Q){if(J<0||J>=this.width||Q<0||Q>=this.height)return null;return this.cells[Q]?.[J]||null}setCell(J,Q,Z){if(J<0||J>=this.width||Q<0||Q>=this.height)return;if(Z.style.fg&&Z.style.fg.alpha!==void 0&&Z.style.fg.alpha<1||Z.style.bg&&Z.style.bg.alpha!==void 0&&Z.style.bg.alpha<1){let Y=this.cells[Q]?.[J]||FH,K=t19(Z.style,Y.style);if(this.cells[Q])this.cells[Q][J]={char:Z.char,style:K,width:Z.width}}else if(this.cells[Q])this.cells[Q][J]={...Z,style:{...Z.style}};if(Z.width>1){for(let Y=1;Y<Z.width;Y++)if(J+Y<this.width&&this.cells[Q])this.cells[Q][J+Y]=FH}}setChar(J,Q,Z,X,Y){this.setCell(J,Q,N9(Z,X,Y))}clear(){for(let J=0;J<this.height;J++)for(let Q=0;Q<this.width;Q++){let Z=this.cells[J];if(Z)Z[Q]=FH}}fill(J,Q,Z,X,Y=" ",K={}){let q=N9(Y,K);for(let G=0;G<X;G++)for(let z=0;z<Z;z++)this.setCell(J+z,Q+G,q)}copyTo(J){let{width:Q,height:Z}=J.getSize();for(let X=0;X<Math.min(this.height,Z);X++)for(let Y=0;Y<Math.min(this.width,Q);Y++){let K=this.getCell(Y,X);if(K)J.setCell(Y,X,K)}}getCells(){return this.cells.map((J)=>J.map((Q)=>({...Q,style:{...Q.style}})))}setCursor(J,Q){}clearCursor(){}setCursorShape(J){}markForRefresh(){}}class Cm{frontBuffer;backBuffer;width;height;needsFullRefresh=!1;cursorPosition=null;cursorVisible=!1;cursorShape=0;constructor(J=80,Q=24){this.width=J,this.height=Q,this.frontBuffer=new mb1(J,Q),this.backBuffer=new mb1(J,Q)}getSize(){return{width:this.width,height:this.height}}resize(J,Q){this.width=J,this.height=Q,this.frontBuffer.resize(J,Q),this.backBuffer.resize(J,Q)}getBuffer(){return this.backBuffer}getCell(J,Q){return this.backBuffer.getCell(J,Q)}setCell(J,Q,Z){this.backBuffer.setCell(J,Q,Z)}setChar(J,Q,Z,X,Y){this.backBuffer.setChar(J,Q,Z,X,Y)}clear(){this.backBuffer.clear()}fill(J,Q,Z,X,Y=" ",K={}){this.backBuffer.fill(J,Q,Z,X,Y,K)}present(){let J=this.frontBuffer;this.frontBuffer=this.backBuffer,this.backBuffer=J,this.processWideCharacters()}processWideCharacters(){for(let J=0;J<this.height;J++)for(let Q=0;Q<this.width;Q++){let Z=this.frontBuffer.getCell(Q,J);if(Z&&Z.width>1){for(let X=1;X<Z.width;X++)if(Q+X<this.width)this.frontBuffer.setCell(Q+X,J,FH)}}}getDiff(){let J=[];if(this.needsFullRefresh){for(let Q=0;Q<this.height;Q++)for(let Z=0;Z<this.width;Z++){let X=this.backBuffer.getCell(Z,Q);if(J.push({x:Z,y:Q,cell:X||FH}),X&&X.width>1)Z+=X.width-1}return this.needsFullRefresh=!1,J}for(let Q=0;Q<this.height;Q++)for(let Z=0;Z<this.width;Z++){let X=this.frontBuffer.getCell(Z,Q),Y=this.backBuffer.getCell(Z,Q);if(X===FH&&Y===FH)continue;if(!X||!Y||!s19(X,Y)){if(J.push({x:Z,y:Q,cell:Y||FH}),Y&&(Y.char.length>1||/[\u{1F000}-\u{1FFFF}]/u.test(Y.char)));if(Y&&Y.width>1)Z+=Y.width-1}else if(Y.char.length>1||/[\u{1F000}-\u{1FFFF}]/u.test(Y.char)){if(Y.width>1)Z+=Y.width-1}}return J}getFrontBuffer(){return this.frontBuffer}getBackBuffer(){return this.backBuffer}markForRefresh(){this.needsFullRefresh=!0}setCursor(J,Q){this.cursorPosition={x:J,y:Q},this.cursorVisible=!0}clearCursor(){this.cursorPosition=null,this.cursorVisible=!1}getCursor(){return this.cursorPosition}isCursorVisible(){return this.cursorVisible}setCursorShape(J){this.cursorShape=J}getCursorShape(){return this.cursorShape}}var e19=0;function J09(){return`amp-${++e19}`}function L56(J,Q){return{uri:J,id:Q??J09()}}function A56(J){return`\x1B]8;id=${J.id};${J.uri}\x1B\\`}function x41(){return"\x1B]8;;\x1B\\"}var O56=new Map;function Q09(J){return/\p{Extended_Pictographic}/u.test(J)}function Z09(J){return J>=9632&&J<=9727||J>=9728&&J<=9983&&!(J>=9728&&J<=9983&&(J===9728||J===9729||J===9889||J===10052||J===9924||J===9925))||J>=8592&&J<=8703||J===10006}function X09(J){return/\p{M}/u.test(J)}function Y09(J,Q=!0){if(!J)return 0;let Z=Array.from(J);if(Q){let X=0;for(let Y=0;Y<Z.length;Y++){let K=Z[Y];if(!K)continue;let q=K.codePointAt(0);if(!q)continue;let G=j56(q);if(G!==0){if(Y+1<Z.length){let U=Z[Y+1]?.codePointAt(0);if(U===65038)G=1;else if(U===65039)G=2}if(X===0){X=G;break}}}return X}else{let X=0;for(let Y of Z){if(!Y)continue;let K=Y.codePointAt(0);if(!K)continue;X+=j56(K)}return X}}function j56(J){if(J===9)return Tm;if(X09(String.fromCodePoint(J))||J===8205||J>=65024&&J<=65039||J>=917760&&J<=917999||J>=127995&&J<=127999)return 0;if(K09(J)){if(Z09(J))return 1;return 2}if(q09(J))return 2;return 1}function K09(J){let Q=String.fromCodePoint(J);return Q09(Q)}function q09(J){return J>=19968&&J<=40959||J>=13312&&J<=19903||J>=131072&&J<=173791||J>=173824&&J<=177983||J>=177984&&J<=178207||J>=178208&&J<=183983||J>=183984&&J<=191471||J>=44032&&J<=55215||J>=12352&&J<=12447||J>=12448&&J<=12543||J>=12784&&J<=12799||J>=65280&&J<=65519||J>=12288&&J<=12351||J>=65281&&J<=65376||J===9001||J===9002||J>=127462&&J<=127487}function y4(J,Q=!0){let Z=O56.get(J);if(Z!==void 0)return Z;let X=Y09(J,Q);return O56.set(J,X),X}var ub1=null;function O2(J){try{if(!ub1)ub1=new Intl.Segmenter("en",{granularity:"grapheme"});return Array.from(ub1.segment(J),(Q)=>Q.segment)}catch(Q){return Array.from(J)}}function sX(J,Q=!0){let Z=0,X=O2(J);for(let Y of X)Z+=y4(Y,Q);return Z}function pb1(J,Q,Z=!0,X="…"){if(Q<=0)return"";let Y=0,K="",q=O2(J);for(let G of q){let z=y4(G,Z);if(Y+z>Q){let U=sX(X,Z);if(Y+U<=Q)K+=X;break}K+=G,Y+=z}return K}var LT={ground:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"ground",action:"execute"}])),...Object.fromEntries(Array.from({length:95},(J,Q)=>[Q+32,{nextState:"ground",action:"print"}])),127:{nextState:"ground",action:"execute"},...Object.fromEntries(Array.from({length:128},(J,Q)=>[Q+128,{nextState:"ground",action:"print"}])),27:{nextState:"escape",action:"clear"}},escape:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"escape",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"esc_dispatch"}])),91:{nextState:"csi_entry",action:"clear"},80:{nextState:"dcs_entry",action:"clear"},93:{nextState:"osc_string",action:"osc_start"},88:{nextState:"sos_pm_apc_string",action:"ignore"},94:{nextState:"sos_pm_apc_string",action:"ignore"},95:{nextState:"sos_pm_apc_string",action:"ignore"},79:{nextState:"escape_intermediate",action:"collect"},127:{nextState:"ground",action:"esc_dispatch"}},escape_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"escape_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"escape_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"esc_dispatch"}])),127:{nextState:"escape_intermediate",action:"ignore"}},csi_entry:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_entry",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"csi_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"csi_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_entry",action:"ignore"}},csi_param:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_param",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"csi_param",action:"param"}])),58:{nextState:"csi_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_param",action:"ignore"}},csi_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_intermediate",action:"execute"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"csi_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"csi_dispatch"}])),127:{nextState:"csi_intermediate",action:"ignore"}},csi_ignore:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"csi_ignore",action:"execute"}])),...Object.fromEntries(Array.from({length:64},(J,Q)=>[Q+32,{nextState:"csi_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"ground",action:"ignore"}])),127:{nextState:"csi_ignore",action:"ignore"}},dcs_entry:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"dcs_entry",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"dcs_param",action:"param"}])),...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"dcs_param",action:"collect"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_entry",action:"ignore"}},dcs_param:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"dcs_param",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"dcs_param",action:"param"}])),58:{nextState:"dcs_param",action:"param"},...Object.fromEntries(Array.from({length:4},(J,Q)=>[Q+60,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_param",action:"ignore"}},dcs_intermediate:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"dcs_intermediate",action:"ignore"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+32,{nextState:"dcs_intermediate",action:"collect"}])),...Object.fromEntries(Array.from({length:16},(J,Q)=>[Q+48,{nextState:"dcs_ignore",action:"ignore"}])),...Object.fromEntries(Array.from({length:63},(J,Q)=>[Q+64,{nextState:"dcs_passthrough",action:"hook"}])),127:{nextState:"dcs_intermediate",action:"ignore"}},dcs_passthrough:{156:{nextState:"ground",action:"unhook"},27:{nextState:"ground",action:"unhook"},...Object.fromEntries(Array.from({length:256},(J,Q)=>{if(Q===156||Q===27)return[Q,void 0];return[Q,{nextState:"dcs_passthrough",action:"put"}]}).filter(([,J])=>J!==void 0))},dcs_ignore:{...Object.fromEntries(Array.from({length:256},(J,Q)=>[Q,{nextState:"dcs_ignore",action:"ignore"}])),156:{nextState:"ground",action:"ignore"},27:{nextState:"escape",action:"clear"}},osc_string:{...Object.fromEntries(Array.from({length:32},(J,Q)=>[Q,{nextState:"osc_string",action:"ignore"}])),...Object.fromEntries(Array.from({length:128},(J,Q)=>[Q+32,{nextState:"osc_string",action:"osc_put"}])),7:{nextState:"ground",action:"osc_end"},156:{nextState:"ground",action:"osc_end"},27:{nextState:"escape",action:"clear"}},sos_pm_apc_string:{...Object.fromEntries(Array.from({length:256},(J,Q)=>[Q,{nextState:"sos_pm_apc_string",action:"ignore"}])),156:{nextState:"ground",action:"ignore"},27:{nextState:"escape",action:"clear"}}},R56={24:{nextState:"ground",action:"execute"},26:{nextState:"ground",action:"execute"},27:{nextState:"escape",action:"clear"}};Object.keys(LT).forEach((J)=>{let Q=J;if(Q==="dcs_passthrough"){let{27:Z,...X}=R56;Object.assign(LT[Q],X)}else Object.assign(LT[Q],R56)});class Sm{context;eventHandlers=[];constructor(){this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,dcsEscSeen:!1}}onEvent(J){this.eventHandlers.push(J)}offEvent(J){let Q=this.eventHandlers.indexOf(J);if(Q!==-1)this.eventHandlers.splice(Q,1)}parse(J){let Q=typeof J==="string"?this.stringToBytes(J):J;for(let Z of Q)this.processByte(Z)}flush(){this.flushPrintBuffer(),this.flushTextBuffer()}stringToBytes(J){return new TextEncoder().encode(J)}processByte(J){if(this.context.state==="osc_string"&&J===27){this.context.oscEscSeen=!0;return}if(this.context.oscEscSeen&&J===92){this.context.oscEscSeen=!1,this.performAction("osc_end",J),this.context.state="ground";return}if(this.context.oscEscSeen){this.context.oscEscSeen=!1,this.performAction("clear",27),this.context.state="escape";let Z=LT["escape"][J];if(Z)this.performAction(Z.action,J),this.context.state=Z.nextState;return}let Q=LT[this.context.state][J];if(!Q)return;if(this.performAction(Q.action,J),this.context.state==="ground"&&Q.nextState!=="ground")this.flushTextBuffer();this.context.state=Q.nextState}performAction(J,Q){if(this.context.dcsEscSeen&&Q===92){this.context.dcsEscSeen=!1;return}if(this.context.dcsEscSeen)this.context.dcsEscSeen=!1;switch(J){case"ignore":break;case"print":this.addToPrintBuffer(Q);break;case"execute":this.flushTextBuffer(),this.emitEvent({type:"execute",code:Q});break;case"clear":this.flushTextBuffer(),this.context.private.length=0,this.context.intermediates.length=0,this.context.final="",this.context.params=[],this.context.oscEscSeen=!1,this.context.paramBuffer.length=0,this.context.subparamBuffer.length=0,this.context.currentSubparams=[],this.context.oscData.length=0,this.context.dcsData.length=0;break;case"collect":if(Q>=60&&Q<=63)this.context.private.push(String.fromCharCode(Q));else this.context.intermediates.push(String.fromCharCode(Q));break;case"param":if(Q>=48&&Q<=57)if(this.context.currentSubparams.length>0)this.context.subparamBuffer.push(String.fromCharCode(Q));else this.context.paramBuffer.push(String.fromCharCode(Q));else if(Q===59)this.finishParameter();else if(Q===58)this.finishSubparameter();break;case"esc_dispatch":this.emitEvent({type:"escape",intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Q)});break;case"csi_dispatch":this.finishParameter(),this.emitEvent({type:"csi",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:String.fromCharCode(Q),params:[...this.context.params]});break;case"hook":this.finishParameter(),this.context.dcsData.length=0,this.context.final=String.fromCharCode(Q);break;case"put":this.context.dcsData.push(String.fromCharCode(Q));break;case"unhook":this.emitEvent({type:"dcs",private:this.context.private.join(""),intermediates:this.context.intermediates.join(""),final:this.context.final,params:[...this.context.params],data:this.context.dcsData.join("")}),this.context.dcsEscSeen=Q===27;break;case"osc_start":this.context.oscData.length=0,this.context.oscEscSeen=!1;break;case"osc_put":this.context.oscData.push(String.fromCharCode(Q));break;case"osc_end":this.emitEvent({type:"osc",data:this.context.oscData.join("")});break}}finishSubparameter(){if(this.context.currentSubparams.length===0)if(this.context.paramBuffer.length>0){let J=parseInt(this.context.paramBuffer.join(""),10);this.context.currentSubparams.push(isNaN(J)?0:J),this.context.paramBuffer.length=0}else this.context.currentSubparams.push(0);else if(this.context.subparamBuffer.length>0){let J=parseInt(this.context.subparamBuffer.join(""),10);this.context.currentSubparams.push(isNaN(J)?0:J),this.context.subparamBuffer.length=0}else this.context.currentSubparams.push(0)}finishParameter(){if(this.context.currentSubparams.length>0){this.finishSubparameter();let[J,...Q]=this.context.currentSubparams,Z={value:J??0};if(Q.length>0)Z.subparams=Q;this.context.params.push(Z),this.context.currentSubparams=[]}else if(this.context.paramBuffer.length>0){let J=parseInt(this.context.paramBuffer.join(""),10);this.context.params.push({value:isNaN(J)?0:J}),this.context.paramBuffer.length=0}else this.context.params.push({value:0})}addToPrintBuffer(J){this.context.printBuffer.push(J),this.tryEmitGraphemes()}tryEmitAccumulatedGraphemes(){if(this.context.textBuffer.length>1000){this.flushTextBuffer();return}if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout);this.context.flushTimeout=setTimeout(()=>{if(this.context.textBuffer.length>0)this.flushTextBuffer()},1)}tryEmitGraphemes(){if(this.context.printBuffer.length===0)return;let J=0,Q=this.context.printBuffer;for(let Z=0;Z<Q.length;Z++){let X=Q[Z];if(X===void 0)continue;if(X<128)J=Z+1;else if((X&224)===192){let Y=Q[Z+1];if(Z+1<Q.length&&Y!==void 0&&(Y&192)===128)J=Z+2,Z++;else break}else if((X&240)===224){let Y=Q[Z+1],K=Q[Z+2];if(Z+2<Q.length&&Y!==void 0&&(Y&192)===128&&K!==void 0&&(K&192)===128)J=Z+3,Z+=2;else break}else if((X&248)===240){let Y=Q[Z+1],K=Q[Z+2],q=Q[Z+3];if(Z+3<Q.length&&Y!==void 0&&(Y&192)===128&&K!==void 0&&(K&192)===128&&q!==void 0&&(q&192)===128)J=Z+4,Z+=3;else break}else if((X&192)===128){this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Z+1),this.tryEmitGraphemes();return}else{this.emitEvent({type:"print",grapheme:"�"}),this.context.printBuffer.splice(0,Z+1),this.tryEmitGraphemes();return}}if(J>0){let Z=new Uint8Array(Q.slice(0,J)),Y=new TextDecoder("utf-8",{fatal:!1}).decode(Z);if(this.context.textBuffer+=Y,this.tryEmitAccumulatedGraphemes(),this.context.printBuffer.splice(0,J),this.context.printBuffer.length>0)this.tryEmitGraphemes()}}flushPrintBuffer(){if(this.context.printBuffer.length>0){let J=new Uint8Array(this.context.printBuffer),Z=new TextDecoder("utf-8",{fatal:!1}).decode(J);if(Z.length>0)this.context.textBuffer+=Z}this.context.printBuffer=[]}flushTextBuffer(){if(this.context.flushTimeout)clearTimeout(this.context.flushTimeout),delete this.context.flushTimeout;if(this.context.textBuffer.length>0){let J=O2(this.context.textBuffer);for(let Q of J)this.emitEvent({type:"print",grapheme:Q});this.context.textBuffer=""}}emitEvent(J){for(let Q of this.eventHandlers)Q(J)}reset(){this.flushPrintBuffer(),this.flushTextBuffer(),this.context={state:"ground",private:[],intermediates:[],final:"",params:[],paramBuffer:[],subparamBuffer:[],currentSubparams:[],oscData:[],dcsData:[],printBuffer:[],textBuffer:"",oscEscSeen:!1,dcsEscSeen:!1}}getState(){return this.context.state}}var w56={57348:"Insert",57349:"Delete",57350:"ArrowLeft",57351:"ArrowRight",57352:"ArrowUp",57353:"ArrowDown",57354:"PageUp",57355:"PageDown",57356:"Home",57357:"End",57358:"CapsLock",57359:"ScrollLock",57360:"NumLock",57361:"PrintScreen",57362:"Pause",57363:"ContextMenu",57364:"F1",57365:"F2",57366:"F3",57367:"F4",57368:"F5",57369:"F6",57370:"F7",57371:"F8",57372:"F9",57373:"F10",57374:"F11",57375:"F12",57376:"F13",57377:"F14",57378:"F15",57379:"F16",57380:"F17",57381:"F18",57382:"F19",57383:"F20",57384:"F21",57385:"F22",57386:"F23",57387:"F24",57388:"F25",57389:"F26",57390:"F27",57391:"F28",57392:"F29",57393:"F30",57394:"F31",57395:"F32",57396:"F33",57397:"F34",57398:"F35",57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57414:"Enter",57415:"=",57416:",",57417:"ArrowLeft",57418:"ArrowRight",57419:"ArrowUp",57420:"ArrowDown",57421:"PageUp",57422:"PageDown",57423:"Home",57424:"End",57425:"Insert",57426:"Delete",57427:"Clear",57428:"MediaPlay",57429:"MediaPause",57430:"MediaPlayPause",57431:"MediaReverse",57432:"MediaStop",57433:"MediaFastForward",57434:"MediaRewind",57435:"MediaTrackNext",57436:"MediaTrackPrevious",57437:"MediaRecord",57438:"AudioVolumeDown",57439:"AudioVolumeUp",57440:"AudioVolumeMute",57441:"ShiftLeft",57442:"ControlLeft",57443:"AltLeft",57444:"MetaLeft",57445:"HyperLeft",57446:"MetaLeft",57447:"ShiftRight",57448:"ControlRight",57449:"AltRight",57450:"MetaRight",57451:"HyperRight",57452:"MetaRight",57453:"AltGraph",57454:"ISOLevel5Shift"};class vm{lexer;keyHandlers=[];deviceAttributesHandlers=[];decrqssHandlers=[];dcsHandlers=[];oscHandlers=[];pasteHandlers=[];sgrMouseHandlers=[];mouseHandlers=[];focusHandlers=[];resizeHandlers=[];escapeTimeout=null;ESCAPE_TIMEOUT_MS=25;pendingEscape=!1;sgrToMouseConverter=Pm;inPaste=!1;pasteBuffer="";constructor(){this.lexer=new Sm,this.lexer.onEvent(this.handleLexicalEvent.bind(this))}onEvent(J){this.lexer.onEvent(J)}offEvent(J){this.lexer.offEvent(J)}onKey(J){this.keyHandlers.push(J)}offKey(J){let Q=this.keyHandlers.indexOf(J);if(Q!==-1)this.keyHandlers.splice(Q,1)}onDeviceAttributes(J){this.deviceAttributesHandlers.push(J)}onDecrqss(J){this.decrqssHandlers.push(J)}onDcs(J){this.dcsHandlers.push(J)}onOsc(J){this.oscHandlers.push(J)}onPaste(J){this.pasteHandlers.push(J)}onSgrMouse(J){this.sgrMouseHandlers.push(J)}onMouse(J){this.mouseHandlers.push(J)}onFocus(J){this.focusHandlers.push(J)}onResize(J){this.resizeHandlers.push(J)}setSgrToMouseConverter(J){this.sgrToMouseConverter=J}parse(J){if(this.isStandaloneEscape(J)){if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null;this.scheduleEscapeTimeout(),this.lexer.parse(J);return}if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null,this.pendingEscape=!1;this.lexer.parse(J)}isStandaloneEscape(J){if(typeof J==="string")return J.length===1&&J.charCodeAt(0)===27;else return J.length===1&&J[0]===27}scheduleEscapeTimeout(){this.pendingEscape=!0,this.escapeTimeout=setTimeout(()=>{this.pendingEscape=!1,this.lexer.reset();let J={type:"key",key:"Escape",shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(J),this.escapeTimeout=null},this.ESCAPE_TIMEOUT_MS)}clearEscapeTimeout(){if(this.escapeTimeout)clearTimeout(this.escapeTimeout),this.escapeTimeout=null;this.pendingEscape=!1}flush(){this.lexer.flush()}reset(){this.clearEscapeTimeout(),this.lexer.reset()}handleLexicalEvent(J){switch(J.type){case"print":this.handlePrintEvent(J);break;case"execute":this.handleExecuteEvent(J);break;case"csi":this.handleCsiEvent(J);break;case"dcs":this.handleDcsEvent(J);break;case"osc":this.handleOscEvent(J);break;case"escape":this.handleEscapeEvent(J);break}}handlePrintEvent(J){if(this.inPaste){this.pasteBuffer+=J.grapheme;return}if(this.pendingEscape){this.clearEscapeTimeout();let Z={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!0,metaKey:!1};this.emitKeyEvent(Z);return}let Q={type:"key",key:J.grapheme,shiftKey:this.isShifted(J.grapheme),ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Q)}handleExecuteEvent(J){if(this.inPaste)switch(J.code){case 10:this.pasteBuffer+=`
5839
5839
  `;return;case 13:this.pasteBuffer+="\r";return;case 9:this.pasteBuffer+="\t";return}if(J.code===10){let Z={type:"key",key:"Enter",shiftKey:!0,ctrlKey:!1,altKey:!1,metaKey:!1};this.emitKeyEvent(Z);return}let Q=this.controlCharacterToGrapheme(J.code);if(Q){let Z={type:"key",key:Q,shiftKey:!1,ctrlKey:this.isControlCharacter(J.code)&&J.code!==127&&J.code!==8&&J.code!==9&&J.code!==10&&J.code!==13&&J.code!==27,altKey:!1,metaKey:!1};this.emitKeyEvent(Z)}}controlCharacterToGrapheme(J){switch(J){case 8:return"Backspace";case 9:return"Tab";case 10:return"Enter";case 13:return"Enter";case 27:return"Escape";case 127:return"Backspace";case 0:return"@";case 1:return"a";case 2:return"b";case 3:return"c";case 4:return"d";case 5:return"e";case 6:return"f";case 7:return"g";case 11:return"k";case 12:return"l";case 14:return"n";case 15:return"o";case 16:return"p";case 17:return"q";case 18:return"r";case 19:return"s";case 20:return"t";case 21:return"u";case 22:return"v";case 23:return"w";case 24:return"x";case 25:return"y";case 26:return"z";default:return null}}isControlCharacter(J){return J>=0&&J<=26||J===27||J===127}handleEscapeEvent(J){this.clearEscapeTimeout();let Q=this.escapeToKey(J);if(Q)this.emitKeyEvent(Q)}handleDcsEvent(J){for(let Q of this.dcsHandlers)Q(J)}handleOscEvent(J){for(let Q of this.oscHandlers)Q(J)}handleCsiEvent(J){if(this.clearEscapeTimeout(),this.handleBracketedPaste(J))return;let Q=this.csiToFocus(J);if(Q){this.emitFocusEvent(Q);return}let Z=this.csiToDeviceAttributes(J);if(Z){this.emitDeviceAttributesEvent(Z);return}let X=this.csiToDecrqss(J);if(X){this.emitDecrqssEvent(X);return}let Y=this.csiToKittyKeyboardResponse(J);if(Y){this.emitDecrqssEvent(Y);return}let K=this.csiToInBandResize(J);if(K){this.emitResizeEvent(K);return}let q=this.csiToSgrMouse(J);if(q){this.emitSgrMouseEvent(q);let z=this.sgrToMouseConverter(q);this.emitMouseEvent(z);return}let G=this.csiToKey(J);if(G)this.emitKeyEvent(G)}escapeToKey(J){if(J.intermediates==="O"){if(J.final==="P")return this.createKeyEvent("F1");if(J.final==="Q")return this.createKeyEvent("F2");if(J.final==="R")return this.createKeyEvent("F3");if(J.final==="S")return this.createKeyEvent("F4")}if(J.intermediates===""&&J.final.length===1){let Q=J.final.charCodeAt(0);if(Q>=32&&Q<=126)return{type:"key",key:J.final,shiftKey:this.isShifted(J.final),ctrlKey:!1,altKey:!0,metaKey:!1};else if(Q==127)return{type:"key",key:"Backspace",shiftKey:!1,ctrlKey:!1,altKey:!0,metaKey:!1}}return null}csiToKey(J){let{final:Q,params:Z}=J;if(Z.length===0||Z.length===1&&Z[0]?.value===0)Z=[{value:1}];let X=null,Y={shift:!1,ctrl:!1,alt:!1,meta:!1},K=1,q="";if(Z.length>=1){let G=Z[0]?.value??1;if(G===1&&Q==="Z")X="Tab",Y.shift=!0;else X=this.getSpecialKey(G,Q)??this.unicodeToKey(G)}if(Z.length>=2){let G=Z[1]?.value??1;Y=this.parseModifiers(G)}if(Z.length>=3){let G=Z[2]?.value??1;if(Q==="u")K=G-1;else if(Q==="~"&&Z[0]?.value===27)X=this.unicodeToKey(G)}if(K!==1&&K!==0)return null;if(!X)return null;if(q===""&&Y.shift&&!Y.ctrl&&!Y.alt&&!Y.meta){let G=this.keyToUnicode(X);if(G&&G>=32&&G<=126)q=X.toUpperCase()}return this.createKeyEventWithModifiers(X,Y,q)}parseModifiers(J){if(J===0||J===1)return{shift:!1,ctrl:!1,alt:!1,meta:!1};let Q=J-1;return{shift:(Q&1)!==0,alt:(Q&2)!==0,ctrl:(Q&4)!==0,meta:(Q&8)!==0}}unicodeToKey(J){if(J===13)return"Enter";if(J===9)return"Tab";if(J===27)return"Escape";if(J===127)return"Backspace";if(J===32)return" ";if(J>=1&&J<=26)return String.fromCharCode(J+96);if(w56[J])return w56[J];if(J>=32&&J<=126)return String.fromCharCode(J);if(J>126)try{return String.fromCharCode(J)}catch{return null}return null}createKeyEvent(J){return{type:"key",key:J,shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1}}createKeyEventWithModifiers(J,Q,Z){return{type:"key",key:J,shiftKey:Q.shift,ctrlKey:Q.ctrl,altKey:Q.alt,metaKey:Q.meta}}static SPECIAL_KEYS=new Map([["1:A","ArrowUp"],["1:B","ArrowDown"],["1:C","ArrowRight"],["1:D","ArrowLeft"],["1:H","Home"],["1:F","End"],["1:P","F1"],["1:Q","F2"],["1:R","F3"],["1:S","F4"],["1:~","Home"],["2:~","Insert"],["3:~","Delete"],["4:~","End"],["5:~","PageUp"],["6:~","PageDown"],["7:~","Home"],["8:~","End"],["9:~","Tab"],["11:~","F1"],["12:~","F2"],["13:~","F3"],["14:~","F4"],["15:~","F5"],["17:~","F6"],["18:~","F7"],["19:~","F8"],["20:~","F9"],["21:~","F10"],["23:~","F11"],["24:~","F12"]]);getSpecialKey(J,Q){let Z=`${J}:${Q}`;return vm.SPECIAL_KEYS.get(Z)||null}keyToUnicode(J){if(J.length===1)return J.charCodeAt(0);switch(J){case"Enter":return 13;case"Tab":return 9;case"Escape":return 27;case"Backspace":return 127;case" ":return 32}return null}isShifted(J){return J!==J.toLowerCase()}emitKeyEvent(J){for(let Q of this.keyHandlers)Q(J)}csiToDeviceAttributes(J){if(J.final==="c"&&J.private==="?"){let Q=0,Z=[];if(J.params.length>0){Q=J.params[0]?.value||0;let X=J.params.slice(1);if(X.length>0&&X[X.length-1]?.value===0)X=X.slice(0,-1);Z=X.map((Y)=>Y.value)}return{type:"device_attributes_primary",primary:Q,secondary:Z}}return null}csiToDecrqss(J){if(J.final==="y"&&J.intermediates.includes("$")){if(J.params.length>=2){let Q=`?${J.params[0]?.value||0}`,Z=String(J.params[1]?.value||0);return{type:"decrqss_response",request:Q,response:Z}}}return null}csiToKittyKeyboardResponse(J){if(J.final==="u"&&J.private==="?"){if(J.params.length>=1)return{type:"decrqss_response",request:"u",response:(J.params[0]?.value||0)>0?"1":"0"}}return null}emitDeviceAttributesEvent(J){for(let Q of this.deviceAttributesHandlers)Q(J)}csiToSgrMouse(J){if((J.final==="M"||J.final==="m")&&J.private==="<"){if(J.params.length>=3){let Q=J.params[0]?.value||0,Z=J.params[1]?.value||1,X=J.params[2]?.value||1,Y=Q&-61,K=J.final==="M"&&Y!==3;return{type:"sgr_mouse",button:Q,x:Z,y:X,pressed:K}}}return null}emitDecrqssEvent(J){for(let Q of this.decrqssHandlers)Q(J)}emitSgrMouseEvent(J){for(let Q of this.sgrMouseHandlers)Q(J)}emitMouseEvent(J){for(let Q of this.mouseHandlers)Q(J)}csiToFocus(J){if(J.intermediates===""&&(J.final==="I"||J.final==="O"))return{type:"focus",focused:J.final==="I"};return null}csiToInBandResize(J){if(J.final==="t"&&J.params.length>=5&&J.params[0]?.value===48){let Q=J.params[1]?.value||0,Z=J.params[2]?.value||0,X=J.params[3]?.value||0,Y=J.params[4]?.value||0;return{type:"resize",width:Z,height:Q,pixelWidth:Y,pixelHeight:X}}return null}emitFocusEvent(J){for(let Q of this.focusHandlers)Q(J)}emitResizeEvent(J){for(let Q of this.resizeHandlers)Q(J)}handleBracketedPaste(J){if(J.final==="~"&&J.params.length===1){let Q=J.params[0]?.value;if(Q===200)return this.inPaste=!0,this.pasteBuffer="",!0;else if(Q===201){if(this.inPaste)this.inPaste=!1,this.emitPasteEvent({type:"paste",text:this.pasteBuffer}),this.pasteBuffer="";return!0}}return!1}emitPasteEvent(J){for(let Q of this.pasteHandlers)Q(J)}}function G09(J){return J.replace(/\r\n|\r/g,`
5840
- `)}function z09(J){return J.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function I56(J){let Q=J;return Q=G09(Q),Q=z09(Q),Q}class db1{parts=[];append(...J){this.parts.push(...J)}toString(){return this.parts.join("")}reset(){this.parts.length=0}get length(){return this.parts.length}get isEmpty(){return this.parts.length===0}}var HH="\x1B",z8="\x1B[",E56=z8+"0m",U09=z8+"m",$56=(J,Q)=>z8+`${J+1};${Q+1}H`,W09=z8+"H",F09=z8+"?25l",H09=z8+"?25h",B09=z8+"2J",D09=z8+"?2026h",M09=z8+"?2026l",V09=z8+"?2004h",N09=z8+"?2004l",P56=[...Array.from({length:216},(J,Q)=>{let Z=Math.floor(Q/36),X=Math.floor(Q%36/6),Y=Q%6,K=(q)=>q===0?0:55+q*40;return[K(Z),K(X),K(Y)]}),...Array.from({length:24},(J,Q)=>{let Z=8+Q*10;return[Z,Z,Z]})],T56=new Map;function L09(J,Q,Z){let X=`${J},${Q},${Z}`,Y=T56.get(X);if(Y!==void 0)return Y;let K=16,q=1/0;for(let G=0;G<P56.length;G++){let[z,U,W]=P56[G],F=(J-z)**2+(Q-U)**2+(Z-W)**2;if(F<q)q=F,K=G+16}return T56.set(X,K),K}var A09=z8+"?1049h",O09=z8+"?1049l",j09=z8+"?1002h"+z8+"?1003h"+z8+"?1004h"+z8+"?1006h",R09=z8+"?1002l"+z8+"?1003l"+z8+"?1004l"+z8+"?1006l",w09=z8+"?1016h",I09=z8+"?1016l",E09=z8+"?2027h",$09=z8+"?2027l",P09=z8+"?2048h",T09=z8+"?2048l",C09=z8+">1u",S09=z8+"<u",v09=(J)=>HH+`]22;${J}`+HH+"\\",k09=(J)=>HH+`]0;${J}\x07`,v56=HH+"]9;4;3"+HH+"\\",k56=HH+"]9;4;0"+HH+"\\",_56=HH+"]9;4;4"+HH+"\\",_09=(J)=>z8+`${J} q`,cb1={DEFAULT:0,BLINKING_BLOCK:1,STEADY_BLOCK:2,BLINKING_UNDERLINE:3,STEADY_UNDERLINE:4,BLINKING_BAR:5,STEADY_BAR:6};function b09(J){return j09+(J?w09:"")}function x09(){return R09+I09}function lb1(J){return k09(J)}function b56(){return v56}function ib1(){return k56}function x56(){return _56}function C56(J,Q,Z){if(!J)return"";switch(J.type){case"default":return z8+(Q?"39":"49")+"m";case"index":return z8+`${Q?"38":"48"};5;${J.value}m`;case"rgb":{if(Z&&!Z.canRgb){let{r:G,g:z,b:U}=J.value,W=L09(G,z,U);return z8+`${Q?"38":"48"};5;${W}m`}let X=Q?"38":"48",{r:Y,g:K,b:q}=J.value;return z8+`${X};2;${Y};${K};${q}m`}default:return""}}function y09(J,Q,Z){let X="";if(J.fg!==Q.fg){if(J.fg===void 0&&Q.fg!==void 0)X+=z8+"39m";else X+=C56(J.fg,!0,Z);Q.fg=J.fg}if(J.bg!==Q.bg){if(J.bg===void 0&&Q.bg!==void 0)X+=z8+"49m";else X+=C56(J.bg,!1,Z);Q.bg=J.bg}if(J.bold!==Q.bold){if(X+=J.bold?z8+"1m":z8+"22m",Q.bold=J.bold,!J.bold&&J.dim)X+=z8+"2m"}if(J.italic!==Q.italic)X+=J.italic?z8+"3m":z8+"23m",Q.italic=J.italic;if(J.underline!==Q.underline)X+=J.underline?z8+"4m":z8+"24m",Q.underline=J.underline;if(J.strikethrough!==Q.strikethrough)X+=J.strikethrough?z8+"9m":z8+"29m",Q.strikethrough=J.strikethrough;if(J.reverse!==Q.reverse)X+=J.reverse?z8+"7m":z8+"27m",Q.reverse=J.reverse;if(J.dim!==Q.dim){if(X+=J.dim?z8+"2m":z8+"22m",Q.dim=J.dim,!J.dim&&J.bold)X+=z8+"1m"}return X}function f09(J,Q){let Z="";if(!b41(J,Q.hyperlink)){if(Q.hyperlink)Z+=x41();if(J)Z+=A56(J);Q.hyperlink=J}return Z}function S56(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;if(J.type!==Q.type)return!1;switch(J.type){case"default":return!0;case"index":return Q.value===J.value;case"rgb":{let Z=Q.value;return Z.r===J.value.r&&Z.g===J.value.g&&Z.b===J.value.b}default:return!1}}function h09(J,Q){return S56(J.fg,Q.fg)&&S56(J.bg,Q.bg)&&J.bold===Q.bold&&J.italic===Q.italic&&J.underline===Q.underline&&J.strikethrough===Q.strikethrough&&J.reverse===Q.reverse&&J.dim===Q.dim}class ab1{capabilities;currentStyle={};currentX=0;currentY=0;constructor(J){this.capabilities=J}updateCapabilities(J){this.capabilities=J}render(J){if(J.length===0)return"";let Q=this.batchDiffs(J),Z=new db1;for(let X of Q){if(this.currentX!==X.x||this.currentY!==X.y)Z.append($56(X.y,X.x)),this.currentX=X.x,this.currentY=X.y;Z.append(y09(X.style,this.currentStyle,this.capabilities)),Z.append(f09(X.hyperlink,this.currentStyle)),Z.append(X.chars.join("")),this.currentX+=X.totalWidth}return Z.toString()}clearScreen(){return this.currentX=0,this.currentY=0,this.currentStyle={},E56+x41()+B09+W09}hideCursor(){return F09}showCursor(){return H09}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return _09(J)}reset(){return this.currentStyle={},E56+x41()}moveTo(J,Q){return this.currentX=J,this.currentY=Q,$56(Q,J)}batchDiffs(J){if(J.length===0)return[];let Q=[],Z=null;for(let X of J)if(Z&&Z.y===X.y&&Z.x+Z.totalWidth===X.x&&h09(Z.style,X.cell.style)&&b41(Z.hyperlink,X.cell.hyperlink)){let K=X.cell.char==="\t"?" ".repeat(Tm):X.cell.char;Z.chars.push(K),Z.totalWidth+=X.cell.width}else{let K=X.cell.char==="\t"?" ".repeat(Tm):X.cell.char;Z={x:X.x,y:X.y,chars:[K],style:X.cell.style,hyperlink:X.cell.hyperlink,totalWidth:X.cell.width},Q.push(Z)}return Q}getCursorPosition(){return{x:this.currentX,y:this.currentY}}resetState(){this.currentStyle={},this.currentX=0,this.currentY=0}startSync(){return D09}endSync(){return M09}enterAltScreen(){return A09+this.clearScreen()}exitAltScreen(){return O09}resetCursor(){return U09}enableMouse(J=!1){return b09(J)}disableMouse(){return x09()}enableEmojiWidth(){return E09}disableEmojiWidth(){return $09}enableInBandResize(){return P09}disableInBandResize(){return T09}enableBracketedPaste(){return V09}disableBracketedPaste(){return N09}enableKittyKeyboard(){return C09}disableKittyKeyboard(){return S09}setMouseShape(J){return v09(J)}setProgressBarIndeterminate(){return v56}setProgressBarOff(){return k56}setProgressBarPaused(){return _56}}import{openSync as g09}from"node:fs";import y56 from"node:tty";function m09(){let J={stdin:null,dataCallback:null,init(){if(this.stdin!==null)return;let Q=g09("/dev/tty","r");if(!y56.isatty(Q))throw Error("/dev/tty is not a TTY device");let Z=new y56.ReadStream(Q);if(this.stdin=Z,Z.setRawMode(!0),this.dataCallback)Z.on("data",this.dataCallback)},on(Q,Z){if(this.dataCallback&&this.stdin)this.stdin.removeAllListeners("data");this.dataCallback=Z,this.stdin?.on(Q,Z)},pause(){if(this.stdin){if(this.stdin.setRawMode(!1),this.dataCallback)this.stdin.removeListener("data",this.dataCallback);this.stdin.destroy()}this.stdin=null},resume(){this.init()},dispose(){if(this.stdin){if(this.stdin.setRawMode(!1),this.dataCallback)this.stdin.removeListener("data",this.dataCallback);this.stdin.destroy()}this.stdin=null,this.dataCallback=null}};return J.init(),J}function u09(){let J={stdin:null,dataCallback:null,init(){if(this.stdin!==null)return;if(this.stdin=process.stdin,this.stdin.isTTY)this.stdin.setRawMode(!0);if(this.dataCallback)this.stdin.on("data",this.dataCallback)},on(Q,Z){if(this.dataCallback&&this.stdin)this.stdin.removeAllListeners("data");this.dataCallback=Z,this.stdin?.on(Q,Z)},pause(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);if(this.stdin&&this.dataCallback)this.stdin.removeListener("data",this.dataCallback)},resume(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!0);if(this.stdin&&this.dataCallback)this.stdin.on("data",this.dataCallback)},dispose(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);if(this.stdin&&this.dataCallback)this.stdin.removeListener("data",this.dataCallback);this.stdin=null,this.dataCallback=null}};return J.init(),J}function f56(){return process.platform==="win32"?u09():m09()}var p09=50,d09=200;class g56{eventBuffer=[];bufferTimer=null;filterDirection=null;lastEventTime=0;onEmitEvent=()=>{};constructor(J){this.onEmitEvent=J}handleWheelEvent(J){if(J.button!=="wheel_up"&&J.button!=="wheel_down")return!0;let Q=Date.now();if(this.filterDirection!==null)if(Q-this.lastEventTime>d09)this.filterDirection=null;else return this.lastEventTime=Q,J.button===this.filterDirection;if(this.lastEventTime=Q,this.eventBuffer.push(J),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},p09);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Q)=>Q.button==="wheel_down")){this.filterDirection="wheel_down";for(let Q of this.eventBuffer)if(Q.button==="wheel_down")this.onEmitEvent(Q)}else{this.filterDirection="wheel_up";for(let Q of this.eventBuffer)this.onEmitEvent(Q)}this.eventBuffer=[]}}class nb1{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;constructor(){this.screen=new Cm(80,24),this.renderer=new ab1,this.tty=f56(),this.jetBrainsWheelFilter=new g56((J)=>{for(let Q of this.mouseHandlers)Q(J)})}init(){if(this.initialized)throw Error("TUI is already initialized");try{this.parser=new vm,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new v41,this.parser.onDeviceAttributes((J)=>{if(this.queryParser&&this.initialized){if(this.queryParser.processDeviceAttributes(J.primary,J.secondary))this.finishInitialization()}}),this.parser.onDecrqss((J)=>{if(this.queryParser&&this.initialized)this.queryParser.processDecrqss(J.request,J.response)}),this.parser.onDcs((J)=>{if(this.queryParser&&this.initialized){if(J.final==="|"&&J.private===">")this.queryParser.processXtversion(J.data);if(J.final==="r"&&J.intermediates==="+"&&J.params.length>0&&J.params[0]?.value===1)this.parseXtgettcapResponse(J.data)}}),this.parser.onMouse((J)=>{if(UG()&&!this.jetBrainsWheelFilter.handleWheelEvent(J))return;for(let Q of this.mouseHandlers)Q(J)}),this.parser.onFocus((J)=>{for(let Q of this.focusHandlers)Q(J)}),this.parser.onResize((J)=>{this.handleInbandResize(J)}),this.tty.on("data",(J)=>{this.parser?.parse(J)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.enableMouse(),this.enableBracketedPaste(),this.createCapabilityPromise(),this.startCapabilityDetection()}catch(J){throw this.deinit(),J}}deinit(){if(this.initialized){let J="";if(J+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+this.renderer.disableKittyKeyboard()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.xtversion?.startsWith("ghostty"))J+=this.renderer.setProgressBarOff();if(this.inAltScreen)J+=this.renderer.exitAltScreen(),this.inAltScreen=!1;process.stdout.write(J)}if(this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null;if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;this.keyHandlers.length=0,this.mouseHandlers.length=0,this.resizeHandlers.length=0,this.focusHandlers.length=0,this.pasteHandlers.length=0,this.capabilityHandlers.length=0,process.removeListener("SIGWINCH",this.boundHandleResize),process.removeListener("SIGINT",this.boundCleanup),process.removeListener("SIGTERM",this.boundCleanup),process.removeListener("exit",this.boundCleanup),process.removeListener("SIGCONT",this.boundHandleResume),this.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1}onKey(J){this.keyHandlers.push(J)}offKey(J){let Q=this.keyHandlers.indexOf(J);if(Q!==-1)this.keyHandlers.splice(Q,1)}onMouse(J){this.mouseHandlers.push(J)}offMouse(J){let Q=this.mouseHandlers.indexOf(J);if(Q!==-1)this.mouseHandlers.splice(Q,1)}onResize(J){this.resizeHandlers.push(J)}offResize(J){let Q=this.resizeHandlers.indexOf(J);if(Q!==-1)this.resizeHandlers.splice(Q,1)}onFocus(J){this.focusHandlers.push(J)}offFocus(J){let Q=this.focusHandlers.indexOf(J);if(Q!==-1)this.focusHandlers.splice(Q,1)}onPaste(J){this.pasteHandlers.push(J)}offPaste(J){let Q=this.pasteHandlers.indexOf(J);if(Q!==-1)this.pasteHandlers.splice(Q,1)}onCapabilities(J){this.capabilityHandlers.push(J)}offCapabilities(J){let Q=this.capabilityHandlers.indexOf(J);if(Q!==-1)this.capabilityHandlers.splice(Q,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}async waitForCapabilities(J=1000){if(!this.initialized)throw Error("TUI is not initialized");if(this.capabilities)return this.capabilities;if(!this.capabilityPromise)throw Error("Capability detection not started");return this.capabilityPromise}getSize(){return{...this.terminalSize}}getScreen(){return this.screen}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let J=this.screen.getDiff(),Q=this.screen.getCursor();if(J.length>0||Q!==null){let X="";X+=this.renderer.startSync(),X+=this.renderer.hideCursor(),X+=this.renderer.reset(),X+=this.renderer.moveTo(0,0);let Y=this.renderer.render(J);if(X+=Y,Q&&this.screen.isCursorVisible())X+=this.renderer.moveTo(Q.x,Q.y),X+=this.renderer.setCursorShape(this.screen.getCursorShape()),X+=this.renderer.showCursor();else X+=this.renderer.hideCursor();X+=this.renderer.endSync(),process.stdout.write(X),this.screen.present()}}clearScreen(){let J=this.renderer.clearScreen()+this.renderer.hideCursor();process.stdout.write(J),this.renderer.resetState()}showCursor(){process.stdout.write(this.renderer.showCursor())}hideCursor(){process.stdout.write(this.renderer.hideCursor())}setCursor(J,Q){this.screen.setCursor(J,Q)}clearCursor(){this.screen.clearCursor()}setCursorShape(J){this.screen.setCursorShape(J)}setMouseCursor(J){let Q=`\x1B]22;${J}\x07`;process.stdout.write(Q)}resetMouseCursor(){this.setMouseCursor(D5.DEFAULT)}enableBracketedPaste(){process.stdout.write(this.renderer.enableBracketedPaste())}disableBracketedPaste(){process.stdout.write(this.renderer.disableBracketedPaste())}enableKittyKeyboard(){process.stdout.write(this.renderer.enableKittyKeyboard())}disableKittyKeyboard(){process.stdout.write(this.renderer.disableKittyKeyboard())}async writeClipboard(J){return WG.writeText(J)}get clipboard(){return WG}enterAltScreen(){if(!this.initialized)throw Error("TUI not initialized");if(!this.inAltScreen)process.stdout.write(this.renderer.enterAltScreen()),this.inAltScreen=!0}exitAltScreen(){if(this.inAltScreen)process.stdout.write(this.renderer.exitAltScreen()),this.inAltScreen=!1}isInAltScreen(){return this.inAltScreen}enableMouse(){if(this.initialized){let J=this.queryParser?.shouldUsePixelMouse()??!1,Q=this.renderer.enableMouse(J);process.stdout.write(Q)}}disableMouse(){if(this.initialized)process.stdout.write(this.renderer.disableMouse())}enableEmojiWidth(){if(this.initialized){let J=this.renderer.enableEmojiWidth();process.stdout.write(J)}}disableEmojiWidth(){if(this.initialized)process.stdout.write(this.renderer.disableEmojiWidth())}enableInBandResize(){if(this.initialized){let J=this.renderer.enableInBandResize();process.stdout.write(J)}}disableInBandResize(){if(this.initialized)process.stdout.write(this.renderer.disableInBandResize())}setMouseShape(J){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(J))}suspend(){if(!this.initialized||this.suspended)return;if(this.disableMouse(),this.disableEmojiWidth(),this.disableInBandResize(),this.disableBracketedPaste(),this.disableKittyKeyboard(),this.exitAltScreen(),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend();try{process.kill(0,"SIGTSTP"),l.debug(`Successfully suspended process ${process.pid}`)}catch(J){l.debug(`Failed to suspend process ${process.pid}: ${J}`)}}handleResume(){if(!this.initialized||!this.suspended)return;this.resume(),setImmediate(()=>{if(this.initialized&&!this.suspended)this.render()})}updateTerminalSize(){if(!this.tty.stdin||!h56(this.tty.stdin)){this.terminalSize={width:80,height:24};return}try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows){this.terminalSize={width:process.stdout.columns,height:process.stdout.rows};return}let J=process.stdout.getWindowSize();if(J[0]>0&&J[1]>0){this.terminalSize={width:J[0],height:J[1]};return}}catch(J){}}handleKeyEvent(J){for(let Q of this.keyHandlers)Q(J)}handlePasteEvent(J){let Q={type:"paste",text:I56(J.text)};for(let Z of this.pasteHandlers)Z(Q)}handleOscEvent(J){if(J.data.startsWith("52;c;")){let Q=J.data.slice(5);if(Q&&Q!=="?")WG.handleOSC52Response(Q)}}createCapabilityPromise(){this.capabilityPromise=new Promise((J)=>{this.capabilityResolve=J})}startCapabilityDetection(){if(!this.tty.stdin||!h56(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new v41,process.env.TERM_PROGRAM==="Apple_Terminal"){let J=$m({canRgb:!1});this.capabilities=J;let Q={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Z of this.capabilityHandlers)Z(Q);if(this.capabilityResolve)this.capabilityResolve(J),this.capabilityResolve=null;return}for(let J of B56)process.stdout.write(J.sequence);this.capabilityTimeout=setTimeout(()=>{if(!this.capabilities&&this.capabilityResolve&&this.queryParser)this.finishInitialization()},2000)}finishInitialization(){if(!this.initialized||!this.queryParser||this.capabilities)return;if(this.capabilities=this.queryParser.getCapabilities(),this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;let J={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Q of this.capabilityHandlers)Q(J);if(this.capabilityResolve)l.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Q=this.queryParser.getPixelDimensions();if(Q){let Z=Q.pixelWidth/Q.columns,X=Q.pixelHeight/Q.rows;this.parser?.setSgrToMouseConverter((Y)=>Pm(Y,!0,Z,X))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();this.enableInBandResize(),WG.setCapabilities(this.capabilities)}parseXtgettcapResponse(J){if(!this.queryParser)return;let Q=J.indexOf("=");if(Q!==-1){let Z=J.slice(0,Q),X=J.slice(Q+1);if(this.queryParser.processXtgettcap(Z,X))this.finishInitialization()}}handleResize(){if(this.pendingResize=!0,this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer);this.resizeDebounceTimer=setTimeout(()=>{this.processResize()},10)}handleInbandResize(J){if(this.terminalSize={width:J.width,height:J.height},this.queryParser&&J.pixelWidth&&J.pixelHeight){let Q=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(J.width,J.height,J.pixelWidth,J.pixelHeight);let Z=this.queryParser.shouldUsePixelMouse();if(!Q&&Z)this.disableMouse(),this.enableMouse();if(Z){let X=J.pixelWidth/J.width,Y=J.pixelHeight/J.height;this.parser?.setSgrToMouseConverter((K)=>Pm(K,!0,X,Y))}}this.screen.resize(J.width,J.height),setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(J)}catch(Z){l.error("Error in resize handler:",Z)}})}processResize(){if(!this.pendingResize||!this.initialized)return;let J={...this.terminalSize};if(this.updateTerminalSize(),J.width===this.terminalSize.width&&J.height===this.terminalSize.height){this.pendingResize=!1;return}this.finishResize(),this.pendingResize=!1}finishResize(){this.screen.resize(this.terminalSize.width,this.terminalSize.height);let J={type:"resize",width:this.terminalSize.width,height:this.terminalSize.height};setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(J)}catch(Z){l.error("Error in resize handler:",Z)}})}setupCleanupHandlers(){process.setMaxListeners(0),process.on("SIGINT",this.boundCleanup),process.on("SIGTERM",this.boundCleanup),process.on("exit",this.boundCleanup),process.on("SIGCONT",this.boundHandleResume)}cleanup(){try{this.deinit()}catch{}}}function h56(J){return"isTTY"in J&&J.isTTY===!0&&typeof J.setRawMode==="function"}F0();F0();R4();var km;((Y)=>{Y.BUILD="build";Y.LAYOUT="layout";Y.PAINT="paint";Y.RENDER="render"})(km||={});var c09=60,rb1=1000/c09;class nQ{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_lastFrameTime=0;TARGET_FPS=60;FRAME_TIME=1000/this.TARGET_FPS;_stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}};_lastCompletedStats=this.deepCopyStats(this._stats);static get instance(){return this._instance??=new nQ}requestFrame(){if(this._frameScheduled)return;this._frameScheduled=!0,setImmediate(()=>this.executeFrame())}addFrameCallback(J,Q,Z,X=0,Y){this._frameCallbacks.set(J,{callback:Q,phase:Z,priority:X,name:Y||J})}removeFrameCallback(J){this._frameCallbacks.delete(J)}addPostFrameCallback(J,Q){if(this._postFrameCallbacks.push({callback:J,name:Q}),!this._frameScheduled&&!this._frameInProgress)this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let J=performance.now();this._frameScheduled=!1,this._frameInProgress=!0,this._lastFrameTime=J;try{for(let Q of["build","layout","paint","render"])this.executePhase(Q);this.executePostFrameCallbacks()}catch(Q){l.error("Frame execution error:",Q instanceof Error?Q.message:String(Q))}finally{this.recordFrameStats(performance.now()-J),this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1}}executePhase(J){let Q=performance.now();try{let Z=Array.from(this._frameCallbacks.values()).filter((X)=>X.phase===J).sort((X,Y)=>X.priority-Y.priority);for(let X of Z)try{X.callback()}catch(Y){l.error(`Frame callback error in ${J} phase (${X.name})`,{errorMessage:Y instanceof Error?Y.message:String(Y),errorType:Y?.constructor?.name,stackTrace:Y instanceof Error?Y.stack:void 0}),G8(!1,`FATAL: ${J} error in ${X.name}: ${Y}`)}}finally{let Z=performance.now()-Q;this.recordPhaseStats(J,Z)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let J=this._postFrameCallbacks.splice(0);for(let{callback:Q,name:Z}of J)try{Q()}catch(X){l.error(`Post-frame callback error (${Z||"anonymous"}):`,X instanceof Error?X.message:String(X))}}recordFrameStats(J){this._stats.lastFrameTime=J}recordPhaseStats(J,Q){this._stats.phaseStats[J].lastTime=Q}get isFrameScheduled(){return this._frameScheduled||this._frameInProgress}get isFrameInProgress(){return this._frameInProgress}get frameStats(){return this.deepCopyStats(this._lastCompletedStats)}deepCopyStats(J){return{...J,phaseStats:{["build"]:{...J.phaseStats.build},["layout"]:{...J.phaseStats.layout},["paint"]:{...J.phaseStats.paint},["render"]:{...J.phaseStats.render}}}}resetStats(){this._stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}}}get pendingPostFrameCallbacks(){return this._postFrameCallbacks.length}dispose(){this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this.resetStats()}}class sb1{_dirtyElements=new Set;_stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0};_buildTimes=[];_elementsPerFrame=[];constructor(){}scheduleBuildFor(J){if(this._dirtyElements.has(J))return;this._dirtyElements.add(J),nQ.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let J=performance.now(),Q=0;try{while(this._dirtyElements.size>0){let Z=Array.from(this._dirtyElements);this._dirtyElements.clear(),Z.sort((X,Y)=>X.depth-Y.depth);for(let X of Z)if(X.dirty)try{X.performRebuild(),X._dirty=!1,Q++}catch(Y){l.error("Element rebuild error:",Y instanceof Error?Y.message:String(Y)),X._dirty=!1}}}finally{this.recordBuildStats(performance.now()-J,Q)}}recordBuildStats(J,Q){if(this._stats.totalRebuilds+=Q,this._stats.elementsRebuiltThisFrame=Q,this._stats.lastBuildTime=J,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Q),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,J),this._buildTimes.push(J),this._elementsPerFrame.push(Q),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((Z,X)=>Z+X,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((Z,X)=>Z+X,0)/this._elementsPerFrame.length}get dirtyElements(){return Array.from(this._dirtyElements)}get hasDirtyElements(){return this._dirtyElements.size>0}get buildStats(){return{...this._stats}}resetBuildStats(){this._stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0},this._buildTimes.length=0,this._elementsPerFrame.length=0}dispose(){this._dirtyElements.clear()}}class j2{_parent=null;_children=new Set;_hasFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_focusChangeListeners=new Set;_debugLabel=null;static _requestFocusCallback=null;constructor(J={}){if(this._debugLabel=J.debugLabel??null,this._canRequestFocus=J.canRequestFocus??!0,this._skipTraversal=J.skipTraversal??!1,J.onKey)this._keyHandlers.push(J.onKey);this._onPasteCallback=J.onPaste??null}get hasFocus(){return this._hasFocus}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(J){if(this._canRequestFocus!==J){if(this._canRequestFocus=J,!J&&this._hasFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(J){this._skipTraversal=J}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(J){this._onPasteCallback=J}static setRequestFocusCallback(J){j2._requestFocusCallback=J}requestFocus(){if(!this._canRequestFocus)return!1;if(j2._requestFocusCallback)return j2._requestFocusCallback(this);return!1}unfocus(){if(this._hasFocus){if(j2._requestFocusCallback)j2._requestFocusCallback(null)}}_attach(J){if(this._parent===J)return;if(this._parent)this._parent._children.delete(this);if(this._parent=J,J)J._children.add(this);if(j2._requestFocusCallback){let Q=j2._requestFocusCallback.__focusManager;if(Q&&Q._invalidateFocusableNodesCache)Q._invalidateFocusableNodesCache()}}_detach(){if(this._parent)this._parent._children.delete(this),this._parent=null;if(j2._requestFocusCallback){let J=j2._requestFocusCallback.__focusManager;if(J&&J._invalidateFocusableNodesCache)J._invalidateFocusableNodesCache()}if(this._hasFocus)this.unfocus()}_setFocus(J){if(this._hasFocus===J)return;this._hasFocus=J,this._notifyListeners()}addFocusChangeListener(J){this._focusChangeListeners.add(J)}removeFocusChangeListener(J){this._focusChangeListeners.delete(J)}_notifyListeners(){for(let J of this._focusChangeListeners)J(this._hasFocus)}_handleKeyEvent(J){return this.handleKeyEvent(J)}_handlePasteEvent(J){if(this._onPasteCallback)return this._onPasteCallback(J);return"ignored"}toStringShort(){let J=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasFocus?" FOCUSED":"",Z=this._canRequestFocus?"":" (can't focus)";return`FocusNode${J}${Q}${Z}`}toStringDeep(J="",Q=!0){let Z=J+this.toStringShort();if(Q&&this._children.size>0){let X=J+" ";for(let Y of this._children)Z+=`
5840
+ `)}function z09(J){return J.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function I56(J){let Q=J;return Q=G09(Q),Q=z09(Q),Q}class db1{parts=[];append(...J){this.parts.push(...J)}toString(){return this.parts.join("")}reset(){this.parts.length=0}get length(){return this.parts.length}get isEmpty(){return this.parts.length===0}}var HH="\x1B",z8="\x1B[",E56=z8+"0m",U09=z8+"m",$56=(J,Q)=>z8+`${J+1};${Q+1}H`,W09=z8+"H",F09=z8+"?25l",H09=z8+"?25h",B09=z8+"2J",D09=z8+"?2026h",M09=z8+"?2026l",V09=z8+"?2004h",N09=z8+"?2004l",P56=[...Array.from({length:216},(J,Q)=>{let Z=Math.floor(Q/36),X=Math.floor(Q%36/6),Y=Q%6,K=(q)=>q===0?0:55+q*40;return[K(Z),K(X),K(Y)]}),...Array.from({length:24},(J,Q)=>{let Z=8+Q*10;return[Z,Z,Z]})],T56=new Map;function L09(J,Q,Z){let X=`${J},${Q},${Z}`,Y=T56.get(X);if(Y!==void 0)return Y;let K=16,q=1/0;for(let G=0;G<P56.length;G++){let[z,U,W]=P56[G],F=(J-z)**2+(Q-U)**2+(Z-W)**2;if(F<q)q=F,K=G+16}return T56.set(X,K),K}var A09=z8+"?1049h",O09=z8+"?1049l",j09=z8+"?1002h"+z8+"?1003h"+z8+"?1004h"+z8+"?1006h",R09=z8+"?1002l"+z8+"?1003l"+z8+"?1004l"+z8+"?1006l",w09=z8+"?1016h",I09=z8+"?1016l",E09=z8+"?2027h",$09=z8+"?2027l",P09=z8+"?2048h",T09=z8+"?2048l",C09=z8+">1u",S09=z8+"<u",v09=(J)=>HH+`]22;${J}`+HH+"\\",k09=(J)=>HH+`]0;${J}\x07`,v56=HH+"]9;4;3"+HH+"\\",k56=HH+"]9;4;0"+HH+"\\",_56=HH+"]9;4;4"+HH+"\\",_09=(J)=>z8+`${J} q`,cb1={DEFAULT:0,BLINKING_BLOCK:1,STEADY_BLOCK:2,BLINKING_UNDERLINE:3,STEADY_UNDERLINE:4,BLINKING_BAR:5,STEADY_BAR:6};function b09(J){return j09+(J?w09:"")}function x09(){return R09+I09}function lb1(J){return k09(J)}function b56(){return v56}function ib1(){return k56}function x56(){return _56}function C56(J,Q,Z){if(!J)return"";switch(J.type){case"default":return z8+(Q?"39":"49")+"m";case"index":return z8+`${Q?"38":"48"};5;${J.value}m`;case"rgb":{if(Z&&!Z.canRgb){let{r:G,g:z,b:U}=J.value,W=L09(G,z,U);return z8+`${Q?"38":"48"};5;${W}m`}let X=Q?"38":"48",{r:Y,g:K,b:q}=J.value;return z8+`${X};2;${Y};${K};${q}m`}default:return""}}function y09(J,Q,Z){let X="";if(J.fg!==Q.fg){if(J.fg===void 0&&Q.fg!==void 0)X+=z8+"39m";else X+=C56(J.fg,!0,Z);Q.fg=J.fg}if(J.bg!==Q.bg){if(J.bg===void 0&&Q.bg!==void 0)X+=z8+"49m";else X+=C56(J.bg,!1,Z);Q.bg=J.bg}if(J.bold!==Q.bold){if(X+=J.bold?z8+"1m":z8+"22m",Q.bold=J.bold,!J.bold&&J.dim)X+=z8+"2m"}if(J.italic!==Q.italic)X+=J.italic?z8+"3m":z8+"23m",Q.italic=J.italic;if(J.underline!==Q.underline)X+=J.underline?z8+"4m":z8+"24m",Q.underline=J.underline;if(J.strikethrough!==Q.strikethrough)X+=J.strikethrough?z8+"9m":z8+"29m",Q.strikethrough=J.strikethrough;if(J.reverse!==Q.reverse)X+=J.reverse?z8+"7m":z8+"27m",Q.reverse=J.reverse;if(J.dim!==Q.dim){if(X+=J.dim?z8+"2m":z8+"22m",Q.dim=J.dim,!J.dim&&J.bold)X+=z8+"1m"}return X}function f09(J,Q){let Z="";if(!b41(J,Q.hyperlink)){if(Q.hyperlink)Z+=x41();if(J)Z+=A56(J);Q.hyperlink=J}return Z}function S56(J,Q){if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;if(J.type!==Q.type)return!1;switch(J.type){case"default":return!0;case"index":return Q.value===J.value;case"rgb":{let Z=Q.value;return Z.r===J.value.r&&Z.g===J.value.g&&Z.b===J.value.b}default:return!1}}function h09(J,Q){return S56(J.fg,Q.fg)&&S56(J.bg,Q.bg)&&J.bold===Q.bold&&J.italic===Q.italic&&J.underline===Q.underline&&J.strikethrough===Q.strikethrough&&J.reverse===Q.reverse&&J.dim===Q.dim}class ab1{capabilities;currentStyle={};currentX=0;currentY=0;constructor(J){this.capabilities=J}updateCapabilities(J){this.capabilities=J}render(J){if(J.length===0)return"";let Q=this.batchDiffs(J),Z=new db1;for(let X of Q){if(this.currentX!==X.x||this.currentY!==X.y)Z.append($56(X.y,X.x)),this.currentX=X.x,this.currentY=X.y;Z.append(y09(X.style,this.currentStyle,this.capabilities)),Z.append(f09(X.hyperlink,this.currentStyle)),Z.append(X.chars.join("")),this.currentX+=X.totalWidth}return Z.toString()}clearScreen(){return this.currentX=0,this.currentY=0,this.currentStyle={},E56+x41()+B09+W09}hideCursor(){return F09}showCursor(){return H09}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return _09(J)}reset(){return this.currentStyle={},E56+x41()}moveTo(J,Q){return this.currentX=J,this.currentY=Q,$56(Q,J)}batchDiffs(J){if(J.length===0)return[];let Q=[],Z=null;for(let X of J)if(Z&&Z.y===X.y&&Z.x+Z.totalWidth===X.x&&h09(Z.style,X.cell.style)&&b41(Z.hyperlink,X.cell.hyperlink)){let K=X.cell.char==="\t"?" ".repeat(Tm):X.cell.char;Z.chars.push(K),Z.totalWidth+=X.cell.width}else{let K=X.cell.char==="\t"?" ".repeat(Tm):X.cell.char;Z={x:X.x,y:X.y,chars:[K],style:X.cell.style,hyperlink:X.cell.hyperlink,totalWidth:X.cell.width},Q.push(Z)}return Q}getCursorPosition(){return{x:this.currentX,y:this.currentY}}resetState(){this.currentStyle={},this.currentX=0,this.currentY=0}startSync(){return D09}endSync(){return M09}enterAltScreen(){return A09+this.clearScreen()}exitAltScreen(){return O09}resetCursor(){return U09}enableMouse(J=!1){return b09(J)}disableMouse(){return x09()}enableEmojiWidth(){return E09}disableEmojiWidth(){return $09}enableInBandResize(){return P09}disableInBandResize(){return T09}enableBracketedPaste(){return V09}disableBracketedPaste(){return N09}enableKittyKeyboard(){return C09}disableKittyKeyboard(){return S09}setMouseShape(J){return v09(J)}setProgressBarIndeterminate(){return v56}setProgressBarOff(){return k56}setProgressBarPaused(){return _56}}import{openSync as g09}from"node:fs";import y56 from"node:tty";function m09(){let J={stdin:null,dataCallback:null,init(){if(this.stdin!==null)return;let Q=g09("/dev/tty","r");if(!y56.isatty(Q))throw Error("/dev/tty is not a TTY device");let Z=new y56.ReadStream(Q);if(this.stdin=Z,Z.setRawMode(!0),this.dataCallback)Z.on("data",this.dataCallback)},on(Q,Z){if(this.dataCallback&&this.stdin)this.stdin.removeAllListeners("data");this.dataCallback=Z,this.stdin?.on(Q,Z)},pause(){if(this.stdin){if(this.stdin.setRawMode(!1),this.dataCallback)this.stdin.removeListener("data",this.dataCallback);this.stdin.destroy()}this.stdin=null},resume(){this.init()},dispose(){if(this.stdin){if(this.stdin.setRawMode(!1),this.dataCallback)this.stdin.removeListener("data",this.dataCallback);this.stdin.destroy()}this.stdin=null,this.dataCallback=null}};return J.init(),J}function u09(){let J={stdin:null,dataCallback:null,init(){if(this.stdin!==null)return;if(this.stdin=process.stdin,this.stdin.isTTY)this.stdin.setRawMode(!0);if(this.dataCallback)this.stdin.on("data",this.dataCallback)},on(Q,Z){if(this.dataCallback&&this.stdin)this.stdin.removeAllListeners("data");this.dataCallback=Z,this.stdin?.on(Q,Z)},pause(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);this.stdin?.pause()},resume(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!0);this.stdin?.resume()},dispose(){if(this.stdin&&this.stdin.isTTY)this.stdin.setRawMode(!1);if(this.stdin&&this.dataCallback)this.stdin.removeListener("data",this.dataCallback);this.stdin=null,this.dataCallback=null}};return J.init(),J}function f56(){return process.platform==="win32"?u09():m09()}var p09=50,d09=200;class g56{eventBuffer=[];bufferTimer=null;filterDirection=null;lastEventTime=0;onEmitEvent=()=>{};constructor(J){this.onEmitEvent=J}handleWheelEvent(J){if(J.button!=="wheel_up"&&J.button!=="wheel_down")return!0;let Q=Date.now();if(this.filterDirection!==null)if(Q-this.lastEventTime>d09)this.filterDirection=null;else return this.lastEventTime=Q,J.button===this.filterDirection;if(this.lastEventTime=Q,this.eventBuffer.push(J),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},p09);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Q)=>Q.button==="wheel_down")){this.filterDirection="wheel_down";for(let Q of this.eventBuffer)if(Q.button==="wheel_down")this.onEmitEvent(Q)}else{this.filterDirection="wheel_up";for(let Q of this.eventBuffer)this.onEmitEvent(Q)}this.eventBuffer=[]}}class nb1{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;constructor(){this.screen=new Cm(80,24),this.renderer=new ab1,this.tty=f56(),this.jetBrainsWheelFilter=new g56((J)=>{for(let Q of this.mouseHandlers)Q(J)})}init(){if(this.initialized)throw Error("TUI is already initialized");try{this.parser=new vm,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new v41,this.parser.onDeviceAttributes((J)=>{if(this.queryParser&&this.initialized){if(this.queryParser.processDeviceAttributes(J.primary,J.secondary))this.finishInitialization()}}),this.parser.onDecrqss((J)=>{if(this.queryParser&&this.initialized)this.queryParser.processDecrqss(J.request,J.response)}),this.parser.onDcs((J)=>{if(this.queryParser&&this.initialized){if(J.final==="|"&&J.private===">")this.queryParser.processXtversion(J.data);if(J.final==="r"&&J.intermediates==="+"&&J.params.length>0&&J.params[0]?.value===1)this.parseXtgettcapResponse(J.data)}}),this.parser.onMouse((J)=>{if(UG()&&!this.jetBrainsWheelFilter.handleWheelEvent(J))return;for(let Q of this.mouseHandlers)Q(J)}),this.parser.onFocus((J)=>{for(let Q of this.focusHandlers)Q(J)}),this.parser.onResize((J)=>{this.handleInbandResize(J)}),this.tty.on("data",(J)=>{this.parser?.parse(J)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.enableMouse(),this.enableBracketedPaste(),this.createCapabilityPromise(),this.startCapabilityDetection()}catch(J){throw this.deinit(),J}}deinit(){if(this.initialized){let J="";if(J+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+this.renderer.disableKittyKeyboard()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.xtversion?.startsWith("ghostty"))J+=this.renderer.setProgressBarOff();if(this.inAltScreen)J+=this.renderer.exitAltScreen(),this.inAltScreen=!1;process.stdout.write(J)}if(this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null;if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;this.keyHandlers.length=0,this.mouseHandlers.length=0,this.resizeHandlers.length=0,this.focusHandlers.length=0,this.pasteHandlers.length=0,this.capabilityHandlers.length=0,process.removeListener("SIGWINCH",this.boundHandleResize),process.removeListener("SIGINT",this.boundCleanup),process.removeListener("SIGTERM",this.boundCleanup),process.removeListener("exit",this.boundCleanup),process.removeListener("SIGCONT",this.boundHandleResume),this.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1}onKey(J){this.keyHandlers.push(J)}offKey(J){let Q=this.keyHandlers.indexOf(J);if(Q!==-1)this.keyHandlers.splice(Q,1)}onMouse(J){this.mouseHandlers.push(J)}offMouse(J){let Q=this.mouseHandlers.indexOf(J);if(Q!==-1)this.mouseHandlers.splice(Q,1)}onResize(J){this.resizeHandlers.push(J)}offResize(J){let Q=this.resizeHandlers.indexOf(J);if(Q!==-1)this.resizeHandlers.splice(Q,1)}onFocus(J){this.focusHandlers.push(J)}offFocus(J){let Q=this.focusHandlers.indexOf(J);if(Q!==-1)this.focusHandlers.splice(Q,1)}onPaste(J){this.pasteHandlers.push(J)}offPaste(J){let Q=this.pasteHandlers.indexOf(J);if(Q!==-1)this.pasteHandlers.splice(Q,1)}onCapabilities(J){this.capabilityHandlers.push(J)}offCapabilities(J){let Q=this.capabilityHandlers.indexOf(J);if(Q!==-1)this.capabilityHandlers.splice(Q,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}async waitForCapabilities(J=1000){if(!this.initialized)throw Error("TUI is not initialized");if(this.capabilities)return this.capabilities;if(!this.capabilityPromise)throw Error("Capability detection not started");return this.capabilityPromise}getSize(){return{...this.terminalSize}}getScreen(){return this.screen}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let J=this.screen.getDiff(),Q=this.screen.getCursor();if(J.length>0||Q!==null){let X="";X+=this.renderer.startSync(),X+=this.renderer.hideCursor(),X+=this.renderer.reset(),X+=this.renderer.moveTo(0,0);let Y=this.renderer.render(J);if(X+=Y,Q&&this.screen.isCursorVisible())X+=this.renderer.moveTo(Q.x,Q.y),X+=this.renderer.setCursorShape(this.screen.getCursorShape()),X+=this.renderer.showCursor();else X+=this.renderer.hideCursor();X+=this.renderer.endSync(),process.stdout.write(X),this.screen.present()}}clearScreen(){let J=this.renderer.clearScreen()+this.renderer.hideCursor();process.stdout.write(J),this.renderer.resetState()}showCursor(){process.stdout.write(this.renderer.showCursor())}hideCursor(){process.stdout.write(this.renderer.hideCursor())}setCursor(J,Q){this.screen.setCursor(J,Q)}clearCursor(){this.screen.clearCursor()}setCursorShape(J){this.screen.setCursorShape(J)}setMouseCursor(J){let Q=`\x1B]22;${J}\x07`;process.stdout.write(Q)}resetMouseCursor(){this.setMouseCursor(D5.DEFAULT)}enableBracketedPaste(){process.stdout.write(this.renderer.enableBracketedPaste())}disableBracketedPaste(){process.stdout.write(this.renderer.disableBracketedPaste())}enableKittyKeyboard(){process.stdout.write(this.renderer.enableKittyKeyboard())}disableKittyKeyboard(){process.stdout.write(this.renderer.disableKittyKeyboard())}async writeClipboard(J){return WG.writeText(J)}get clipboard(){return WG}enterAltScreen(){if(!this.initialized)throw Error("TUI not initialized");if(!this.inAltScreen)process.stdout.write(this.renderer.enterAltScreen()),this.inAltScreen=!0}exitAltScreen(){if(this.inAltScreen)process.stdout.write(this.renderer.exitAltScreen()),this.inAltScreen=!1}isInAltScreen(){return this.inAltScreen}enableMouse(){if(this.initialized){let J=this.queryParser?.shouldUsePixelMouse()??!1,Q=this.renderer.enableMouse(J);process.stdout.write(Q)}}disableMouse(){if(this.initialized)process.stdout.write(this.renderer.disableMouse())}enableEmojiWidth(){if(this.initialized){let J=this.renderer.enableEmojiWidth();process.stdout.write(J)}}disableEmojiWidth(){if(this.initialized)process.stdout.write(this.renderer.disableEmojiWidth())}enableInBandResize(){if(this.initialized){let J=this.renderer.enableInBandResize();process.stdout.write(J)}}disableInBandResize(){if(this.initialized)process.stdout.write(this.renderer.disableInBandResize())}setMouseShape(J){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(J))}suspend(){if(!this.initialized||this.suspended)return;if(this.disableMouse(),this.disableEmojiWidth(),this.disableInBandResize(),this.disableBracketedPaste(),this.disableKittyKeyboard(),this.exitAltScreen(),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend();try{process.kill(0,"SIGTSTP"),l.debug(`Successfully suspended process ${process.pid}`)}catch(J){l.debug(`Failed to suspend process ${process.pid}: ${J}`)}}handleResume(){if(!this.initialized||!this.suspended)return;this.resume(),setImmediate(()=>{if(this.initialized&&!this.suspended)this.render()})}updateTerminalSize(){if(!this.tty.stdin||!h56(this.tty.stdin)){this.terminalSize={width:80,height:24};return}try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows){this.terminalSize={width:process.stdout.columns,height:process.stdout.rows};return}let J=process.stdout.getWindowSize();if(J[0]>0&&J[1]>0){this.terminalSize={width:J[0],height:J[1]};return}}catch(J){}}handleKeyEvent(J){for(let Q of this.keyHandlers)Q(J)}handlePasteEvent(J){let Q={type:"paste",text:I56(J.text)};for(let Z of this.pasteHandlers)Z(Q)}handleOscEvent(J){if(J.data.startsWith("52;c;")){let Q=J.data.slice(5);if(Q&&Q!=="?")WG.handleOSC52Response(Q)}}createCapabilityPromise(){this.capabilityPromise=new Promise((J)=>{this.capabilityResolve=J})}startCapabilityDetection(){if(!this.tty.stdin||!h56(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new v41,process.env.TERM_PROGRAM==="Apple_Terminal"){let J=$m({canRgb:!1});this.capabilities=J;let Q={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Z of this.capabilityHandlers)Z(Q);if(this.capabilityResolve)this.capabilityResolve(J),this.capabilityResolve=null;return}for(let J of B56)process.stdout.write(J.sequence);this.capabilityTimeout=setTimeout(()=>{if(!this.capabilities&&this.capabilityResolve&&this.queryParser)this.finishInitialization()},2000)}finishInitialization(){if(!this.initialized||!this.queryParser||this.capabilities)return;if(this.capabilities=this.queryParser.getCapabilities(),this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;let J={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let Q of this.capabilityHandlers)Q(J);if(this.capabilityResolve)l.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Q=this.queryParser.getPixelDimensions();if(Q){let Z=Q.pixelWidth/Q.columns,X=Q.pixelHeight/Q.rows;this.parser?.setSgrToMouseConverter((Y)=>Pm(Y,!0,Z,X))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();this.enableInBandResize(),WG.setCapabilities(this.capabilities)}parseXtgettcapResponse(J){if(!this.queryParser)return;let Q=J.indexOf("=");if(Q!==-1){let Z=J.slice(0,Q),X=J.slice(Q+1);if(this.queryParser.processXtgettcap(Z,X))this.finishInitialization()}}handleResize(){if(this.pendingResize=!0,this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer);this.resizeDebounceTimer=setTimeout(()=>{this.processResize()},10)}handleInbandResize(J){if(this.terminalSize={width:J.width,height:J.height},this.queryParser&&J.pixelWidth&&J.pixelHeight){let Q=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(J.width,J.height,J.pixelWidth,J.pixelHeight);let Z=this.queryParser.shouldUsePixelMouse();if(!Q&&Z)this.disableMouse(),this.enableMouse();if(Z){let X=J.pixelWidth/J.width,Y=J.pixelHeight/J.height;this.parser?.setSgrToMouseConverter((K)=>Pm(K,!0,X,Y))}}this.screen.resize(J.width,J.height),setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(J)}catch(Z){l.error("Error in resize handler:",Z)}})}processResize(){if(!this.pendingResize||!this.initialized)return;let J={...this.terminalSize};if(this.updateTerminalSize(),J.width===this.terminalSize.width&&J.height===this.terminalSize.height){this.pendingResize=!1;return}this.finishResize(),this.pendingResize=!1}finishResize(){this.screen.resize(this.terminalSize.width,this.terminalSize.height);let J={type:"resize",width:this.terminalSize.width,height:this.terminalSize.height};setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(J)}catch(Z){l.error("Error in resize handler:",Z)}})}setupCleanupHandlers(){process.setMaxListeners(0),process.on("SIGINT",this.boundCleanup),process.on("SIGTERM",this.boundCleanup),process.on("exit",this.boundCleanup),process.on("SIGCONT",this.boundHandleResume)}cleanup(){try{this.deinit()}catch{}}}function h56(J){return"isTTY"in J&&J.isTTY===!0&&typeof J.setRawMode==="function"}F0();F0();R4();var km;((Y)=>{Y.BUILD="build";Y.LAYOUT="layout";Y.PAINT="paint";Y.RENDER="render"})(km||={});var c09=60,rb1=1000/c09;class nQ{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_lastFrameTime=0;TARGET_FPS=60;FRAME_TIME=1000/this.TARGET_FPS;_stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}};_lastCompletedStats=this.deepCopyStats(this._stats);static get instance(){return this._instance??=new nQ}requestFrame(){if(this._frameScheduled)return;this._frameScheduled=!0,setImmediate(()=>this.executeFrame())}addFrameCallback(J,Q,Z,X=0,Y){this._frameCallbacks.set(J,{callback:Q,phase:Z,priority:X,name:Y||J})}removeFrameCallback(J){this._frameCallbacks.delete(J)}addPostFrameCallback(J,Q){if(this._postFrameCallbacks.push({callback:J,name:Q}),!this._frameScheduled&&!this._frameInProgress)this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let J=performance.now();this._frameScheduled=!1,this._frameInProgress=!0,this._lastFrameTime=J;try{for(let Q of["build","layout","paint","render"])this.executePhase(Q);this.executePostFrameCallbacks()}catch(Q){l.error("Frame execution error:",Q instanceof Error?Q.message:String(Q))}finally{this.recordFrameStats(performance.now()-J),this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1}}executePhase(J){let Q=performance.now();try{let Z=Array.from(this._frameCallbacks.values()).filter((X)=>X.phase===J).sort((X,Y)=>X.priority-Y.priority);for(let X of Z)try{X.callback()}catch(Y){l.error(`Frame callback error in ${J} phase (${X.name})`,{errorMessage:Y instanceof Error?Y.message:String(Y),errorType:Y?.constructor?.name,stackTrace:Y instanceof Error?Y.stack:void 0}),G8(!1,`FATAL: ${J} error in ${X.name}: ${Y}`)}}finally{let Z=performance.now()-Q;this.recordPhaseStats(J,Z)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let J=this._postFrameCallbacks.splice(0);for(let{callback:Q,name:Z}of J)try{Q()}catch(X){l.error(`Post-frame callback error (${Z||"anonymous"}):`,X instanceof Error?X.message:String(X))}}recordFrameStats(J){this._stats.lastFrameTime=J}recordPhaseStats(J,Q){this._stats.phaseStats[J].lastTime=Q}get isFrameScheduled(){return this._frameScheduled||this._frameInProgress}get isFrameInProgress(){return this._frameInProgress}get frameStats(){return this.deepCopyStats(this._lastCompletedStats)}deepCopyStats(J){return{...J,phaseStats:{["build"]:{...J.phaseStats.build},["layout"]:{...J.phaseStats.layout},["paint"]:{...J.phaseStats.paint},["render"]:{...J.phaseStats.render}}}}resetStats(){this._stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}}}get pendingPostFrameCallbacks(){return this._postFrameCallbacks.length}dispose(){this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this.resetStats()}}class sb1{_dirtyElements=new Set;_stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0};_buildTimes=[];_elementsPerFrame=[];constructor(){}scheduleBuildFor(J){if(this._dirtyElements.has(J))return;this._dirtyElements.add(J),nQ.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let J=performance.now(),Q=0;try{while(this._dirtyElements.size>0){let Z=Array.from(this._dirtyElements);this._dirtyElements.clear(),Z.sort((X,Y)=>X.depth-Y.depth);for(let X of Z)if(X.dirty)try{X.performRebuild(),X._dirty=!1,Q++}catch(Y){l.error("Element rebuild error:",Y instanceof Error?Y.message:String(Y)),X._dirty=!1}}}finally{this.recordBuildStats(performance.now()-J,Q)}}recordBuildStats(J,Q){if(this._stats.totalRebuilds+=Q,this._stats.elementsRebuiltThisFrame=Q,this._stats.lastBuildTime=J,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Q),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,J),this._buildTimes.push(J),this._elementsPerFrame.push(Q),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((Z,X)=>Z+X,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((Z,X)=>Z+X,0)/this._elementsPerFrame.length}get dirtyElements(){return Array.from(this._dirtyElements)}get hasDirtyElements(){return this._dirtyElements.size>0}get buildStats(){return{...this._stats}}resetBuildStats(){this._stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0},this._buildTimes.length=0,this._elementsPerFrame.length=0}dispose(){this._dirtyElements.clear()}}class j2{_parent=null;_children=new Set;_hasFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_focusChangeListeners=new Set;_debugLabel=null;static _requestFocusCallback=null;constructor(J={}){if(this._debugLabel=J.debugLabel??null,this._canRequestFocus=J.canRequestFocus??!0,this._skipTraversal=J.skipTraversal??!1,J.onKey)this._keyHandlers.push(J.onKey);this._onPasteCallback=J.onPaste??null}get hasFocus(){return this._hasFocus}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(J){if(this._canRequestFocus!==J){if(this._canRequestFocus=J,!J&&this._hasFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(J){this._skipTraversal=J}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(J){this._onPasteCallback=J}static setRequestFocusCallback(J){j2._requestFocusCallback=J}requestFocus(){if(!this._canRequestFocus)return!1;if(j2._requestFocusCallback)return j2._requestFocusCallback(this);return!1}unfocus(){if(this._hasFocus){if(j2._requestFocusCallback)j2._requestFocusCallback(null)}}_attach(J){if(this._parent===J)return;if(this._parent)this._parent._children.delete(this);if(this._parent=J,J)J._children.add(this);if(j2._requestFocusCallback){let Q=j2._requestFocusCallback.__focusManager;if(Q&&Q._invalidateFocusableNodesCache)Q._invalidateFocusableNodesCache()}}_detach(){if(this._parent)this._parent._children.delete(this),this._parent=null;if(j2._requestFocusCallback){let J=j2._requestFocusCallback.__focusManager;if(J&&J._invalidateFocusableNodesCache)J._invalidateFocusableNodesCache()}if(this._hasFocus)this.unfocus()}_setFocus(J){if(this._hasFocus===J)return;this._hasFocus=J,this._notifyListeners()}addFocusChangeListener(J){this._focusChangeListeners.add(J)}removeFocusChangeListener(J){this._focusChangeListeners.delete(J)}_notifyListeners(){for(let J of this._focusChangeListeners)J(this._hasFocus)}_handleKeyEvent(J){return this.handleKeyEvent(J)}_handlePasteEvent(J){if(this._onPasteCallback)return this._onPasteCallback(J);return"ignored"}toStringShort(){let J=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasFocus?" FOCUSED":"",Z=this._canRequestFocus?"":" (can't focus)";return`FocusNode${J}${Q}${Z}`}toStringDeep(J="",Q=!0){let Z=J+this.toStringShort();if(Q&&this._children.size>0){let X=J+" ";for(let Y of this._children)Z+=`
5841
5841
  `+Y.toStringDeep(X,!0)}return Z}addKeyHandler(J){this._keyHandlers.push(J)}removeKeyHandler(J){let Q=this._keyHandlers.indexOf(J);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(J){for(let Q of this._keyHandlers)if(Q(J)==="handled")return"handled";return"ignored"}dispose(){this._detach(),this._children.clear(),this._keyHandlers=[]}}class UV{static _instance=null;_rootScope;_primaryFocus=null;_cachedFocusableNodes=null;constructor(){this._rootScope=new j2({debugLabel:"Root Focus Scope",canRequestFocus:!1});let J=(Q)=>this.requestFocus(Q);J.__focusManager=this,j2.setRequestFocusCallback(J)}static get instance(){if(!this._instance)this._instance=new UV;return this._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(J){if(this._primaryFocus===J)return!0;if(J&&!J.canRequestFocus)return!1;if(this._primaryFocus)this._primaryFocus._setFocus(!1);if(this._primaryFocus=J,J)J._setFocus(!0);return!0}handleKeyEvent(J){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handleKeyEvent(J)==="handled")return!0;Q=Q.parent}return!1}handlePasteEvent(J){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(J)==="handled")return!0;Q=Q.parent}return!1}registerNode(J,Q=null){this._invalidateFocusableNodesCache();let Z=Q??this._rootScope;J._attach(Z)}unregisterNode(J){if(this._invalidateFocusableNodesCache(),this._primaryFocus===J)this.requestFocus(null);J._detach()}findNearestFocusableAncestor(J){let Q=J.parent;while(Q){if(Q.canRequestFocus&&!Q.skipTraversal)return Q;Q=Q.parent}return null}findAllFocusableNodes(){if(this._cachedFocusableNodes!==null)return this._cachedFocusableNodes;let J=[],Q=(Z)=>{if(Z.canRequestFocus&&!Z.skipTraversal)J.push(Z);for(let X of Z.children)Q(X)};return Q(this._rootScope),this._cachedFocusableNodes=J,J}_invalidateFocusableNodesCache(){this._cachedFocusableNodes=null}focusNext(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[0]??null);let Q=J.indexOf(this._primaryFocus);if(Q===-1)return this.requestFocus(J[0]??null);let Z=(Q+1)%J.length;return this.requestFocus(J[Z]??null)}focusPrevious(){let J=this.findAllFocusableNodes();if(J.length===0)return!1;if(!this._primaryFocus)return this.requestFocus(J[J.length-1]??null);let Q=J.indexOf(this._primaryFocus);if(Q===-1)return this.requestFocus(J[J.length-1]??null);let Z=Q===0?J.length-1:Q-1;return this.requestFocus(J[Z]??null)}dispose(){this._primaryFocus=null,this._cachedFocusableNodes=null,this._rootScope.dispose(),UV._instance=null}}function y41(J){if(J.length===0)return 0;let Q=[...J].sort((X,Y)=>X-Y),Z=Math.ceil(Q.length*0.99)-1;return Q[Math.max(0,Z)]||0}class m56{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];lastKeyEventTime=0;lastMouseEventTime=0;MAX_SAMPLES=1024;recordFrame(J){if(this.frameTimes.push(J),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(J,Q){let Z=this.phaseTimes[J];if(Z.push(Q),Z.length>this.MAX_SAMPLES)Z.shift()}recordKeyEvent(J){if(this.lastKeyEventTime=J,this.keyEventTimes.push(J),this.keyEventTimes.length>this.MAX_SAMPLES)this.keyEventTimes.shift()}recordMouseEvent(J){if(this.lastMouseEventTime=J,this.mouseEventTimes.push(J),this.mouseEventTimes.length>this.MAX_SAMPLES)this.mouseEventTimes.shift()}getFrameP99(){return y41(this.frameTimes)}getPhaseP99(J){return y41(this.phaseTimes[J])}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return y41(this.keyEventTimes)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return y41(this.mouseEventTimes)}reset(){this.frameTimes=[];for(let J of Object.values(km))this.phaseTimes[J]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0}}class ob1{enabled=!1;tracker=new m56;setEnabled(J){this.enabled=J}isEnabled(){return this.enabled}recordKeyEvent(J){this.tracker.recordKeyEvent(J)}recordMouseEvent(J){this.tracker.recordMouseEvent(J)}recordStats(J){this.tracker.recordFrame(J.lastFrameTime);for(let Q of Object.values(km))this.tracker.recordPhase(Q,J.phaseStats[Q].lastTime)}draw(J,Q){if(!this.enabled)return;let{width:Z,height:X}=J.getSize(),Y=26,K=12,q=Z-Y-2,G=1;if(q<0||G+K>=X)return;let z=b1.white,U=b1.brightWhite,W=b1.yellow,F=" Gotta Go Fast ",H=Math.floor((Y-F.length)/2);J.setCell(q,G,N9("╭",{fg:U}));for(let b=1;b<Y-1;b++)if(b>=H&&b<H+F.length)J.setCell(q+b,G,N9(F[b-H]||"─",{fg:W}));else J.setCell(q+b,G,N9("─",{fg:U}));J.setCell(q+Y-1,G,N9("╮",{fg:U}));for(let b=1;b<K-1;b++){J.setCell(q,G+b,N9("│",{fg:U})),J.setCell(q+Y-1,G+b,N9("│",{fg:U}));for(let m=1;m<Y-1;m++)J.setCell(q+m,G+b,N9(" ",{fg:U}))}J.setCell(q,G+K-1,N9("╰",{fg:U}));for(let b=1;b<Y-1;b++)J.setCell(q+b,G+K-1,N9("─",{fg:U}));J.setCell(q+Y-1,G+K-1,N9("╯",{fg:U}));let B=q+1,M=G+1;this.drawText(J,B,M++," Last P99",z);let V=this.tracker.getLastKeyEventTime(),N=this.tracker.getKeyEventP99(),L=V.toFixed(2).padStart(5," "),A=N.toFixed(2).padStart(5," "),O=this.getTimingColor(V),j=this.getTimingColor(N),R=` ${"Key".padStart(6," ")} `;this.drawText(J,B,M,R,z),this.drawText(J,B+R.length,M,L,O),this.drawText(J,B+R.length+L.length,M," ",z),this.drawText(J,B+R.length+L.length+3,M++,A,j);let I=this.tracker.getLastMouseEventTime(),w=this.tracker.getMouseEventP99(),E=I.toFixed(2).padStart(5," "),$=w.toFixed(2).padStart(5," "),P=this.getTimingColor(I),C=this.getTimingColor(w),k=` ${"Mouse".padStart(6," ")} `;this.drawText(J,B,M,k,z),this.drawText(J,B+k.length,M,E,P),this.drawText(J,B+k.length+E.length,M," ",z),this.drawText(J,B+k.length+E.length+3,M++,$,C),M++;for(let b of["build","layout","paint","render"]){let m=Q.phaseStats[b].lastTime,a=this.tracker.getPhaseP99(b),p=m.toFixed(2).padStart(5," "),J1=a.toFixed(2).padStart(5," "),q1=this.getTimingColor(m),F1=this.getTimingColor(a),W1=` ${(b.charAt(0).toUpperCase()+b.slice(1)).padStart(6," ")} `;this.drawText(J,B,M,W1,z),this.drawText(J,B+W1.length,M,p,q1),this.drawText(J,B+W1.length+p.length,M," ",z),this.drawText(J,B+W1.length+p.length+3,M++,J1,F1)}M++;let h=Q.lastFrameTime,T=this.tracker.getFrameP99(),v=h.toFixed(2).padStart(5," "),f=T.toFixed(2).padStart(5," "),g=this.getTimingColor(h),S=this.getTimingColor(T),y=` ${"Frame".padStart(6," ")} `;this.drawText(J,B,M,y,U),this.drawText(J,B+y.length,M,v,g),this.drawText(J,B+y.length+v.length,M," ",U),this.drawText(J,B+y.length+v.length+3,M++,f,S)}getTimingColor(J){let Q=rb1,Z=rb1*0.7;if(J>=Q)return b1.red;if(J>=Z)return b1.yellow;return b1.white}drawText(J,Q,Z,X,Y){for(let K=0;K<X.length;K++)J.setCell(Q+K,Z,N9(X[K]||" ",{fg:Y}))}}zH();class oX extends ZQ{child;constructor({key:J,child:Q}){super(J!==void 0?{key:J}:{});this.child=Q}createElement(){return new u56(this)}}class u56 extends nX{_child;_dependents=new Set;constructor(J){super(J)}get inheritedWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.inheritedWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._dependents.clear(),super.unmount()}update(J){let Q=this.inheritedWidget;super.update(J);let Z=this.inheritedWidget;if(Z.updateShouldNotify(Q))this.notifyDependents();if(this._child&&this._child.widget.canUpdate(Z.child))this._child.update(Z.child);else{if(this._child)this._child.unmount(),this.removeChild(this._child);this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount()}}addDependent(J){this._dependents.add(J)}removeDependent(J){this._dependents.delete(J)}notifyDependents(){for(let J of this._dependents)J.markNeedsRebuild()}performRebuild(){}}class AT{size;capabilities;constructor(J,Q){this.size=J;this.capabilities=Q}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}class m8 extends oX{data;constructor({key:J,data:Q,child:Z}){super(J!==void 0?{key:J,child:Z}:{child:Z});this.data=Q}updateShouldNotify(J){return this.data!==J.data||this.data.size.width!==J.data.size.width||this.data.size.height!==J.data.size.height||this.data.capabilities!==J.data.capabilities}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(m8);if(Q)return Q.widget.data;throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.")}static sizeOf(J){return m8.of(J).size}static capabilitiesOf(J){return m8.of(J).capabilities}}R4();v9();zH();class OT extends ZQ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new _m(this)}updateRenderObject(J){}}class f4 extends OT{child;constructor({key:J,child:Q}={}){super(J?{key:J}:{});this.child=Q}createElement(){return new FV(this)}}class tX extends OT{children;constructor({key:J,children:Q=[]}={}){super(J?{key:J}:{});this.children=[...Q]}createElement(){return new f41(this)}}class BH extends OT{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new HV(this)}}class _m extends nX{_renderObject;constructor(J){super(J)}get renderObjectWidget(){return this.widget}get renderObject(){return this._renderObject}mount(){this._renderObject=this.renderObjectWidget.createRenderObject(),this._renderObject.attach(),this.markMounted()}unmount(){if(this._renderObject)this._renderObject.detach(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Q=this.renderObjectWidget;if(this._renderObject)Q.updateRenderObject(this._renderObject)}performRebuild(){}}class FV extends _m{_child;constructor(J){super(J)}get singleChildWidget(){return this.widget}get child(){return this._child}mount(){if(super.mount(),this.singleChildWidget.child){if(this._child=this.singleChildWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject&&this.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Q=this.singleChildWidget;if(Q.child&&this._child){if(this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject){if(this.renderObject.removeAllChildren(),this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}else if(Q.child&&!this._child){if(this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject&&this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}else if(!Q.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this.renderObject)this.renderObject.removeAllChildren()}}performRebuild(){}}class f41 extends _m{_childElements=[];constructor(J){super(J)}get multiChildWidget(){return this.widget}get children(){return this._childElements}mount(){super.mount();for(let J of this.multiChildWidget.children){let Q=J.createElement();if(this._childElements.push(Q),this.addChild(Q),Q.mount(),Q.renderObject&&this.renderObject)this.renderObject.adoptChild(Q.renderObject)}}unmount(){for(let J of this._childElements)J.unmount(),this.removeChild(J);this._childElements.length=0,super.unmount()}update(J){super.update(J);let Q=this.multiChildWidget;this.updateChildren(this._childElements,[...Q.children])}updateChildren(J,Q){let Z=[],X=0,Y=0,K=J.length-1,q=Q.length-1;while(X<=K&&Y<=q){let U=J[X],W=Q[Y];if(!U||!W||!U.widget.canUpdate(W))break;if(U.widget!==W)U.update(W);Z.push(U),X++,Y++}let G=[];while(X<=K&&Y<=q){let U=J[K],W=Q[q];if(!U||!W||!U.widget.canUpdate(W))break;if(U.widget!==W)U.update(W);G.unshift(U),K--,q--}if(X>K)for(let U=Y;U<=q;U++){let W=Q[U];if(W){let F=this.createChildElement(W);Z.push(F)}}else if(Y>q)for(let U=X;U<=K;U++){let W=J[U];if(W)this.deactivateChild(W)}else{let U=new Map,W=new Map;for(let F=X;F<=K;F++){let H=J[F];if(H.widget.key){let B=H.widget.key.toString();U.set(B,H),W.set(B,F)}}for(let F=Y;F<=q;F++){let H=Q[F];if(!H)continue;let B;if(H.key){let M=H.key.toString();if(B=U.get(M),B){U.delete(M);let V=W.get(M);if(V!==void 0)J[V]=null;if(B.widget===H);else if(B.widget.canUpdate(H))B.update(H);else this.deactivateChild(B),B=this.createChildElement(H)}else B=this.createChildElement(H)}else{let M=!1;for(let V=X;V<=K;V++){let N=J[V];if(N&&!N.widget.key){if(N.widget===H){B=N,J[V]=null,M=!0;break}else if(N.widget.canUpdate(H)){B=N,J[V]=null,B.update(H),M=!0;break}}}if(!M)B=this.createChildElement(H)}if(B)Z.push(B)}for(let F=X;F<=K;F++){let H=J[F];if(H)this.deactivateChild(H)}for(let F of U.values())this.deactivateChild(F)}Z.push(...G);let z=this._childElements;if(this._childElements=Z,this.renderObject){let U=[];for(let H of Z)if(H.renderObject)U.push(H.renderObject);let W=this.renderObject.children;if(W.length!==U.length||W.some((H,B)=>H!==U[B]))this.renderObject.replaceChildren(U)}}createChildElement(J){let Q=J.createElement();return this.addChild(Q),Q.mount(),Q}deactivateChild(J){J.unmount(),this.removeChild(J)}performRebuild(){}}class HV extends _m{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}class h4 extends f4{child;onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;constructor({key:J,child:Q,onClick:Z,onEnter:X,onExit:Y,onHover:K,onScroll:q,onRelease:G,onDrag:z,cursor:U,opaque:W=!0}){super({key:J});this.child=Q,this.onClick=Z??null,this.onEnter=X??null,this.onExit=Y??null,this.onHover=K??null,this.onScroll=q??null,this.onRelease=G??null,this.onDrag=z??null,this.cursor=U??null,this.opaque=W}createElement(){return new p56(this)}createRenderObject(){return new FG({onClick:this.onClick,onEnter:this.onEnter,onExit:this.onExit,onHover:this.onHover,onScroll:this.onScroll,onRelease:this.onRelease,onDrag:this.onDrag,cursor:this.cursor,opaque:this.opaque})}updateRenderObject(J){J.onClick=this.onClick,J.onEnter=this.onEnter,J.onExit=this.onExit,J.onHover=this.onHover,J.onScroll=this.onScroll,J.onRelease=this.onRelease,J.onDrag=this.onDrag,J.cursor=this.cursor,J.opaque=this.opaque}}class p56 extends FV{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}}class FG extends i6{onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;_isHovered=!1;constructor({onClick:J,onEnter:Q,onExit:Z,onHover:X,onScroll:Y,onRelease:K,onDrag:q,cursor:G,opaque:z}){super();this.onClick=J,this.onEnter=Q,this.onExit=Z,this.onHover=X,this.onScroll=Y,this.onRelease=K,this.onDrag=q,this.cursor=G,this.opaque=z}get hasMouseListeners(){return!!(this.onClick||this.onEnter||this.onExit||this.onHover||this.onScroll||this.onRelease||this.onDrag)}get isHovered(){return this._isHovered}handleMouseEvent(J){switch(J.type){case"click":this.onClick?.(J);break;case"enter":this._isHovered=!0,this.onEnter?.(J);break;case"exit":this._isHovered=!1,this.onExit?.(J);break;case"hover":this.onHover?.(J);break;case"scroll":this.onScroll?.(J);break}}handleMouseRelease(J){this.onRelease?.(J)}handleMouseDrag(J){this.onDrag?.(J)}performLayout(){let J=this._lastConstraints;if(G8(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height),Q.setOffset(0,0)}else this.setSize(0,0);super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}getMinIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}paint(J,Q=0,Z=0){if(this.children.length>0)this.children[0].paint(J,Q+this.offset.x,Z+this.offset.y)}hitTest(J,Q,Z=0,X=0){let Y=super.hitTest(J,Q,Z,X);if(Y&&this.hasMouseListeners)J.addMouseTarget(this,Q);return Y}getDebugProperties(){return{hasMouseListeners:this.hasMouseListeners,isHovered:this.isHovered,cursor:this.cursor,opaque:this.opaque}}dispose(){YQ.instance.removeRegion(this),this.onClick=null,this.onEnter=null,this.onExit=null,this.onHover=null,this.onScroll=null,this.onRelease=null,this.onDrag=null,this.cursor=null,super.dispose()}}v9();class tb1{static hitTest(J,Q){let Z=new d56;return J.hitTest(Z,Q),Z}}class d56{_hits=[];get hits(){return this._hits}add(J){this._hits.push(J)}addWithPaintOffset(J,Q,Z){let X={x:Z.x-Q.x,y:Z.y-Q.y};this.add({target:J,localPosition:X})}addMouseTarget(J,Q){}}function l09(){if(!ZV.prototype.hitTest)ZV.prototype.hitTest=function(J,Q,Z=0,X=0){if("size"in this&&"offset"in this){let K=this,q=K.size,G=K.offset;if(q&&G){let z=Z+G.x,U=X+G.y,W=Q.x>=z&&Q.x<z+q.width,F=Q.y>=U&&Q.y<U+q.height;if(W&&F){let H={x:Q.x-z,y:Q.y-U};J.add({target:this,localPosition:H});let B=this.children,M=!0;for(let V=B.length-1;V>=0;V--)if(B[V].hitTest(J,Q,z,U))M=!0;return M}if(this.allowHitTestOutsideBounds){let H=!1,B=this.children;for(let M=B.length-1;M>=0;M--)if(B[M].hitTest(J,Q,z,U))H=!0;return H}return!1}}let Y=!1;for(let K of this.children)if(K.hitTest(J,Q,Z,X))Y=!0;return Y}}l09();function c56(J,Q,Z){return{position:Q,localPosition:Z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}}}function l56(J,Q,Z,X=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:X,...c56(J,Q,Z)}}function i56(J,Q,Z){return{type:"scroll",direction:J.button==="wheel_up"?"up":"down",...c56(J,Q,Z)}}class YQ{static _instance=null;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=D5.DEFAULT;_lastMousePosition=null;_dragTargets=[];_globalReleaseCallbacks=new Set;_globalClickCallbacks=new Set;_lastClickTime=new Map;_lastClickPosition=new Map;_currentClickCount=new Map;static DOUBLE_CLICK_TIME=500;static DOUBLE_CLICK_DISTANCE=2;static DOUBLE_CLICK_DISTANCE_SQUARED=YQ.DOUBLE_CLICK_DISTANCE*YQ.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!this._instance)this._instance=new YQ;return this._instance}setRootRenderObject(J){this._rootRenderObject=J}setTui(J){this._vaxis=J}handleMouseEvent(J){if(!this._rootRenderObject)return;let Q={x:J.x,y:J.y},Z=tb1.hitTest(this._rootRenderObject,Q),X=this._findMouseTargets(Z.hits);switch(J.action){case"press":if(J.button==="left"||J.button==="middle"||J.button==="right"){if(this._handleClick(J,Q,X),J.button==="left")this._dragTargets=X.map(({target:Y,localPosition:K})=>{let q={x:Q.x-K.x,y:Q.y-K.y};return{target:Y,localPosition:K,globalOffset:q}})}break;case"release":this._handleRelease(J,Q,X),this._dragTargets=[];break;case"scroll":if(J.button==="wheel_up"||J.button==="wheel_down")this._handleScroll(J,Q,X);break;case"move":if(this._handleMove(J,Q,X),J.drag)this._handleDrag(J,Q,X);break}this._lastMousePosition=Q}addGlobalReleaseCallback(J){this._globalReleaseCallbacks.add(J)}removeGlobalReleaseCallback(J){this._globalReleaseCallbacks.delete(J)}addGlobalClickCallback(J){this._globalClickCallbacks.add(J)}removeGlobalClickCallback(J){this._globalClickCallbacks.delete(J)}requestCursorChange(J){if(this._vaxis&&J!==this._currentCursor)this._currentCursor=J,this._vaxis.setMouseCursor(J)}_handleRelease(J,Q,Z){for(let X of this._globalReleaseCallbacks)X();for(let{target:X,localPosition:Y}of Z){if(typeof X.handleMouseRelease==="function")X.handleMouseRelease({type:"release",position:Q,localPosition:Y,button:J.button,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}});if(X instanceof FG&&X.opaque)break}}_handleDrag(J,Q,Z){for(let{target:X,globalOffset:Y}of this._dragTargets)if(typeof X.handleMouseDrag==="function"){let K={x:Q.x-Y.x,y:Q.y-Y.y};X.handleMouseDrag({type:"drag",position:Q,localPosition:K,button:J.button,drag:J.drag,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}})}}_handleClick(J,Q,Z){let X=this._calculateClickCount(Q,J.button);for(let Y of this._globalClickCallbacks)Y({event:J,globalPosition:Q,mouseTargets:Z,clickCount:X});for(let{target:Y,localPosition:K}of Z){let q=l56(J,Q,K,X);if(Y.handleMouseEvent(q),Y instanceof FG&&Y.opaque)break}}_handleScroll(J,Q,Z){for(let{target:X,localPosition:Y}of Z){let K=i56(J,Q,Y);if(X.handleMouseEvent(K),X instanceof FG&&X.opaque)break}}_handleMove(J,Q,Z){let X=Z.filter((G)=>G.target instanceof FG),Y=this._scratchCurrentRegions,K=this._scratchExitedRegions,q=this._scratchEnteredRegions;Y.clear();for(let{target:G}of X)Y.add(G);K.clear();for(let G of this._hoveredRegions)if(!Y.has(G))K.add(G);q.clear();for(let G of Y)if(!this._hoveredRegions.has(G))q.add(G);for(let G of K)if(G.onExit){let z={type:"exit",position:Q,localPosition:Q,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(z)}for(let{target:G,localPosition:z}of X)if(q.has(G)&&G.onEnter){let U={type:"enter",position:Q,localPosition:z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(U)}for(let{target:G,localPosition:z}of X)if(G.onHover&&this._hoveredRegions.has(G)){let U={type:"hover",position:Q,localPosition:z,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt}};G.handleMouseEvent(U)}this._hoveredRegions.clear();for(let G of Y)this._hoveredRegions.add(G);this._updateCursor(X)}_updateCursor(J){if(!this._vaxis)return;let Q=D5.DEFAULT;for(let{target:Z}of J)if(Z.cursor!==null)Q=Z.cursor;if(Q!==this._currentCursor)this._currentCursor=Q,this._vaxis.setMouseCursor(Q)}_findMouseTargets(J){let Q=[];for(let Z of J)if(this._canHandleMouseEvents(Z.target))Q.push({target:Z.target,localPosition:Z.localPosition});return Q}_canHandleMouseEvents(J){if(J instanceof FG)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==D5.DEFAULT)this._currentCursor=D5.DEFAULT,this._vaxis.setMouseCursor(D5.DEFAULT)}removeRegion(J){this._hoveredRegions.delete(J)}reestablishHoverState(){if(!this._lastMousePosition||!this._rootRenderObject)return;let J={type:"mouse",action:"move",x:this._lastMousePosition.x,y:this._lastMousePosition.y,button:"unknown",drag:!1,modifiers:{shift:!1,ctrl:!1,alt:!1,meta:!1}};this.handleMouseEvent(J)}_calculateClickCount(J,Q="left"){let Z=Date.now(),X=this._lastClickTime.get(Q)??0,Y=Z-X,K=1,q=this._lastClickPosition.get(Q);if(q&&Y<=YQ.DOUBLE_CLICK_TIME&&this._isWithinDoubleClickDistance(J,q))K=(this._currentClickCount.get(Q)??0)+1;else K=1;return this._lastClickTime.set(Q,Z),this._lastClickPosition.set(Q,J),this._currentClickCount.set(Q,K),K}_isWithinDoubleClickDistance(J,Q){let Z=J.x-Q.x,X=J.y-Q.y;return Z*Z+X*X<=YQ.DOUBLE_CLICK_DISTANCE_SQUARED}dispose(){this.clearHoverState(),this._lastMousePosition=null,this._rootRenderObject=null,this._lastClickTime.clear(),this._lastClickPosition.clear(),this._currentClickCount.clear(),this._globalReleaseCallbacks.clear(),this._globalClickCallbacks.clear(),YQ._instance=null}}v9();class eb1{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(J){if(!nQ.instance.isFrameInProgress)nQ.instance.requestFrame()}requestPaint(J){if(this._nodesNeedingPaint.has(J))return;if(this._nodesNeedingPaint.add(J),!nQ.instance.isFrameInProgress)nQ.instance.requestFrame()}setRootRenderObject(J){this._rootRenderObject=J}updateRootConstraints(J){let Q=new u6(0,J.width,0,J.height),Z=!this._rootConstraints||this._rootConstraints.maxWidth!==Q.maxWidth||this._rootConstraints.maxHeight!==Q.maxHeight;if(this._rootConstraints=Q,Z&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){if(this._rootRenderObject&&this._rootConstraints&&"needsLayout"in this._rootRenderObject&&this._rootRenderObject.needsLayout){if("layout"in this._rootRenderObject&&typeof this._rootRenderObject.layout==="function")this._rootRenderObject.layout(this._rootConstraints)}}flushPaint(){if(this._nodesNeedingPaint.size===0)return;try{for(let J of this._nodesNeedingPaint)if(J.needsPaint)J._needsPaint=!1}finally{this._nodesNeedingPaint.clear()}}get nodesNeedingLayout(){return[]}get nodesNeedingPaint(){return Array.from(this._nodesNeedingPaint)}get hasNodesNeedingLayout(){return!1}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(J){this._nodesNeedingPaint.delete(J)}}class HG{static _instance;frameScheduler=nQ.instance;buildOwner;pipelineOwner;focusManager=UV.instance;mouseManager=YQ.instance;frameStatsOverlay=new ob1;tui=new nb1;rootElement;isRunning=!1;rootElementMountedCallback;static get instance(){return this._instance??=new HG}pendingResizeEvent=null;constructor(){this.buildOwner=new sb1,this.pipelineOwner=new eb1,this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>this.buildOwner.buildScopes(),"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{this.updateRootConstraints(),this.pipelineOwner.flushLayout()},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),g26({scheduleBuildFor:(J)=>this.buildOwner.scheduleBuildFor(J)},{requestLayout:(J)=>this.pipelineOwner.requestLayout(J),requestPaint:(J)=>this.pipelineOwner.requestPaint(J),removeFromQueues:(J)=>this.pipelineOwner.removeFromQueues(J)}),this.setupErrorHandler()}setupErrorHandler(){process.on("uncaughtException",(J)=>{l.error("Framework uncaught exception",J)})}async runApp(J){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Q}=await Promise.resolve().then(() => a56);Q(this.tui);let{initIdleTracking:Z}=await Promise.resolve().then(() => (Xx1(),r56));Z(this.tui),await this.tui.waitForCapabilities(1000);let X=this.createMediaQueryWrapper(J);if(this.rootElement=X.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let Y=this.rootElement.renderObject;if(!Y&&this.rootElement.children.length>0)Y=this.rootElement.children[0]?.renderObject;if(Y)this.pipelineOwner.setRootRenderObject(Y),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),l.debug("Setting up event handlers..."),this.setupEventHandlers(),l.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),l.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),l.debug("waitForExit completed")}finally{l.debug("Cleaning up..."),await this.cleanup()}}stop(){if(this.isRunning=!1,this.exitResolve)this.exitResolve(),this.exitResolve=null}updateRootConstraints(){let J=this.tui.getSize();this.pipelineOwner.updateRootConstraints(J)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let J=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Q={width:J.width,height:J.height},Z=this.tui.getCapabilities()||$m(),X=new AT(Q,Z),Y=this.rootElement;if(Y.widget instanceof m8){let q=new m8({data:X,child:Y.widget.child});Y.update(q)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Q),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}paint(){if(this.pipelineOwner.flushPaint(),!this.rootElement)return;let J=this.rootElement.renderObject;if(!J&&this.rootElement.children.length>0)J=this.rootElement.children[0]?.renderObject;if(!J)return;try{let Q=this.tui.getScreen();Q.clear(),Q.clearCursor(),this.renderRenderObject(J,Q,0,0);let Z=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats(Z),this.frameStatsOverlay.draw(Q,Z)}catch(Q){l.error("Paint error:",Q)}}render(){try{this.tui.render()}catch(J){l.error("Render error:",J)}}renderRenderObject(J,Q,Z,X){if("paint"in J&&typeof J.paint==="function")J.paint(Q,Z,X)}createMediaQueryWrapper(J){let Q=this.tui.getCapabilities()||$m(),Z=this.tui.getSize(),X=new AT(Z,Q);return new m8({data:X,child:J})}setupEventHandlers(){this.tui.onResize((J)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=J,this.frameScheduler.requestFrame()}),this.tui.onKey((J)=>{let Q=performance.now();if(this.focusManager.handleKeyEvent(J)){let Y=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(Y);return}this.handleGlobalKeyEvent(J);let X=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(X)}),this.tui.onMouse((J)=>{let Q=performance.now();this.mouseManager.handleMouseEvent(J);let Z=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent(Z)}),this.tui.onPaste((J)=>{this.focusManager.handlePasteEvent(J)}),this.tui.onCapabilities((J)=>{if(this.rootElement){let Q=this.tui.getSize(),Z=new AT(Q,J.capabilities),X=this.rootElement;if(X.widget instanceof m8){let Y=new m8({data:Z,child:X.widget.child});X.update(Y)}this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame()}})}handleGlobalKeyEvent(J){if(J.ctrlKey&&J.key==="z"&&!J.shiftKey&&!J.altKey&&!J.metaKey){this.tui.handleSuspend();return}}toggleFrameStatsOverlay(){let J=!this.frameStatsOverlay.isEnabled();this.frameStatsOverlay.setEnabled(J),this.frameScheduler.requestFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise)return this.exitPromise;return this.exitPromise=new Promise((J)=>{if(this.exitResolve=J,!this.isRunning)J()}),this.exitPromise}async cleanup(){if(this.isRunning=!1,this.rootElement)this.rootElement.unmount(),this.rootElement=void 0;this.buildOwner.dispose(),this.pipelineOwner.dispose(),this.focusManager.dispose(),this.mouseManager.dispose(),this.frameScheduler.removeFrameCallback("resize"),this.frameScheduler.removeFrameCallback("build"),this.frameScheduler.removeFrameCallback("layout"),this.frameScheduler.removeFrameCallback("paint"),this.frameScheduler.removeFrameCallback("render"),await this.tui.deinit()}get tuiInstance(){return this.tui}get rootElementInstance(){return this.rootElement}setRootElementMountedCallback(J){this.rootElementMountedCallback=J}}async function Yx1(J,Q){let Z=HG.instance;if(Q?.onRootElementMounted)Z.setRootElementMountedCallback(Q.onRootElementMounted);await Z.runApp(J)}zm();class Kx1{constructor(){}}class O7 extends Kx1{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof O7))return!1;return this.value===J.value}get hashCode(){if(this.value===null||this.value===void 0)return 0;if(typeof this.value==="string")return this.stringHash(this.value);if(typeof this.value==="number")return this.value;if(typeof this.value==="boolean")return this.value?1:0;return this.stringHash(String(this.value))}stringHash(J){let Q=0;for(let Z=0;Z<J.length;Z++){let X=J.charCodeAt(Z);Q=(Q<<5)-Q+X,Q=Q&Q}return Q}toString(){return`ValueKey(${this.value})`}}R4();v9();class M5 extends f4{widthFactor;heightFactor;constructor({key:J,child:Q,widthFactor:Z,heightFactor:X}={}){super({key:J,child:Q});this.widthFactor=Z,this.heightFactor=X}createRenderObject(){return new qx1(this.widthFactor,this.heightFactor)}updateRenderObject(J){if(J instanceof qx1)J.widthFactor=this.widthFactor,J.heightFactor=this.heightFactor}static child(J){return new M5({child:J})}}class qx1 extends i6{widthFactor;heightFactor;constructor(J,Q){super();this.widthFactor=J,this.heightFactor=Q}getMinIntrinsicWidth(J){return(this.children[0]?.getMinIntrinsicWidth(J)??0)*(this.widthFactor??1)}getMaxIntrinsicWidth(J){return(this.children[0]?.getMaxIntrinsicWidth(J)??0)*(this.widthFactor??1)}getMinIntrinsicHeight(J){return(this.children[0]?.getMinIntrinsicHeight(J)??0)*(this.heightFactor??1)}getMaxIntrinsicHeight(J){return(this.children[0]?.getMaxIntrinsicHeight(J)??0)*(this.heightFactor??1)}performLayout(){let J=this._lastConstraints;G8(!!J,"performLayout called without constraints");let Q=this.widthFactor!==void 0||J.maxWidth===Number.POSITIVE_INFINITY,Z=this.heightFactor!==void 0||J.maxHeight===Number.POSITIVE_INFINITY,X=this.children[0];if(!X){let W=Q?0:Number.POSITIVE_INFINITY,F=Z?0:Number.POSITIVE_INFINITY,H=isFinite(W)?Math.max(J.minWidth,Math.min(J.maxWidth,W)):J.maxWidth,B=isFinite(F)?Math.max(J.minHeight,Math.min(J.maxHeight,F)):J.maxHeight;this.setSize(H,B),super.performLayout();return}X.layout(J.loosen());let Y=Q?X.size.width*(this.widthFactor??1):Number.POSITIVE_INFINITY,K=Z?X.size.height*(this.heightFactor??1):Number.POSITIVE_INFINITY,q=isFinite(Y)?Math.max(J.minWidth,Math.min(J.maxWidth,Y)):J.maxWidth,G=isFinite(K)?Math.max(J.minHeight,Math.min(J.maxHeight,K)):J.maxHeight;this.setSize(q,G);let z=(this.size.width-X.size.width)/2,U=(this.size.height-X.size.height)/2;X.setOffset(z,U),super.performLayout()}}R4();class DH extends Cm{_screen;_clipX;_clipY;_clipWidth;_clipHeight;constructor(J,Q,Z,X,Y){super(X,Y);this._screen=J,this._clipX=Q,this._clipY=Z,this._clipWidth=X,this._clipHeight=Y}setChar(J,Q,Z,X,Y=1){if(J>=this._clipX&&J<this._clipX+this._clipWidth&&Q>=this._clipY&&Q<this._clipY+this._clipHeight)this._screen.setChar(J,Q,Z,X||{},Y)}setCell(J,Q,Z){if(J>=this._clipX&&J<this._clipX+this._clipWidth&&Q>=this._clipY&&Q<this._clipY+this._clipHeight)this._screen.setCell(J,Q,Z)}fill(J,Q,Z,X,Y=" ",K){let q=Math.max(J,this._clipX),G=Math.max(Q,this._clipY),z=Math.min(J+Z,this._clipX+this._clipWidth),U=Math.min(Q+X,this._clipY+this._clipHeight);if(q<z&&G<U)this._screen.fill(q,G,z-q,U-G,Y,K)}getSize(){return this._screen.getSize()}resize(J,Q){return this._screen.resize(J,Q)}getBuffer(){return this._screen.getBuffer()}getFrontBuffer(){return this._screen.getFrontBuffer()}getBackBuffer(){return this._screen.getBackBuffer()}getCell(J,Q){return this._screen.getCell(J,Q)}clear(){return this._screen.clear()}present(){return this._screen.present()}getDiff(){return this._screen.getDiff()}markForRefresh(){return this._screen.markForRefresh()}setCursor(J,Q){return this._screen.setCursor(J,Q)}clearCursor(){return this._screen.clearCursor()}getCursor(){return this._screen.getCursor()}isCursorVisible(){return this._screen.isCursorVisible()}}v9();class Gx1 extends f4{clipBehavior;constructor(J,{key:Q,clipBehavior:Z="antiAlias"}={}){super(Q?{child:J,key:Q}:{child:J});this.clipBehavior=Z}createRenderObject(){return new s56(this.clipBehavior)}updateRenderObject(J){J.updateClipBehavior(this.clipBehavior)}}class s56 extends i6{_clipBehavior;constructor(J){super();this._clipBehavior=J}updateClipBehavior(J){if(this._clipBehavior!==J)this._clipBehavior=J,this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;if(G8(!!J,"performLayout called without constraints"),this.children.length===0){this.setSize(J.minWidth,J.minHeight),super.performLayout();return}this.children[0].layout(J),this.setSize(J.maxWidth,J.maxHeight),super.performLayout()}paint(J,Q=0,Z=0){if(this.children.length===0||this._clipBehavior==="none"){super.paint(J,Q,Z);return}let X=this.children[0],Y=Q+this.offset.x,K=Z+this.offset.y,q=this.size.width,G=this.size.height,z=new DH(J,Y,K,q,G);X.paint(z,Q+this.offset.x,Z+this.offset.y)}}R4();function bm(J,Q,Z){return Math.min(Math.max(J,Q),Z)}var r09=0.01;function zx1(J){if(J==null||J===0)return"$0.00";let Q=J*r09;if(Q>=0.01)return`$${Q.toFixed(2)}`;return`$${Q.toFixed(3)}`}function o56(J){if(J>=1e6)return`${Math.round(J/1e6)}M`;if(J>=1000)return`${Math.round(J/1000)}k`;return J.toString()}function s09(J){if(!J)return"";let Q=J.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return J}function t56(J){let Q=zx1(J.credits),Z=[];if(J.inputTokens)Z.push(`${o56(J.inputTokens)} in`);if(J.outputTokens)Z.push(`${o56(J.outputTokens)} out`);if(J.model)Z.push(s09(J.model));if(Z.length>0)return`${Q} (${Z.join(", ")})`;return Q}v9();class xm{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}class ym extends xm{flex;fit;constructor(J=0,Q="tight"){super();this.flex=J,this.fit=Q}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}class fm extends tX{direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Q,children:Z=[],mainAxisAlignment:X="start",crossAxisAlignment:Y="center",mainAxisSize:K="min"}){super({...J?{key:J}:{},children:Z});this.direction=Q,this.mainAxisAlignment=X,this.crossAxisAlignment=Y,this.mainAxisSize=K}createRenderObject(){return new JJ6(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new e56(this)}}class e56 extends f41{constructor(J){super(J)}get flexWidget(){return this.widget}mount(){super.mount(),this._setupChildParentData()}update(J){super.update(J),this._setupChildParentData()}performRebuild(){super.performRebuild(),this._setupChildParentData()}_setupChildParentData(){for(let J of this.children){let Q=J.renderObject;if(Q&&!Q.parentData)Q.parentData=new ym(0,"tight")}}}class JJ6 extends i6{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Q,Z,X){super();this._direction=J;this._mainAxisAlignment=Q;this._crossAxisAlignment=Z;this._mainAxisSize=X}updateProperties(J,Q,Z,X){this._direction=J,this._mainAxisAlignment=Q,this._crossAxisAlignment=Z,this._mainAxisSize=X,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;G8(!!J,"performLayout called without constraints");let Q=this._direction==="horizontal",Z=[],X=[];for(let M of this.children){let V=M.parentData;if(V&&V.flex>0)Z.push({child:M,flex:V.flex,fit:V.fit});else X.push(M)}let Y=0,K=0,q,G=Q?J.maxHeight:J.maxWidth;if(isFinite(G))q=G;else{let M=0;for(let V of X){let N=Q?V.getMaxIntrinsicHeight(1/0):V.getMaxIntrinsicWidth(1/0);M=Math.max(M,N)}q=M}for(let M of X){let V=this._crossAxisAlignment==="stretch"?q:0,N=Q?new u6(0,1/0,V,q):new u6(V,q,0,1/0);if(M.layout(N),Q)Y+=M.size.width,K=Math.max(K,M.size.height);else Y+=M.size.height,K=Math.max(K,M.size.width)}let z=Q?J.maxWidth:J.maxHeight,U=Number.isFinite(z)?Math.max(0,z-Y):0,W=Z.reduce((M,V)=>M+V.flex,0);if(!(z<1/0)&&W>0){for(let{flex:M,fit:V}of Z)if(M>0&&(this._mainAxisSize==="max"||V==="tight")){let N=Q?"row":"column",L=Q?"horizontal":"vertical",A=Q?"width":"height";G8(!1,`RenderFlex children have non-zero flex but incoming ${A} constraints are unbounded.
5842
5842
 
5843
5843
  When a ${N} is in a parent that does not provide a finite ${A} constraint, for example if it is in a ${L} scrollable, it will try to shrink-wrap its children along the ${L} axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining space in the ${L} direction.
@@ -5936,9 +5936,9 @@ The context used was: `+J.widget.constructor.name);return Q}updateShouldNotify(J
5936
5936
  `,new u1({color:b1.green}))),q++}else if(G.startsWith("-")){let z=K.toString().padStart(4);X.push(new C1(` ${z} `,Z)),X.push(new C1(`${G}
5937
5937
  `,new u1({color:b1.red}))),K++}else{let z=q.toString().padStart(4);X.push(new C1(` ${z} `,Z)),X.push(new C1(`${G}
5938
5938
  `,Z)),K++,q++}return X}}function q49(J){return J?.status==="done"&&typeof J.result==="object"}class SO extends M6{toolUse;toolRun;name;detail;inputSection;outputSection;subagentTools;constructor(J){super();this.toolUse=J.toolUse,this.toolRun=J.toolRun,this.name=J.name,this.detail=J.detail,this.inputSection=J.inputSection,this.outputSection=J.outputSection,this.subagentTools=J.subagentTools}createState(){return new lZ6}}class lZ6 extends D6{_thinkingBlockStates=new Map;_listenerUnsubscribe;initState(){this._listenerUnsubscribe=VG.instance.addListener(()=>{this.setState(()=>{this._thinkingBlockStates.clear()})})}dispose(){this._listenerUnsubscribe?.()}getThinkingBlockExpanded(J){return this._thinkingBlockStates.get(J)??VG.instance.allExpanded}toggleThinking=(J)=>{return(Q)=>{this.setState(()=>{this._thinkingBlockStates.set(J,Q)})}};build(J){let{toolRun:Q,name:Z,detail:X,inputSection:Y,outputSection:K,subagentTools:q}=this.widget,G=[];if(X&&X.length>0)G.push(new K0({text:new C1("",void 0,X)}));let z=new oZ({name:Z,status:Q.status,children:G}),U=[];if(Y)U.push(new PK({markdown:Y.content}));if((Q.status==="in-progress"||Q.status==="done"||Q.status==="cancelled"||Q.status==="error")&&Q.progress){let F=Q.progress??[],H=q??[],B=0,M=0;for(let V=0;V<F.length;V++){let N=F[V];if(N?.reasoning){let L=V===F.length-1,A=Q.status==="in-progress"&&L,O=new Fu({key:new O7(`thinking-${M}`),thinkingBlock:{type:"thinking",thinking:N.reasoning,signature:""},expanded:this.getThinkingBlockExpanded(M),onToggle:this.toggleThinking(M),isStreaming:A});U.push(O),M++}if(N?.tool_uses)for(let L of N.tool_uses){let A=H[B];if(A)U.push(new CO({toolUse:A.toolUse,toolRun:A.toolRun})),B++}}for(;B<H.length;B++){let V=H[B];if(V)U.push(new CO({toolUse:V.toolUse,toolRun:V.toolRun}))}}else if(q&&q.length>0)for(let F of q)U.push(new CO({toolUse:F.toolUse,toolRun:F.toolRun}));if(K)U.push(new PK({markdown:K.content}));return new R6({crossAxisAlignment:"start",children:[z,new w8({padding:new U6(2,0,2,0),child:new Ju({children:U})})]})}}class $f1 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z,subagentTools:X}=this.props,Y=Z.status==="done"?Z.result:Z.status==="in-progress"?Z.result:void 0;return new SO({toolUse:Q,toolRun:Z,name:"Oracle",inputSection:Q.input?.task&&typeof Q.input.task==="string"?{content:Q.input.task}:void 0,outputSection:Y?{content:Y}:void 0,subagentTools:X})}}class Pf1 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z,subagentTools:X}=this.props,Y=[];if(Q.input?.description&&typeof Q.input.description==="string")Y.push(new C1(Q.input.description,new u1({color:b1.blue,bold:!0})));return new SO({toolUse:Q,toolRun:Z,name:"Subagent",detail:Y,inputSection:Q.input?.prompt&&typeof Q.input.prompt==="string"?{content:Q.input.prompt}:void 0,subagentTools:X})}}class CO extends O8{props;constructor(J){super();this.props=J}build(J){return this.buildToolWidget(J)}buildToolWidget(J){let{toolUse:Q,toolRun:Z}=this.props;switch(Q.name){case"todo_write":return this.buildTodoWriteTool(J,Q,Z);case"todo_read":return this.buildGenericTool(J,Q,Z,void 0,"Read TODOs");case"Read":return this.buildReadTool(Q,Z);case"create_file":return this.buildCreateFileTool(Q,Z);case"edit_file":return this.buildEditFileTool(Q,Z);case"undo_edit":return this.buildGenericTool(J,Q,Z,Q.input?.path,"Undo Edit");case"glob":case"Glob":return this.buildGenericTool(J,Q,Z,Q.input?.filePattern,"Glob");case EJ:return this.buildCodebaseSearchTool(J,Q,Z);case Fj:return this.buildCodebaseSearchTool(J,Q,Z);case Hj:return this.buildCodebaseSearchTool(J,Q,Z);case Xp:return this.buildCodebaseSearchTool(J,Q,Z);case Yp:return this.buildCodebaseSearchTool(J,Q,Z);case"Grep":return this.buildGrepTool(Q,Z);case"web_search":return this.buildGenericTool(J,Q,Z,Q.input?.query,"Web Search");case"read_web_page":return this.buildReadWebPageTool(J,Q,Z);case"Bash":return this.buildBashTool(Q,Z);case"Task":return this.buildTaskTool(J,Q,Z);case"oracle":return this.buildOracleTool(J,Q,Z);case"mermaid":return this.buildMermaidTool(J,Q,Z);case"format_file":return this.buildGenericTool(J,Q,Z,Q.input?.path,"Format");case"get_diagnostics":return this.buildGenericTool(J,Q,Z,Q.input?.path,"Get Diagnostics");case"call_openai":return this.buildGenericTool(J,Q,Z,Q.input?.model,"OpenAI Call");case"run_routine":return this.buildGenericTool(J,Q,Z,Q.input?.routine,"Run Routine");case"run_javascript":{let X=Q.input?.code?.split(`
5939
- `).length||0;return this.buildGenericTool(J,Q,Z,`${X} lines`,"Run JavaScript")}default:return this.buildGenericTool(J,Q,Z,JSON.stringify(Q.input))}}buildTodoWriteTool(J,Q,Z){return new oZ({name:"Update TODOs",status:Z.status})}buildOracleTool(J,Q,Z){return new $f1({toolUse:Q,toolRun:Z,subagentTools:this.props.subagentTools})}buildReadTool(J,Q){return new iZ6({toolUse:J,toolRun:Q})}buildEditFileTool(J,Q){return new Ef1({toolUse:J,toolRun:Q})}buildCodebaseSearchTool(J,Q,Z){let X=Z.status==="done"?Z.result:Z.status==="in-progress"?Z.result:void 0;return new SO({toolUse:Q,toolRun:Z,name:"Search",inputSection:typeof Q.input?.query==="string"?{content:Q.input.query}:void 0,outputSection:X&&typeof X==="string"?{content:X}:void 0,subagentTools:this.props.subagentTools})}buildGrepTool(J,Q){return new nZ6({toolUse:J,toolRun:Q})}buildReadWebPageTool(J,Q,Z){let X=[];if(typeof Q.input?.url==="string")X.push(new K0({text:new C1(Q.input.url,new u1)}));return new oZ({name:"Read Web",status:Z.status,children:X})}buildBashTool(J,Q){return new sZ6({toolUse:J,toolRun:Q})}buildTaskTool(J,Q,Z){return new Pf1({toolUse:Q,toolRun:Z,subagentTools:this.props.subagentTools})}buildMermaidTool(J,Q,Z){let Y=C8.of(J).colors,q=Q.input?.code||"",G=q.split(`
5940
- `).length,z=[];if(q.trim())z.push(new K0({text:new C1(`diagram (${G} lines)`,new u1({color:Y.foreground,dim:!0}))}));let U=[];if(Z.status==="error"&&Z.error?.message)U.push(new C1(`
5941
- `)),U.push(new C1(` Error: ${Z.error.message}`,new u1({color:b1.red})));else if(Z.status==="done"&&q.trim()){let W=`https://mermaid.live/edit#base64:${Buffer.from(JSON.stringify({code:q})).toString("base64")}`,F=new h4({onClick:()=>{wU(W)},cursor:"pointer",child:new K0({text:new C1("View",new u1({color:b1.cyan})),selectable:!0})});z.push(F)}return new oZ({name:"Mermaid",status:Z.status,children:z,tail:U.length>0?U:void 0})}buildCreateFileTool(J,Q){return new aZ6({toolUse:J,toolRun:Q})}buildGenericTool(J,Q,Z,X,Y){return new rZ6({context:J,toolUse:Q,toolRun:Z,detail:X,name:Y})}}class iZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z}=this.props,X=LO(J),Y=[];if(Q.input?.path){let K=Q.input.path,q=IT(K,J);if(Y.push(new EU({uri:`file://${K}`,text:q,style:new u1({color:b1.cyan,dim:!0,underline:!0})})),Q.input.read_range){let[G,z]=Q.input.read_range;if(typeof G==="number"&&typeof z==="number"&&G>=0&&z>=0)Y.push(new K0({text:new C1(` @${G}-${z}`,new u1({color:b1.yellow,dim:!0}))}))}}return new oZ({name:"Read",status:Z.status,children:Y})}}class aZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z}=this.props,X=[];if(Q.input?.path){let Y=Q.input.path,K=IT(Y,J);X.push(new EU({uri:`file://${Y}`,text:K,style:new u1({color:b1.cyan,dim:!0,underline:!0})}))}return new oZ({name:"Create",status:Z.status,children:X})}}class nZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z}=this.props,Y=C8.of(J).colors,K=new u1({color:Y.foreground,dim:!0}),q=[];if(Q.input?.pattern)q.push(new C1(Q.input.pattern,new u1({color:b1.yellow})));if(Q.input?.path){let z=IT(Q.input.path,J);if(z.length>0)q.push(new C1(` in ${z}`,K))}let G=[];if(q.length>0)G.push(new K0({text:new C1("",void 0,q)}));return new oZ({name:"Grep",status:Z.status,children:G})}}class rZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z,detail:X,name:Y}=this.props,q=C8.of(J).colors,G=new u1({color:q.foreground,dim:!0}),z=[];if(X){let W=Q.name===eQ||Q.name===Kp||Q.name===d9||Q.name===Gp||Q.name===eV,F;if(W)try{let H=LO(J),B=b0.file(X);F=YY(B,H??void 0)}catch{F=X}else F=X;z.push(new K0({text:new C1(F,G)}))}let U=[];if(Z.status==="error"&&Z.error?.message)U.push(new C1(`
5939
+ `).length||0;return this.buildGenericTool(J,Q,Z,`${X} lines`,"Run JavaScript")}default:return this.buildGenericTool(J,Q,Z,JSON.stringify(Q.input))}}buildTodoWriteTool(J,Q,Z){return new oZ({name:"Update TODOs",status:Z.status})}buildOracleTool(J,Q,Z){return new $f1({toolUse:Q,toolRun:Z,subagentTools:this.props.subagentTools})}buildReadTool(J,Q){return new iZ6({toolUse:J,toolRun:Q})}buildEditFileTool(J,Q){return new Ef1({toolUse:J,toolRun:Q})}buildCodebaseSearchTool(J,Q,Z){let X=Z.status==="done"?Z.result:Z.status==="in-progress"?Z.result:void 0;return new SO({toolUse:Q,toolRun:Z,name:"Search",inputSection:typeof Q.input?.query==="string"?{content:Q.input.query}:void 0,outputSection:X&&typeof X==="string"?{content:X}:void 0,subagentTools:this.props.subagentTools})}buildGrepTool(J,Q){return new nZ6({toolUse:J,toolRun:Q})}buildReadWebPageTool(J,Q,Z){let X=[];if(typeof Q.input?.url==="string")X.push(new K0({text:new C1(Q.input.url,new u1),selectable:!0}));return new oZ({name:"Read Web",status:Z.status,children:X})}buildBashTool(J,Q){return new sZ6({toolUse:J,toolRun:Q})}buildTaskTool(J,Q,Z){return new Pf1({toolUse:Q,toolRun:Z,subagentTools:this.props.subagentTools})}buildMermaidTool(J,Q,Z){let Y=C8.of(J).colors,q=Q.input?.code||"",G=q.split(`
5940
+ `).length,z=[];if(q.trim())z.push(new K0({text:new C1(`diagram (${G} lines)`,new u1({color:Y.foreground,dim:!0})),selectable:!0}));let U=[];if(Z.status==="error"&&Z.error?.message)U.push(new C1(`
5941
+ `)),U.push(new C1(` Error: ${Z.error.message}`,new u1({color:b1.red})));else if(Z.status==="done"&&q.trim()){let W=`https://mermaid.live/edit#base64:${Buffer.from(JSON.stringify({code:q})).toString("base64")}`,F=new h4({onClick:()=>{wU(W)},cursor:"pointer",child:new K0({text:new C1("View",new u1({color:b1.cyan})),selectable:!0})});z.push(F)}return new oZ({name:"Mermaid",status:Z.status,children:z,tail:U.length>0?U:void 0})}buildCreateFileTool(J,Q){return new aZ6({toolUse:J,toolRun:Q})}buildGenericTool(J,Q,Z,X,Y){return new rZ6({context:J,toolUse:Q,toolRun:Z,detail:X,name:Y})}}class iZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z}=this.props,X=LO(J),Y=[];if(Q.input?.path){let K=Q.input.path,q=IT(K,J);if(Y.push(new EU({uri:`file://${K}`,text:q,style:new u1({color:b1.cyan,dim:!0,underline:!0})})),Q.input.read_range){let[G,z]=Q.input.read_range;if(typeof G==="number"&&typeof z==="number"&&G>=0&&z>=0)Y.push(new K0({text:new C1(` @${G}-${z}`,new u1({color:b1.yellow,dim:!0})),selectable:!0}))}}return new oZ({name:"Read",status:Z.status,children:Y})}}class aZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z}=this.props,X=[];if(Q.input?.path){let Y=Q.input.path,K=IT(Y,J);X.push(new EU({uri:`file://${Y}`,text:K,style:new u1({color:b1.cyan,dim:!0,underline:!0})}))}return new oZ({name:"Create",status:Z.status,children:X})}}class nZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z}=this.props,Y=C8.of(J).colors,K=new u1({color:Y.foreground,dim:!0}),q=[];if(Q.input?.pattern)q.push(new C1(Q.input.pattern,new u1({color:b1.yellow})));if(Q.input?.path){let z=IT(Q.input.path,J);if(z.length>0)q.push(new C1(` in ${z}`,K))}let G=[];if(q.length>0)G.push(new K0({text:new C1("",void 0,q),selectable:!0}));return new oZ({name:"Grep",status:Z.status,children:G})}}class rZ6 extends O8{props;constructor(J){super();this.props=J}build(J){let{toolUse:Q,toolRun:Z,detail:X,name:Y}=this.props,q=C8.of(J).colors,G=new u1({color:q.foreground,dim:!0}),z=[];if(X){let W=Q.name===eQ||Q.name===Kp||Q.name===d9||Q.name===Gp||Q.name===eV,F;if(W)try{let H=LO(J),B=b0.file(X);F=YY(B,H??void 0)}catch{F=X}else F=X;z.push(new K0({text:new C1(F,G),selectable:!0}))}let U=[];if(Z.status==="error"&&Z.error?.message)U.push(new C1(`
5942
5942
  `)),U.push(new C1(` Error: ${Z.error.message}`,new u1({color:b1.red})));return new oZ({name:Y||Q.name,status:Z.status,children:z,tail:U.length>0?U:void 0})}}class sZ6 extends M6{props;constructor(J){super();this.props=J}createState(){return new oZ6}}class oZ6 extends D6{_animationTimer;_animationFrame=0;_animationDirection=1;_animationFrames=["⸫","⁖","⸪","⸬","⁘","⸭","⁙"];initState(){if(super.initState(),this.widget.props.toolRun.status==="in-progress")this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.props.toolRun.status!=="in-progress"&&this.widget.props.toolRun.status==="in-progress")this._startAnimation();else if(J.props.toolRun.status==="in-progress"&&this.widget.props.toolRun.status!=="in-progress")this._stopAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{if(this._animationFrame+=this._animationDirection,this._animationFrame>=this._animationFrames.length-1)this._animationDirection=-1;else if(this._animationFrame<=0)this._animationDirection=1})},100)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let{toolUse:Q,toolRun:Z}=this.widget.props,Y=C8.of(J).colors,K=Q.input,q=K?.cmd||"",G=Z.status,z=If1(Z.status),U=G==="done"&&typeof Z.result.exitCode==="number"&&Z.result.exitCode!==0,W=new u1({color:Y.foreground,bold:!0}),F=G==="cancelled"?W.copyWith({strikethrough:!0}):G==="rejected-by-user"?W.copyWith({dim:!0}):W,H=q.split(`
5943
5943
  `),B=H[0]||"",M=H.slice(1),V=[];if(G==="in-progress"){let N=this._animationFrames[this._animationFrame];V.push(new C1(`${N} `,new u1({color:z})))}else{let N=new u1({color:U?b1.red:z,bold:!0});V.push(new C1("$ ",N))}if(V.push(new C1(B,F)),G!=="rejected-by-user"){let N=G49(K,Z,J);if(N.length>0)V.push(new C1("",void 0,N))}if(G==="rejected-by-user")V.push(new C1(" (rejected)",new u1({dim:!0,italic:!0})));else if(G==="cancelled")V.push(new C1(" (cancelled)",new u1({color:b1.yellow,italic:!0})));V.push(new C1(`
5944
5944
  `));for(let N of M)V.push(new C1(` ${N}
@@ -6014,7 +6014,7 @@ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTr
6014
6014
  `),J.stdout.write(`Thread: ${H}
6015
6015
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
6016
6016
  `)}}function tX6(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return b1.index(Z[X])}Xx1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){t2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6017
- `)}var Gh1=qh1.join(fu1||qh1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function _79(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function IV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")_U("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new A2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${J8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")_U("experimental.agentMode",Q.agentMode)}var b79=O0.union([O0.object({command:O0.string(),args:O0.array(O0.string()).optional(),env:O0.record(O0.string(),O0.string()).optional()}).strict(),O0.object({url:O0.string()}).strict()]),x79=O0.record(O0.string(),b79);async function Uh1(J){try{await S79(qh1.dirname(Gh1),{recursive:!0}),await v79(Gh1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function y79(){try{return(await KY6(Gh1,"utf-8")).trim()}catch(J){return null}}async function f79(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return x79.parse(Q)}catch(Z){if(Z instanceof O0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function h79(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var ZY6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??B5,description:`Custom settings file path (overrides the default location ${B5})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${f_1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:UG(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:Nb1(),hidden:!0,description:(J)=>J?"Enable IDE connection. When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:ZN}],XY6=(J)=>("deprecated"in J)&&J.deprecated===!0,g79=(J)=>("hidden"in J)&&J.hidden===!0,m79=(J)=>("default"in J),u79=(J)=>("default"in J)?J.default:void 0;function p79(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new A2(wK.unknownCommand(Z),1,q)}}var qY6=null;function i_2(){return qY6}function Y51(J){return{...J,getThreadEnvironment:o21,vfs:Ie1({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new vv(J.fileSystem),generateThreadTitle:Xn,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Wh1=b0.file(k79.homedir()),GY6=process.env.XDG_CONFIG_HOME?b0.file(process.env.XDG_CONFIG_HOME):p0.joinPath(Wh1,".config");async function EV(J,Q){pd1("0.0.1759852911-g557057");let Z=qQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:y_1,homeDir:Wh1,userConfigDir:GY6}),X=await n8();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=Cl(Vj()),K=ot1({configService:Z,toolService:Y}),q=a30(Y,x9,Gt).catch((L)=>{l.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{l.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)dd1(!0);if(Q.ide&&Nb1())cd1(!0);if(i16(Y),Q.jetbrains||Q.ide)Y.registerTool($n);let z;if(!J.executeMode)z=new F41(process.cwd(),{},!0);else z=new class extends F41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
6017
+ `)}var Gh1=qh1.join(fu1||qh1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function _79(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function IV(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")_U("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new A2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${J8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")_U("experimental.agentMode",Q.agentMode)}var b79=O0.union([O0.object({command:O0.string(),args:O0.array(O0.string()).optional(),env:O0.record(O0.string(),O0.string()).optional()}).strict(),O0.object({url:O0.string()}).strict()]),x79=O0.record(O0.string(),b79);async function Uh1(J){try{await S79(qh1.dirname(Gh1),{recursive:!0}),await v79(Gh1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function y79(){try{return(await KY6(Gh1,"utf-8")).trim()}catch(J){return null}}async function f79(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return x79.parse(Q)}catch(Z){if(Z instanceof O0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function h79(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var ZY6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??B5,description:`Custom settings file path (overrides the default location ${B5})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${f_1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:UG(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:Nb1(),hidden:!0,description:(J)=>J?"Enable IDE connection. When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:ZN}],XY6=(J)=>("deprecated"in J)&&J.deprecated===!0,g79=(J)=>("hidden"in J)&&J.hidden===!0,m79=(J)=>("default"in J),u79=(J)=>("default"in J)?J.default:void 0;function p79(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new A2(wK.unknownCommand(Z),1,q)}}var qY6=null;function i_2(){return qY6}function Y51(J){return{...J,getThreadEnvironment:o21,vfs:Ie1({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new vv(J.fileSystem),generateThreadTitle:Xn,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Wh1=b0.file(k79.homedir()),GY6=process.env.XDG_CONFIG_HOME?b0.file(process.env.XDG_CONFIG_HOME):p0.joinPath(Wh1,".config");async function EV(J,Q){pd1("0.0.1759858678-g356ccd");let Z=qQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:y_1,homeDir:Wh1,userConfigDir:GY6}),X=await n8();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=Cl(Vj()),K=ot1({configService:Z,toolService:Y}),q=a30(Y,x9,Gt).catch((L)=>{l.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{l.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)dd1(!0);if(Q.ide&&Nb1())cd1(!0);if(i16(Y),Q.jetbrains||Q.ide)Y.registerTool($n);let z;if(!J.executeMode)z=new F41(process.cwd(),{},!0);else z=new class extends F41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
6018
6018
  `),!await d79(J))await GO(),process.exit(1)}let U=await ke1({isDevelopment:!1}),W=new VU1(U),F=new DU1(U,{lazy:!0}),H=new QD1(W),B=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=n16({playNotificationSound:async(L)=>{if(B){a16(L);let A=Qx1(),O=Zx1();if((!A||O)&&X.settings["notifications.system.enabled"]!==!1){if(L==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(L==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:W});l.info("Starting Amp background services");let V=gX0({threadService:W,threadHistoryService:F,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:W,threadHistoryService:F,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?je1:x9};return{...N,async asyncDispose(){await N.mcpService.dispose(),await N.threadService.asyncDispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function d79(J){if(!J.executeMode){if(!await Ib1("Would you like to log in to Amp? [(y)es, (n)o]: "))return u2.write(`Login cancelled. Run the command again to retry.
6019
6019
  `),!1}return await zY6(J)}async function zY6(J){let Q=C79(32).toString("hex"),Z=await wb1(J.ampURL,Q);try{await wU(Z)}catch(Y){l.error("Failed to open browser",{error:Y})}let X=await wb1(J.ampURL,Q,!1);u2.write(`If your browser did not open automatically, visit:
6020
6020
 
@@ -6024,12 +6024,12 @@ ${J8.blue.bold(X)}
6024
6024
  Login successful! You can now use the Amp CLI.
6025
6025
  `),!0}catch(Y){return l.error("Login failed",{error:Y}),t2.write(`
6026
6026
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6027
- `),!1}}function c79(){let J=new _g().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)UO(),process.exit(0);let H=F.originalError??F;r26(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759852911-g557057 (released 2025-10-07T16:08:02.284Z)
6028
- `),process.exit(0)}),J.addHelpText("after",r46()),J.configureHelp({formatHelp:s46}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await n79(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await a79(M,await Fb1(B,M.settings))});let Q=async(F,H,B)=>{qQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Wh1,userConfigDir:GY6});let M={...H,executeMode:!1};await zh1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await YY6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await Q59(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);if(H.pick)await Q(M,V,B);else await J59(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await e79(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await YY6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await t79(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await o79(M,V,F,B)}),l76(J,async(F,H)=>{let B=await QY(H);IV(F,H);let M=await EV(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:UO,asyncDispose:M.asyncDispose.bind(M)}}),j76(J),D76(J,async(F)=>{return(await QY(F)).settings}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);IV(H,B);let V=await EV(M,B);try{await n_1(V,{})}finally{await V.asyncDispose(),await UO()}});let X=new _g().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await Ab1(F.force||!1,F.verbose||!1,"0.0.1759852911-g557057"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new rM(H,V),L=u79(F);if(L)N.default(L);if(N.hidden=g79(F)||XY6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of ZY6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new rM("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new rM("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new rM("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new rM("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new rM("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new rM("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await QY(B);if(Object.keys(B).forEach((V)=>{let N=ZY6.find((L)=>L.name===V);if(N&&XY6(N)&&!m79(N))t2.write(J8.yellow(`Warning: '--${V}' flag is deprecated
6027
+ `),!1}}function c79(){let J=new _g().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)UO(),process.exit(0);let H=F.originalError??F;r26(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759858678-g356ccd (released 2025-10-07T17:43:47.723Z)
6028
+ `),process.exit(0)}),J.addHelpText("after",r46()),J.configureHelp({formatHelp:s46}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await n79(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await a79(M,await Fb1(B,M.settings))});let Q=async(F,H,B)=>{qQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:J0.of([b0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Wh1,userConfigDir:GY6});let M={...H,executeMode:!1};await zh1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await YY6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await Q59(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);if(H.pick)await Q(M,V,B);else await J59(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await e79(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);await YY6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await t79(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await QY(M);await o79(M,V,F,B)}),l76(J,async(F,H)=>{let B=await QY(H);IV(F,H);let M=await EV(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:UO,asyncDispose:M.asyncDispose.bind(M)}}),j76(J),D76(J,async(F)=>{return(await QY(F)).settings}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await QY(B);IV(H,B);let V=await EV(M,B);try{await n_1(V,{})}finally{await V.asyncDispose(),await UO()}});let X=new _g().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await Ab1(F.force||!1,F.verbose||!1,"0.0.1759858678-g356ccd"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new rM(H,V),L=u79(F);if(L)N.default(L);if(N.hidden=g79(F)||XY6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of ZY6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new rM("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new rM("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new rM("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new rM("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new rM("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new rM("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await QY(B);if(Object.keys(B).forEach((V)=>{let N=ZY6.find((L)=>L.name===V);if(N&&XY6(N)&&!m79(N))t2.write(J8.yellow(`Warning: '--${V}' flag is deprecated
6029
6029
  `))}),H.args.length>0)p79(M,H);await zh1(M,B,H)});let U=new _g("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await s79(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new _g("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(F)=>{await r79(F.version)});return J.addCommand(W),J}async function X51(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??fK(),K=Y51(J);if(Z)await J.threadStorage.set(Y,Z);let q=await _J.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,R41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(j5(z,"assistant"))await Uh1(Y),G.unsubscribe()});return await q.resume(),q}async function zh1(J,Q,Z){let X=j41(Q);if(X instanceof Error)tZ(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await Eb1()).trimEnd();if(O)K=O}else Y=(await Eb1()).trimEnd();if(Q.remote&&!J.executeMode)throw new A2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new A2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new A2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new A2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new A2("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new A2("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new A2("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
6030
6030
  Or pipe via stdin: echo "your message" | amp --execute`);IV(Z,Q);let q=await EV(J,Q);qY6=q;let G=Y51(q),z=async(O)=>{let j=await KY6(O,"utf-8"),R=JSON.parse(j);if(!fU(R.id))throw new A2(wK.invalidThreadId);return X51(q,{visibility:X,thread:R})},U=async(O)=>{if(!fU(O))throw new A2(wK.invalidThreadId);let j=await q.threadService.get(O)??void 0;return X51(q,{visibility:X,thread:j})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return X51(q,{visibility:X})}catch(O){if(O instanceof A2)throw O;throw await X41(O,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return X51(q,{visibility:X})};if(Q.format==="jsonl")t2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6031
- `),await GO(),process.exit(1);if(J.executeMode&&Q.remote)await R76(Y,K),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await q46(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Hi1();let O=await bj({jetbrainsOnly:Q.jetbrains});if(O.length===0)if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall");else w5.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(O.length===1){let j=O[0];if(j)w5.selectConfig(j)}else B=!0}let V=jb1("0.0.1759852911-g557057",q.settingsStorage),N=J0.of([b0.file(process.cwd())]),L=lT(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await n8();await QY6({stdout:process.stdout,history:new t_1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:TJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:w5,connectedClientsService:new Ap,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId}),await q.asyncDispose(),process.exit(0)}async function QY(J){if(J.interactive)t2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6032
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=await OU(J.settingsFile),K=jU({...J,settingsFile:Y,getHook:process.env.AMP_URL?(z,U)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(await I76(K),await E76(K),J.mcpConfig){let z=await f79(J.mcpConfig);K=h79(K,z)}let q=await K.get("url","global");if(!q)q=oQ;if(!_H(q))l.info("Targeting custom Amp server",{ampURL:q});if(K=Kp1(K),await K.get("debug.httpLogging"))Zp1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:q,settings:K,secrets:w76(await Fb1(J,K))}}function l79(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function i79(){let J=l79(process.argv);if(k26({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),_79(l),l.info("Starting Amp CLI.",{version:"0.0.1759852911-g557057",buildTimestamp:"2025-10-07T16:08:02.284Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new A2(wK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await c79().parseAsync(process.argv)}i79().catch(X41);async function a79(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6031
+ `),await GO(),process.exit(1);if(J.executeMode&&Q.remote)await R76(Y,K),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await q46(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Hi1();let O=await bj({jetbrainsOnly:Q.jetbrains});if(O.length===0)if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall");else w5.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(O.length===1){let j=O[0];if(j)w5.selectConfig(j)}else B=!0}let V=jb1("0.0.1759858678-g356ccd",q.settingsStorage),N=J0.of([b0.file(process.cwd())]),L=lT(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await n8();await QY6({stdout:process.stdout,history:new t_1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:TJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:w5,connectedClientsService:new Ap,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId}),await q.asyncDispose(),process.exit(0)}async function QY(J){if(J.interactive)t2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6032
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=await OU(J.settingsFile),K=jU({...J,settingsFile:Y,getHook:process.env.AMP_URL?(z,U)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(await I76(K),await E76(K),J.mcpConfig){let z=await f79(J.mcpConfig);K=h79(K,z)}let q=await K.get("url","global");if(!q)q=oQ;if(!_H(q))l.info("Targeting custom Amp server",{ampURL:q});if(K=Kp1(K),await K.get("debug.httpLogging"))Zp1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:q,settings:K,secrets:w76(await Fb1(J,K))}}function l79(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function i79(){let J=l79(process.argv);if(k26({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),_79(l),l.info("Starting Amp CLI.",{version:"0.0.1759858678-g356ccd",buildTimestamp:"2025-10-07T17:43:47.723Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new A2(wK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await c79().parseAsync(process.argv)}i79().catch(X41);async function a79(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6033
6033
  `);else if(!_H(J.ampURL))u2.write(`Logging in to ${new URL(J.ampURL).hostname}
6034
6034
  `);let Z=process.env.AMP_API_KEY;if(Z)u2.write(`API key found in environment variable, storing...
6035
6035
  `),await Q.set("apiKey",Z,J.ampURL),u2.write(`API key successfully stored.
@@ -6045,7 +6045,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);IV(Z,Q);let q=await EV(
6045
6045
  `));try{let Q;if(J)Q=J,t2.write(J8.blue(`Updating to version ${J}...
6046
6046
  `)),await HT(J),t2.write(J8.green(`✓ Successfully updated to version ${J}
6047
6047
  `));else{t2.write(J8.blue(`Checking for updates...
6048
- `));let{hasUpdate:X,latestVersion:Y}=await ER("0.0.1759852911-g557057");if(!X)t2.write(J8.green(`✓ Amp CLI is already up to date.
6048
+ `));let{hasUpdate:X,latestVersion:Y}=await ER("0.0.1759858678-g356ccd");if(!X)t2.write(J8.green(`✓ Amp CLI is already up to date.
6049
6049
  `)),process.exit(0);if(!Y)t2.write(J8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,t2.write(J8.blue(`Updating to version ${Y}...
6050
6050
  `)),await HT(Y),t2.write(J8.green(`✓ Successfully updated to version ${Y}
6051
6051
  `))}let Z=await BO(Q);if(Z.warning)t2.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1759852911-g557057",
3
+ "version": "0.0.1759858678-g356ccd",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {