@sourcegraph/amp 0.0.1764302548-g389529 → 0.0.1764309291-g33b630
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +12 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -104,7 +104,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
104
104
|
[... directory listing truncated, ${I} more ${$5(I,"entry","entries")} not shown ...]`}return{status:"done",progress:{},result:{absolutePath:H.fsPath,content:P,isDirectory:!0,directoryEntries:E,contentURL:void 0},trackFiles:[A6(H)]}}let U=await Ka(K,H,W);if(U){let M=await Q(H,W),L=vz1(M)?M.toString("base64"):btoa(String.fromCharCode(...M)),A=L.length;if(A>kM){let E=(A/1048576).toFixed(1),P=(kM/1048576).toFixed(1);return{status:"error",error:{message:`Error: Image file (${E} MB) exceeds maximum allowed size (${P} MB).`,absolutePath:H.fsPath}}}return{status:"done",progress:{},result:{absolutePath:H.fsPath,content:L,contentURL:void 0,isImage:!0,imageInfo:{mimeType:U.mimeType,size:U.size}},trackFiles:[A6(H)]}}if(!await K.isExclusiveWriterFor(H))yy(H,V.id,Date.now());let N;if(Z.read_range&&H.scheme==="file")N=(await Jz4(H,Z.read_range,W,G)).join(`
|
|
105
105
|
`);else if(Z.read_range){let L=(await J(H,W)).split(`
|
|
106
106
|
`);N=tH4(L,Z,X,G)}else{let L=await new qa(K).readFile(H,{maxBytes:Y,signal:W,textProcessing:{addLineNumbers:!0,maxLines:X,maxLineBytes:G,truncationStrategy:"ellipsis"}});if(L.error)return{status:"error",error:{message:L.error.message,absolutePath:H.fsPath}};if(L.binary)return{status:"error",error:{message:`File appears to be binary and cannot be read as text (${(L.fileSize/1024).toFixed(1)} KB). Binary files like executables, archives, or compiled assets are not supported by the ${l6} tool.`,absolutePath:H.fsPath}};if(L.content===void 0){let A=Math.round(L.fileSize/1024),E=Math.round(Y/1024);return{status:"error",error:{message:`Error: File content (${A} KB) exceeds maximum allowed size (${E} KB). Use read_range parameters to read specific line ranges in the file, or use the ${y8} tool to search for specific content.`,absolutePath:H.fsPath}}}N=L.content}return{status:"done",progress:{},result:{absolutePath:H.fsPath,content:N,contentURL:void 0},trackFiles:[A6(H)]}}catch(z){return{status:"error",error:{message:z instanceof Error?z.message:String(z),absolutePath:H.fsPath}}}}}function tH4(J,Q,Y,X){let G=J[J.length-1]===""?J.slice(0,-1):J,Z={start:0,end:Math.min(G.length,Y)},q=Q.read_range?{start:Math.max(0,Q.read_range[0]-1),end:Math.min(G.length,Q.read_range[1])}:Z,V=G.slice(q.start,q.end).map((K)=>V5.pruneWideLine(K,X)).map((K,W)=>`${W+q.start+1}: ${K}`);if(q.start>0)V.unshift(`[... omitted lines 1 to ${q.start} ...]`);if(q.end<G.length)V.push(`[... omitted lines ${q.end+1} to ${G.length} ...]`);return V.join(`
|
|
107
|
-
`)}async function vO0(J,Q,Y,X){if(Y=Y.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(Z,q)=>{return process.env[q]||Z}),Y=Y.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(Z,q)=>{return process.env[q]||Z}),Y.startsWith("~")&&typeof process<"u"&&process.env.HOME)Y=rH4.join(process.env.HOME,Y.slice(1));if(y$(Y))return n0.file(Y);for(let Z of Q){let q=Z6.joinPath(Z,Y);try{return await J.getMtime(q,{signal:X}),q}catch{continue}}let G=Q.at(0);if(G)return Z6.joinPath(G,Y);return n0.file(Y)}function wQ(J){if(!y$(J))throw Error(`Path must be absolute, not relative: ${J}`);return n0.file(J)}function xy(J){let Q=nD(J),Y=Jl(Q).slice(1).toLowerCase();if(eH4.includes(Y))return!1;if(Q===".env.example"||Q===".env.sample")return!1;return/^\.env(\..*)?$/.test(Q)||/^env\..+$/.test(Q)||/\.(env|secret|credentials|envrc)$/i.test(Q)}async function Jz4(J,Q,Y,X){let G=Q?Math.max(1,Q[0]):1,Z=Q?Math.max(G,Q[1]):G+1000-1,q=[],V=0,{createInterface:K}=await import("node:readline"),{createReadStream:W}=await import("node:fs"),H=K({input:W(J.fsPath,{encoding:"utf8",highWaterMark:65536}),crlfDelay:1/0}),z=_M(Y,()=>H.close());try{for await(let N of H){if(V++,V<G)continue;if(V>Z)break;q.push(V5.pruneWideLine(N,X))}}finally{z(),H.close()}if(G>1)q.unshift(`[... omitted lines 1 to ${G-1} ...]`);if(V>Z)q.push(`[... omitted lines ${Z+1} to ∞ ...]`);let U=G;return q.map((N)=>N.startsWith("[... omitted lines")?N:`${U++}: ${N}`)}var Wa=262144,yO0=32768,bz1=1000,gz1=4096,hz1=1000,eH4;var OX=L1(()=>{K4();WE();ZU();_I();kI();xI();JH();L4();fz1();eH4=["py","js","ts","tsx","jsx","go","rs","cpp","c","cc","cxx","cs","java","scala","rb","php","swift","kt","dart","pl","r","m","mm","h","hpp","lua","zig"]});function pz1(J){let Q=J;if(Q.startsWith("~/")){let Y=process.env.HOME||process.env.USERPROFILE||"";Q=Q.replace("~/",`${Y}/`)}else if(Q==="~")Q=process.env.HOME||process.env.USERPROFILE||"";if(Q=Q.replace(/%([^%]+)%/g,(Y,X)=>{return process.env[X]||`%${X}%`}),Q.includes("%USERPROFILE%")&&process.env.USERPROFILE)Q=Q.replace(/%USERPROFILE%/g,process.env.USERPROFILE);return n0.file(Q)}function mz1(J,Q){let Y=pz1(Q);if(Y.path.includes("*")){let X=J.toString(),G=Y.path;if(!G.startsWith("file://")){if(!G.startsWith("/"))G=`/${G}`;G=`file://${G}`}let Z=G.replace(/\./g,"\\.").replace(/\*\*/g,"§DOUBLESTAR§").replace(/\*/g,"[^/]*").replace(/§DOUBLESTAR§/g,".*");return new RegExp(`^${Z}$`).test(X)}else return Y.toString()===J.toString()}function fO0(J,Q){return Q.some((Y)=>mz1(J,Y))}async function Qz4(J,Q,Y){try{let X=await Q.realpath(J).catch(()=>J),Z=[...["~/.config/AGENT.md"],...Y];for(let q of Z)if(mz1(X,q)||mz1(J,q))return null;for(let{key:q,pattern:V}of uz1)if(fO0(X,V.patterns)||fO0(J,V.patterns))return{key:q,pattern:V};return null}catch{return null}}async function qU(J,Q,Y){if(Y?.dangerouslyAllowAll??!1)return{requiresConsent:!1};try{let G=await Qz4(J,Q,Y["guardedFiles.allowlist"]??[]);if(G)return{requiresConsent:!0,reason:`${G.pattern.description}`,toAllow:J.fsPath};return{requiresConsent:!1}}catch{return{requiresConsent:!0,reason:"Unable to resolve file path",toAllow:J.fsPath}}}var uz1;var yM=L1(()=>{K4();uz1=[{key:"vscode-user-settings",pattern:{description:"VS Code User Settings",patterns:["~/Library/Application Support/Code/User/settings.json","~/.config/Code/User/settings.json","%APPDATA%/Code/User/settings.json"]}},{key:"vscode-workspace-settings",pattern:{description:"VS Code Workspace Settings",patterns:["**/.vscode/settings.json"]}},{key:"vscode-extensions",pattern:{description:"VS Code Extensions Configuration",patterns:["**/.vscode/extensions.json"]}},{key:"amp-settings",pattern:{description:"Amp Configuration Files",patterns:["**/amp.json","**/.amp/**"]}},{key:"shell-configs",pattern:{description:"Shell Configuration Files",patterns:["~/.bashrc","~/.zshrc","~/.fishrc","~/.cshrc","~/.tcshrc"]}},{key:"ssh-keys",pattern:{description:"SSH Keys and Configuration",patterns:["**/.ssh/**","~/.ssh/**"]}},{key:"gnupg-keys",pattern:{description:"GnuPG Keys and Configuration",patterns:["**/.gnupg/**","~/.gnupg/**"]}},{key:"environment-files",pattern:{description:"Environment Variable Files",patterns:["**/.env","**/.env.*"]}},{key:"claude-config",pattern:{description:"Claude AI Configuration",patterns:["**/.claude/**","~/.claude/**"]}},{key:"git-internals",pattern:{description:"Git Internal Files",patterns:["**/.git/**"]}},{key:"kubernetes-config",pattern:{description:"Kubernetes Configuration",patterns:["**/.kube/**","~/.kube/**"]}},{key:"cache-directories",pattern:{description:"Cache Directories",patterns:["**/.cache/**","~/.cache/**"]}},{key:"windows-appdata",pattern:{description:"Windows Application Data",patterns:["%APPDATA%/**"]}},{key:"sqlite3-files",pattern:{description:"SQLite Database Files",patterns:["**/*.db","**/*.sqlite","**/*.sqlite3"]}},{key:"common-configuration-patterns",pattern:{description:"Configuration Directories",patterns:["~/.*","~/.*/**","~/.config/**","~/Library/**","~/Libary/Preferences/**"]}}]});function dz1(){if(xM.size===0)return;h.info("Killing all child processes");for(let J of xM)hO0(J);xM.clear(),h.info("All child processes killed")}function hO0(J){if(!J.pid){try{J.kill("SIGKILL")}catch(Q){h.error("Failed to kill process without PID",Q)}return}if(vy.has(J.pid)){h.debug(`Process ${J.pid} already being killed, skipping`);return}vy.add(J.pid);try{if(process.platform==="win32"){let{spawn:Q}=k1("node:child_process"),Y=Q("taskkill",["/F","/T","/PID",J.pid.toString()],{stdio:"ignore"});Y.on("error",(X)=>{h.error(`Failed to kill Windows process tree ${J.pid}`,X);try{J.kill("SIGKILL")}catch(G){h.error(`Fallback kill also failed for ${J.pid}`,G)}}),Y.on("exit",()=>{vy.delete(J.pid)})}else{try{process.kill(J.pid,0),process.kill(-J.pid,"SIGKILL")}catch(Q){h.debug(`Process ${J.pid} no longer exists, skipping kill`)}vy.delete(J.pid)}}catch(Q){h.error(`Failed to kill process ${J.pid}`,Q),vy.delete(J.pid)}}function hV(...J){return new X0((Q)=>{let Y=!1,X,G=!1;return(async()=>{try{let{spawn:q}=await import("node:child_process");if(Y)return;let V={...J[2],detached:process.platform!=="win32",env:{...process.env,...J[2]?.env||{},NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive"}};if(!V.stdio)V.stdio=["pipe","pipe","pipe"];X=q(J[0],J[1],V),xM.add(X);let K={stdout:"",stderr:"",combinedOutput:"",exitCode:null,exited:!1,pid:X.pid};X.on("spawn",()=>{Q.next({...K,process:X})}),X.stdout?.on("data",(W)=>{if(Y)return;let H=W.toString();K.stdout+=H,K.combinedOutput+=H,K.lastData=W,Q.next({...K,process:X})}),X.stderr?.on("data",(W)=>{if(Y)return;let H=W.toString();K.stderr+=H,K.combinedOutput+=H,K.lastData=W,Q.next({...K,process:X})}),X.on("exit",(W)=>{if(Y)return;if(G)return;if(G=!0,K.exitCode=W??-1,K.exited=!0,K.lastData=void 0,Q.next({...K,process:X}),Q.complete(),X)xM.delete(X)}),X.on("error",(W)=>{if(Y)return;if(Q.error(W),X)xM.delete(X)})}catch(q){if(Y)return;Q.error(q)}})(),()=>{if(Y=!0,X&&!G)hO0(X),xM.delete(X)}})}function Ha(J){if(typeof J!=="string")throw Error("arg is not a string");if(J.startsWith("-"))throw Error("arg is not safe")}function fI(J){if(!J)throw Error("tool requires a working directory");if(J.scheme!=="file"&&J.scheme!=="vscode-vfs")throw Error(`tool requires a dir with a file: URI (got ${JSON.stringify(J.scheme)})`)}var xM,vy;var bV=L1(()=>{r0();L0();xM=new Set,vy=new Set;if(typeof process<"u")process.on("exit",()=>{dz1()}),process.on("SIGINT",()=>{if(h.info("Received SIGINT signal, shutting down"),dz1(),!process.versions.electron)process.exit(0)}),process.on("SIGTERM",()=>{if(h.info("Received SIGTERM signal, shutting down"),dz1(),!process.versions.electron)process.exit(0)})});import Wz4 from"node:os";function Ua(){try{
|
|
107
|
+
`)}async function vO0(J,Q,Y,X){if(Y=Y.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(Z,q)=>{return process.env[q]||Z}),Y=Y.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(Z,q)=>{return process.env[q]||Z}),Y.startsWith("~")&&typeof process<"u"&&process.env.HOME)Y=rH4.join(process.env.HOME,Y.slice(1));if(y$(Y))return n0.file(Y);for(let Z of Q){let q=Z6.joinPath(Z,Y);try{return await J.getMtime(q,{signal:X}),q}catch{continue}}let G=Q.at(0);if(G)return Z6.joinPath(G,Y);return n0.file(Y)}function wQ(J){if(!y$(J))throw Error(`Path must be absolute, not relative: ${J}`);return n0.file(J)}function xy(J){let Q=nD(J),Y=Jl(Q).slice(1).toLowerCase();if(eH4.includes(Y))return!1;if(Q===".env.example"||Q===".env.sample")return!1;return/^\.env(\..*)?$/.test(Q)||/^env\..+$/.test(Q)||/\.(env|secret|credentials|envrc)$/i.test(Q)}async function Jz4(J,Q,Y,X){let G=Q?Math.max(1,Q[0]):1,Z=Q?Math.max(G,Q[1]):G+1000-1,q=[],V=0,{createInterface:K}=await import("node:readline"),{createReadStream:W}=await import("node:fs"),H=K({input:W(J.fsPath,{encoding:"utf8",highWaterMark:65536}),crlfDelay:1/0}),z=_M(Y,()=>H.close());try{for await(let N of H){if(V++,V<G)continue;if(V>Z)break;q.push(V5.pruneWideLine(N,X))}}finally{z(),H.close()}if(G>1)q.unshift(`[... omitted lines 1 to ${G-1} ...]`);if(V>Z)q.push(`[... omitted lines ${Z+1} to ∞ ...]`);let U=G;return q.map((N)=>N.startsWith("[... omitted lines")?N:`${U++}: ${N}`)}var Wa=262144,yO0=32768,bz1=1000,gz1=4096,hz1=1000,eH4;var OX=L1(()=>{K4();WE();ZU();_I();kI();xI();JH();L4();fz1();eH4=["py","js","ts","tsx","jsx","go","rs","cpp","c","cc","cxx","cs","java","scala","rb","php","swift","kt","dart","pl","r","m","mm","h","hpp","lua","zig"]});function pz1(J){let Q=J;if(Q.startsWith("~/")){let Y=process.env.HOME||process.env.USERPROFILE||"";Q=Q.replace("~/",`${Y}/`)}else if(Q==="~")Q=process.env.HOME||process.env.USERPROFILE||"";if(Q=Q.replace(/%([^%]+)%/g,(Y,X)=>{return process.env[X]||`%${X}%`}),Q.includes("%USERPROFILE%")&&process.env.USERPROFILE)Q=Q.replace(/%USERPROFILE%/g,process.env.USERPROFILE);return n0.file(Q)}function mz1(J,Q){let Y=pz1(Q);if(Y.path.includes("*")){let X=J.toString(),G=Y.path;if(!G.startsWith("file://")){if(!G.startsWith("/"))G=`/${G}`;G=`file://${G}`}let Z=G.replace(/\./g,"\\.").replace(/\*\*/g,"§DOUBLESTAR§").replace(/\*/g,"[^/]*").replace(/§DOUBLESTAR§/g,".*");return new RegExp(`^${Z}$`).test(X)}else return Y.toString()===J.toString()}function fO0(J,Q){return Q.some((Y)=>mz1(J,Y))}async function Qz4(J,Q,Y){try{let X=await Q.realpath(J).catch(()=>J),Z=[...["~/.config/AGENT.md"],...Y];for(let q of Z)if(mz1(X,q)||mz1(J,q))return null;for(let{key:q,pattern:V}of uz1)if(fO0(X,V.patterns)||fO0(J,V.patterns))return{key:q,pattern:V};return null}catch{return null}}async function qU(J,Q,Y){if(Y?.dangerouslyAllowAll??!1)return{requiresConsent:!1};try{let G=await Qz4(J,Q,Y["guardedFiles.allowlist"]??[]);if(G)return{requiresConsent:!0,reason:`${G.pattern.description}`,toAllow:J.fsPath};return{requiresConsent:!1}}catch{return{requiresConsent:!0,reason:"Unable to resolve file path",toAllow:J.fsPath}}}var uz1;var yM=L1(()=>{K4();uz1=[{key:"vscode-user-settings",pattern:{description:"VS Code User Settings",patterns:["~/Library/Application Support/Code/User/settings.json","~/.config/Code/User/settings.json","%APPDATA%/Code/User/settings.json"]}},{key:"vscode-workspace-settings",pattern:{description:"VS Code Workspace Settings",patterns:["**/.vscode/settings.json"]}},{key:"vscode-extensions",pattern:{description:"VS Code Extensions Configuration",patterns:["**/.vscode/extensions.json"]}},{key:"amp-settings",pattern:{description:"Amp Configuration Files",patterns:["**/amp.json","**/.amp/**"]}},{key:"shell-configs",pattern:{description:"Shell Configuration Files",patterns:["~/.bashrc","~/.zshrc","~/.fishrc","~/.cshrc","~/.tcshrc"]}},{key:"ssh-keys",pattern:{description:"SSH Keys and Configuration",patterns:["**/.ssh/**","~/.ssh/**"]}},{key:"gnupg-keys",pattern:{description:"GnuPG Keys and Configuration",patterns:["**/.gnupg/**","~/.gnupg/**"]}},{key:"environment-files",pattern:{description:"Environment Variable Files",patterns:["**/.env","**/.env.*"]}},{key:"claude-config",pattern:{description:"Claude AI Configuration",patterns:["**/.claude/**","~/.claude/**"]}},{key:"git-internals",pattern:{description:"Git Internal Files",patterns:["**/.git/**"]}},{key:"kubernetes-config",pattern:{description:"Kubernetes Configuration",patterns:["**/.kube/**","~/.kube/**"]}},{key:"cache-directories",pattern:{description:"Cache Directories",patterns:["**/.cache/**","~/.cache/**"]}},{key:"windows-appdata",pattern:{description:"Windows Application Data",patterns:["%APPDATA%/**"]}},{key:"sqlite3-files",pattern:{description:"SQLite Database Files",patterns:["**/*.db","**/*.sqlite","**/*.sqlite3"]}},{key:"common-configuration-patterns",pattern:{description:"Configuration Directories",patterns:["~/.*","~/.*/**","~/.config/**","~/Library/**","~/Libary/Preferences/**"]}}]});function dz1(){if(xM.size===0)return;h.info("Killing all child processes");for(let J of xM)hO0(J);xM.clear(),h.info("All child processes killed")}function hO0(J){if(!J.pid){try{J.kill("SIGKILL")}catch(Q){h.error("Failed to kill process without PID",Q)}return}if(vy.has(J.pid)){h.debug(`Process ${J.pid} already being killed, skipping`);return}vy.add(J.pid);try{if(process.platform==="win32"){let{spawn:Q}=k1("node:child_process"),Y=Q("taskkill",["/F","/T","/PID",J.pid.toString()],{stdio:"ignore"});Y.on("error",(X)=>{h.error(`Failed to kill Windows process tree ${J.pid}`,X);try{J.kill("SIGKILL")}catch(G){h.error(`Fallback kill also failed for ${J.pid}`,G)}}),Y.on("exit",()=>{vy.delete(J.pid)})}else{try{process.kill(J.pid,0),process.kill(-J.pid,"SIGKILL")}catch(Q){h.debug(`Process ${J.pid} no longer exists, skipping kill`)}vy.delete(J.pid)}}catch(Q){h.error(`Failed to kill process ${J.pid}`,Q),vy.delete(J.pid)}}function hV(...J){return new X0((Q)=>{let Y=!1,X,G=!1;return(async()=>{try{let{spawn:q}=await import("node:child_process");if(Y)return;let V={...J[2],detached:process.platform!=="win32",env:{...process.env,...J[2]?.env||{},NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive"}};if(!V.stdio)V.stdio=["pipe","pipe","pipe"];X=q(J[0],J[1],V),xM.add(X);let K={stdout:"",stderr:"",combinedOutput:"",exitCode:null,exited:!1,pid:X.pid};X.on("spawn",()=>{Q.next({...K,process:X})}),X.stdout?.on("data",(W)=>{if(Y)return;let H=W.toString();K.stdout+=H,K.combinedOutput+=H,K.lastData=W,Q.next({...K,process:X})}),X.stderr?.on("data",(W)=>{if(Y)return;let H=W.toString();K.stderr+=H,K.combinedOutput+=H,K.lastData=W,Q.next({...K,process:X})}),X.on("exit",(W)=>{if(Y)return;if(G)return;if(G=!0,K.exitCode=W??-1,K.exited=!0,K.lastData=void 0,Q.next({...K,process:X}),Q.complete(),X)xM.delete(X)}),X.on("error",(W)=>{if(Y)return;if(Q.error(W),X)xM.delete(X)})}catch(q){if(Y)return;Q.error(q)}})(),()=>{if(Y=!0,X&&!G)hO0(X),xM.delete(X)}})}function Ha(J){if(typeof J!=="string")throw Error("arg is not a string");if(J.startsWith("-"))throw Error("arg is not safe")}function fI(J){if(!J)throw Error("tool requires a working directory");if(J.scheme!=="file"&&J.scheme!=="vscode-vfs")throw Error(`tool requires a dir with a file: URI (got ${JSON.stringify(J.scheme)})`)}var xM,vy;var bV=L1(()=>{r0();L0();xM=new Set,vy=new Set;if(typeof process<"u")process.on("exit",()=>{dz1()}),process.on("SIGINT",()=>{if(h.info("Received SIGINT signal, shutting down"),dz1(),!process.versions.electron)process.exit(0)}),process.on("SIGTERM",()=>{if(h.info("Received SIGTERM signal, shutting down"),dz1(),!process.versions.electron)process.exit(0)})});import Wz4 from"node:os";function Ua(){try{let J=Wz4.userInfo().shell;if(!J||J==="unknown")return;return J}catch(J){if(J?.code==="ENOENT")h.warn("os.userInfo() failed – user probably provided by NSS/FreeIPA");else h.warn("os.userInfo() failed",{err:J});return}}var iz1=L1(()=>{L0()});var mO0={};n8(mO0,{loadProfileEnvironmentVariables:()=>oz1});import{spawn as Hz4}from"node:child_process";import nz1 from"node:os";function az1(J){return{CLAUDECODE:"1",AGENT:"amp",AGENT_THREAD_ID:J?.thread?.id||"",AMP_CURRENT_THREAD_ID:J?.thread?.id||""}}function gV(J,Q){let Y=az1(Q);return{...J,...Y}}function oz1(J,Q="always",Y){if(Q==="never")return X0.of(gV(QH,Y));return X0.of(gV(QH,Y))}function gO0(J,Q){if(nz1.platform()!=="darwin"&&nz1.platform()!=="linux")return X0.of(gV(QH,Q));let Y=Date.now();return new X0((X)=>{let G=Ua()??process.env.SHELL??"/bin/bash",Z="AMP_SHELL_ENV_MARKER",V=`${J?`cd '${J.replace(/'/g,"\\'")}';`:""}printf '%s' AMP_SHELL_ENV_MARKER; /usr/bin/env;`,K=setTimeout(()=>{h.error("Shell environment collection timed out"),H.kill(),X.next(gV(QH,Q)),X.complete()},5000),W=["-l","-i","-c",V],H=Hz4(G,W,{stdio:["ignore","pipe","pipe"],detached:!0,env:{...process.env,NONINTERACTIVE:"1",DEBIAN_FRONTEND:"noninteractive",...az1()}}),z="",U="";if(H.stdout)H.stdout.on("data",(N)=>{z+=N.toString()});if(H.stderr)H.stderr.on("data",(N)=>{U+=N.toString()});return H.on("error",(N)=>{h.error("Failed to spawn shell:",{err:N}),clearTimeout(K),X.next(gV(QH,Q)),X.complete()}),H.on("close",(N)=>{clearTimeout(K);let L=Date.now()-Y;if(N!==0){h.error(`Shell process exited with code ${N}`),X.next(gV(QH,Q)),X.complete();return}let A={},E=z.indexOf("AMP_SHELL_ENV_MARKER");if(E!==-1)z.substring(E+20).split(`
|
|
108
108
|
`).forEach((I)=>{let R=I.match(/^([^=]+)=(.*)$/);if(R&&R[1]&&R[2]){let S=R[1],y=R[2];A[S]=y}});else h.warn("Failed to detect Amp marker while loading the login shell",{marker:"AMP_SHELL_ENV_MARKER"}),Object.assign(A,QH);h.info("Loaded login shell environment",{shell:G,shellArgs:W,durationMillis:L,directory:J,loadedVariableCount:Object.keys(A).length,selectEnvVars:{HOME:A.HOME,PATH:A.PATH,GOROOT:A.GOROOT,SHELL:A.SHELL}}),X.next(gV(A,Q)),X.complete()}),()=>{clearTimeout(K),H.kill()}})}function Fz4(){for(let[J,Q]of Object.entries(Ba))if(Uz4(Q))Ba.delete(J)}function Uz4(J){return J.timestamp+zz4>Date.now()}function Nz4(){if(process.env.IN_NIX_SHELL==="false")return!1;if(process.env.IN_NIX_SHELL)return!0;return(process.env.PATH??"").split(Bz4).some((Q)=>Q.startsWith("/nix/store"))}var zz4=86400000,Ba,QH,Bz4;var rz1=L1(()=>{r0();L0();iz1();Ba=new Map,QH=process.env;Bz4=nz1.platform()==="win32"?";":":"});var lO0=f((Yn8,cO0)=>{cO0.exports=dO0;dO0.sync=Mz4;var uO0=k1("fs");function Dz4(J,Q){var Y=Q.pathExt!==void 0?Q.pathExt:process.env.PATHEXT;if(!Y)return!0;if(Y=Y.split(";"),Y.indexOf("")!==-1)return!0;for(var X=0;X<Y.length;X++){var G=Y[X].toLowerCase();if(G&&J.substr(-G.length).toLowerCase()===G)return!0}return!1}function pO0(J,Q,Y){if(!J.isSymbolicLink()&&!J.isFile())return!1;return Dz4(Q,Y)}function dO0(J,Q,Y){uO0.stat(J,function(X,G){Y(X,X?!1:pO0(G,J,Q))})}function Mz4(J,Q){return pO0(uO0.statSync(J),J,Q)}});var rO0=f((Xn8,oO0)=>{oO0.exports=nO0;nO0.sync=Lz4;var iO0=k1("fs");function nO0(J,Q,Y){iO0.stat(J,function(X,G){Y(X,X?!1:aO0(G,Q))})}function Lz4(J,Q){return aO0(iO0.statSync(J),Q)}function aO0(J,Q){return J.isFile()&&Az4(J,Q)}function Az4(J,Q){var{mode:Y,uid:X,gid:G}=J,Z=Q.uid!==void 0?Q.uid:process.getuid&&process.getuid(),q=Q.gid!==void 0?Q.gid:process.getgid&&process.getgid(),V=parseInt("100",8),K=parseInt("010",8),W=parseInt("001",8),H=V|K,z=Y&W||Y&K&&G===q||Y&V&&X===Z||Y&H&&Z===0;return z}});var tO0=f((Zn8,sO0)=>{var Gn8=k1("fs"),Na;if(process.platform==="win32"||global.TESTING_WINDOWS)Na=lO0();else Na=rO0();sO0.exports=sz1;sz1.sync=Oz4;function sz1(J,Q,Y){if(typeof Q==="function")Y=Q,Q={};if(!Y){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(X,G){sz1(J,Q||{},function(Z,q){if(Z)G(Z);else X(q)})})}Na(J,Q||{},function(X,G){if(X){if(X.code==="EACCES"||Q&&Q.ignoreErrors)X=null,G=!1}Y(X,G)})}function Oz4(J,Q){try{return Na.sync(J,Q||{})}catch(Y){if(Q&&Q.ignoreErrors||Y.code==="EACCES")return!1;else throw Y}}});var Zw0=f(($n8,Gw0)=>{var bI=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",eO0=k1("path"),wz4=bI?";":":",Jw0=tO0(),Qw0=(J)=>Object.assign(Error(`not found: ${J}`),{code:"ENOENT"}),Yw0=(J,Q)=>{let Y=Q.colon||wz4,X=J.match(/\//)||bI&&J.match(/\\/)?[""]:[...bI?[process.cwd()]:[],...(Q.path||process.env.PATH||"").split(Y)],G=bI?Q.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",Z=bI?G.split(Y):[""];if(bI){if(J.indexOf(".")!==-1&&Z[0]!=="")Z.unshift("")}return{pathEnv:X,pathExt:Z,pathExtExe:G}},Xw0=(J,Q,Y)=>{if(typeof Q==="function")Y=Q,Q={};if(!Q)Q={};let{pathEnv:X,pathExt:G,pathExtExe:Z}=Yw0(J,Q),q=[],V=(W)=>new Promise((H,z)=>{if(W===X.length)return Q.all&&q.length?H(q):z(Qw0(J));let U=X[W],N=/^".*"$/.test(U)?U.slice(1,-1):U,M=eO0.join(N,J),L=!N&&/^\.[\\\/]/.test(J)?J.slice(0,2)+M:M;H(K(L,W,0))}),K=(W,H,z)=>new Promise((U,N)=>{if(z===G.length)return U(V(H+1));let M=G[z];Jw0(W+M,{pathExt:Z},(L,A)=>{if(!L&&A)if(Q.all)q.push(W+M);else return U(W+M);return U(K(W,H,z+1))})});return Y?V(0).then((W)=>Y(null,W),Y):V(0)},Ez4=(J,Q)=>{Q=Q||{};let{pathEnv:Y,pathExt:X,pathExtExe:G}=Yw0(J,Q),Z=[];for(let q=0;q<Y.length;q++){let V=Y[q],K=/^".*"$/.test(V)?V.slice(1,-1):V,W=eO0.join(K,J),H=!K&&/^\.[\\\/]/.test(J)?J.slice(0,2)+W:W;for(let z=0;z<X.length;z++){let U=H+X[z];try{if(Jw0.sync(U,{pathExt:G}))if(Q.all)Z.push(U);else return U}catch(N){}}}if(Q.all&&Z.length)return Z;if(Q.nothrow)return null;throw Qw0(J)};Gw0.exports=Xw0;Xw0.sync=Ez4});var qw0=f((qn8,tz1)=>{var $w0=(J={})=>{let Q=J.env||process.env;if((J.platform||process.platform)!=="win32")return"PATH";return Object.keys(Q).reverse().find((X)=>X.toUpperCase()==="PATH")||"Path"};tz1.exports=$w0;tz1.exports.default=$w0});var Hw0=f((Vn8,Ww0)=>{var Vw0=k1("path"),Iz4=Zw0(),Pz4=qw0();function Kw0(J,Q){let Y=J.options.env||process.env,X=process.cwd(),G=J.options.cwd!=null,Z=G&&process.chdir!==void 0&&!process.chdir.disabled;if(Z)try{process.chdir(J.options.cwd)}catch(V){}let q;try{q=Iz4.sync(J.command,{path:Y[Pz4({env:Y})],pathExt:Q?Vw0.delimiter:void 0})}catch(V){}finally{if(Z)process.chdir(X)}if(q)q=Vw0.resolve(G?J.options.cwd:"",q);return q}function Tz4(J){return Kw0(J)||Kw0(J,!0)}Ww0.exports=Tz4});var zw0=f((jz4,JF1)=>{var ez1=/([()\][%!^"`<>&|;, *?])/g;function Rz4(J){return J=J.replace(ez1,"^$1"),J}function Cz4(J,Q){if(J=`${J}`,J=J.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),J=J.replace(/(?=(\\+?)?)\1$/,"$1$1"),J=`"${J}"`,J=J.replace(ez1,"^$1"),Q)J=J.replace(ez1,"^$1");return J}jz4.command=Rz4;jz4.argument=Cz4});var Uw0=f((Kn8,Fw0)=>{Fw0.exports=/^#!(.*)/});var Nw0=f((Wn8,Bw0)=>{var kz4=Uw0();Bw0.exports=(J="")=>{let Q=J.match(kz4);if(!Q)return null;let[Y,X]=Q[0].replace(/#! ?/,"").split(" "),G=Y.split("/").pop();if(G==="env")return X;return X?`${G} ${X}`:G}});var Mw0=f((Hn8,Dw0)=>{var QF1=k1("fs"),yz4=Nw0();function xz4(J){let Y=Buffer.alloc(150),X;try{X=QF1.openSync(J,"r"),QF1.readSync(X,Y,0,150,0),QF1.closeSync(X)}catch(G){}return yz4(Y.toString())}Dw0.exports=xz4});var ww0=f((zn8,Ow0)=>{var vz4=k1("path"),Lw0=Hw0(),Aw0=zw0(),fz4=Mw0(),hz4=process.platform==="win32",bz4=/\.(?:com|exe)$/i,gz4=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function mz4(J){J.file=Lw0(J);let Q=J.file&&fz4(J.file);if(Q)return J.args.unshift(J.file),J.command=Q,Lw0(J);return J.file}function uz4(J){if(!hz4)return J;let Q=mz4(J),Y=!bz4.test(Q);if(J.options.forceShell||Y){let X=gz4.test(Q);J.command=vz4.normalize(J.command),J.command=Aw0.command(J.command),J.args=J.args.map((Z)=>Aw0.argument(Z,X));let G=[J.command].concat(J.args).join(" ");J.args=["/d","/s","/c",`"${G}"`],J.command=process.env.comspec||"cmd.exe",J.options.windowsVerbatimArguments=!0}return J}function pz4(J,Q,Y){if(Q&&!Array.isArray(Q))Y=Q,Q=null;Q=Q?Q.slice(0):[],Y=Object.assign({},Y);let X={command:J,args:Q,options:Y,file:void 0,original:{command:J,args:Q}};return Y.shell?X:uz4(X)}Ow0.exports=pz4});var Pw0=f((Fn8,Iw0)=>{var YF1=process.platform==="win32";function XF1(J,Q){return Object.assign(Error(`${Q} ${J.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Q} ${J.command}`,path:J.command,spawnargs:J.args})}function dz4(J,Q){if(!YF1)return;let Y=J.emit;J.emit=function(X,G){if(X==="exit"){let Z=Ew0(G,Q);if(Z)return Y.call(J,"error",Z)}return Y.apply(J,arguments)}}function Ew0(J,Q){if(YF1&&J===1&&!Q.file)return XF1(Q.original,"spawn");return null}function cz4(J,Q){if(YF1&&J===1&&!Q.file)return XF1(Q.original,"spawnSync");return null}Iw0.exports={hookChildProcess:dz4,verifyENOENT:Ew0,verifyENOENTSync:cz4,notFoundError:XF1}});var Cw0=f((Un8,gI)=>{var Tw0=k1("child_process"),GF1=ww0(),ZF1=Pw0();function Rw0(J,Q,Y){let X=GF1(J,Q,Y),G=Tw0.spawn(X.command,X.args,X.options);return ZF1.hookChildProcess(G,X),G}function lz4(J,Q,Y){let X=GF1(J,Q,Y),G=Tw0.spawnSync(X.command,X.args,X.options);return G.error=G.error||ZF1.verifyENOENTSync(G.status,X),G}gI.exports=Rw0;gI.exports.spawn=Rw0;gI.exports.sync=lz4;gI.exports._parse=GF1;gI.exports._enoent=ZF1});class $F1{append(J){this._buffer=this._buffer?Buffer.concat([this._buffer,J]):J}readMessage(){if(!this._buffer)return null;let J=this._buffer.indexOf(`
|
|
109
109
|
`);if(J===-1)return null;let Q=this._buffer.toString("utf8",0,J).replace(/\r$/,"");return this._buffer=this._buffer.subarray(J+1),iz4(Q)}clear(){this._buffer=void 0}}function iz4(J){return sF.parse(JSON.parse(J))}function jw0(J){return JSON.stringify(J)+`
|
|
110
110
|
`}var Sw0=L1(()=>{tW()});var vw0={};n8(vw0,{getDefaultEnvironment:()=>yw0,StdioClientTransport:()=>xw0,DEFAULT_INHERITED_ENV_VARS:()=>kw0});import Da from"node:process";import{PassThrough as nz4}from"node:stream";function yw0(){let J={};for(let Q of kw0){let Y=Da.env[Q];if(Y===void 0)continue;if(Y.startsWith("()"))continue;J[Q]=Y}return J}class xw0{constructor(J){if(this._abortController=new AbortController,this._readBuffer=new $F1,this._stderrStream=null,this._serverParams=J,J.stderr==="pipe"||J.stderr==="overlapped")this._stderrStream=new nz4}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((J,Q)=>{var Y,X,G,Z,q;if(this._process=_w0.default(this._serverParams.command,(Y=this._serverParams.args)!==null&&Y!==void 0?Y:[],{env:{...yw0(),...this._serverParams.env},stdio:["pipe","pipe",(X=this._serverParams.stderr)!==null&&X!==void 0?X:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:Da.platform==="win32"&&az4(),cwd:this._serverParams.cwd}),this._process.on("error",(V)=>{var K,W;if(V.name==="AbortError"){(K=this.onclose)===null||K===void 0||K.call(this);return}Q(V),(W=this.onerror)===null||W===void 0||W.call(this,V)}),this._process.on("spawn",()=>{J()}),this._process.on("close",(V)=>{var K;this._process=void 0,(K=this.onclose)===null||K===void 0||K.call(this)}),(G=this._process.stdin)===null||G===void 0||G.on("error",(V)=>{var K;(K=this.onerror)===null||K===void 0||K.call(this,V)}),(Z=this._process.stdout)===null||Z===void 0||Z.on("data",(V)=>{this._readBuffer.append(V),this.processReadBuffer()}),(q=this._process.stdout)===null||q===void 0||q.on("error",(V)=>{var K;(K=this.onerror)===null||K===void 0||K.call(this,V)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){var J,Q;if(this._stderrStream)return this._stderrStream;return(Q=(J=this._process)===null||J===void 0?void 0:J.stderr)!==null&&Q!==void 0?Q:null}get pid(){var J,Q;return(Q=(J=this._process)===null||J===void 0?void 0:J.pid)!==null&&Q!==void 0?Q:null}processReadBuffer(){var J,Q;while(!0)try{let Y=this._readBuffer.readMessage();if(Y===null)break;(J=this.onmessage)===null||J===void 0||J.call(this,Y)}catch(Y){(Q=this.onerror)===null||Q===void 0||Q.call(this,Y)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(J){return new Promise((Q)=>{var Y;if(!((Y=this._process)===null||Y===void 0?void 0:Y.stdin))throw Error("Not connected");let X=jw0(J);if(this._process.stdin.write(X))Q();else this._process.stdin.once("drain",Q)})}}function az4(){return"type"in Da}var _w0,kw0;var fw0=L1(()=>{Sw0();_w0=D6(Cw0(),1),kw0=Da.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"]});function v$(){}function cw0(J,Q,Y,X,G){var Z=[],q;while(Q)Z.push(Q),q=Q.previousComponent,delete Q.previousComponent,Q=q;Z.reverse();var V=0,K=Z.length,W=0,H=0;for(;V<K;V++){var z=Z[V];if(!z.removed){if(!z.added&&G){var U=Y.slice(W,W+z.count);U=U.map(function(N,M){var L=X[H+M];return L.length>N.length?L:N}),z.value=J.join(U)}else z.value=J.join(Y.slice(W,W+z.count));if(W+=z.count,!z.added)H+=z.count}else z.value=J.join(X.slice(H,H+z.count)),H+=z.count}return Z}function lw0(J,Q){var Y;for(Y=0;Y<J.length&&Y<Q.length;Y++)if(J[Y]!=Q[Y])return J.slice(0,Y);return J.slice(0,Y)}function iw0(J,Q){var Y;if(!J||!Q||J[J.length-1]!=Q[Q.length-1])return"";for(Y=0;Y<J.length&&Y<Q.length;Y++)if(J[J.length-(Y+1)]!=Q[Q.length-(Y+1)])return J.slice(-Y);return J.slice(-Y)}function zF1(J,Q,Y){if(J.slice(0,Q.length)!=Q)throw Error("string ".concat(JSON.stringify(J)," doesn't start with prefix ").concat(JSON.stringify(Q),"; this is a bug"));return Y+J.slice(Q.length)}function FF1(J,Q,Y){if(!Q)return J+Y;if(J.slice(-Q.length)!=Q)throw Error("string ".concat(JSON.stringify(J)," doesn't end with suffix ").concat(JSON.stringify(Q),"; this is a bug"));return J.slice(0,-Q.length)+Y}function by(J,Q){return zF1(J,Q,"")}function Aa(J,Q){return FF1(J,Q,"")}function nw0(J,Q){return Q.slice(0,GF4(J,Q))}function GF4(J,Q){var Y=0;if(J.length>Q.length)Y=J.length-Q.length;var X=Q.length;if(J.length<Q.length)X=J.length;var G=Array(X),Z=0;G[0]=0;for(var q=1;q<X;q++){if(Q[q]==Q[Z])G[q]=G[Z];else G[q]=Z;while(Z>0&&Q[q]!=Q[Z])Z=G[Z];if(Q[q]==Q[Z])Z++}Z=0;for(var V=Y;V<J.length;V++){while(Z>0&&J[V]!=Q[Z])Z=G[Z];if(J[V]==Q[Z])Z++}return Z}function aw0(J,Q,Y,X){if(Q&&Y){var G=Q.value.match(/^\s*/)[0],Z=Q.value.match(/\s*$/)[0],q=Y.value.match(/^\s*/)[0],V=Y.value.match(/\s*$/)[0];if(J){var K=lw0(G,q);J.value=FF1(J.value,q,K),Q.value=by(Q.value,K),Y.value=by(Y.value,K)}if(X){var W=iw0(Z,V);X.value=zF1(X.value,V,W),Q.value=Aa(Q.value,W),Y.value=Aa(Y.value,W)}}else if(Y){if(J)Y.value=Y.value.replace(/^\s*/,"");if(X)X.value=X.value.replace(/^\s*/,"")}else if(J&&X){var H=X.value.match(/^\s*/)[0],z=Q.value.match(/^\s*/)[0],U=Q.value.match(/\s*$/)[0],N=lw0(H,z);Q.value=by(Q.value,N);var M=iw0(by(H,N),U);Q.value=Aa(Q.value,M),X.value=zF1(X.value,H,M),J.value=FF1(J.value,H,H.slice(0,H.length-M.length))}else if(X){var L=X.value.match(/^\s*/)[0],A=Q.value.match(/\s*$/)[0],E=nw0(A,L);Q.value=Aa(Q.value,E)}else if(J){var P=J.value.match(/\s*$/)[0],I=Q.value.match(/^\s*/)[0],R=nw0(P,I);Q.value=by(Q.value,R)}}function ow0(J,Q,Y){return Ia.diff(J,Q,Y)}function rw0(J,Q){var Y=Object.keys(J);if(Object.getOwnPropertySymbols){var X=Object.getOwnPropertySymbols(J);Q&&(X=X.filter(function(G){return Object.getOwnPropertyDescriptor(J,G).enumerable})),Y.push.apply(Y,X)}return Y}function wa(J){for(var Q=1;Q<arguments.length;Q++){var Y=arguments[Q]!=null?arguments[Q]:{};Q%2?rw0(Object(Y),!0).forEach(function(X){HF4(J,X,Y[X])}):Object.getOwnPropertyDescriptors?Object.defineProperties(J,Object.getOwnPropertyDescriptors(Y)):rw0(Object(Y)).forEach(function(X){Object.defineProperty(J,X,Object.getOwnPropertyDescriptor(Y,X))})}return J}function KF4(J,Q){if(typeof J!="object"||!J)return J;var Y=J[Symbol.toPrimitive];if(Y!==void 0){var X=Y.call(J,Q||"default");if(typeof X!="object")return X;throw TypeError("@@toPrimitive must return a primitive value.")}return(Q==="string"?String:Number)(J)}function WF4(J){var Q=KF4(J,"string");return typeof Q=="symbol"?Q:Q+""}function UF1(J){return UF1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},UF1(J)}function HF4(J,Q,Y){if(Q=WF4(Q),Q in J)Object.defineProperty(J,Q,{value:Y,enumerable:!0,configurable:!0,writable:!0});else J[Q]=Y;return J}function HF1(J){return zF4(J)||FF4(J)||UF4(J)||BF4()}function zF4(J){if(Array.isArray(J))return BF1(J)}function FF4(J){if(typeof Symbol<"u"&&J[Symbol.iterator]!=null||J["@@iterator"]!=null)return Array.from(J)}function UF4(J,Q){if(!J)return;if(typeof J==="string")return BF1(J,Q);var Y=Object.prototype.toString.call(J).slice(8,-1);if(Y==="Object"&&J.constructor)Y=J.constructor.name;if(Y==="Map"||Y==="Set")return Array.from(J);if(Y==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(Y))return BF1(J,Q)}function BF1(J,Q){if(Q==null||Q>J.length)Q=J.length;for(var Y=0,X=Array(Q);Y<Q;Y++)X[Y]=J[Y];return X}function BF4(){throw TypeError(`Invalid attempt to spread non-iterable instance.
|
|
@@ -2190,7 +2190,7 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};class
|
|
|
2190
2190
|
`].join("")}function fo0(J){if(J.flags!==void 0)return J.flags;return[J.global?"g":"",J.ignoreCase?"i":"",J.multiline?"m":"",J.unicode?"u":"",J.sticky?"y":""].join("")}function d68(J){return RegExp("^(?:"+J.source+")",fo0(J))}function J01(){var J=[].slice.call(arguments),Q=J.length;for(var Y=0;Y<Q;Y+=1)NR(J[Y]);return g6(function(X,G){var Z,q=Array(Q);for(var V=0;V<Q;V+=1){if(Z=AZ(J[V]._(X,G),Z),!Z.status)return Z;q[V]=Z.value,G=Z.index}return AZ(A2(G,q),Z)})}function c68(){var J={},Q=0,Y=_68(arguments),X=Y.length;for(var G=0;G<X;G+=1){var Z=Y[G];if(Ib(Z))continue;if(BR(Z)){var q=Z.length===2&&typeof Z[0]==="string"&&Ib(Z[1]);if(q){var V=Z[0];if(Object.prototype.hasOwnProperty.call(J,V))throw Error("seqObj: duplicate key "+V);J[V]=!0,Q++;continue}}throw Error("seqObj arguments must be parsers or [string, parser] array pairs.")}if(Q===0)throw Error("seqObj expects at least one named parser, found zero");return g6(function(K,W){var H,z={};for(var U=0;U<X;U+=1){var N,M;if(BR(Y[U]))N=Y[U][0],M=Y[U][1];else N=null,M=Y[U];if(H=AZ(M._(K,W),H),!H.status)return H;if(N)z[N]=H.value;W=H.index}return AZ(A2(W,z),H)})}function NA(){var J=[].slice.call(arguments);if(J.length===0)throw Error("seqMap needs at least one argument");var Q=J.pop();return UA(Q),J01.apply(null,J).map(function(Y){return Q.apply(null,Y)})}function l68(J){var Q={};for(var Y in J)if({}.hasOwnProperty.call(J,Y))(function(X){var G=function(){return J[X](Q)};Q[X]=go0(G)})(Y);return Q}function Q01(){var J=[].slice.call(arguments),Q=J.length;if(Q===0)return Y01("zero alternates");for(var Y=0;Y<Q;Y+=1)NR(J[Y]);return g6(function(X,G){var Z;for(var q=0;q<J.length;q+=1)if(Z=AZ(J[q]._(X,G),Z),Z.status)return Z;return Z})}function ho0(J,Q){return BI1(J,Q).or(DA([]))}function BI1(J,Q){NR(J),NR(Q);var Y=Q.then(J).many();return NA(J,Y,function(X,G){return[X].concat(G)})}D8.parse=function(J){if(typeof J!=="string"&&!wb(J))throw Error(".parse must be called with a string or Buffer as its argument");var Q=this.skip(DI1)._(J,0),Y;if(Q.status)Y={status:!0,value:Q.value};else Y={status:!1,index:xo0(J,Q.furthest),expected:Q.expected};return delete a11[J],Y};D8.tryParse=function(J){var Q=this.parse(J);if(Q.status)return Q.value;else{var Y=vo0(J,Q),X=Error(Y);throw X.type="ParsimmonError",X.result=Q,X}};D8.assert=function(J,Q){return this.chain(function(Y){return J(Y)?DA(Y):Y01(Q)})};D8.or=function(J){return Q01(this,J)};D8.trim=function(J){return this.wrap(J,J)};D8.wrap=function(J,Q){return NA(J,this,Q,function(Y,X){return X})};D8.thru=function(J){return J(this)};D8.then=function(J){return NR(J),J01(this,J).map(function(Q){return Q[1]})};D8.many=function(){var J=this;return g6(function(Q,Y){var X=[],G=void 0;for(;;)if(G=AZ(J._(Q,Y),G),G.status){if(Y===G.index)throw Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");Y=G.index,X.push(G.value)}else return AZ(A2(Y,X),G)})};D8.tieWith=function(J){return Eb(J),this.map(function(Q){if(y68(Q),Q.length){Eb(Q[0]);var Y=Q[0];for(var X=1;X<Q.length;X++)Eb(Q[X]),Y+=J+Q[X];return Y}else return""})};D8.tie=function(){return this.tieWith("")};D8.times=function(J,Q){var Y=this;if(arguments.length<2)Q=J;return DR(J),DR(Q),g6(function(X,G){var Z=[],q=void 0,V=void 0;for(var K=0;K<J;K+=1)if(q=Y._(X,G),V=AZ(q,V),q.status)G=q.index,Z.push(q.value);else return V;for(;K<Q;K+=1)if(q=Y._(X,G),V=AZ(q,V),q.status)G=q.index,Z.push(q.value);else break;return AZ(A2(G,Z),V)})};D8.result=function(J){return this.map(function(){return J})};D8.atMost=function(J){return this.times(0,J)};D8.atLeast=function(J){return NA(this.times(J),this.many(),function(Q,Y){return Q.concat(Y)})};D8.map=function(J){UA(J);var Q=this;return g6(function(Y,X){var G=Q._(Y,X);if(!G.status)return G;return AZ(A2(G.index,J(G.value)),G)})};D8.contramap=function(J){UA(J);var Q=this;return g6(function(Y,X){var G=Q.parse(J(Y.slice(X)));if(!G.status)return G;return A2(X+Y.length,G.value)})};D8.promap=function(J,Q){return UA(J),UA(Q),this.contramap(J).map(Q)};D8.skip=function(J){return J01(this,J).map(function(Q){return Q[0]})};D8.mark=function(){return NA(Pb,this,Pb,function(J,Q,Y){return{start:J,value:Q,end:Y}})};D8.node=function(J){return NA(Pb,this,Pb,function(Q,Y,X){return{name:J,value:Y,start:Q,end:X}})};D8.sepBy=function(J){return ho0(this,J)};D8.sepBy1=function(J){return BI1(this,J)};D8.lookahead=function(J){return this.skip(r11(J))};D8.notFollowedBy=function(J){return this.skip(bo0(J))};D8.desc=function(J){if(!BR(J))J=[J];var Q=this;return g6(function(Y,X){var G=Q._(Y,X);if(!G.status)G.expected=J;return G})};D8.fallback=function(J){return this.or(DA(J))};D8.ap=function(J){return NA(J,this,function(Q,Y){return Q(Y)})};D8.chain=function(J){var Q=this;return g6(function(Y,X){var G=Q._(Y,X);if(!G.status)return G;var Z=J(G.value);return AZ(Z._(Y,G.index),G)})};function Tb(J){Eb(J);var Q="'"+J+"'";return g6(function(Y,X){var G=X+J.length,Z=Y.slice(X,G);if(Z===J)return A2(G,Z);else return cX(X,Q)})}function i68(J){if(s11(),DR(J),J>255)throw Error("Value specified to byte constructor ("+J+"=0x"+J.toString(16)+") is larger in value than a single byte.");var Q=(J>15?"0x":"0x0")+J.toString(16);return g6(function(Y,X){var G=e11(Y,X);if(G===J)return A2(X+1,G);else return cX(X,Q)})}function eH(J,Q){if(x68(J),arguments.length>=2)DR(Q);else Q=0;var Y=d68(J),X=""+J;return g6(function(G,Z){var q=Y.exec(G.slice(Z));if(q){if(0<=Q&&Q<=q.length){var V=q[0],K=q[Q];return A2(Z+V.length,K)}var W="valid match group (0 to "+q.length+") in "+X;return cX(Z,W)}return cX(Z,X)})}function DA(J){return g6(function(Q,Y){return A2(Y,J)})}function Y01(J){return g6(function(Q,Y){return cX(Y,J)})}function r11(J){if(Ib(J))return g6(function(Q,Y){var X=J._(Q,Y);return X.index=Y,X.value="",X});else if(typeof J==="string")return r11(Tb(J));else if(J instanceof RegExp)return r11(eH(J));throw Error("not a string, regexp, or parser: "+J)}function bo0(J){return NR(J),g6(function(Q,Y){var X=J._(Q,Y),G=Q.slice(Y,X.index);return X.status?cX(Y,'not "'+G+'"'):A2(Y,null)})}function X01(J){return UA(J),g6(function(Q,Y){var X=e11(Q,Y);if(Y<Q.length&&J(X))return A2(Y+1,X);else return cX(Y,"a character/byte matching "+J)})}function n68(J){var Q=J.split("");for(var Y=0;Y<Q.length;Y++)Q[Y]="'"+Q[Y]+"'";return X01(function(X){return J.indexOf(X)>=0}).desc(Q)}function a68(J){return X01(function(Q){return J.indexOf(Q)<0}).desc("none of '"+J+"'")}function o68(J){return g6(J(A2,cX))}function r68(J,Q){return X01(function(Y){return J<=Y&&Y<=Q}).desc(J+"-"+Q)}function s68(J){return UA(J),g6(function(Q,Y){var X=Y;while(X<Q.length&&J(e11(Q,X)))X++;return A2(X,Q.slice(Y,X))})}function go0(J,Q){if(arguments.length<2)Q=J,J=void 0;var Y=g6(function(X,G){return Y._=Q()._,Y._(X,G)});if(J)return Y.desc(J);else return Y}function NI1(){return Y01("fantasy-land/empty")}D8.concat=D8.or;D8.empty=NI1;D8.of=DA;D8["fantasy-land/ap"]=D8.ap;D8["fantasy-land/chain"]=D8.chain;D8["fantasy-land/concat"]=D8.concat;D8["fantasy-land/empty"]=D8.empty;D8["fantasy-land/of"]=D8.of;D8["fantasy-land/map"]=D8.map;var Pb=g6(function(J,Q){return A2(Q,xo0(J,Q))}),t68=g6(function(J,Q){if(Q>=J.length)return cX(Q,"any character/byte");return A2(Q+1,e11(J,Q))}),e68=g6(function(J,Q){return A2(J.length,J.slice(Q))}),DI1=g6(function(J,Q){if(Q<J.length)return cX(Q,"EOF");return A2(Q,null)}),J48=eH(/[0-9]/).desc("a digit"),Q48=eH(/[0-9]*/).desc("optional digits"),Y48=eH(/[a-z]/i).desc("a letter"),X48=eH(/[a-z]*/i).desc("optional letters"),G48=eH(/\s*/).desc("optional whitespace"),Z48=eH(/\s+/).desc("whitespace"),mo0=Tb("\r"),uo0=Tb(`
|
|
2191
2191
|
`),po0=Tb(`\r
|
|
2192
2192
|
`),do0=Q01(po0,uo0,mo0).desc("newline"),$48=Q01(do0,DI1);g6.all=e68;g6.alt=Q01;g6.any=t68;g6.cr=mo0;g6.createLanguage=l68;g6.crlf=po0;g6.custom=o68;g6.digit=J48;g6.digits=Q48;g6.empty=NI1;g6.end=$48;g6.eof=DI1;g6.fail=Y01;g6.formatError=vo0;g6.index=Pb;g6.isParser=Ib;g6.lazy=go0;g6.letter=Y48;g6.letters=X48;g6.lf=uo0;g6.lookahead=r11;g6.makeFailure=cX;g6.makeSuccess=A2;g6.newline=do0;g6.noneOf=a68;g6.notFollowedBy=bo0;g6.of=DA;g6.oneOf=n68;g6.optWhitespace=G48;g6.Parser=g6;g6.range=r68;g6.regex=eH;g6.regexp=eH;g6.sepBy=ho0;g6.sepBy1=BI1;g6.seq=J01;g6.seqMap=NA;g6.seqObj=c68;g6.string=Tb;g6.succeed=DA;g6.takeWhile=s68;g6.test=X01;g6.whitespace=Z48;g6["fantasy-land/empty"]=NI1;g6["fantasy-land/of"]=DA;g6.Binary={bitSeq:yo0,bitSeqObj:E68,byte:i68,buffer:I68,encodedString:P68,uintBE:d11,uint8BE:d11(1),uint16BE:d11(2),uint32BE:d11(4),uintLE:c11,uint8LE:c11(1),uint16LE:c11(2),uint32LE:c11(4),intBE:l11,int8BE:l11(1),int16BE:l11(2),int32BE:l11(4),intLE:i11,int8LE:i11(1),int16LE:i11(2),int32LE:i11(4),floatBE:R68(),floatLE:C68(),doubleBE:j68(),doubleLE:S68()};co0.exports=g6});function no0(J,Q){return J.then(Q).skip(J)}function q48(J){return $6.default((Q,Y)=>{let X=Q.indexOf(J,Y);if(X!==-1)return $6.default.makeSuccess(X+J.length,Q.substring(Y,X));return $6.default.makeFailure(Y,[J])})}function V48(J,Q,Y){return $6.default((X,G)=>{let Z=[],q=G;if(Y._(X,q).status)return $6.default.makeFailure(q,["at least one match before terminator"]);let K=J._(X,q);if(!K.status)return K;Z.push(K.value),q=K.index;while(!0){if(Y._(X,q).status)break;let H=Q._(X,q);if(!H.status)break;q=H.index;let z=J._(X,q);if(!z.status)break;Z.push(z.value),q=z.index}return $6.default.makeSuccess(q,Z)})}class MI1{platform;constructor(J){this.platform=J}whitespaceWithEscapes=$6.default.alt($6.default.string(" "),$6.default.string("\t"),$6.default.string(`
|
|
2193
|
-
`),$6.default.string("\r"),$6.default.string("\\").then($6.default.whitespace)).many().tie();escapeSequences=$6.default.string("\\").then($6.default.oneOf('\\|&<>();"'));unquotedEscapeSequences=$6.default.string("\\").then($6.default.oneOf('\\|&<>(); "[]'));doubleQuotedString=no0($6.default.string('"'),$6.default.alt(this.escapeSequences,$6.default.noneOf('"')).many().tie()).desc("double-quoted string");singleQuotedString=no0($6.default.string("'"),$6.default.alt($6.default.string("\\").then($6.default.any),$6.default.noneOf("'\\")).many().tie()).desc("single-quoted string");braceExpansion=$6.default.lazy(()=>{let J=$6.default.lazy(()=>$6.default.alt($6.default.string("{").then(J).skip($6.default.string("}")).map((Q)=>`{${Q}}`),$6.default.noneOf("}")).many().tie());return $6.default.string("{").then(J).skip($6.default.string("}")).map((Q)=>`{${Q}}`)}).desc("brace expansion");unquotedString=$6.default.lazy(()=>{if(this.platform==="win32")return $6.default.alt($6.default.regexp(/[a-zA-Z]:[\\/]\S+/),$6.default.regexp(/\\\\\S+\\\S*/),$6.default.alt(this.unquotedEscapeSequences,$6.default.regexp(/[a-zA-Z0-9_\-:/.*~@=\\^,[\]#!]/),$6.default.regexp(/\$(?![A-Za-z_{(])/),$6.default.regexp(/\([a-zA-Z0-9_-]*\)/)).atLeast(1).tie()).desc("unquoted string");else return $6.default.alt(this.unquotedEscapeSequences,$6.default.regexp(/[a-zA-Z0-9_\-:/.*~@=+^,[\]#!]/),$6.default.regexp(/\$(?![A-Za-z_{(])/),$6.default.regexp(/\([a-zA-Z0-9_-]*\)/)).atLeast(1).tie().desc("unquoted string")});commandSubstitution=$6.default.lazy(()=>$6.default.string("$(").then(this.expression).skip($6.default.string(")")).map((J)=>({type:"invocations",trees:J})));word=$6.default.lazy(()=>{return $6.default.alt(this.doubleQuotedString,this.singleQuotedString,this.braceExpansion,this.unquotedString,this.commandSubstitution,this.envVariable).sepBy1($6.default.string("")).map((J)=>{let[Q,...Y]=J;if(Q===void 0)throw Error("Expect non-empty array of parts in argument: "+JSON.stringify(J));else if(Y.length===0)return Q;else if(J.every((X)=>typeof X==="string"))return J.join("");else return{type:"concatenation",values:J}})}).node("word");envVariable=$6.default.regexp(/\$([A-Za-z_][A-Za-z0-9_]*|\{[A-Za-z_][A-Za-z0-9_]*\})/).map((J)=>K48).desc("environment variable");envVarAssignment=$6.default.seqMap($6.default.regexp(/[A-Za-z_][A-Za-z0-9_]*/),$6.default.string("="),$6.default.alt(this.doubleQuotedString,this.singleQuotedString,this.unquotedString).or($6.default.succeed("")),(J,Q,Y)=>({name:J,value:Y})).desc("environment variable assignment");heredoc=$6.default.regex(/<<-?'?(\w+)'?/).chain((J)=>q48(J)).desc("heredoc");operator=$6.default.alt($6.default.regex(/&{1,2}/).desc("background|conjunction"),$6.default.regex(/\|{1,2}/).desc("pipe|disjunction"),$6.default.string(";").desc("semicolon")).map((J)=>{return});redirect=$6.default.lazy(()=>{let J=$6.default.alt($6.default.string(">>"),$6.default.string(">")),Q=$6.default.alt($6.default.string("&>>"),$6.default.string("&>")),Y=$6.default.string("<"),X=$6.default.regexp(/\d+>(&\d+|\S+)/);return $6.default.alt($6.default.seq($6.default.alt(J,Q),$6.default.optWhitespace,this.word),$6.default.seq(J,$6.default.optWhitespace,this.word,$6.default.whitespace,$6.default.string("&>"),$6.default.optWhitespace,this.word),$6.default.seq(Y,$6.default.optWhitespace,this.word),$6.default.seq($6.default.digit,Y,$6.default.optWhitespace,this.word),X,this.heredoc).map((G)=>{return}).desc("redirect")});args=V48($6.default.notFollowedBy($6.default.alt(this.operator,this.redirect)).then(this.word),this.whitespaceWithEscapes,$6.default.alt(this.operator,this.redirect));invocationWithoutArgs=$6.default.lazy(()=>$6.default.seqMap(this.envVarAssignment.skip(this.whitespaceWithEscapes).many(),this.word,(J,Q)=>({program:Q,arguments:[],...J.length>0&&{envVars:J}})));invocationWithArgs=$6.default.lazy(()=>$6.default.seqMap(this.envVarAssignment.skip(this.whitespaceWithEscapes).many(),this.word.skip(this.whitespaceWithEscapes),this.args,(J,Q,Y)=>({program:Q,arguments:Y,...J.length>0&&{envVars:J}})));invocation=$6.default.lazy(()=>{let J=$6.default.alt(this.invocationWithArgs,this.invocationWithoutArgs);return $6.default.alt(J.skip(this.redirect.trim(io0).many()),J)});bareExpression=$6.default.lazy(()=>{let J=$6.default.sepBy1(this.invocation,this.operator.trim($6.default.optWhitespace));return $6.default.alt(J.skip($6.default.string("&").trim(io0)),J)});subshellExpression=$6.default.lazy(()=>$6.default.string("(").then(this.expression).skip($6.default.string(")")));expression=$6.default.lazy(()=>$6.default.alt(this.bareExpression,this.subshellExpression));parseShellCommand(J){return this.expression.tryParse(J)}}function oo0(J,Q){return(Q===void 0||Q===ao0.platform?ao0:new MI1(Q)).parseShellCommand(J)}var $6,io0,ao0,K48;var ro0=L1(()=>{$6=D6(lo0(),1),{optWhitespace:io0}=$6.default;ao0=new MI1(typeof process<"u"?process.platform:"browser");K48=Symbol("Dynamic")});async function so0(J,Q,Y){let X=await Q.getAllRecords(),G=oe(X,(q)=>!q.reverted),Z=Array.from(G.entries());await re(Z,W48,async([q,V])=>{try{await J.stat(q)}catch(K){if(!aJ(K))throw K;if(V.after==="")return;await Q.record({toolUse:Y,uri:q,before:V.after,after:null})}})}var W48=8;var to0=L1(()=>{EQ();se()});import{execFileSync as H48}from"node:child_process";function Z01(J){if(G01.has(J))return G01.get(J);try{let Q=H48("git",["rev-parse","--show-toplevel"],{cwd:J,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return G01.set(J,Q),Q}catch{G01.set(J,void 0);return}}var G01;var LI1=L1(()=>{G01=new Map});function z48(J){return/\bgit(\.exe)?\b/.test(J)}function F48(J){let Q=eo0.get(J);if(!Q)Q=new h$,eo0.set(J,Q);return Q}function Jr0(J,Q,Y,X,G,Z){let q=FU0(Q),V=q!==null,K=z48(Y.cmd),W=K?Z01(J)??J:void 0;return new X0((H)=>{let z=$01(),U=!1,N,M,L=void 0,A=Date.now(),E,P;function I(y){if(U||!L)return;if(U=!0,E)clearTimeout(E),E=void 0;h.info(`Stopping bash command (${y}) with PID:`,N);let x=Rb(z),g=Math.round((Date.now()-A)/1000),p;try{if(L.kill&&N)if(process.platform==="win32"){let{spawn:i}=k1("node:child_process");i("taskkill",["/F","/T","/PID",N.toString()],{stdio:"ignore"}).on("error",(a)=>{if(h.error(`Failed to kill Windows process tree ${N}`,a),L)L.kill("SIGKILL")})}else L.kill("SIGTERM"),p=setTimeout(()=>{if(L&&L.kill&&!L.killed)try{process.kill(-N,"SIGKILL")}catch(i){L.kill("SIGKILL")}},1000)}catch(i){h.warn("Error stopping process:",i)}if(P)P.unsubscribe();let b=y==="user-stop"?`Command stopped by user after ${g} seconds`:`Command timed out after ${g} seconds of inactivity`;if(H.next({status:"done",result:{...x,exitCode:-1,stopReason:b,stopCode:y},reason:Z}),H.complete(),p)clearTimeout(p)}function R(){if(!V||!q)return;if(E)clearTimeout(E);E=setTimeout(()=>I("inactivity-timeout"),q)}if(X)h.info("Setting up tool message subscription for bash command"),M=X.subscribe((y)=>{if(h.info("Received tool message:",y.type),y.type==="stop-command")I("user-stop")});R();let S=oz1(J,Q.settings["terminal.commands.nodeSpawn.loadProfile"],G).pipe($X((y)=>{let x=K?{...y,GIT_OPTIONAL_LOCKS:"0"}:y;return hV(Y.cmd,[],{shell:Ua()??process.env.SHELL
|
|
2193
|
+
`),$6.default.string("\r"),$6.default.string("\\").then($6.default.whitespace)).many().tie();escapeSequences=$6.default.string("\\").then($6.default.oneOf('\\|&<>();"'));unquotedEscapeSequences=$6.default.string("\\").then($6.default.oneOf('\\|&<>(); "[]'));doubleQuotedString=no0($6.default.string('"'),$6.default.alt(this.escapeSequences,$6.default.noneOf('"')).many().tie()).desc("double-quoted string");singleQuotedString=no0($6.default.string("'"),$6.default.alt($6.default.string("\\").then($6.default.any),$6.default.noneOf("'\\")).many().tie()).desc("single-quoted string");braceExpansion=$6.default.lazy(()=>{let J=$6.default.lazy(()=>$6.default.alt($6.default.string("{").then(J).skip($6.default.string("}")).map((Q)=>`{${Q}}`),$6.default.noneOf("}")).many().tie());return $6.default.string("{").then(J).skip($6.default.string("}")).map((Q)=>`{${Q}}`)}).desc("brace expansion");unquotedString=$6.default.lazy(()=>{if(this.platform==="win32")return $6.default.alt($6.default.regexp(/[a-zA-Z]:[\\/]\S+/),$6.default.regexp(/\\\\\S+\\\S*/),$6.default.alt(this.unquotedEscapeSequences,$6.default.regexp(/[a-zA-Z0-9_\-:/.*~@=\\^,[\]#!]/),$6.default.regexp(/\$(?![A-Za-z_{(])/),$6.default.regexp(/\([a-zA-Z0-9_-]*\)/)).atLeast(1).tie()).desc("unquoted string");else return $6.default.alt(this.unquotedEscapeSequences,$6.default.regexp(/[a-zA-Z0-9_\-:/.*~@=+^,[\]#!]/),$6.default.regexp(/\$(?![A-Za-z_{(])/),$6.default.regexp(/\([a-zA-Z0-9_-]*\)/)).atLeast(1).tie().desc("unquoted string")});commandSubstitution=$6.default.lazy(()=>$6.default.string("$(").then(this.expression).skip($6.default.string(")")).map((J)=>({type:"invocations",trees:J})));word=$6.default.lazy(()=>{return $6.default.alt(this.doubleQuotedString,this.singleQuotedString,this.braceExpansion,this.unquotedString,this.commandSubstitution,this.envVariable).sepBy1($6.default.string("")).map((J)=>{let[Q,...Y]=J;if(Q===void 0)throw Error("Expect non-empty array of parts in argument: "+JSON.stringify(J));else if(Y.length===0)return Q;else if(J.every((X)=>typeof X==="string"))return J.join("");else return{type:"concatenation",values:J}})}).node("word");envVariable=$6.default.regexp(/\$([A-Za-z_][A-Za-z0-9_]*|\{[A-Za-z_][A-Za-z0-9_]*\})/).map((J)=>K48).desc("environment variable");envVarAssignment=$6.default.seqMap($6.default.regexp(/[A-Za-z_][A-Za-z0-9_]*/),$6.default.string("="),$6.default.alt(this.doubleQuotedString,this.singleQuotedString,this.unquotedString).or($6.default.succeed("")),(J,Q,Y)=>({name:J,value:Y})).desc("environment variable assignment");heredoc=$6.default.regex(/<<-?'?(\w+)'?/).chain((J)=>q48(J)).desc("heredoc");operator=$6.default.alt($6.default.regex(/&{1,2}/).desc("background|conjunction"),$6.default.regex(/\|{1,2}/).desc("pipe|disjunction"),$6.default.string(";").desc("semicolon")).map((J)=>{return});redirect=$6.default.lazy(()=>{let J=$6.default.alt($6.default.string(">>"),$6.default.string(">")),Q=$6.default.alt($6.default.string("&>>"),$6.default.string("&>")),Y=$6.default.string("<"),X=$6.default.regexp(/\d+>(&\d+|\S+)/);return $6.default.alt($6.default.seq($6.default.alt(J,Q),$6.default.optWhitespace,this.word),$6.default.seq(J,$6.default.optWhitespace,this.word,$6.default.whitespace,$6.default.string("&>"),$6.default.optWhitespace,this.word),$6.default.seq(Y,$6.default.optWhitespace,this.word),$6.default.seq($6.default.digit,Y,$6.default.optWhitespace,this.word),X,this.heredoc).map((G)=>{return}).desc("redirect")});args=V48($6.default.notFollowedBy($6.default.alt(this.operator,this.redirect)).then(this.word),this.whitespaceWithEscapes,$6.default.alt(this.operator,this.redirect));invocationWithoutArgs=$6.default.lazy(()=>$6.default.seqMap(this.envVarAssignment.skip(this.whitespaceWithEscapes).many(),this.word,(J,Q)=>({program:Q,arguments:[],...J.length>0&&{envVars:J}})));invocationWithArgs=$6.default.lazy(()=>$6.default.seqMap(this.envVarAssignment.skip(this.whitespaceWithEscapes).many(),this.word.skip(this.whitespaceWithEscapes),this.args,(J,Q,Y)=>({program:Q,arguments:Y,...J.length>0&&{envVars:J}})));invocation=$6.default.lazy(()=>{let J=$6.default.alt(this.invocationWithArgs,this.invocationWithoutArgs);return $6.default.alt(J.skip(this.redirect.trim(io0).many()),J)});bareExpression=$6.default.lazy(()=>{let J=$6.default.sepBy1(this.invocation,this.operator.trim($6.default.optWhitespace));return $6.default.alt(J.skip($6.default.string("&").trim(io0)),J)});subshellExpression=$6.default.lazy(()=>$6.default.string("(").then(this.expression).skip($6.default.string(")")));expression=$6.default.lazy(()=>$6.default.alt(this.bareExpression,this.subshellExpression));parseShellCommand(J){return this.expression.tryParse(J)}}function oo0(J,Q){return(Q===void 0||Q===ao0.platform?ao0:new MI1(Q)).parseShellCommand(J)}var $6,io0,ao0,K48;var ro0=L1(()=>{$6=D6(lo0(),1),{optWhitespace:io0}=$6.default;ao0=new MI1(typeof process<"u"?process.platform:"browser");K48=Symbol("Dynamic")});async function so0(J,Q,Y){let X=await Q.getAllRecords(),G=oe(X,(q)=>!q.reverted),Z=Array.from(G.entries());await re(Z,W48,async([q,V])=>{try{await J.stat(q)}catch(K){if(!aJ(K))throw K;if(V.after==="")return;await Q.record({toolUse:Y,uri:q,before:V.after,after:null})}})}var W48=8;var to0=L1(()=>{EQ();se()});import{execFileSync as H48}from"node:child_process";function Z01(J){if(G01.has(J))return G01.get(J);try{let Q=H48("git",["rev-parse","--show-toplevel"],{cwd:J,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return G01.set(J,Q),Q}catch{G01.set(J,void 0);return}}var G01;var LI1=L1(()=>{G01=new Map});function z48(J){return/\bgit(\.exe)?\b/.test(J)}function F48(J){let Q=eo0.get(J);if(!Q)Q=new h$,eo0.set(J,Q);return Q}function Jr0(J,Q,Y,X,G,Z){let q=FU0(Q),V=q!==null,K=z48(Y.cmd),W=K?Z01(J)??J:void 0;return new X0((H)=>{let z=$01(),U=!1,N,M,L=void 0,A=Date.now(),E,P;function I(y){if(U||!L)return;if(U=!0,E)clearTimeout(E),E=void 0;h.info(`Stopping bash command (${y}) with PID:`,N);let x=Rb(z),g=Math.round((Date.now()-A)/1000),p;try{if(L.kill&&N)if(process.platform==="win32"){let{spawn:i}=k1("node:child_process");i("taskkill",["/F","/T","/PID",N.toString()],{stdio:"ignore"}).on("error",(a)=>{if(h.error(`Failed to kill Windows process tree ${N}`,a),L)L.kill("SIGKILL")})}else L.kill("SIGTERM"),p=setTimeout(()=>{if(L&&L.kill&&!L.killed)try{process.kill(-N,"SIGKILL")}catch(i){L.kill("SIGKILL")}},1000)}catch(i){h.warn("Error stopping process:",i)}if(P)P.unsubscribe();let b=y==="user-stop"?`Command stopped by user after ${g} seconds`:`Command timed out after ${g} seconds of inactivity`;if(H.next({status:"done",result:{...x,exitCode:-1,stopReason:b,stopCode:y},reason:Z}),H.complete(),p)clearTimeout(p)}function R(){if(!V||!q)return;if(E)clearTimeout(E);E=setTimeout(()=>I("inactivity-timeout"),q)}if(X)h.info("Setting up tool message subscription for bash command"),M=X.subscribe((y)=>{if(h.info("Received tool message:",y.type),y.type==="stop-command")I("user-stop")});R();let S=oz1(J,Q.settings["terminal.commands.nodeSpawn.loadProfile"],G).pipe($X((y)=>{let x=K?{...y,GIT_OPTIONAL_LOCKS:"0"}:y;return hV(Y.cmd,[],{shell:Ua()??process.env.SHELL??"/bin/sh",cwd:J,stdio:["ignore","pipe","pipe"],env:x})}),$X(({lastData:y,exitCode:x,exited:g,pid:p,process:b})=>{return N=p,L=b,R(),C3(new Promise((i)=>{let Q1=y?.subarray()??new Uint8Array;if(H.closed){i({status:"cancelled",reason:Z});return}z.write(Q1,()=>{let a=Rb(z);if(g)i({status:"done",result:{...a,exitCode:x??-1},reason:Z});else i({status:"in-progress",progress:a,reason:Z})})}))}),M$(()=>{if(E)clearTimeout(E);z.dispose()}));if(K&&W){let y=F48(W);y.acquire().then(()=>{if(!H.closed)P=S.pipe(M$(()=>{y.release()})).subscribe(H);else y.release()})}else P=S.subscribe(H);return()=>{if(M?.unsubscribe(),E)clearTimeout(E);if(!U&&P)U=!0,P.unsubscribe()}})}var eo0;var Qr0=L1(()=>{r0();LI1();L0();pl();bV();rz1();iz1();AI1();eo0=new Map});var Yr0={};n8(Yr0,{nodeBashTool:()=>U48});function B48(J){if(typeof J!=="string")return"`cmd` must be a string representing a command.";return}var U48=({args:J,userInput:Q},Y)=>{let{dir:X,config:G,toolMessages:Z,thread:q,filesystem:V,fileChangeTracker:K,toolUseID:W}=Y;fI(X);let H=J.cwd?wQ(J.cwd):X,z=(M)=>({status:"done",result:{output:`Error: ${M}`,exitCode:1}}),U=B48(J.cmd);if(U)return X0.of(z(U));if(J.cmd.startsWith("git commit")){let M=Y.config.settings["git.commit.ampThread.enabled"]??!0,L=Y.config.settings["git.commit.coauthor.enabled"]??!0,A=[];if(M)A.push(`--trailer "Amp-Thread-ID: https://ampcode.com/threads/${q.id}"`);if(L)A.push('--trailer "Co-authored-by: Amp <amp@ampcode.com>"');if(A.length>0){let E=["-c trailer.AmpThread.key=Amp-Thread-ID","-c trailer.AmpThread.ifexists=replace","-c trailer.AmpCoauth.key=Co-authored-by","-c trailer.AmpCoauth.ifexists=addIfDifferent"].join(" ");J={...J,cmd:J.cmd.replace(/^git commit\b/,`git ${E} commit ${A.join(" ")}`)}}}let N=(M)=>C3(so0(V,K,W)).pipe(b7((L)=>{return h.error("Error detecting external file deletions:",L),X0.of(M)}),q6(()=>M));return Jr0(H.fsPath,G,J,Z,Y).pipe(b7((M)=>{let L={status:"error",error:{message:"message"in M?M.message:String(M)}};return X0.of(L)}),$X((M)=>{return wU0(M)?N(M):X0.of(M)}))};var Xr0=L1(()=>{r0();L0();to0();m7();OX();bV();Qr0()});function D48(J){if(J==="")return"''";if(J=J.replace(/\n/g,"\\n").replace(/\t/g,"\\t"),!/[\s"'\\$&|<>^`(){}!*?;~]/.test(J)&&J)return J;return"'"+J.replace(/'/g,"'\\'''")+"'"}function Zr0(J){if(!J.cmd)return;if(J.args)return[J.cmd,...J.args??[]].filter((Q)=>Q!==void 0).map(D48).join(" ");return J.cmd}var OI1=50000,N48,Gr0;var q01=L1(()=>{K4();m$();L4();bV();ro0();N48=`Executes the given shell command in the user's default shell.
|
|
2194
2194
|
|
|
2195
2195
|
## Important notes
|
|
2196
2196
|
|
|
@@ -4099,15 +4099,15 @@ Actual: ${G}`)}async function dG8(J,Q,Y){let{execSync:X}=await import("node:ch
|
|
|
4099
4099
|
${N}`;if(G==="pnpm"&&N.includes("Unable to find the global bin directory"))M+=`
|
|
4100
4100
|
|
|
4101
4101
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4102
|
-
npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}L0();L0();async function A61(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=aG8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return h.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return h.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function aG8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}r0();function O61(J,Q){let Y=new d4,X=Y.pipe(a8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new AV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await vU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=bA(),W=await A61(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await L61();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Lg(W.latestVersion,z);let U=await cB(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await vU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as SK}from"node:process";function N86(J){let Q=new IA().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(X)=>{await zR1(X.force||!1,X.verbose||!1,"0.0.
|
|
4102
|
+
npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}L0();L0();async function A61(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=aG8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return h.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return h.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function aG8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}r0();function O61(J,Q){let Y=new d4,X=Y.pipe(a8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new AV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await vU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=bA(),W=await A61(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await L61();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Lg(W.latestVersion,z);let U=await cB(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await vU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as SK}from"node:process";function N86(J){let Q=new IA().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(X)=>{await zR1(X.force||!1,X.verbose||!1,"0.0.1764309291-g33b630"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new IA("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("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await oG8(X.targetVersion)});J.addCommand(Y)}async function oG8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")SK.write(v4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4103
4103
|
|
|
4104
4104
|
`));try{if(!J){SK.write(v4.blue(`Checking for updates...
|
|
4105
|
-
`));let X=bA(),{hasUpdate:G,latestVersion:Z}=await A61("0.0.
|
|
4106
|
-
`));let V=await cB("0.0.
|
|
4105
|
+
`));let X=bA(),{hasUpdate:G,latestVersion:Z}=await A61("0.0.1764309291-g33b630",X);if(!G){SK.write(v4.green(`✓ Amp CLI is already up to date: ${"0.0.1764309291-g33b630"} (${"released"} ${"2025-11-28T06:00:12.433Z"})
|
|
4106
|
+
`));let V=await cB("0.0.1764309291-g33b630");if(V.warning)SK.write(`
|
|
4107
4107
|
`+v4.yellow(V.warning)+`
|
|
4108
4108
|
`);process.exit(0)}if(!Z)SK.write(v4.yellow("[WARN] could not find latest version")),process.exit(0);J=Z}SK.write(v4.blue(`Updating to version ${J}...
|
|
4109
4109
|
`)),await Lg(J,void 0,(X)=>{SK.write(v4.dim(`Running: ${X}
|
|
4110
|
-
`))});let Q="released";SK.write(v4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-11-
|
|
4110
|
+
`))});let Q="released";SK.write(v4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-11-28T06:00:12.433Z"})
|
|
4111
4111
|
`));let Y=await cB(J);if(Y.warning)SK.write(`
|
|
4112
4112
|
`+v4.yellow(Y.warning)+`
|
|
4113
4113
|
`);process.exit(0)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);SK.write(v4.red.bold("Error: ")+Y+`
|
|
@@ -4726,7 +4726,7 @@ exit code: ${Z}`,new H1({color:X.foreground,dim:!0,italic:!0})));if(q)V.push(new
|
|
|
4726
4726
|
`,N),...M],A=[new d1({text:new e("",void 0,L)})];if(K.url){let P=K.url.replace(/^https?:\/\//,"");A.push(new Q4({children:[new d1({text:new e("See more: ",N)}),new I7({uri:K.url,text:P,style:new H1({color:Y.secondary,underline:!0})})]}))}let E=new a0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:A});return H8.child(new t0({constraints:new a6(40,120,0,1/0),child:new Q4({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new z4({flex:1,child:new SC1({width:40,height:40,agentMode:this.agentMode,fps:q==="fast"?60:q==="slow"?15:0,...q==="disabled"&&{seed:42,t:3}})}),new U0({width:1}),new z4({flex:2,child:E})]})}))}}L0();D9();L4();m7();D9();r0();function LB8(J,Q){return`${J}:${Q}`}class q_1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new X0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new X0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new X0((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(zM()).subscribe((Z)=>{this.threadsMap.set(Q,Z);let q=this.subthreadsMap.get(Q)||[],V=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:Z,subthreads:q,workerStatus:V})});this.mainThreadSubs.set(Q,Y);let X=J.status.subscribe((Z)=>{if(this.workers.set(Q,Z),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:Z})});this.workerStatusSubs.set(Q,X);let G=J.subthreads.subscribe((Z)=>{this.subthreadsMap.set(Q,Z);for(let q of Z){let V=LB8(Q,q.toolUse.id);if(this.subthreadPatchSubs.has(V))continue;let K=this.threadService.observePatches(q.threadID).pipe(zM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:q})});this.subthreadPatchSubs.set(V,K)}});this.subthreadsSubs.set(Q,G)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let X=this.subthreadsSubs.get(J);if(X)X.unsubscribe(),this.subthreadsSubs.delete(J);for(let[G,Z]of this.subthreadPatchSubs.entries())if(G.startsWith(`${J}:`))Z.unsubscribe(),this.subthreadPatchSubs.delete(G);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new X0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new X0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new X0((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let X=this.workers.get(Q);if(X)J[Q]=ZA(Y,X)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function AB8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,G=J.subagents[X.threadID];if(!G){if(G={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=nJ(J.mainThread);G.isCompleted=aJ6(W,X.toolUse.id)}}let Z=OB8(Y,G.agentState),q=G.agentState===Z?G:{...G,agentState:Z},V={...J.tools},K=PC(Y).items.filter((W)=>W.type==="toolResult");for(let W of K)V[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[X.threadID]:q},tools:V,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:X,workerStatus:G}=Q,Z=nJ(Y),q={...J.subagents};for(let z of X){let U=q[z.threadID];if(!U)continue;let N=aJ6(Z,z.toolUse.id);q[z.threadID]={...U,isCompleted:N}}let{items:V}=PC(Y),K=ZA(Y,G),W=nE({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:q,items:V,viewState:K,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=ZA(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function PC(J){let Q=[],Y=new Map,X=new Set;for(let[G,Z]of J.messages.entries()){let q=`${Z.role}-${G}`;switch(Z.role){case"assistant":{let V=Z.state.type==="streaming";for(let W of Z.content)if(W.type==="tool_use"){if(Y.set(W.id,W),V)X.add(W.id)}if(Z.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:q,message:Z});for(let W of Z.content)if(W.type==="tool_use"){let H=!1;for(let z=G+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let N of U.content)if(N.type==="tool_result"&&N.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:V?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:q,message:Z});break;case"user":{let V=Z.content.some((K)=>K.type==="text"&&K.text.trim()||K.type==="image");for(let K of Z.content)if(K.type==="tool_result"){let W=Y.get(K.toolUseID)??FX(J,K.toolUseID);if(!W)throw Error(`(bug) tool use ${K.toolUseID} not found`);Q.push({type:"toolResult",id:K.toolUseID,toolUse:W,toolResult:K})}if(V)Q.push({type:"message",id:q,message:Z});break}}}return{items:Q}}function aJ6(J,Q){let Y=J.get(Q);return(Y&&F2(Y.run))??!1}function OB8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((G)=>G.type==="tool_result"&&G.run.status==="blocked-on-user"))return h.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(PC(J).items.some((G)=>G.type==="toolResult"&&G.toolResult.run.status==="in-progress")){let G=Q?.type==="running-tools"?Q.startTime:Date.now();return h.info("Subagent status: running-tools",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return h.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return h.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let Z=Q?.type==="running-tools"?Q.startTime:Date.now();return h.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}default:return h.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return h.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class V_1 extends X6{props;constructor(J){super();this.props=J}createState(){return new oJ6}}class oJ6 extends Y6{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new q_1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((Z)=>{this.dispatch({type:"main-thread-patch",thread:Z.mainThread,subthreads:Z.subthreads,workerStatus:Z.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((Z)=>{this.dispatch({type:"subthread-patch",thread:Z.thread,subthread:Z.subthread})});this.subscriptions.push(X);let G=Q.workerStatus.subscribe((Z)=>{this.dispatch({type:"worker-status-change",workerStatus:Z.status})});this.subscriptions.push(G)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=AB8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Z)=>({toolUse:Z.toolUse,toolRun:Z.toolRun,subthreadID:Z.subthreadID})),Q={};for(let Z of Object.values(this.state.subagents)){let q=J.filter((V)=>V.subthreadID===Z.subThreadID);Q[Z.parentToolID]=q}let Y=(Z)=>Z===r5||Z===q9||Z===zX,X=new Map;for(let Z of this.state.items)if(Z.type==="toolResult"&&Y(Z.toolUse.name))X.set(Z.toolUse.id,{toolUseId:Z.toolUse.id,toolName:Z.toolUse.name,toolRun:Z.toolResult.run});let G=Array.from(X.values());for(let{toolUseId:Z,toolRun:q}of G){let V=[],K;if(q.status==="in-progress"||q.status==="done"||q.status==="error"||q.status==="cancelled")K=q.progress;if(K){let W=0;for(let H of K)if(H.tool_uses)for(let z of H.tool_uses){let U=`${Z}:progress:${W++}`;V.push({toolUse:cE(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[Z]=V}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class K_1 extends X6{props;constructor(J){super({key:J.key});this.props=J}createState(){return new rJ6}}class rJ6 extends Y6{build(J){let Y=S6.of(J).colors,{todos:X,title:G="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new U0({width:0,height:0});let Z=X.map((q)=>this.buildTodoItem(q,Y));return new t0({child:new d6({padding:v0.symmetric(1,0),child:new a0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new d1({text:new e(G,new H1({bold:!0,color:Y.foreground}))}),...Z]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",G=new H1({bold:J.status==="in-progress",color:Q.foreground,dim:X}),Z=new H1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new Q4({crossAxisAlignment:"start",children:[new d1({text:new e(Y,G)}),new U0({width:1}),new z4({child:new d1({text:new e(J.content,Z)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class W_1 extends j6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=X}build(J){let Q=S6.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new t0({decoration:new B8(void 0,new h4(new O4(Y,1,"rounded"),new O4(Y,1,"rounded"),void 0,new O4(Y,1,"rounded"))),child:new d6({padding:v0.horizontal(1),child:new a0({children:[new Q4({crossAxisAlignment:"start",children:[new z4({child:new d1({text:new e(this.ad.content,new H1({color:X}))})}),new U0({width:4}),new I7({uri:"https://ampcode.com/free",text:"Ad",style:new H1({color:X,dim:!0})})]}),new Q4({crossAxisAlignment:"start",children:[new pC1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:v0.horizontal(1),color:Y,reverse:!0}),new U0({width:2}),new d1({text:new e(this.ad.destinationUrlHostname,new H1({color:X,dim:!0}))})]})]})})})}}class H_1 extends X6{props;constructor(J){super();this.props=J}createState(){return new sJ6(this.props.autofocus??!0)}}class sJ6 extends Y6{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(V.ctrlKey&&V.key==="c"||V.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=W8.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,Z=[];if(this.widget.props.title)Z.push(new d1({text:new e(this.widget.props.title,new H1({bold:!0,color:O1.blue}))}),new U0({height:1}));if(this.widget.props.message)Z.push(new d1({text:new e(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)Z.push(new U0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new d1({text:new e("Enter to copy",new H1({dim:!0}))}));return q.push(new d1({text:new e("Escape to close",new H1({dim:!0}))})),Z.push(new Q4({children:q.flatMap((V,K)=>K<q.length-1?[V,new U0({width:1}),new d1({text:new e("•",new H1({dim:!0}))}),new U0({width:1})]:[V]),mainAxisSize:"min"})),new H8({child:new t0({constraints:new a6(X,X,0,G),decoration:new B8(O1.default(),new h4(new O4(O1.blue,1,"rounded"),new O4(O1.blue,1,"rounded"),new O4(O1.blue,1,"rounded"),new O4(O1.blue,1,"rounded"))),padding:new v0(2,2,2,2),child:new Q9({autofocus:this.autofocus,onKey:Q,child:new a0({children:Z,mainAxisSize:"min"})})})})}}class m81 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,m81.prototype)}}class u81 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,u81.prototype)}}function z_1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}ZU();L0();import{spawn as wB8}from"node:child_process";import{promises as EB8}from"node:fs";function tJ6(J){return J.kind==="executable"}function eJ6(J){return J.kind==="markdown"}var Az=50000,JQ6=300000;async function F_1(J,Q,Y,X={}){let{timeoutMs:G=JQ6,signal:Z,source:q}=X;try{let V=await Y.getCommand(J,q);if(!V)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,q))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(h.debug("Executing command",{commandName:J,filePath:V.filePath,args:Q}),eJ6(V))return await IB8(V,Q);else if(tJ6(V))return await PB8(V,Q,G,Z);else return{success:!1,output:"",error:"Unsupported command type"}}catch(V){return h.error("Failed to execute command",{commandName:J,error:V}),{success:!1,output:"",error:V instanceof Error?V.message:"Unknown error occurred"}}}async function IB8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await EB8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>Az?Y.slice(0,Az)+`
|
|
4727
4727
|
... (output truncated at ${Az} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function PB8(J,Q,Y=JQ6,X){return new Promise((G)=>{let[Z,q]=TB8(J,Q);h.debug("Spawning command",{spawnCommand:Z,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Y});let V=jO0(X),K=!1,W=setTimeout(()=>{K=!0,V.abort(),h.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=wB8(Z,q,{stdio:["pipe","pipe","pipe"],signal:V.signal,detached:!0}),z=[],U=[],N=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=Az)z.push(L);else{let A=Az-(N-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=Az)U.push(L);else{let A=Az-(N-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),K){G({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(V.signal.aborted){G({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),P=A;if(!L&&!A.trim()&&E.trim())P=E;else if(E.trim())P+=A?`
|
|
4728
4728
|
${E}`:E;if(N>Az)P+=`
|
|
4729
|
-
... (output truncated at ${Az} characters)`;G({success:L,output:P.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function TB8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return CB8(Y,X?[...X]:null,G,Q);else return RB8(Y,X?[...X]:null,G,Q)}function RB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function CB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.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]}}L0();R$();S3();bW();oG();u$();JH();LH();m7();u_();r0();var WQ6=D6(wP(),1);import{writeFile as qQ6}from"fs/promises";import VQ6 from"path";L0();oG();class U_1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;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,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.
|
|
4729
|
+
... (output truncated at ${Az} characters)`;G({success:L,output:P.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function TB8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return CB8(Y,X?[...X]:null,G,Q);else return RB8(Y,X?[...X]:null,G,Q)}function RB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function CB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.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]}}L0();R$();S3();bW();oG();u$();JH();LH();m7();u_();r0();var WQ6=D6(wP(),1);import{writeFile as qQ6}from"fs/promises";import VQ6 from"path";L0();oG();class U_1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;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,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764309291-g33b630"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await la(Q,this.configService)}catch(Q){h.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}}class B_1 extends X6{props;constructor(J){super();this.props=J}createState(){return new QQ6}}class QQ6 extends Y6{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class YQ6 extends Y6{controller=new yZ;focusNode=new d8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=S6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,q=!G||Z,V=h4.all(new O4(Y.foreground,1,"solid")),K=new sA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(N)=>{let M=N.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new Q4({children:[new t0({decoration:{color:O1.default()},child:new d1({text:new e(">",new H1({color:Y.foreground}))})}),new z4({child:K})]}),H=new t0({padding:v0.symmetric(1,0),child:new d1({text:new e("",void 0,[new e("Command: ",new H1({color:Y.foreground})),new e(this.widget.props.commandName,new H1({color:O1.yellow,bold:!0}))])})}),z=[];if(q)z.push(new e("Enter",new H1({color:X.keybind}))),z.push(new e(" to submit, ",new H1({color:Y.foreground,dim:!0})));z.push(new e("Esc",new H1({color:X.keybind}))),z.push(new e(" to cancel",new H1({color:Y.foreground,dim:!0})));let U=new t0({padding:v0.symmetric(1,0),child:new d1({text:new e("",void 0,z)})});return new t0({decoration:{border:V,color:O1.default()},padding:v0.all(1),child:new a0({children:[H,new U0({height:1}),W,new i5,U]})})}}class p81 extends X6{props;constructor(J){super();this.props=J}createState(){return new YQ6}}JH();class XQ6 extends Y6{controller=new yZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new d8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=$U)return!1;let Q=qC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=S6.of(J),{colors:Y,app:X}=Q,Z=W8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new WO({controller:this.controller,triggers:[new VN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:I9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new Q9({focusNode:this.focusNode,child:V}),W=new t0({constraints:new a6({maxHeight:q}),padding:v0.symmetric(1,0),child:K}),H=new t0({padding:v0.symmetric(1,0),child:new d1({text:new e("",void 0,[new e("Command: ",new H1({color:Y.foreground})),new e(this.widget.props.commandName,new H1({color:O1.yellow,bold:!0}))])})}),z=new t0({padding:v0.symmetric(1,0),child:new d1({text:this.isConfirmingClearInput?new e("",void 0,[new e("Esc",new H1({color:X.keybind})),new e(" again to clear input",new H1({color:Y.foreground,dim:!0}))]):new e("",void 0,[new e("Press ",new H1({color:Y.foreground,dim:!0})),new e("Enter",new H1({color:X.keybind})),new e(" to submit, ",new H1({color:Y.foreground,dim:!0})),new e("Esc",new H1({color:X.keybind})),new e(" to clear",new H1({color:Y.foreground,dim:!0}))])})}),U=[H,new U0({height:1}),new z4({child:W}),new U0({height:1}),z];return new t0({decoration:{border:h4.all(new O4(Y.foreground,1,"solid")),color:O1.default()},padding:v0.all(1),child:new a0({children:U})})}}class HO extends X6{props;constructor(J){super();this.props=J}createState(){return new XQ6}}function GQ6(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/60000),G=Math.floor(Y/3600000),Z=Math.floor(Y/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(G<24)return`${G}h ago`;if(Z<7)return`${Z}d ago`;return J.toLocaleDateString()}class N_1 extends j6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((G,Z)=>Z.pubDate.getTime()-G.pubDate.getTime()),Y=Math.max(0,...Q.map((G)=>GQ6(G.pubDate).length));return new xK({items:Q,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(G,Z,q,V)=>{let K=S6.of(V),{colors:W}=K,H=Z?O1.yellow:void 0,z=Z?O1.black:W.foreground,U=O1.index(8),N=G.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new U0({width:A,child:Q4.end([new d1({text:new e(L,new H1({color:U}))})])});return new t0({decoration:H?{color:H}:void 0,padding:v0.symmetric(2,0),child:new Q4({children:[new z4({child:new d1({text:new e(G.title,new H1({color:z})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),new d1({text:new e(N,new H1({color:U})),maxLines:1}),new U0({width:2}),M(GQ6(G.pubDate),Y)]})})}})}}class D_1 extends j6{props;constructor(J){super();this.props=J}build(){return new H8({child:new d1({text:new e("",void 0,[new e(`Forked to new thread:
|
|
4730
4730
|
|
|
4731
4731
|
`,new H1({color:O1.white,dim:!0})),new e(`"${this.props.newThreadTitle||"Untitled"}"`,new H1({color:O1.white}))]),textAlign:"center"})})}}class Oz extends X6{props;constructor(J){super();this.props=J}createState(){return new ZQ6}}class ZQ6 extends Y6{_spinner=new gK;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=S6.of(J),{colors:Y}=Q,X=h4.all(new O4(Y.foreground,1,"solid")),G=this._spinner.toBraille(),Z=new d1({textAlign:"center",text:new e("",void 0,[new e(G,new H1({color:O1.yellow})),new e(" ",void 0),new e(this.widget.props.message,new H1({color:Y.foreground}))])}),V=[new z4({child:new a0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)V.push(new U0({height:2,child:new t0({padding:v0.symmetric(2,0),child:new d1({text:new e("",new H1({dim:!0}),[new e("Press ",new H1({color:Y.foreground})),new e("Esc",new H1({color:Y.info})),new e(" to cancel",new H1({color:Y.foreground}))])})})}));let K=new t0({decoration:new B8(O1.default(),X),child:new U0({width:60,height:7,child:new a0({mainAxisAlignment:"start",children:V})})});if(this.widget.props.onAbort)return new Q9({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:K});return K}}class wz extends X6{props;constructor(J){super();this.props=J}createState(){return new $Q6}}class $Q6 extends Y6{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof vK}build(J){let Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=n41(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Y.type==="error"?O1.red:O1.yellow,G=h4.all(new O4(O1.default(),1,"solid")),Z=new t0({padding:v0.symmetric(1,0),child:new d1({text:new e(Y.title,new H1({color:X,bold:!0}))})}),q=this.isWidgetMessage(Q)?Q.widget:new d1({text:new e(Y.description,new H1({color:O1.default()})),selectable:!0}),V=new z4({child:new aA({child:new t0({padding:v0.symmetric(1,0),child:q})})}),K=new t0({padding:v0.symmetric(1,0),child:new d1({text:this.widget.props.onRetry?new e("",void 0,[new e("Press ",new H1({color:O1.default(),dim:!0})),new e("R",new H1({color:O1.yellow})),new e(" to retry, ",new H1({color:O1.default(),dim:!0})),new e("Esc",new H1({color:O1.yellow})),new e(" to cancel",new H1({color:O1.default(),dim:!0}))]):new e("Press any key to close",new H1({color:O1.default(),dim:!0,italic:!0}))})});return new Q9({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new t0({decoration:{border:G,color:O1.default()},padding:v0.all(1),child:new a0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),V,K]})})})}}class M_1 extends j6{build(){return new H8({child:new d1({text:new e("",void 0,[new e(`✓ Thread Shared
|
|
4732
4732
|
|
|
@@ -4814,7 +4814,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
4814
4814
|
`)?`${V}...`:G,W=new H1({color:O1.index(8)}),H=[new e(K,W)];if(q>0){let z=new H1({color:Y.success});for(let U=1;U<=q;U++)H.push(new e(" ")),H.push(new e(`[${U}]`,z))}return new d6({padding:v0.only({bottom:0}),child:new Q4({crossAxisAlignment:"start",children:[new d6({padding:v0.only({right:1}),child:new d1({text:new e("•",new H1({color:O1.index(8)}))})}),new z4({child:new d1({text:new e("",void 0,H)})})]})})}}class a_1 extends X6{createState(){return new YY6}}class YY6 extends Y6{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new H1({color:O1.red}),Y=new H1({color:this._visible?O1.red:O1.transparent()});return new Q4({children:[new d1({text:new e("⏺",Y)}),new U0({width:1}),new d1({text:new e("Replay",Q)})]})}}class o_1 extends j6{entry;constructor({key:J,entry:Q}){super({key:J});this.entry=Q}build(J){let Q=S6.of(J),Y=Q.colors.secondary,X=Q.colors.foreground,G=this.entry.authors.map((Z)=>Z.name).join(", ");return new t0({decoration:new B8(void 0,new h4(new O4(Y,1,"rounded"),new O4(Y,1,"rounded"),void 0,new O4(Y,1,"rounded"))),child:new d6({padding:v0.horizontal(1),child:new a0({children:[new Q4({crossAxisAlignment:"start",children:[new z4({child:new d1({text:new e(this.entry.title,new H1({color:X,bold:!0}))})}),new U0({width:4}),new d1({text:new e(G||"Community",new H1({color:X,dim:!0}))})]}),new Q4({crossAxisAlignment:"start",children:[new z4({child:new d1({text:new e(this.truncateDescription(this.entry.description),new H1({color:X,dim:!0}))})}),new U0({width:2}),new I7({uri:this.entry.link,text:"View Thread",style:new H1({color:Y,underline:!0})})]})]})})})}truncateDescription(J){let Y=J.replace(/\s+/g," ").trim();if(Y.length<=80)return Y;return Y.slice(0,79)+"…"}}r0();function bN8(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),G=Math.floor(X/24),Z=Math.floor(G/7),q=Math.floor(G/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;if(Z<=4)return`${Z}w ago`;return`${q}mo ago`}class r_1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList().subscribe((G)=>{X.unsubscribe(),Y(G)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((X)=>{if(!Q.trim())return!0;let G=X.title?.toLowerCase()||"untitled",Z=X.id.toLowerCase(),q=Q.toLowerCase();return G.includes(q)||Z.includes(q)}).map((X)=>{let G=new Date(X.userLastInteractedAt),Z=bN8(G),q=X.id.slice(-8),V=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:Z,title:X.title||"Untitled",shortThreadID:q},diffStats:X.summaryStats?.diffStats,workspaceURI:V,parentRelationships:X.parentRelationships}})}}L0();D9();class s_1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new u3;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){h.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){h.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(zM()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function XY6(J,Q){switch(J){case"update-available":return[new e("A newer Amp is available. Run ",new H1({color:Q.foreground,dim:!0})),new e("amp update",new H1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new e("Update complete, run ",new H1({color:Q.foreground,dim:!0})),new e("amp update",new H1({color:Q.warning})),new e(" to see warnings",new H1({color:Q.foreground,dim:!0}))];case"update-error":return[new e("Update failed, run ",new H1({color:Q.foreground,dim:!0})),new e("amp update",new H1({color:Q.warning})),new e(" to see warnings",new H1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function dN8(J){return new Promise((Q)=>{mN8("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let G=X.trim();Q(G||null)})})}class HY6 extends X6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new zY6}}class zY6 extends Y6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteInitialCommandId=null;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new s_1;previewThread=null;planScrollController=(()=>{let J=new u3;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new u3;return J.followMode=!1,J})();isShowingStandaloneThreadPicker=!1;filterThreadPickerByWorkspace=!0;agentModePulseSeq=0;currentGitBranch=null;messageViewFocusNode=new d8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new d8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedShownIDs=new Set;threadFeedLatestShownPubDate=null;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;pendingMCPServers=[];mcpTrustSubscription=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=gG();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;toastController=new rC1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;async initThreadFeed(){let J=await B6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Y=Q.includes("localhost")||Q.includes("127.0.0.1");try{let q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(q.ok){let V=q.result,K="user"in V?V.user:V;this.currentUserInfo={username:K.username??void 0,displayName:K.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Y&&V.team?.id!==W)return}else return}catch(q){h.debug("Failed to fetch user info for thread feed filtering",q);return}let X="/threads.rss",G=async(q,V)=>{let K=q instanceof Request?q.url:q.toString();return PQ(K,V,this.widget.dependencies.configService)},Z=Ac0();Z.get("entries").then((q)=>{if(q){let V=this.filterEntries(q);if(this.threadFeedEntries=V,V.length>0&&!this.currentThreadFeedEntry){let K=this.getNextFeedEntry(V);if(K)this.setState(()=>{this.currentThreadFeedEntry=K})}}}),this.threadFeedReader=new FC1(Z,G,{url:X}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(q)=>{try{let V=this.filterEntries(q);if(V.length>0){this.threadFeedEntries=[...V,...this.threadFeedEntries];let K=this.getNextFeedEntry(V);if(K)this.setState(()=>{this.currentThreadFeedEntry=K}),this.resetThreadFeedRotation()}}catch(V){h.error("Thread feed: error in next handler",V)}},error:(q)=>{h.error("Thread feed error:",q)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Y}=this.currentUserInfo;return J.filter((X)=>{return!X.authors.some((G)=>{let Z=G.name;if(!Z)return!1;return Q&&Z===Q||Y&&Z===Y||Q&&Z.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{if(this.threadFeedEntries.length>0){let J=this.getNextFeedEntry(this.threadFeedEntries);if(J)this.setState(()=>{this.currentThreadFeedEntry=J})}},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(J){let Q=J.filter((X)=>!this.threadFeedShownIDs.has(X.id));if(this.threadFeedLatestShownPubDate)Q=Q.filter((X)=>X.pubDate.getTime()>=this.threadFeedLatestShownPubDate.getTime());if(Q.length===0&&J.length>0)this.threadFeedShownIDs.clear(),this.threadFeedLatestShownPubDate=null,Q=J;if(Q.length===0)return null;Q.sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime());let Y=Q[0];if(this.threadFeedShownIDs.add(Y.id),!this.threadFeedLatestShownPubDate||Y.pubDate>this.threadFeedLatestShownPubDate)this.threadFeedLatestShownPubDate=Y.pubDate;return Y}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:X}=J,G=Q.messages;for(let Z=0;Z<G.length;Z++){if(this.replayAbortController.signal.aborted)break;let q=G[Z];if(!q)continue;if(Z>0)await this.replaySleep(J.messageDelayMs);if(q.role==="user"&&Y){let W=q.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
4815
4815
|
`);if(W)await this.replayTypeMessage(W,X)}if(q.role==="assistant"){let W=q.content.some((U)=>U.type==="tool_use"),H=G[Z+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...q,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let N=J.thread.id;this.getMessageScrollController(N).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),q]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,q],this.textController.clear()});let V=J.thread.id;this.getMessageScrollController(V).scrollToBottom()}await this.replaySleep(J.exitDelayMs),I9.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let G of Y){if(this.replayAbortController.signal.aborted)break;let Z=X/G.length;for(let q of G){this.textController.text=this.textController.text+q,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let V=0.8+Math.random()*0.4,K=Z*V;await this.replaySleep(K)}}}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return L41(this.widget.dependencies.worker.thread,this.inMemoryAgentModeOverride?{agentMode:this.inMemoryAgentModeOverride}:null,this.freeTierStatus,{"experimental.agentMode":this.currentAgentMode})}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((Z)=>Z.type==="toolResult").filter((Z)=>Z.toolResult.run.status==="in-progress"||Z.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((Z)=>Z.toolRun.status==="in-progress"||Z.toolRun.status==="queued");return[...Y,...X].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new e(this.submitDisabledHint,new H1({color:J.foreground,dim:!0}));if(this.isExiting)return new e("Exiting...",new H1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new e("",void 0,[new e("Ctrl+C",new H1({color:Q.keybind})),new e(" again to exit",new H1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new e("",void 0,[new e("Esc",new H1({color:Q.keybind})),new e(" again to clear input",new H1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new e("",void 0,[new e("Escape",new H1({color:Q.keybind})),new e(" to close help",new H1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let G=this.getEffectiveAgentMode(),Z=Xk1(G);return new e("",void 0,[new e("Images aren't supported in ",new H1({color:J.warning,dim:!1})),new e(G,new H1({color:Z})),new e(" mode.",new H1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new e("",void 0,[new e("Esc",new H1({color:Q.keybind})),new e(" again to cancel",new H1({color:J.foreground,dim:!0}))]);return new e("",void 0,[new e("Esc",new H1({color:Q.keybind})),new e(" to cancel",new H1({color:J.foreground,dim:!0}))])}if(this.showingCannotToggleMessage)return new e(this.showingCannotToggleMessage,new H1({color:J.warning,dim:!1}));let Y=XY6(this.updateState,J);if(Y)return new e("",void 0,Y);let X=this.widget.dependencies.worker.thread;if(X.agentMode==="plan"&&uA(X))return new e("",void 0,[new e("Ctrl+O",new H1({color:Q.keybind})),new e(" → Execute Plan",new H1({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let G=Q.mainThread?.messages.findIndex((Z)=>Z===J);if(G===void 0||G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:G}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(Z){h.error("Failed to edit message:",Z)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:X}=this.widget.dependencies,G=Q.mainThread?.id;if(!G)return;let Z=Q.mainThread?.messages.findIndex((q)=>q===J);if(Z===void 0||Z<=0)return;try{let q=await N3.getOrCreateForThread(Y,G),V=await YR(q,X,Z-1);await this.switchToExistingThread(V)}catch(q){h.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,G=Y.mainThread;if(!G)return;let Z=G.messages.findIndex((q)=>q.messageId!==void 0&&q.messageId===J.messageId);if(Z===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=QN(Q);if(q)await X.handle({type:"thread:truncate",fromIndex:Z}),this.invokeBashCommand(q.cmd,{visibility:q.visibility});else{let V=[{type:"text",text:Q}];if(this.imageAttachments.length>0)V.push(...this.imageAttachments);let K={content:V,agentMode:G.agentMode},W=Z===0;if(G.agentMode&&!W&&K.agentMode!==G.agentMode){h.error(`Cannot edit message: This thread uses ${G.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:K,index:Z})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){h.error("Failed to edit message:",q)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(e3)}catch(Y){return h.error("Failed to get affected files:",Y),[]}};textController=new yZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new u3);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let G=this.searchElementTreeByKey(X,Q);if(G)return G}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(RR1(X))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new a7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Y=QN(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),e8.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.loadThreadsForPicker(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!0})};dismissStandaloneThreadPicker=()=>{this.exitApplication()};handleStandaloneThreadSelect=async(J)=>{try{await this.switchToExistingThread(J,{recordInNavigationHistory:!1}),this.threadPreviewController.clear(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!1}),e8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker)this.autocompleteFocusNode.requestFocus()})}catch(Q){h.error("Failed to switch thread:",Q),this.showErrorMessage(`Failed to switch thread: ${Q}`)}};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteInitialCommandId=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new A_1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding);return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new E_1(this.widget.dependencies.fuzzyServer,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteInitialCommandId=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Y}=this.widget.dependencies;if(!Q.mainThread)return null;let X=n0.file(process.cwd()),G=A6(X);return{recentThreadIDs:Y,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},setImageAttachments:(Z)=>{this.setState(()=>{this.imageAttachments=Z})},editorDispatch:(Z)=>{switch(Z.type){case"set-input":this.textController.clear(),this.textController.insertText(Z.input);break;case"insert-text":this.textController.insertText(Z.text);break;case"clear":this.textController.clear();break}},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(Z)=>{return await this.switchToExistingThread(Z),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(Z,q,V)=>{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K)throw Error("No active thread");let W=setTimeout(()=>{V.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(K,Z,q,this.widget.dependencies.configService,V);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(Z,q)=>{let{goal:V,generatedPrompt:K,images:W}=q;if(!V&&!K)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>Z.abort(new m81("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:V,generatedPrompt:K,images:W},this.widget.dependencies.configService,Z.signal);return clearTimeout(z),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(z),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw Z.signal.reason;throw U}}catch(H){return h.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(Z)=>{if(!Q.mainThread)return[];return(await Nr({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,Z)).map((V)=>({uri:V.uri,type:V.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let Z=Q.mainThread?.id;if(!Z){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let q=await this.widget.dependencies.threadService.createPlanExecutionThread(Z,"smart");await this.switchToExistingThread(q)}catch(Z){h.error("Failed to execute plan",Z),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${Z instanceof Error?Z.message:String(Z)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:G,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,setThreadFeedHidden:(Z)=>{this.setState(()=>{this.threadFeedHidden=Z})}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new r_1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await dN8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),X=`bash-${Y}-${Math.random().toString(36).substring(7)}`,G={cmd:J},Z=new AbortController;this.widget.dependencies.worker.invokeBashTool(G,Z.signal,Q===JN).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((K)=>K.id===X))this.bashInvocations=this.bashInvocations.map((K)=>K.id===X?{...K,toolRun:q}:K);else{let K={id:X,args:G,toolRun:q,startTime:Y,abortController:Z,hidden:Q===JN};this.bashInvocations=[...this.bashInvocations,K]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{let J=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(S$(J.thread)>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.getEffectiveAgentMode(),G=Lk(X,this.cachedVisibleModes);if(G!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=G,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.getEffectiveAgentMode(),Y=Lk(Q,this.cachedVisibleModes);if(Y===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),I5(Y))this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Mk(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=$U)return!1;let Y=qC(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:G,writeFile:Z}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),V=await import("node:path");try{let K=await Q(V.join(q(),"amp-edit-")),W=V.join(K,"message.amp.md");await Z(W,J,"utf-8"),await Fz(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")h.error("Failed to read temporary file",H)}try{await X(W),await G(K)}catch(H){h.warn("Failed to clean up temporary file",H)}}catch(K){h.error("Error opening editor:",K)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=QN(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};initState(){if(aX.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();I9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),I9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),I9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{e8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus,B6(this.widget.dependencies.configService.config).then((Y)=>{let X=L41(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Y.settings);if(h.info(`[initState] Resolved agentMode: ${X}`),this.widget.dependencies.sessionState?.agentMode)this.setState(()=>{this.inMemoryAgentModeOverride=X})}),this.updateGitBranch(),this.adSubscription=nR1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride&&I5(this.inMemoryAgentModeOverride)||this.randomAd===null)&&iR1(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=uN8(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (q91(),$91)).then(({recordAdEvent:G})=>{let Z=this.widget.dependencies.worker.thread,q=Z.messages[Z.messages.length-1];G("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:Z.id,messageId:q?.messageId,impressionId:X,placement:"tui",matchType:Y.metadata?.matchType,matchedPatterns:Y.metadata?.matchedPatterns,candidateAdPoolCount:Y.metadata?.candidateAdPoolCount,clientRegion:Y.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Y}),e8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{this.setState(()=>{this.ideStatus=Y})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let X=this.widget.dependencies.getCurrentWorker();if(!X){h.warn("No active thread worker found to handle IDE message");return}await new Promise((G)=>setTimeout(G,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),h.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),h.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Y)=>{this.setState(()=>{this.connectedClientsStatus=Y})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Y)=>{let X=gG(Y.settings,this.freeTierStatus?.canUseAmpFree);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(RR1("")),this.shouldUseProgressBar())process.stdout.write(Z96())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((V)=>V.type==="toolResult").map((V)=>({toolUse:V.toolUse,toolRun:V.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((V)=>V.toolRun.status==="blocked-on-user");if(X.length===0)return null;let G=X[0],Z=G.toolRun.status==="blocked-on-user"?G.toolRun.toAllow??[]:[],q=G.toolRun.status==="blocked-on-user"?G.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:G.toolUse,toAllow:Z}],subthreadID:G.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){h.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){h.error("No tool use block found in confirmation");return}if(J==="allow-all-session")A$("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(G){if(G&&G instanceof Error)this.setState(()=>{this.displayMessage=G});else h.error("Failed to write dangerouslyAllowAll setting:",G);return}if(J==="always-guarded"){let G=Q.tools[0]?.toAllow??[],Z=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...G,...Z];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let G=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await mY(this.context,G);return}if(J==="disable-librarian"){let G=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!G.includes(zX))await this.widget.dependencies.settingsStorage.set("tools.disable",[...G,zX],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let G={type:"user:tool-input",toolUse:Y.id,value:{accepted:X}};if(Q.subthreadID)await(await N3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(G);else await this.widget.dependencies.worker.handle(G)}catch(G){h.error("Failed to send tool confirmation:",G)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Y=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Y)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Y=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Y.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),T61({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette("handoff");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await Fz(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await N3.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Y=J.messages[Q];if(Y?.role==="user"&&!Y.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Y=!0}=Q;if(Y){let X=this.widget.dependencies.worker.thread.id;if(X!==J)this.recordNavigation(X)}try{h.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);h.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`);let G=await this.widget.dependencies.configService.getLatest(),Z=L41(X.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,G.settings);if(h.info(`[switchToExistingThread] Thread ${J} resolved agentMode: ${Z}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),this.setState(()=>{h.info("[switchToExistingThread] Clearing inMemoryAgentModeOverride"),this.inMemoryAgentModeOverride=null}),X.thread.draft)if(h.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let q=X.thread.draft.filter((W)=>W.type==="text"),V=X.thread.draft.filter((W)=>W.type==="image"),K=q.map((W)=>W.text).join(`
|
|
4816
4816
|
`);if(K)this.textController.insertText(K);if(V.length>0)this.setState(()=>{this.imageAttachments=V})}}catch(X){throw h.error("Failed to switch to thread:",J,X),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Y=S$(Q.thread)===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let G=[{type:"text",text:J}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);if(await Q.handle({type:"user:message",message:{content:G,agentMode:X}}),Y)T61({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]}),e8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();T61({agentMode:Q}).catch((Y)=>{h.warn("Failed to save session state on exit:",Y)}).finally(()=>{I9.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=pN8();if(J===Q)return"~";if(J.startsWith(Q+Bm.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Bm.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Bm.sep),"…",Q.slice(-2).join(Bm.sep)].join(Bm.sep)}build(J){let Q=W8.of(J),Y=S6.of(J),X=Y.base;this.themeColors=X;let{colors:G,app:Z}=Y;this.themeApp=Z;let q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,V=q.thread.agentMode&&I5(q.thread.agentMode),K=V&&this.randomAd!==null,W=!V&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,H=K||W,{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),N=this.widget.dependencies.replayMode,M=Boolean(N),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,P=z.todosList;if(M){let i6={...N.thread,messages:this.replayDisplayedMessages};L=PC(i6).items,A=i6,E={};let P4=nE({messages:this.replayDisplayedMessages});P=Array.isArray(P4)?P4:[]}let I=A?.id,R=A,S=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(i6)=>new h81({key:new a7(`preview-message-view-${i6.id}`),items:PC(i6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:i6,focusNode:new d8({debugLabel:"PreviewFocus"})}),x=this.previewThread,g=x?x.messages.length>2000?new a0({mainAxisSize:"max",children:[new z4({child:new U0}),new d6({padding:v0.all(2),child:new H8({child:new d1({text:new e("Thread too long for preview",new H1({color:G.mutedForeground,dim:!0}))})})})]}):y(x):S?new g81({agentMode:this.getEffectiveAgentMode()}):new h81({key:I?new a7(`message-view-${I}`):void 0,items:L,subagentToolsByParentID:E,controller:I?this.getMessageScrollController(I):new u3,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:R,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),p=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),i=this.buildBottomWidget(b,U,G,Y,z,P,p,H,M),Q1=Q.size.width<40,a=z.mainThread?kU0(z.mainThread):void 0,m=new t41({threadViewState:z.viewState,threadTokenUsage:a,threadID:I??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:Q1,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),s=new s41({bashInvocations:this.bashInvocations}),K1=[],W1=this.getEffectiveAgentMode(),o=this.currentShellModeStatus,r=Xk1(W1),l=!o?W1.length+1:0,F1=Q.capabilities.animationSupport,y1=F1==="disabled"?0:F1==="slow"?30:60,t=CV(W1)?.uiHints?.fasterAnimation?3:1,f1=y1>0&&this.agentModePulseSeq>0?new B5({children:[i,new r7({top:0,left:1,right:1,height:1,child:new l_1({color:r,trigger:this.agentModePulseSeq,fps:y1,speed:t,leftOffset:l})})]}):i;K1.push(new z4({child:g}),s);let j1=new B5({children:[new a0({mainAxisSize:"min",children:[K?new W_1({ad:this.randomAd,onButtonClick:async()=>{let i6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (q91(),$91)).then(({recordAdEvent:z8})=>{let J8=this.widget.dependencies.worker.thread,C9=J8.messages[J8.messages.length-1];z8("clicked",{adId:i6.id,advertiserId:i6.advertiserId,threadId:J8.id,messageId:C9?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:i6.metadata?.matchType,matchedPatterns:i6.metadata?.matchedPatterns,candidateAdPoolCount:i6.metadata?.candidateAdPoolCount,clientRegion:i6.metadata?.clientRegion})});if(!await mY(this.context,i6.shortDestinationUrl)){let J8=I9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:J8,url:i6.shortDestinationUrl}})}}}):W?new o_1({entry:this.currentThreadFeedEntry}):new U0({height:0}),new t0({constraints:new a6(0,Q.size.width,0,p),child:f1})]}),H?new r7({top:0,left:0,right:0,child:new BY6({userHeight:this.bottomGridUserHeight,maxHeight:p,onInitializeHeight:(i6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(i6,p)})},onDrag:(i6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(i6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let P4=Math.floor(i6.localPosition.y)-this.bottomGridDragStartY,z8=Math.max(4,this.bottomGridDragStartHeight-P4),J8=Math.min(z8,p),C9=Math.floor(J8);if(this.bottomGridUserHeight!==C9)this.setState(()=>{this.bottomGridUserHeight=C9})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new U0({height:0})]});K1.push(j1,new U0({height:1,child:new d6({padding:v0.horizontal(1),child:m})}));let w0=new a0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:K1}),C1=M?new B5({children:[w0,new r7({top:0,left:0,child:new a_1})]}):w0,s1=new J9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((P4)=>{h.error("Failed to mark message as interrupted:",P4)}),this.cancelStreamingMessage().catch((P4)=>{h.error("Failed to cancel streaming message:",P4)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return h.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),U1=new J9(()=>{return this.onExitPressed(),"handled"}),Y1=new J9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),A1=new J9(()=>{return LJ.instance.toggleAll(),"handled"}),w1=new J9(()=>{return this.widget.dependencies.configService.getLatest().then((i6)=>{A$("internal.showCost",!(i6.settings["internal.showCost"]??!0))}),"handled"}),I1=new J9(()=>{return I9.instance.toggleFrameStatsOverlay(),"handled"}),E1=new J9(()=>{return I9.instance.tuiInstance.getScreen().markForRefresh(),e8.instance.requestFrame(),"handled"}),p1=new J9(()=>{return this.toggleAgentMode(),"handled"}),h1=new J9(()=>{let P4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:z8}=this.widget.dependencies,J8=z8.mainThread?.id;return J8?this.getMessageScrollController(J8):null})();if(P4){let z8=Math.max(Math.floor(Q.size.height*0.4),10),J8=Q.size.height-z8;P4.animatePageUp(J8,100)}return"handled"}),r1=new J9(()=>{let P4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:z8}=this.widget.dependencies,J8=z8.mainThread?.id;return J8?this.getMessageScrollController(J8):null})();if(P4){let z8=Math.max(Math.floor(Q.size.height*0.4),10),J8=Q.size.height-z8;P4.animatePageDown(J8,100)}return"handled"}),$0=new J9(()=>{let P4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:z8}=this.widget.dependencies,J8=z8.mainThread?.id;return J8?this.getMessageScrollController(J8):null})();if(P4)P4.animateTo(0,100);return"handled"}),G0=new J9(()=>{let P4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:z8}=this.widget.dependencies,J8=z8.mainThread?.id;return J8?this.getMessageScrollController(J8):null})();if(P4)P4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),R0=new J9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:i6}=this.widget.dependencies;if(!i6.mainThread?.messages.some((z8)=>z8.role==="user"||iE(z8)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),F6=new J9((i6)=>{if(i6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),M6=new J9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return i41().then(async(i6)=>{if(i6)try{this.handleInsertImage(i6)}finally{try{let{unlink:P4}=await import("node:fs/promises");await P4(i6)}catch{}}}),"handled"}),N4=new Map([[B4.ctrl("c"),new dg],[B4.ctrl("l"),new ag],[B4.ctrl("o"),new h41],[B4.ctrl("v"),new ug],[B4.alt("s"),new WC],[B4.ctrl("s"),new WC],[B4.alt("p"),new ng],[B4.ctrl("r"),new lg],[B4.alt("d"),new ig],[B4.ctrl("t"),new og],[B4.key("PageUp"),new y41],[B4.key("PageDown"),new x41],[B4.key("Home"),new v41],[B4.key("End"),new f41],[B4.key("Escape"),new pg],[B4.ctrl("p"),new HC("previous")],[B4.ctrl("n"),new HC("next")],[B4.key("Tab"),new rg]]);if(!n2())N4.set(B4.key("ArrowUp"),new rg);if(!1)N4.set(B4.alt("c"),new cg);let k9=new J9(()=>{if(this.isShowingStandaloneThreadPicker)return"handled";return this.showCommandPalette(),"handled"}),I0=new J9(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),u0=new Map([[pg,s1],[ag,E1],[WC,p1],[h41,k9],[ug,M6],[cg,Y1],[lg,A1],[ig,w1],[ng,I1],[og,I0],[dg,U1],[y41,h1],[x41,r1],[v41,$0],[f41,G0],[rg,R0],[HC,F6]]),k6=[C1];if(this.isShowingConsoleOverlay)k6.push(new T_1);if(this.isShowingHelp){let i6=this.getPaletteCommands().getAllCommands();k6.push(new j_1({commands:i6}))}if(this.adActionModal)k6.push(new H_1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(i6)=>{let P4=this.adActionModal.url;if(i6==="copy")try{await I9.instance.tuiInstance.clipboard.writeText(P4),this.setState(()=>{this.displayMessage=new JG("Link copied to clipboard")})}catch(z8){h.error("Failed to copy to clipboard",{error:z8}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:i6}=this.widget.dependencies;k6.push(new i_1({servers:this.pendingMCPServers,onAlwaysTrust:i6.trustAlways.bind(i6),onTrustOnce:i6.trustOnce.bind(i6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:i6.deny.bind(i6)}))}if(this.isShowingFileChangesOverlay)k6.push(new Fj1({threadData:z}));if(this.isShowingCostBreakdownOverlay&&z.mainThread)k6.push(new R_1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)k6.push(new I_1({details:this.confirmationOverlayContent}));let e4=this.getCommandPaletteContext(J);if(e4&&this.isShowingPalette)k6.push(new H8({child:new t0({constraints:a6.loose(80,20),child:new w_1({commandContext:e4,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,initialCommandId:this.paletteInitialCommandId??void 0})})}));if(this.isShowingIdePicker)k6.push(new __1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));if(this.isShowingStandaloneThreadPicker){let i6=n0.file(process.cwd()),P4=A6(i6);k6.push(new H8({child:new t0({constraints:a6.loose(80,20),child:new NC({threads:this.threadsForPicker,title:"Continue Thread",onSelect:this.handleStandaloneThreadSelect,onDismiss:this.dismissStandaloneThreadPicker,previewController:this.threadPreviewController,isLoading:this.isLoadingThreads,currentWorkspaceURI:P4,filterByWorkspace:this.filterThreadPickerByWorkspace,threadViewStates:this.widget.dependencies.workerController.threadViewStates,recentThreadIDs:this.widget.dependencies.recentThreadIDs,currentThreadID:this.widget.dependencies.threadState.mainThread?.id})})}))}let k8=new B5({children:k6});if(this.isShowingJetBrainsInstaller)return new rA({child:new mQ({actions:u0,child:new Iq({shortcuts:N4,debugLabel:"jetbrains-installer-shortcuts",child:new c_1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new Bz({controller:this.toastController,child:new rA({child:new sC1({controller:this.toastController,child:new mQ({actions:u0,child:new Iq({shortcuts:N4,debugLabel:"main-app-shortcuts",child:k8})})})})})}buildScrollableTodoList(J,Q,Y){return new FY6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,G,Z,q,V,K){if(J)return new C_1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new P_1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new n_1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let W=X.app,H=r41(X),z=this.isInRestrictedFreeMode(),U=new WO({key:this.textFieldKey,controller:this.textController,triggers:K?[]:[new VN],completionBuilder:K?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:K?void 0:this.onTextSubmitted,theme:Y,placeholder:K?"Press Ctrl+C to exit":z?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!z&&!this.isShowingStandaloneThreadPicker,shellPromptRules:H,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker,clipboard:I9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage}),N=G.mainThread?.queuedMessages??[],M=Array.isArray(Z)&&Z.length>0,L=Array.isArray(N)&&N.length>0,A=G.mainThread?.agentMode==="plan"&&uA(G.mainThread),E,P;if(A){if(E=new kC1(new b81({thread:G.mainThread,onExecute:async()=>{let b=this.getCommandPaletteContext();if(b)await this.getPaletteCommands().execute("execute-plan",b,void 0,new AbortController)},onEdit:async()=>{try{let b=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:i}=await this.widget.dependencies.planFileManager.ensureSync(G.mainThread.id);I9.instance.tuiInstance.suspend();let{execSync:Q1}=await import("child_process");Q1(`${b} "${i}"`,{stdio:"inherit"}),I9.instance.tuiInstance.resume()}catch(b){h.error("Failed to edit plan",b),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),L)P=new Z91({queuedMessages:N});else if(M)P=this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X)}else E=L?new Z91({queuedMessages:N}):void 0,P=M?this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X):void 0;let I=[],R=this.currentShellModeStatus;if(R)I.push({text:new e(R==="hidden"?"shell mode (incognito)":"shell mode",new H1({color:R==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});if(!R&&this.cachedVisibleModes.length>1){let b=this.previewThread,i=b?b.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),Q1=Xk1(i);if(b)I.push({text:new e(i,new H1({color:Q1})),position:"top-left",offsetY:0});else{let m=Lk(i,this.cachedVisibleModes)!==i,s=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K1=S$(s.thread)===0,o=z||!this.hasToggledAgentMode&&m&&K1?new e("",void 0,[new e(i,new H1({color:Q1})),new e(" (click or ",new H1({color:Y.foreground,dim:!0})),new e("Ctrl+S",new H1({color:W.keybind})),new e(" to switch)",new H1({color:Y.foreground,dim:!0}))]):new e(i,new H1({color:Q1}));I.push({text:o,position:"top-left",offsetY:0,onClick:K1?this.toggleAgentMode:void 0})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let b=this.connectedClientsStatus,i=b.mode||"disconnected",Q1=!!b.errorMessage,a=b.clientID||"unknown",m,s;if(Q1)m="●",s=O1.red;else if(i==="presence")m="○",s=O1.yellow;else if(i==="connected"&&b.connected)m="●",s=O1.green;else m="○",s=O1.yellow;let K1=this.connectedClientsStatusExpanded?`${a} ${m}`:m;I.push({text:new e(K1,new H1({color:s})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let S=K?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:G.mainThread?.env?.initial.trees?.[0]?.uri,y;if(S)y=n0.parse(S).fsPath;else y=process.cwd();let x=this.toHomeRelative(y),g=this.shorten(x),p=!K&&this.currentGitBranch?`${g} (${this.currentGitBranch})`:g;return I.push({text:new e(p,new H1({color:Y.foreground,dim:!0})),position:"bottom-right"}),new Gj1({leftChild:new z4({child:U}),rightChild1:E,rightChild2:P,maxHeight:q,overlayTexts:I,borderColor:z||!this.isTextfieldAndAutocompleteFocused?O1.index(8):void 0,hasBanner:V,userHeight:this.bottomGridUserHeight,onInitializeHeight:(b)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(b,q)})},onDrag:(b)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(b.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let i=Math.floor(b.localPosition.y)-this.bottomGridDragStartY,Q1=Math.max(4,this.bottomGridDragStartHeight-i),a=Math.min(Q1,q),m=Math.floor(a);if(this.bottomGridUserHeight!==m)this.setState(()=>{this.bottomGridUserHeight=m})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!V})}}async function Gk1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)I9.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,Z=!1,q=new $z(Z,1000,J.inspectorPort),V=J.features?.find((A)=>A.name==="amp-connect")?.enabled??!1,K=new V_1({threadService:J.threadService,worker:J.worker,builder:(A,E,P,I,R,S)=>{if(X=R,J.threadDependencies&&V)DC1(J.threadDependencies,J.configService,R,I,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((g)=>{h.error("Failed to start automatic presence:",g)});let y=R(),x={...J,worker:y,threadID:y.thread.id};return new HY6({...x,threadState:E,workerController:P,switchWorker:I,getCurrentWorker:R,recentThreadIDs:S})}}),W=new Kj1({configService:J.configService,child:K}),H=new $j1({configService:J.configService,child:W}),z=new dC1(H),U=new S6({data:zC.fromBaseTheme(kZ.default()),child:z});try{await pR1(U,{onRootElementMounted:(A)=>{if(h.info("TUI input ready for user interaction"),Z)q.start(A)}})}finally{if(Z)q.stop();if(J.threadDependencies&&V){let{stopGlobalSession:A}=await Promise.resolve().then(() => (MC1(),G76));A()}}let M=X()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;T76(L,A,J.stdout)}}function Xk1(J){let Y=CV(J)?.uiHints?.secondaryColor;if(Y)return O1.rgb(Y.r,Y.g,Y.b);return cN8(J)}class FY6 extends X6{props;constructor(J){super();this.props=J}createState(){return new UY6}}class UY6 extends Y6{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Y,appTheme:X}=this.widget.props;return new Q4({crossAxisAlignment:"stretch",children:[new z4({child:new E2({controller:Y,autofocus:!1,child:new K_1({todos:Q})})}),new YG({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:G,offset:Z}=Y,q=this.viewportHeight,V=G+q;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(Z,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class BY6 extends j6{props;constructor(J){super();this.props=J}build(J){return new _8({child:new U0({height:1}),cursor:i9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function cN8(J){let Q=0;for(let G=0;G<J.length;G++){let Z=J.charCodeAt(G);Q=(Q<<5)-Q+Z,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Y.length;return O1.index(Y[X])}uR1();try{if(process.platform==="win32")await Promise.resolve().then(() => D6(cC(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){pZ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
4817
|
-
`)}var yy1=ky1.join(Kz0||ky1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function HO8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function kq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")A$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")A$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")A$("model.sonnet",Q.useSonnet)}async function vy1(J){try{await VO8(ky1.dirname(yy1),{recursive:!0}),await KO8(yy1,J,"utf-8")}catch(Q){h.debug("Failed to save last thread ID",Q)}}async function zO8(){try{return(await uZ6(yy1,"utf-8")).trim()}catch(J){return null}}var bZ6=[{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??TZ,description:`Custom settings file path (overrides the default location ${TZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(h).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${iT1})`},{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:n2(),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:!0,description:(J)=>J?"Enable IDE connection (default). 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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:mE.SMART.key,description:`Set the agent mode (${gG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gG().map((J)=>J.mode)}],gZ6=(J)=>("deprecated"in J)&&J.deprecated===!0,FO8=(J)=>("hidden"in J)&&J.hidden===!0,UO8=(J)=>("default"in J),BO8=(J)=>("default"in J)?J.default:void 0;function NO8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new j8(PZ.unknownCommand(Y),1,q)}}var pZ6=null;function XF5(){return pZ6}function bm(J){return{...J,getThreadEnvironment:Q61,vfs:yE0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Dx(J.fileSystem),generateThreadTitle:Rc0,deleteThread:(Q)=>J.threadService.delete(Q)}}var fy1=n0.file(WO8.homedir()),dZ6=process.env.XDG_CONFIG_HOME?n0.file(process.env.XDG_CONFIG_HOME):Z6.joinPath(fy1,".config");async function yq(J,Q){cU0("0.0.
|
|
4817
|
+
`)}var yy1=ky1.join(Kz0||ky1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function HO8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function kq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")A$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")A$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")A$("model.sonnet",Q.useSonnet)}async function vy1(J){try{await VO8(ky1.dirname(yy1),{recursive:!0}),await KO8(yy1,J,"utf-8")}catch(Q){h.debug("Failed to save last thread ID",Q)}}async function zO8(){try{return(await uZ6(yy1,"utf-8")).trim()}catch(J){return null}}var bZ6=[{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??TZ,description:`Custom settings file path (overrides the default location ${TZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(h).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${iT1})`},{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:n2(),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:!0,description:(J)=>J?"Enable IDE connection (default). 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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:mE.SMART.key,description:`Set the agent mode (${gG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gG().map((J)=>J.mode)}],gZ6=(J)=>("deprecated"in J)&&J.deprecated===!0,FO8=(J)=>("hidden"in J)&&J.hidden===!0,UO8=(J)=>("default"in J),BO8=(J)=>("default"in J)?J.default:void 0;function NO8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new j8(PZ.unknownCommand(Y),1,q)}}var pZ6=null;function XF5(){return pZ6}function bm(J){return{...J,getThreadEnvironment:Q61,vfs:yE0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Dx(J.fileSystem),generateThreadTitle:Rc0,deleteThread:(Q)=>J.threadService.delete(Q)}}var fy1=n0.file(WO8.homedir()),dZ6=process.env.XDG_CONFIG_HOME?n0.file(process.env.XDG_CONFIG_HOME):Z6.joinPath(fy1,".config");async function yq(J,Q){cU0("0.0.1764309291-g33b630");let Y=W$1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:X0.of([n0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:fy1,userConfigDir:dZ6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (q91(),$91));X(Y);let G=await Y.getLatest();h.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:Z,dispose:q}=rs0({configService:Y}),V=new Map,K=()=>V.clear(),W=new WF1(Y,J.settings.getWorkspaceRootPath()),H=mw0({configService:Y,trustStore:W,createOAuthProvider:async(a)=>{let m=V.get(a);if(m)return h.debug("Reusing existing OAuth provider for server",{serverName:a}),m;h.debug("Creating OAuth provider for server",{serverName:a});let s=(async()=>{let K1=new SM(J.secrets),W1=await K1.getClientInfo(a),o=new kz1({storage:K1,serverName:a,clientId:W1?.clientId,clientSecret:W1?.clientSecret,scopes:W1?.scopes});return h.debug("OAuth provider created",{serverName:a,hasManualClientId:!!W1?.clientId,willUseDCR:!W1?.clientId}),o})();return V.set(a,s),s}}),z=H01({configService:Y,filesystem:U5,spawn:LA}),{initializeToolProviders:U}=await Promise.resolve().then(() => (hZ6(),fZ6)),{registrations:N,initErrors:M}=await U({toolService:Z,providers:[H,z],initialTimeout:J.executeMode?15000:5000});for(let[a,m]of M)h.warn(`${a} provider initialization slow or failed:`,m);if(Q.jetbrains)oE("JetBrains");else if(Q.ide&&e46())oE("VS Code");else if(Q.ide&&J86())oE("Neovim");if(J.executeMode)lU0(!0);let L,A=U2.status.pipe(q6((a)=>Boolean(a.connected&&a.authenticated)),y4()).subscribe((a)=>{if(a){if(!L)L=Z.registerTool(xr0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode)E=new z61(process.cwd(),{},!0);else E=new class extends z61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(f5.write(`No API key found. Starting login flow...
|
|
4818
4818
|
`),!await DO8(J))await fA(),process.exit(1)}let P=await WP0({isDevelopment:!1}),I=new zE1(P,Y),R=new qE1(P,{lazy:!0}),S=new AF1(I,(a,m)=>{let s=N3.get(a);if(s)s.handle(m).catch((K1)=>{h.error("Failed to apply artifact delta",K1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,x=ts0({playNotificationSound:async(a)=>{if(y){ss0(a);let m=gR1(),s=mR1();if((!m||s)&&G.settings["notifications.system.enabled"]!==!1){if(a==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(a==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:I,configService:Y});h.info("Starting Amp background services");let g=jc0({threadService:I,threadHistoryService:R,configService:Y,isExtensionDevelopment:!1}),p;U2.status.subscribe((a)=>{p=a});let b=new oG1({workspaceRoots:[n0.file(process.cwd())],getCurrentFile:()=>{if(!p?.openFile)return;try{return n0.parse(p.openFile)}catch(a){h.warn("Failed to parse current file URI",{uri:p.openFile,error:a});return}},getOpenFiles:()=>{if(!p?.visibleFiles?.length)return[];let a=p.openFile;return p.visibleFiles.filter((m)=>m!==a).map((m)=>{try{return n0.parse(m)}catch(s){return h.warn("Failed to parse visible file URI",{uri:m,error:s}),null}}).filter((m)=>m!==null)}}),i=new dR1,Q1={codebaseContextService:b,configService:Y,toolService:Z,mcpService:H,trustStore:W,threadService:I,threadHistoryService:R,threadSyncService:g,planFileManager:S,threadStorage:P,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:x,fileSystem:Q.jetbrains||Q.ide?SE0:U5,terminal:i};return{...Q1,async asyncDispose(){if(Q1.mcpService.hasAuthenticatingClients())h.info("Waiting for OAuth authentication to complete before exit..."),await Q1.mcpService.waitForAuthentication();for(let a of N.values())a.dispose();await Q1.mcpService.dispose(),K(),await Q1.threadService.asyncDispose(),Q1.configService.unsubscribe(),q(),Q1.fuzzyServer.dispose(),Q1.threadSyncService.dispose(),Q1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function DO8(J){if(!J.executeMode){if(!await DR1("Would you like to log in to Amp? [(y)es, (n)o]: "))return f5.write(`Login cancelled. Run the command again to retry.
|
|
4819
4819
|
`),!1}return await cZ6(J)}async function cZ6(J){let Q=qO8(32).toString("hex"),Y=await NR1(J.ampURL,Q),X=new AbortController;try{await FE(Y,X.signal)}catch(Z){h.error("Error opening browser",{error:Z})}let G=await NR1(J.ampURL,Q,!1);f5.write(`If your browser does not open automatically, visit:
|
|
4820
4820
|
|
|
@@ -4824,7 +4824,7 @@ ${v4.blue.bold(G)}
|
|
|
4824
4824
|
Login successful! You can now use the Amp CLI.
|
|
4825
4825
|
`),!0}catch(Z){return h.error("Login failed",{error:Z}),pZ.write(`
|
|
4826
4826
|
Login failed: ${Z instanceof Error?Z.message:String(Z)}
|
|
4827
|
-
`),!1}}function MO8(){let J=new IA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)kR(),process.exit(0);let z=H.originalError??H;a66(z)}),J.option("-V, --version","Print the version number and exit",()=>{f5.write(`0.0.
|
|
4827
|
+
`),!1}}function MO8(){let J=new IA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)kR(),process.exit(0);let z=H.originalError??H;a66(z)}),J.option("-V, --version","Print the version number and exit",()=>{f5.write(`0.0.1764309291-g33b630 (released 2025-11-28T06:00:12.433Z)
|
|
4828
4828
|
`),process.exit(0)}),J.addHelpText("after",r46()),J.configureHelp({formatHelp:s46}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await aQ(U);await wO8(N)}),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(H,z)=>{let U=z.optsWithGlobals(),N=await aQ(U);await OO8(N,await ZR1(U,N.settings))});let Q=async(H,z,U)=>{W$1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:X0.of([n0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:fy1,userConfigDir:dZ6});let N={...z,executeMode:!1};await xy1(N,{...H,openThreadSwitcher:!0},U)},Y=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(H,z)=>{let U=z.optsWithGlobals(),N=await aQ(U);await mZ6(U,N,z)});Y.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(H,z)=>{let U=z.optsWithGlobals(),N=await aQ(U);await jO8(U,N,z)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await aQ(N);if(z.pick)pZ.write(`${v4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
4829
4829
|
`);if(z.last||H||M.executeMode)await CO8(N,M,H,U);else await Q(N,M,U)}),Y.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(H,z,U)=>{let N=U.optsWithGlobals(),M=await aQ(N);await RO8(N,M,H,U)}),Y.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(H,z)=>{let U=z.optsWithGlobals(),N=await aQ(U);await mZ6(U,N,z)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, 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, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await aQ(N);await TO8(N,M,H,U,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,N)=>{let M=N.optsWithGlobals(),L=await aQ(M);await EO8(M,L,H,z,N)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await aQ(N);await IO8(N,M,H,U)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await aQ(N);await PO8(N,M,H,z,U)}),i96(J,async(H,z)=>{let U=await aQ(z);kq(H,z);let N=await yq(U,z);return{context:U,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,configService:N.configService,cleanupTerminal:kR,asyncDispose:N.asyncDispose.bind(N)}}),x86(J,async(H)=>{let z=H.optsWithGlobals();return await aQ(z)}),I86(J,async(H)=>{let z=await aQ(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{kq(U,H);let N=await yq(z,H);return{mcpService:N.mcpService,settings:z.settings,asyncDispose:N.asyncDispose.bind(N)}}}});function G(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new vB(z,M),A=BO8(H);if(A)L.default(A);if(L.hidden=FO8(H)||gZ6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of bZ6)switch(H.type){case"flag":{J.addOption(G(H,`--${H.long}`)),J.addOption(G(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(G(H,`--${H.long}`,!0));break}default:{J.addOption(G(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let Z=new vB("-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);J.addOption(Z);let q=new vB("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let V=new vB("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(V);let K=new vB("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(K);let W=new vB("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let H=new vB("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let U=H,N=await aQ(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")f5.write(v4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
|
|
4830
4830
|
`)),process.exit(0);if(Object.keys(U).forEach((M)=>{let L=bZ6.find((A)=>A.name===M);if(L&&gZ6(L)&&!UO8(L))pZ.write(v4.yellow(`Warning: '--${M}' flag is deprecated
|
|
@@ -4832,8 +4832,8 @@ Login failed: ${Z instanceof Error?Z.message:String(Z)}
|
|
|
4832
4832
|
Or pipe via stdin: echo "your message" | amp --execute`);kq(Y,Q);let q=await yq(J,Q);pZ6=q;let V=bm(q),K=async(i)=>{let Q1=await uZ6(i,"utf-8"),a=JSON.parse(Q1);if(!j$(a.id))throw new j8(PZ.invalidThreadId);return o91(q,{visibility:X,agentMode:Q.mode,thread:a})},W=async(i)=>{if(!j$(i))throw new j8(PZ.invalidThreadId);try{let[a,m]=await Promise.all([P5.getThreadLinkInfo({thread:i},{config:q.configService}),P5.getUserInfo({},{config:q.configService})]);if(a.ok&&m.ok){let s=a.result.creatorUserID,K1=m.result.id;if(s&&s!==K1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new j8(`Cannot resume thread created by another user.
|
|
4833
4833
|
|
|
4834
4834
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}catch(a){if(a instanceof j8)throw a;h.warn("Failed to validate thread ownership in CLI, allowing to open",{error:a})}let Q1=await q.threadService.get(i)??void 0;return h.info(`[fetchAndStartThread] Loaded thread ${i}, agentMode: ${Q1?.agentMode??"undefined"}`),o91(q,{visibility:X,agentMode:Q1?void 0:Q.mode,thread:Q1})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return o91(q,{visibility:X})}catch(i){if(i instanceof j8)throw i;throw await qg(i,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return o91(q,{visibility:X})};if(Q.format==="jsonl")pZ.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
4835
|
-
`),await fA(),process.exit(1);if(J.executeMode&&Q.remote)await v86(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)R86(q.mcpService,J.settings),await V46(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await VD0();let i=HI({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(i.length===1){let Q1=i[0];if(Q1)U2.selectConfig(Q1)}else N=!0}let L=O61("0.0.
|
|
4836
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await x46({...J,workspaceTrust:{current:!0,changes:d_},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await P86(J.mcpConfig);X=T86(X,Z)}let G=await X.get("url","global");if(!G)G=VY;if(!yF(G))h.info("Targeting custom Amp server",{ampURL:G});return X=VF0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:f86(await ZR1(J,X))}}function LO8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function AO8(){let J=LO8(process.argv);if(g66({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),HO8(h),h.info("Starting Amp CLI.",{version:"0.0.
|
|
4835
|
+
`),await fA(),process.exit(1);if(J.executeMode&&Q.remote)await v86(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)R86(q.mcpService,J.settings),await V46(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await VD0();let i=HI({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(i.length===1){let Q1=i[0];if(Q1)U2.selectConfig(Q1)}else N=!0}let L=O61("0.0.1764309291-g33b630",q.settingsStorage),A=new G11(q.threadStorage),E=X0.of([n0.file(process.cwd())]),P=$Z1(void 0,E),I=new w61(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let R=(async()=>{try{let i=await P5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(i.ok)return h.info("User free tier status:",i),i.result}catch(i){h.error("Failed to fetch free tier status:",i)}})(),S=(async()=>{try{let i=await P5.getUserInfo({},{config:q.configService});if(i.ok)return i.result}catch(i){h.debug("Failed to fetch user workspace info:",i)}})(),[y,x]=await Promise.all([R,S]),g=x?.email,p=g&&(g.endsWith("@sourcegraph.com")||g.endsWith("@ampcode.com")||g==="auth-bypass-user@example.com");if(p)q.toolService.registerTool(hr0);let b=await g86();h.info("Loaded session state:",b),await Gk1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new Z61,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:A,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:P5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:U2,connectedClientsService:new sl,commandRegistry:P,mcpService:q.mcpService,mcpTrustHandler:I,showJetBrainsInstaller:M,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:x?.team??null,features:x?.features??[],isDogfooding:p||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function aQ(J){if(J.interactive)pZ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
4836
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await x46({...J,workspaceTrust:{current:!0,changes:d_},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await P86(J.mcpConfig);X=T86(X,Z)}let G=await X.get("url","global");if(!G)G=VY;if(!yF(G))h.info("Targeting custom Amp server",{ampURL:G});return X=VF0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:f86(await ZR1(J,X))}}function LO8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function AO8(){let J=LO8(process.argv);if(g66({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),HO8(h),h.info("Starting Amp CLI.",{version:"0.0.1764309291-g33b630",buildTimestamp:"2025-11-28T06:00:12.433Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new j8(PZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await MO8().parseAsync(process.argv)}YE1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await AO8().catch(qg)});async function OO8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),f5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
4837
4837
|
`);else if(!yF(J.ampURL))f5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
4838
4838
|
`);let Y=process.env.AMP_API_KEY;if(Y)f5.write(`API key found in environment variable, storing...
|
|
4839
4839
|
`),await Q.set("apiKey",Y,J.ampURL),f5.write(`API key successfully stored.
|
|
@@ -4846,7 +4846,7 @@ This thread belongs to a different user and cannot be continued for security rea
|
|
|
4846
4846
|
`);else f5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
|
|
4847
4847
|
`);process.exit(0)}async function EO8(J,Q,Y,X,G){kq(G,J);let Z=await yq(Q,J);try{let q=r91(Y);if(!q)s91(Y);let V=q,K=X.trim();if(K.length===0)uZ("Thread name cannot be empty");if(K.length>256)uZ("Thread name cannot exceed 256 characters");if(!(await lC(V,Z)).messages.length)uZ("Cannot rename an empty thread.");let H=bm(Z);await(await N3.getOrCreateForThread(H,V)).handle({type:"title",value:K}),h.info("GOT HERE"),await Z.threadSyncService.sync(),h.info("GOT THERE"),f5.write(v4.green(`✓ Thread ${V} renamed to "${K}"
|
|
4848
4848
|
`)),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose();let V=`Failed to rename thread: ${q instanceof Error?q.message:String(q)}`;uZ(V)}}async function IO8(J,Q,Y,X){kq(X,J);let G=await yq(Q,J);try{let Z=r91(Y);if(!Z)s91(Y);let V=await lC(Z,G),K=QR(V);f5.write(K+`
|
|
4849
|
-
`),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;uZ(q)}}async function PO8(J,Q,Y,X,G){kq(G,J);let Z=await yq(Q,J);try{let q=await hy1(Y),V=await lC(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=bm(Z),L=V.id;await Z.threadStorage.set(L,V);let A=await N3.getOrCreateForThread(M,L);await A.resume();let E=X11.fromWorker(A),P=new G11(Z.threadStorage),I=X0.of([n0.file(process.cwd())]),R=$Z1(void 0,I),S=new w61(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=O61("0.0.
|
|
4849
|
+
`),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;uZ(q)}}async function PO8(J,Q,Y,X,G){kq(G,J);let Z=await yq(Q,J);try{let q=await hy1(Y),V=await lC(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=bm(Z),L=V.id;await Z.threadStorage.set(L,V);let A=await N3.getOrCreateForThread(M,L);await A.resume();let E=X11.fromWorker(A),P=new G11(Z.threadStorage),I=X0.of([n0.file(process.cwd())]),R=$Z1(void 0,I),S=new w61(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=O61("0.0.1764309291-g33b630",Z.settingsStorage);await Gk1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new Z61,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:P,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:P5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:U2,connectedClientsService:new sl,commandRegistry:R,mcpService:Z.mcpService,mcpTrustHandler:S,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await qg(q,Y)}}async function TO8(J,Q,Y,X,G){kq(X,J);let Z=await yq(Q,J);try{let q=r91(Y);if(!q)s91(Y);let V=q,K=await P5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=E61(J,W);if(!H&&!G)uZ("Must specify either --visibility or --support");if(H&&G)uZ("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)uZ(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,I61(H)),f5.write(v4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
|
|
4850
4850
|
`);if(G){await lC(V,Z);let z=typeof G==="string"?G:void 0;await GP0(Z.threadService,V,Z.configService,z),f5.write(v4.green("✓ ")+`Thread ${V} has been shared with Amp support. These thread reports will be aggregated and analysed.
|
|
4851
4851
|
`)}await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),uZ(`Failed to update thread: ${q instanceof Error?q.message:String(q)}`)}}async function RO8(J,Q,Y,X){kq(X,J);let G=await yq(Q,J),Z=bm(G);try{let q=await hy1(Y),K=(await lC(q,G)).messages.length-1,W=await N3.getOrCreateForThread(Z,q),H=await YR(W,G.threadSyncService,K);await Promise.all([G.threadSyncService.uploadThread(q),G.threadSyncService.uploadThread(H)]),await vy1(H),f5.write(`${H}
|
|
4852
4852
|
`),await G.asyncDispose(),process.exit(0)}catch(q){pZ.write(`Error forking thread: ${q instanceof Error?q.message:String(q)}
|