@sourcegraph/amp 0.0.1759363307-g6ad5b4 → 0.0.1759377701-g6ad5b4
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 +7 -7
- package/package.json +1 -1
package/dist/main.js
CHANGED
@@ -5795,7 +5795,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||YR}function QZ6(J,Q){let
|
|
5795
5795
|
`);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),W;if(tQ6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await sQ6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}var ZZ6=u(()=>{hS();GV();xQ6();gQ6();uQ6();eQ6()});function XZ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}import l49 from"node:fs";import YZ6 from"node:path";function KZ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!YZ6.isAbsolute(Q))return null;return n.debug("Extracted image path",{original:J,extracted:Q}),Q}function qZ6(J){try{let Q=YZ6.extname(J).toLowerCase(),Z=Mt1(Q);if(!Z)return n.warn("Unsupported image file extension",{ext:Q}),null;try{let X=l49.readFileSync(J);return i49(X,Z)}catch(X){n.error(`Failed to read image file ${J}:`,X)}}catch(Q){n.error("Error handling image file path",{imagePath:J,error:Q})}return null}function i49(J,Q){if(J.length>AR)return n.warn(`Image file too large: ${J.length} bytes (max: ${AR})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}var GZ6=u(()=>{D0();EN()});function zZ6(J){return J.kind==="executable"}function UZ6(J){return J.kind==="markdown"}import{spawn as n49}from"node:child_process";import{promises as a49}from"node:fs";async function Tx1(J,Q,Z,X={}){let{timeoutMs:Y=WZ6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(n.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),UZ6(q))return await r49(q,Q);else if(zZ6(q))return await s49(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return n.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function r49(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await a49.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>LH?Z.slice(0,LH)+`
|
5796
5796
|
... (output truncated at ${LH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function s49(J,Q,Z=WZ6,X){return new Promise((Y)=>{let[K,q]=o49(J,Q);n.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=Ft1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),n.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=n49(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=LH)F.push(V);else{let N=LH-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=LH)H.push(V);else{let N=LH-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
5797
5797
|
${L}`:L;if(B>LH)A+=`
|
5798
|
-
... (output truncated at ${LH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function o49(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return e49(Z,X?[...X]:null,Y,Q);else return t49(Z,X?[...X]:null,Y,Q)}function t49(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function e49(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}var LH=50000,WZ6=300000;var FZ6=u(()=>{NR();D0()});var HZ6=u(()=>{FZ6();GQ1()});var a41,PF2,TF2,CF2,SF2,vF2,kF2,_F2,bF2,xF2,am,yF2,fF2,hF2,gF2,mF2;var BZ6=u(()=>{a41=globalThis.window?.document!==void 0,PF2=globalThis.process?.versions?.node!==void 0,TF2=globalThis.process?.versions?.bun!==void 0,CF2=globalThis.Deno?.version?.deno!==void 0,SF2=globalThis.process?.versions?.electron!==void 0,vF2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,kF2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,_F2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,bF2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,xF2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,am=globalThis.navigator?.userAgentData?.platform,yF2=am==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",fF2=am==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",hF2=am==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",gF2=am==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),mF2=am==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var r41={};L6(r41,{scrollUp:()=>A79,scrollDown:()=>O79,link:()=>$79,image:()=>P79,iTerm:()=>T79,exitAlternativeScreen:()=>I79,eraseUp:()=>L79,eraseStartLine:()=>V79,eraseScreen:()=>Cx1,eraseLines:()=>D79,eraseLine:()=>NZ6,eraseEndLine:()=>M79,eraseDown:()=>N79,enterAlternativeScreen:()=>w79,cursorUp:()=>MZ6,cursorTo:()=>Z79,cursorShow:()=>B79,cursorSavePosition:()=>G79,cursorRestorePosition:()=>z79,cursorPrevLine:()=>F79,cursorNextLine:()=>W79,cursorMove:()=>X79,cursorLeft:()=>VZ6,cursorHide:()=>H79,cursorGetPosition:()=>U79,cursorForward:()=>K79,cursorDown:()=>Y79,cursorBackward:()=>q79,clearTerminal:()=>R79,clearScreen:()=>j79,beep:()=>E79});import Sx1 from"node:process";var U2="\x1B[",sm="\x1B]",_T="\x07",rm=";",DZ6,J79,Q79,Z79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return U2+(J+1)+"G";return U2+(Q+1)+rm+(J+1)+"H"},X79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=U2+-J+"D";else if(J>0)Z+=U2+J+"C";if(Q<0)Z+=U2+-Q+"A";else if(Q>0)Z+=U2+Q+"B";return Z},MZ6=(J=1)=>U2+J+"A",Y79=(J=1)=>U2+J+"B",K79=(J=1)=>U2+J+"C",q79=(J=1)=>U2+J+"D",VZ6,G79,z79,U79,W79,F79,H79,B79,D79=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=NZ6+(Z<J-1?MZ6():"");if(J)Q+=VZ6;return Q},M79,V79,NZ6,N79,L79,Cx1,A79,O79,j79="\x1Bc",R79,w79,I79,E79,$79=(J,Q)=>[sm,"8",rm,rm,Q,_T,J,sm,"8",rm,rm,_T].join(""),P79=(J,Q={})=>{let Z=`${sm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+_T},T79;var vx1=u(()=>{BZ6();DZ6=!a41&&Sx1.env.TERM_PROGRAM==="Apple_Terminal",J79=!a41&&Sx1.platform==="win32",Q79=a41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Sx1.cwd,VZ6=U2+"G",G79=DZ6?"\x1B7":U2+"s",z79=DZ6?"\x1B8":U2+"u",U79=U2+"6n",W79=U2+"E",F79=U2+"F",H79=U2+"?25l",B79=U2+"?25h",M79=U2+"K",V79=U2+"1K",NZ6=U2+"2K",N79=U2+"J",L79=U2+"1J",Cx1=U2+"2J",A79=U2+"S",O79=U2+"T",R79=J79?`${Cx1}${U2}0f`:`${Cx1}${U2}3J${U2}H`,w79=U2+"?1049h",I79=U2+"?1049l",E79=_T,T79={setCwd:(J=Q79())=>`${sm}50;CurrentDir=${J}${_T}`,annotation(J,Q={}){let Z=`${sm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+_T}}});var LZ6=u(()=>{vx1();vx1()});var kx1=e((iF2,AZ6)=>{AZ6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var RZ6=e((nF2,jZ6)=>{var C79=o1("os"),OZ6=o1("tty"),bK=kx1(),{env:n5}=process,NV;if(bK("no-color")||bK("no-colors")||bK("color=false")||bK("color=never"))NV=0;else if(bK("color")||bK("colors")||bK("color=true")||bK("color=always"))NV=1;if("FORCE_COLOR"in n5)if(n5.FORCE_COLOR==="true")NV=1;else if(n5.FORCE_COLOR==="false")NV=0;else NV=n5.FORCE_COLOR.length===0?1:Math.min(parseInt(n5.FORCE_COLOR,10),3);function _x1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function bx1(J,Q){if(NV===0)return 0;if(bK("color=16m")||bK("color=full")||bK("color=truecolor"))return 3;if(bK("color=256"))return 2;if(J&&!Q&&NV===void 0)return 0;let Z=NV||0;if(n5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=C79.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in n5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in n5))||n5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in n5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n5.TEAMCITY_VERSION)?1:0;if(n5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in n5){let X=parseInt((n5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(n5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n5.TERM))return 1;if("COLORTERM"in n5)return 1;return Z}function S79(J){let Q=bx1(J,J&&J.isTTY);return _x1(Q)}jZ6.exports={supportsColor:S79,stdout:_x1(bx1(!0,OZ6.isatty(1))),stderr:_x1(bx1(!0,OZ6.isatty(2)))}});var EZ6=e((aF2,IZ6)=>{var v79=RZ6(),bT=kx1();function wZ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function xx1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(bT("no-hyperlink")||bT("no-hyperlinks")||bT("hyperlink=false")||bT("hyperlink=never"))return!1;if(bT("hyperlink=true")||bT("hyperlink=always"))return!0;if(X)return!0;if(!v79.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=wZ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=wZ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}IZ6.exports={supportsHyperlink:xx1,stdout:xx1(process.stdout),stderr:xx1(process.stderr)}});function LV(J,Q,{target:Z="stdout",...X}={}){if(!s41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return r41.link(J,Q)}var s41;var $Z6=u(()=>{LZ6();s41=p6(EZ6(),1);LV.isSupported=s41.default.stdout;LV.stderr=(J,Q,Z={})=>LV(J,Q,{target:"stderr",...Z});LV.stderr.isSupported=s41.default.stderr});class yx1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759363307-g6ad5b4"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await z00(Q)}catch(Q){n.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}}var PZ6=u(()=>{D0();Qz()});class GY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function TZ6(J){if(J instanceof o41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof GY)return{title:"Info",description:J.message,type:"info"};return n.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var o41;var fx1=u(()=>{D0();o41=class o41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as CZ6}from"node:child_process";import{rmdir as k79}from"node:fs/promises";import{tmpdir as _79}from"node:os";import SZ6 from"node:path";import{mkdtemp as b79,readFile as x79,unlink as y79,writeFile as jH2}from"fs/promises";class hx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=DC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new yx1(async()=>{try{return(await U9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),k9.pipe(v0((Q)=>Q.settings["internal.modes"]),P8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...f79},J)Object.assign(this.commands,h79)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{n.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Tx1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var f79,h79;var vZ6=u(()=>{HZ6();D0();iw();u2();MC();lw();q7();JN();wx1();Qz();ZD();a6();b0();$Z6();p41();Ix1();PZ6();fx1();f79={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${qJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:SK0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new o41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await b79(SZ6.join(_79(),"amp-edit-")),Y=SZ6.join(X,"message.amp.md");CZ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await x79(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return n.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await y79(Y),await k79(X)}catch(K){n.warn("Failed to clean up temporary file",K)}return}catch(Z){return n.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return pU("dangerouslyAllowAll",!1),new GY("Amp is now following permissions rules for this session")}catch(K){return n.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return pU("dangerouslyAllowAll",!0),new GY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return n.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await vT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw n.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:vT};await i41(Y);return}catch(Y){n.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return n.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new GY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return n.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
|
5798
|
+
... (output truncated at ${LH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function o49(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return e49(Z,X?[...X]:null,Y,Q);else return t49(Z,X?[...X]:null,Y,Q)}function t49(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function e49(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}var LH=50000,WZ6=300000;var FZ6=u(()=>{NR();D0()});var HZ6=u(()=>{FZ6();GQ1()});var a41,PF2,TF2,CF2,SF2,vF2,kF2,_F2,bF2,xF2,am,yF2,fF2,hF2,gF2,mF2;var BZ6=u(()=>{a41=globalThis.window?.document!==void 0,PF2=globalThis.process?.versions?.node!==void 0,TF2=globalThis.process?.versions?.bun!==void 0,CF2=globalThis.Deno?.version?.deno!==void 0,SF2=globalThis.process?.versions?.electron!==void 0,vF2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,kF2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,_F2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,bF2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,xF2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,am=globalThis.navigator?.userAgentData?.platform,yF2=am==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",fF2=am==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",hF2=am==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",gF2=am==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),mF2=am==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var r41={};L6(r41,{scrollUp:()=>A79,scrollDown:()=>O79,link:()=>$79,image:()=>P79,iTerm:()=>T79,exitAlternativeScreen:()=>I79,eraseUp:()=>L79,eraseStartLine:()=>V79,eraseScreen:()=>Cx1,eraseLines:()=>D79,eraseLine:()=>NZ6,eraseEndLine:()=>M79,eraseDown:()=>N79,enterAlternativeScreen:()=>w79,cursorUp:()=>MZ6,cursorTo:()=>Z79,cursorShow:()=>B79,cursorSavePosition:()=>G79,cursorRestorePosition:()=>z79,cursorPrevLine:()=>F79,cursorNextLine:()=>W79,cursorMove:()=>X79,cursorLeft:()=>VZ6,cursorHide:()=>H79,cursorGetPosition:()=>U79,cursorForward:()=>K79,cursorDown:()=>Y79,cursorBackward:()=>q79,clearTerminal:()=>R79,clearScreen:()=>j79,beep:()=>E79});import Sx1 from"node:process";var U2="\x1B[",sm="\x1B]",_T="\x07",rm=";",DZ6,J79,Q79,Z79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return U2+(J+1)+"G";return U2+(Q+1)+rm+(J+1)+"H"},X79=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=U2+-J+"D";else if(J>0)Z+=U2+J+"C";if(Q<0)Z+=U2+-Q+"A";else if(Q>0)Z+=U2+Q+"B";return Z},MZ6=(J=1)=>U2+J+"A",Y79=(J=1)=>U2+J+"B",K79=(J=1)=>U2+J+"C",q79=(J=1)=>U2+J+"D",VZ6,G79,z79,U79,W79,F79,H79,B79,D79=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=NZ6+(Z<J-1?MZ6():"");if(J)Q+=VZ6;return Q},M79,V79,NZ6,N79,L79,Cx1,A79,O79,j79="\x1Bc",R79,w79,I79,E79,$79=(J,Q)=>[sm,"8",rm,rm,Q,_T,J,sm,"8",rm,rm,_T].join(""),P79=(J,Q={})=>{let Z=`${sm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+_T},T79;var vx1=u(()=>{BZ6();DZ6=!a41&&Sx1.env.TERM_PROGRAM==="Apple_Terminal",J79=!a41&&Sx1.platform==="win32",Q79=a41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Sx1.cwd,VZ6=U2+"G",G79=DZ6?"\x1B7":U2+"s",z79=DZ6?"\x1B8":U2+"u",U79=U2+"6n",W79=U2+"E",F79=U2+"F",H79=U2+"?25l",B79=U2+"?25h",M79=U2+"K",V79=U2+"1K",NZ6=U2+"2K",N79=U2+"J",L79=U2+"1J",Cx1=U2+"2J",A79=U2+"S",O79=U2+"T",R79=J79?`${Cx1}${U2}0f`:`${Cx1}${U2}3J${U2}H`,w79=U2+"?1049h",I79=U2+"?1049l",E79=_T,T79={setCwd:(J=Q79())=>`${sm}50;CurrentDir=${J}${_T}`,annotation(J,Q={}){let Z=`${sm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+_T}}});var LZ6=u(()=>{vx1();vx1()});var kx1=e((iF2,AZ6)=>{AZ6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var RZ6=e((nF2,jZ6)=>{var C79=o1("os"),OZ6=o1("tty"),bK=kx1(),{env:n5}=process,NV;if(bK("no-color")||bK("no-colors")||bK("color=false")||bK("color=never"))NV=0;else if(bK("color")||bK("colors")||bK("color=true")||bK("color=always"))NV=1;if("FORCE_COLOR"in n5)if(n5.FORCE_COLOR==="true")NV=1;else if(n5.FORCE_COLOR==="false")NV=0;else NV=n5.FORCE_COLOR.length===0?1:Math.min(parseInt(n5.FORCE_COLOR,10),3);function _x1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function bx1(J,Q){if(NV===0)return 0;if(bK("color=16m")||bK("color=full")||bK("color=truecolor"))return 3;if(bK("color=256"))return 2;if(J&&!Q&&NV===void 0)return 0;let Z=NV||0;if(n5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=C79.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in n5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in n5))||n5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in n5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n5.TEAMCITY_VERSION)?1:0;if(n5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in n5){let X=parseInt((n5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(n5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n5.TERM))return 1;if("COLORTERM"in n5)return 1;return Z}function S79(J){let Q=bx1(J,J&&J.isTTY);return _x1(Q)}jZ6.exports={supportsColor:S79,stdout:_x1(bx1(!0,OZ6.isatty(1))),stderr:_x1(bx1(!0,OZ6.isatty(2)))}});var EZ6=e((aF2,IZ6)=>{var v79=RZ6(),bT=kx1();function wZ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function xx1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(bT("no-hyperlink")||bT("no-hyperlinks")||bT("hyperlink=false")||bT("hyperlink=never"))return!1;if(bT("hyperlink=true")||bT("hyperlink=always"))return!0;if(X)return!0;if(!v79.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=wZ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=wZ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}IZ6.exports={supportsHyperlink:xx1,stdout:xx1(process.stdout),stderr:xx1(process.stderr)}});function LV(J,Q,{target:Z="stdout",...X}={}){if(!s41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return r41.link(J,Q)}var s41;var $Z6=u(()=>{LZ6();s41=p6(EZ6(),1);LV.isSupported=s41.default.stdout;LV.stderr=(J,Q,Z={})=>LV(J,Q,{target:"stderr",...Z});LV.stderr.isSupported=s41.default.stderr});class yx1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759377701-g6ad5b4"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await z00(Q)}catch(Q){n.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}}var PZ6=u(()=>{D0();Qz()});class GY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function TZ6(J){if(J instanceof o41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof GY)return{title:"Info",description:J.message,type:"info"};return n.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var o41;var fx1=u(()=>{D0();o41=class o41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as CZ6}from"node:child_process";import{rmdir as k79}from"node:fs/promises";import{tmpdir as _79}from"node:os";import SZ6 from"node:path";import{mkdtemp as b79,readFile as x79,unlink as y79,writeFile as jH2}from"fs/promises";class hx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=DC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new yx1(async()=>{try{return(await U9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),k9.pipe(v0((Q)=>Q.settings["internal.modes"]),P8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...f79},J)Object.assign(this.commands,h79)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{n.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Tx1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var f79,h79;var vZ6=u(()=>{HZ6();D0();iw();u2();MC();lw();q7();JN();wx1();Qz();ZD();a6();b0();$Z6();p41();Ix1();PZ6();fx1();f79={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${qJ} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:SK0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new o41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await b79(SZ6.join(_79(),"amp-edit-")),Y=SZ6.join(X,"message.amp.md");CZ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await x79(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return n.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await y79(Y),await k79(X)}catch(K){n.warn("Failed to clean up temporary file",K)}return}catch(Z){return n.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return pU("dangerouslyAllowAll",!1),new GY("Amp is now following permissions rules for this session")}catch(K){return n.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return pU("dangerouslyAllowAll",!0),new GY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return n.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await vT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw n.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:vT};await i41(Y);return}catch(Y){n.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return n.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new GY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return n.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
|
5799
5799
|
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=tv(new URL(Y),Z.id).toString(),G=`Thread URL: ${LV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new GY(`${G}
|
5800
5800
|
|
5801
5801
|
This thread's visibility has been updated to: ${z}`)}catch(W){let F=W instanceof Error?W.message:String(W);if(F.includes("no-workspace"))return Error("You are not a member of any workspace.");if(F.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(F.includes("no-groups"))return Error("You are not a member of any groups.");return n.error("Unexpected failure to update thread visibility",W),Error(`Failed to update thread visibility for ${Z.id}`)}}},browser:{name:"browser",description:"Open the current thread in your browser",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=tv(new URL(X),Z.id).toString();try{return await ST(Y),new GY("Thread opened in browser")}catch(K){n.error("Failed to open browser",{error:K});let q=LV(Y,Y,{fallback:()=>Y});return new GY(`Could not open browser automatically. Thread URL: ${q}`)}},isVisible:(J)=>J.messages.length!==0},settings:{name:"settings",description:"Open CLI settings file in $EDITOR",launchesWindow:!0,execute:async(J)=>{let Q=await vT();if(Q===null)return Error("No editor found, please set $EDITOR to edit settings");try{CZ6(`${Q} "${J.settingsFilePath}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");return}catch(Z){return n.error("Failed to open settings in editor",Z),Error(`Failed to open ${Q}`)}}},"agent-files":{name:"agent-files",description:"List AGENTS.md guidance files in use for the current thread",execute:async(J)=>{try{let Q=await J.getGuidanceFiles();if(Q.length===0)return new GY("No guidance files are currently in use for this thread.");let Z=Q.length,X=`Agent ${BX(Z,"File")} (${Z}):`,Y=Q.map((K)=>` • ${MY(FX(K.uri))} (${K.type})`).join(`
|
@@ -5968,7 +5968,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
5968
5968
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${U}
|
5969
5969
|
`)}}function LK9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return l1.index(Z[X])}var HF6,BF6;var MF6=u(()=>{D0();iw();u2();MC();lw();q7();EN();Q4();$3();a6();b0();GZ6();vZ6();kZ6();R5();A71();wO();YY6();Gu();$H();Vy1();RJ();TO();GY6();p9();O71();M2();wY6();qX();Q2();cy1();p7();Zu();L9();rU6();JZ();sY6();QW6();ZW6();zW6();HW6();Tu();BW6();Hf1();DW6();LW6();lW6();iW6();cU6();aW6();th1();oW6();eW6();zf1();aU6();KF6();UF6();FF6();HF6=class HF6 extends j6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new BF6}};BF6=class BF6 extends O6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;currentProgressBarState="off";progressReportTimer=null;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;currentAgentMode=void 0;agentModeSubscription=null;updateState="hidden";updateServiceSubscription=null;isFreeTierEnabled=!1;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(Boolean(J.viewState.state==="active"&&J.viewState.inferenceState==="running"))return!0;return[...J.activeTools,...J.subagentActiveTools].filter((Y)=>Y.toolRun.status==="in-progress"||Y.toolRun.status==="queued").length>0}isSummarizing(J){return J.state==="active"&&J.summaryState!=="idle"}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!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 C1(this.submitDisabledHint,new h1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C1("",void 0,[new C1("Ctrl+C",new h1({color:Q.keybind})),new C1(" again to exit",new h1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C1("",void 0,[new C1("Esc",new h1({color:Q.keybind})),new C1(" again to clear input",new h1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C1("",void 0,[new C1("Escape",new h1({color:Q.keybind})),new C1(" to close help",new h1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new C1("",void 0,[new C1("Esc",new h1({color:Q.keybind})),new C1(" to cancel",new h1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new C1("Selection copied to clipboard",new h1({color:J.foreground,dim:!0}));let Z=WF6(this.updateState,J);if(Z)return new C1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new S71;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new EV);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 Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}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=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(ax1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new A5("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;commands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new hx1(this.widget.dependencies.commandRegistry);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new zg1(this.getCommands(),this.widget.dependencies.fuzzyServer,new n51);return this.completionBuilder}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.widget.dependencies.ideClient.sendStatus({enabled:!1}),this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J)=>{try{await this.connectToSelectedIde(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J){await this.widget.dependencies.ideClient.start(J)}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},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()};handleHistoryNavigation=(J)=>{if(J.key==="p"&&J.ctrlKey)return this.navigateHistoryPrevious(),"handled";if(J.key==="n"&&J.ctrlKey)return this.navigateHistoryNext(),"handled";return"ignored"};onTextSubmitted=async(J)=>{let{threadState:Q}=this.widget.dependencies;if(this.isSummarizing(Q.viewState)){this.showSubmitDisabledHint("Unable to submit while compacting.");return}if(!J.trim())return;let Z=this.parseShellModeInput(J);if(Z){if(Z.cmd&&!this.isProcessing())this.invokeBashCommand(Z.cmd,{hidden:Z.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let X=XZ6(J);if(this.isSlashCommand(X)&&Q.mainThread){let Y=X.slice(1).split(" "),K=Y[0],q=Y.slice(1).filter((G)=>G.trim()!=="");if(K){let G=Q.viewState,z=this.getCommands().query(K,Q.mainThread,G).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&q.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,q)}return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(X)};onOptionSelected=(J)=>{switch(J.type){case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.textController.clear(),this.textController.insertText(G),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),q={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=q});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();d71(z);return}if(J.launchesWindow)IG.instance.tuiInstance.suspend();let G=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},exitApp:()=>{process.exit(0)},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await Ia({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))}},Q,X.signal);if(J.launchesWindow)IG.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){n.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=yg1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if($G.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;this.checkFreeTierStatus(),d71(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Q)=>{this.setState(()=>{this.ideStatus=Q})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Q)=>{let Z=iT();if(!Z){n.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Z.handle({type:"user:message",message:{content:[{type:"text",text:Q}]}}),n.debug("Message sent from IDE to agent",{message:Q.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Q)=>{this.textController.insertText(Q),n.debug("Appended text to CLI prompt from IDE",{text:Q.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Q)=>{this.setState(()=>{this.updateState=Q})}),this.agentModeSubscription=k9.pipe(v0((Q)=>Dz(Q.settings)),P8()).subscribe((Q)=>{this.setState(()=>{this.currentAgentMode=Q})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Q,Z)=>{if(Q.length<=3)return!0;let X=KZ6(Q);if(!X)return!0;if(this.imageAttachments.length>=Vt1)return!1;let Y=qZ6(X);if(Y)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return!0},this.updateTerminalTitle();let J=this.widget.dependencies.ideClient.getSelectedConfig();if(J)this.connectToSelectedIde(J).catch((Q)=>{let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{n.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(ax1("")),this.shouldUseProgressBar())process.stdout.write(rx1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Z=[...J.activeTools,...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(Z.length===0)return null;let X=Z[0],Y=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],K=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:Y}],subthreadID:X.subthreadID,reason:K}}shouldUseProgressBar(){return d8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let{threadState:J}=this.widget.dependencies,Q=this.getCurrentConfirmation(),Z="off";if(Q)Z="paused";else if(this.isProcessing())Z="indeterminate";if(Z!==this.currentProgressBarState)this.currentProgressBarState=Z,this.sendProgressReport(Z);this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(ZX6());break;case"paused":process.stdout.write(XX6());break;case"off":process.stdout.write(rx1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;if(this.getCurrentConfirmation()||this.isProcessing())this.progressReportTimer=setTimeout(()=>{this.sendProgressReport(this.currentProgressBarState),this.scheduleProgressReportTimer()},1e4)}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){n.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){n.error("No tool use block found in confirmation");return}if(J==="allow-all-session")pU("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else n.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q)}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await gJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){n.error("Failed to send tool confirmation:",Y)}};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 Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"compact":this.dismissedEphemeralErrorKey=null,await Z.summarizeThread();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await gJ.cancel(this.widget.dependencies.threadID)};switchToExistingThread=async(J)=>{try{let Q=await this.widget.dependencies.switchToThread(J);this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,d71(Q),p71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{})}catch(Q){throw n.error("Failed to switch to thread:",J,Q),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=iT()||this.widget.dependencies.worker,Z=[{type:"text",text:J}];if(this.imageAttachments.length>0)Z.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Z}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};onTrainingModeDialogResponse=async(J)=>{if(this.setState(()=>{this.isShowingTrainingModeDialog=!1}),J&&this.pendingTrainingMode)try{let Q=await this.widget.dependencies.internalAPIClient.updateUserTrainingMode({enabled:!0});if(!Q.ok){let Z=Q.error.message||"Failed to enable training mode";await this.showErrorMessage(Z),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else await this.proceedWithUserMessage(this.pendingTrainingMode)}catch(Q){await this.showErrorMessage(`Failed to enable training mode:
|
5970
5970
|
|
5971
|
-
${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){n.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;IG.instance.stop()}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=VK9();if(J===Q)return"~";if(J.startsWith(Q+cu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(cu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(cu.sep),"…",Q.slice(-2).join(cu.sep)].join(cu.sep)}build(J){let Q=d8.of(J),Z=y8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new SH({child:new kg1({onSelect:async(x)=>{if(x)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(x);else process.exit(0)},pageSize:50,threadFetcher:new n51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,F=this.isTranscriptEmpty()?new S51({useGpt5:this.widget.dependencies.useGpt5}):new Kg1({key:U?new A5(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,subagentToolsByParentID:q.subagentToolsByParentID,controller:U?this.getMessageScrollController(U):new EV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),B=this.getCurrentEphemeralError(),M=this.buildBottomWidget(B,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Yl1(q.mainThread):void 0,L=new c71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,thread:q.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),A=new u71({bashInvocations:this.bashInvocations}),O=[];if(this.isFreeTierEnabled)O.push(new i6({decoration:new h2(Y.secondary),child:new v8({padding:B6.horizontal(1),child:new W0({text:new C1("Thank you for trying the ad-supported Amp Free experiment — AD",new h1({color:l1.black})),textAlign:"center"})})}));O.push(new o2({child:F}),A,new i6({constraints:new f6(0,Q.size.width,0,H),child:M}),new n0({height:1,child:new v8({padding:B6.horizontal(1),child:L})}));let j=new k6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:O}),R=new j5(()=>{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.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.clearActiveSelection())return"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.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return n.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((b)=>{n.error("Failed to cancel streaming message:",b)}),"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"}),I=new j5(()=>{return this.onExitPressed(),"handled"}),w=new j5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),E=new j5(()=>{return kV.instance.toggleAll(),"handled"}),$=new j5(()=>{return IG.instance.toggleFrameStatsOverlay(),"handled"}),P=new j5(()=>{return IG.instance.tuiInstance.getScreen().markForRefresh(),eQ.instance.requestFrame(),"handled"}),C=new j5(()=>{let x=this.findElementByKey("message-view-selection-area");if(x?.state){let b=x.state,m=b.controller?.copySelection();if(m&&m.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{b.controller.endCopyHighlight(),b.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),k=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),a=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-a;m.animatePageUp(p,100)}return"handled"}),g=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),a=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-a;m.animatePageDown(p,100)}return"handled"}),T=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(0,100);return"handled"}),v=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),f=new Map([[g2.key("Escape"),new Mu],[g2.ctrl("c"),new pT],[g2.ctrl("l"),new Au],[g2.alt("c"),new Vu],[g2.alt("p"),new Lu],[g2.ctrl("r"),new Nu],[g2.key("PageUp"),new R71],[g2.key("PageDown"),new w71],[g2.key("Home"),new I71],[g2.key("End"),new E71]]);if(process.platform==="darwin")f.set(g2.meta("c"),new pT);let h=new Map([[Mu,R],[N71,I],[Au,P],[Vu,w],[Nu,E],[Lu,$],[pT,C],[R71,k],[w71,g],[I71,T],[E71,v]]),S=j;if(this.isShowingConsoleOverlay)S=new xK({children:[S,new Hg1]});if(this.isShowingHelp)S=new xK({children:[S,new Dg1]});if(this.isShowingFileChangesOverlay)S=new xK({children:[S,new Ff1]});if(this.isShowingConfirmationOverlay)S=new xK({children:[S,new Ug1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new SH({child:new yK({actions:h,child:new IV({shortcuts:f,debugLabel:"ide-picker-shortcuts",child:new Vg1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new SH({child:new yK({actions:h,child:new IV({shortcuts:f,debugLabel:"jetbrains-installer-shortcuts",child:new Cg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new SH({child:new yK({actions:h,child:new IV({shortcuts:f,debugLabel:"main-app-shortcuts",child:S})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new Bg1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new _g1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Fg1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Sg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=NK9(X),U=new k71({key:this.textFieldKey,controller:this.textController,triggers:[yg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Gg1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:IG.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,k)=>{let g=k?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=Gg1(C);break}let x=JW6(C),b=new C1(h,new h1({color:T})),m=new C1(S,new h1({color:v})),a=[b,m];if(x){let p=new C1(" - ",new h1({color:f,dim:!0})),Q1=new C1(x,new h1({color:f,dim:!0}));a.push(p,Q1)}return new i6({decoration:new h2(g),child:new W0({text:new C1("",void 0,a),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new Z2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,B=this.imageAttachments.length>0?new i6({padding:B6.only({bottom:1,left:1}),child:new W0({text:new C1("",void 0,[new C1("Images: ",new h1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new C1(`[image ${C+1}]`,new h1({color:Z.success})),...C<this.imageAttachments.length-1?[new C1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=B?new k6({crossAxisAlignment:"start",children:[B,F]}):F,L=V?new vg1({queuedMessages:W}):void 0,A=M?new My1(new qg1({todos:K}),{clipBehavior:"antiAlias"}):void 0,O=[],j=Y.viewState;if(!this.isSummarizing(j))O.push({text:new C1("",void 0,[new C1("Enter",new h1({color:G.keybind})),new C1(" to send",new h1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)O.push({text:new C1(H==="hidden"?"shell mode (incognito)":"shell mode",new h1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:B?1:0});let R=this.currentAgentMode;if(R&&!["default",xj[0]].includes(R)&&!H){let P=LK9(R);O.push({text:new C1("",void 0,[new C1("agent-mode: ",new h1({color:Z.foreground,dim:!0})),new C1(R,new h1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=P0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return O.push({text:new C1($,new h1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Zf1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:O,borderColor:Z.border})}}});import{randomBytes as AK9}from"node:crypto";import{mkdir as OK9,readFile as AF6,writeFile as jK9}from"node:fs/promises";import RK9 from"node:os";import fg1 from"node:path";import{stderr as t2,stdout as m2}from"node:process";function wK9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function aO(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")pU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")pU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")pU("experimental.agentMode",Q.agentMode)}async function mg1(J){try{await OK9(fg1.dirname(hg1),{recursive:!0}),await jK9(hg1,J,"utf-8")}catch(Q){n.debug("Failed to save last thread ID",Q)}}async function $K9(){try{return(await AF6(hg1,"utf-8")).trim()}catch(J){return null}}async function PK9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return EK9.parse(Q)}catch(Z){if(Z instanceof C0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function TK9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}function kK9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new $2(kK.unknownCommand(Z),1,q)}}function Ag2(){return OF6}function r51(J){return{...J,getThreadEnvironment:O41,vfs:Y00({os:J.fileSystem}),fileChangeTrackerStorage:new Jk(J.fileSystem),generateThreadTitle:Ta,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function rO(J,Q){Vl1("0.0.1759363307-g6ad5b4");let Z=oQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:yb1,homeDir:ug1,userConfigDir:jF6}),X=await U9();n.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=Ji(vj()),K=f10({configService:Z,toolService:Y}),q=gA0(Y,R8,St).catch((L)=>{n.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{n.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)Nl1(!0);if(Q.ide&&Bx1())Ll1(!0);if(B86(Y),Q.jetbrains)Y.registerTool(ea);else if(Q.ide)Y.registerTool(vq0);let z;if(!J.executeMode)z=new S41(process.cwd(),{},!0);else z=new class extends S41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(m2.write(`No API key found. Starting login flow...
|
5971
|
+
${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){n.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;IG.instance.stop()}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=VK9();if(J===Q)return"~";if(J.startsWith(Q+cu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(cu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(cu.sep),"…",Q.slice(-2).join(cu.sep)].join(cu.sep)}build(J){let Q=d8.of(J),Z=y8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new SH({child:new kg1({onSelect:async(x)=>{if(x)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(x);else process.exit(0)},pageSize:50,threadFetcher:new n51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,F=this.isTranscriptEmpty()?new S51({useGpt5:this.widget.dependencies.useGpt5}):new Kg1({key:U?new A5(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,subagentToolsByParentID:q.subagentToolsByParentID,controller:U?this.getMessageScrollController(U):new EV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),B=this.getCurrentEphemeralError(),M=this.buildBottomWidget(B,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Yl1(q.mainThread):void 0,L=new c71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,thread:q.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),A=new u71({bashInvocations:this.bashInvocations}),O=[];if(this.isFreeTierEnabled)O.push(new i6({decoration:new h2(Y.secondary),child:new v8({padding:B6.horizontal(1),child:new W0({text:new C1("Thank you for trying the ad-supported Amp Free experiment — AD",new h1({color:l1.black})),textAlign:"center"})})}));O.push(new o2({child:F}),A,new i6({constraints:new f6(0,Q.size.width,0,H),child:M}),new n0({height:1,child:new v8({padding:B6.horizontal(1),child:L})}));let j=new k6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:O}),R=new j5(()=>{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.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.clearActiveSelection())return"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.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return n.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((b)=>{n.error("Failed to cancel streaming message:",b)}),"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"}),I=new j5(()=>{return this.onExitPressed(),"handled"}),w=new j5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),E=new j5(()=>{return kV.instance.toggleAll(),"handled"}),$=new j5(()=>{return IG.instance.toggleFrameStatsOverlay(),"handled"}),P=new j5(()=>{return IG.instance.tuiInstance.getScreen().markForRefresh(),eQ.instance.requestFrame(),"handled"}),C=new j5(()=>{let x=this.findElementByKey("message-view-selection-area");if(x?.state){let b=x.state,m=b.controller?.copySelection();if(m&&m.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{b.controller.endCopyHighlight(),b.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),k=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),a=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-a;m.animatePageUp(p,100)}return"handled"}),g=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b){let m=this.getMessageScrollController(b),a=Math.max(Math.floor(Q.size.height*0.4),10),p=Q.size.height-a;m.animatePageDown(p,100)}return"handled"}),T=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(0,100);return"handled"}),v=new j5(()=>{let{threadState:x}=this.widget.dependencies,b=x.mainThread?.id;if(b)this.getMessageScrollController(b).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),f=new Map([[g2.key("Escape"),new Mu],[g2.ctrl("c"),new pT],[g2.ctrl("l"),new Au],[g2.alt("c"),new Vu],[g2.alt("p"),new Lu],[g2.ctrl("r"),new Nu],[g2.key("PageUp"),new R71],[g2.key("PageDown"),new w71],[g2.key("Home"),new I71],[g2.key("End"),new E71]]);if(process.platform==="darwin")f.set(g2.meta("c"),new pT);let h=new Map([[Mu,R],[N71,I],[Au,P],[Vu,w],[Nu,E],[Lu,$],[pT,C],[R71,k],[w71,g],[I71,T],[E71,v]]),S=j;if(this.isShowingConsoleOverlay)S=new xK({children:[S,new Hg1]});if(this.isShowingHelp)S=new xK({children:[S,new Dg1]});if(this.isShowingFileChangesOverlay)S=new xK({children:[S,new Ff1]});if(this.isShowingConfirmationOverlay)S=new xK({children:[S,new Ug1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new SH({child:new yK({actions:h,child:new IV({shortcuts:f,debugLabel:"ide-picker-shortcuts",child:new Vg1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new SH({child:new yK({actions:h,child:new IV({shortcuts:f,debugLabel:"jetbrains-installer-shortcuts",child:new Cg1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new SH({child:new yK({actions:h,child:new IV({shortcuts:f,debugLabel:"main-app-shortcuts",child:S})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new Bg1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new _g1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Fg1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Sg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=NK9(X),U=new k71({key:this.textFieldKey,controller:this.textController,triggers:[yg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Gg1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:IG.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,k)=>{let g=k?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=Gg1(C);break}let x=JW6(C),b=new C1(h,new h1({color:T})),m=new C1(S,new h1({color:v})),a=[b,m];if(x){let p=new C1(" - ",new h1({color:f,dim:!0})),Q1=new C1(x,new h1({color:f,dim:!0}));a.push(p,Q1)}return new i6({decoration:new h2(g),child:new W0({text:new C1("",void 0,a),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new Z2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,B=this.imageAttachments.length>0?new i6({padding:B6.only({bottom:1,left:1}),child:new W0({text:new C1("",void 0,[new C1("Images: ",new h1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new C1(`[image ${C+1}]`,new h1({color:Z.success})),...C<this.imageAttachments.length-1?[new C1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=B?new k6({crossAxisAlignment:"start",children:[B,F]}):F,L=V?new vg1({queuedMessages:W}):void 0,A=M?new My1(new qg1({todos:K}),{clipBehavior:"antiAlias"}):void 0,O=[],j=Y.viewState;if(!this.isSummarizing(j))O.push({text:new C1("",void 0,[new C1("Enter",new h1({color:G.keybind})),new C1(" to send",new h1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)O.push({text:new C1(H==="hidden"?"shell mode (incognito)":"shell mode",new h1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:B?1:0});let R=this.currentAgentMode;if(R&&!["default",xj[0]].includes(R)&&!H){let P=LK9(R);O.push({text:new C1("",void 0,[new C1("agent-mode: ",new h1({color:Z.foreground,dim:!0})),new C1(R,new h1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=P0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return O.push({text:new C1($,new h1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Zf1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:O,borderColor:Z.border})}}});import{randomBytes as AK9}from"node:crypto";import{mkdir as OK9,readFile as AF6,writeFile as jK9}from"node:fs/promises";import RK9 from"node:os";import fg1 from"node:path";import{stderr as t2,stdout as m2}from"node:process";function wK9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function aO(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")pU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")pU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")pU("experimental.agentMode",Q.agentMode)}async function mg1(J){try{await OK9(fg1.dirname(hg1),{recursive:!0}),await jK9(hg1,J,"utf-8")}catch(Q){n.debug("Failed to save last thread ID",Q)}}async function $K9(){try{return(await AF6(hg1,"utf-8")).trim()}catch(J){return null}}async function PK9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return EK9.parse(Q)}catch(Z){if(Z instanceof C0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function TK9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}function kK9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new $2(kK.unknownCommand(Z),1,q)}}function Ag2(){return OF6}function r51(J){return{...J,getThreadEnvironment:O41,vfs:Y00({os:J.fileSystem}),fileChangeTrackerStorage:new Jk(J.fileSystem),generateThreadTitle:Ta,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function rO(J,Q){Vl1("0.0.1759377701-g6ad5b4");let Z=oQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:yb1,homeDir:ug1,userConfigDir:jF6}),X=await U9();n.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=Ji(vj()),K=f10({configService:Z,toolService:Y}),q=gA0(Y,R8,St).catch((L)=>{n.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{n.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)Nl1(!0);if(Q.ide&&Bx1())Ll1(!0);if(B86(Y),Q.jetbrains)Y.registerTool(ea);else if(Q.ide)Y.registerTool(vq0);let z;if(!J.executeMode)z=new S41(process.cwd(),{},!0);else z=new class extends S41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(m2.write(`No API key found. Starting login flow...
|
5972
5972
|
`),!await _K9(J))await VO(),process.exit(1)}let U=await O00({isDevelopment:!1}),W=new HW1(U),F=new UW1(U,{lazy:!0}),H=new YM1(W),B=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=N86({playNotificationSound:async(L)=>{if(B){M86(L);let A=Wy1(),O=Fy1();if((!A||O)&&X.settings["notifications.system.enabled"]!==!1){if(L==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(L==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:W});n.info("Starting Amp background services");let V=hK0({threadService:W,threadHistoryService:F,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:W,threadHistoryService:F,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?J00:R8};return{...N,async asyncDispose(){await N.mcpService.dispose(),await N.threadService.asyncDispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function _K9(J){if(!J.executeMode){if(!await Rx1("Would you like to log in to Amp? [(y)es, (n)o]: "))return m2.write(`Login cancelled. Run the command again to retry.
|
5973
5973
|
`),!1}return await RF6(J)}async function RF6(J){let Q=AK9(32).toString("hex"),Z=await jx1(J.ampURL,Q);try{await ST(Z)}catch(Y){n.error("Failed to open browser",{error:Y})}let X=await jx1(J.ampURL,Q,!1);m2.write(`If your browser did not open automatically, visit:
|
5974
5974
|
|
@@ -5978,12 +5978,12 @@ ${Z8.blue.bold(X)}
|
|
5978
5978
|
Login successful! You can now use the Amp CLI.
|
5979
5979
|
`),!0}catch(Y){return n.error("Login failed",{error:Y}),t2.write(`
|
5980
5980
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
5981
|
-
`),!1}}function bK9(){let J=new Xm().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)MT(),process.exit(0);let H=F.originalError??F;M56(H)}),J.option("-V, --version","output the version number",()=>{m2.write(`0.0.
|
5982
|
-
`),process.exit(0)}),J.addHelpText("after",hJ6()),J.configureHelp({formatHelp:gJ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await hK9(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await fK9(M,await Gx1(B,M.settings))});let Q=async(F,H,B)=>{oQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:ug1,userConfigDir:jF6});let M={...H,executeMode:!1};await gg1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await LF6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await lK9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);if(H.pick)await Q(M,V,B);else await cK9(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);await dK9(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await LF6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);await pK9(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);await uK9(M,V,F,B)}),QZ6(J,async(F,H)=>{let B=await fK(H);aO(F,H);let M=await rO(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:MT,asyncDispose:M.asyncDispose.bind(M)}}),OQ6(J),zQ6(J,async(F)=>{return(await fK(F)).settings});let X=new Xm().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await Mx1(F.force||!1,F.verbose||!1,"0.0.
|
5981
|
+
`),!1}}function bK9(){let J=new Xm().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)MT(),process.exit(0);let H=F.originalError??F;M56(H)}),J.option("-V, --version","output the version number",()=>{m2.write(`0.0.1759377701-g6ad5b4 (released 2025-10-02T04:06:46.623Z)
|
5982
|
+
`),process.exit(0)}),J.addHelpText("after",hJ6()),J.configureHelp({formatHelp:gJ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await hK9(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await fK9(M,await Gx1(B,M.settings))});let Q=async(F,H,B)=>{oQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:Z0.of([P0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:ug1,userConfigDir:jF6});let M={...H,executeMode:!1};await gg1(M,{...F,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await LF6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await lK9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);if(H.pick)await Q(M,V,B);else await cK9(M,V,F,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);await dK9(M,V,F,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await fK(B);await LF6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);await pK9(M,V,F,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(F,H,B)=>{let M=B.optsWithGlobals(),V=await fK(M);await uK9(M,V,F,B)}),QZ6(J,async(F,H)=>{let B=await fK(H);aO(F,H);let M=await rO(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:MT,asyncDispose:M.asyncDispose.bind(M)}}),OQ6(J),zQ6(J,async(F)=>{return(await fK(F)).settings});let X=new Xm().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(F)=>{await Mx1(F.force||!1,F.verbose||!1,"0.0.1759377701-g6ad5b4"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new KO(H,V),L=vK9(F);if(L)N.default(L);if(N.hidden=CK9(F)||NF6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of VF6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new KO("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new KO("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new KO("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new KO("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new KO("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z),J.action(async(F,H)=>{let B=F,M=await fK(B);if(Object.keys(B).forEach((V)=>{let N=VF6.find((L)=>L.name===V);if(N&&NF6(N)&&!SK9(N))t2.write(Z8.yellow(`Warning: '--${V}' flag is deprecated
|
5983
5983
|
`))}),H.args.length>0)kK9(M,H);await gg1(M,B,H)});let U=new Xm("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await mK9(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new Xm("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(F)=>{await gK9(F.version)});return J.addCommand(W),J}async function a51(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??nK(),K=r51(J);if(Z)await J.threadStorage.set(Y,Z);let q=await gJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,c41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(K7(z,"assistant"))await mg1(Y),G.unsubscribe()});return await q.resume(),q}async function gg1(J,Q,Z){let X=process.stdin,Y=d41(Q);if(Y instanceof Error)GX(Y.message);let K,q=null;if(Q.streamJsonInput)K="";else if(typeof Q.execute==="string"){K=Q.execute;let j=(await Ex1()).trimEnd();if(j)q=j}else K=(await Ex1()).trimEnd();if(Q.remote&&!J.executeMode)throw new $2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new $2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new $2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new $2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new $2("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new $2("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&K===""&&!Q.streamJsonInput)throw new $2("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
5984
5984
|
Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMode&&!J.streamJsonMode&&typeof Q.execute!=="string")X=await SQ6();aO(Z,Q);let G=await rO(J,Q);OF6=G;let z=r51(G),U=async(j)=>{let R=await AF6(j,"utf-8"),I=JSON.parse(R);if(!iU(I.id))throw new $2(kK.invalidThreadId);return a51(G,{visibility:Y,thread:I})},W=async(j)=>{if(!iU(j))throw new $2(kK.invalidThreadId);let R=await G.threadService.get(j)??void 0;return a51(G,{visibility:Y,thread:R})},F=async()=>{try{if(Q.threadId)return W(Q.threadId);else return a51(G,{visibility:Y})}catch(j){if(j instanceof $2)throw j;throw await j41(j,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return a51(G,{visibility:Y})};if(Q.format==="jsonl")t2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
5985
|
-
`),await VO(),process.exit(1);if(J.executeMode&&Q.remote)await RQ6(K,q),await G.asyncDispose(),process.exit(0);let B=await F();if(J.executeMode)await T56(B,B.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1;if(Q.jetbrains||Q.ide){await Nr1();let j=await Wc();if(j.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(j.length===1){let R=j[0];if(R)SJ.selectConfig(R)}else M=!0}let N=Ax1("0.0.
|
5986
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=SU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await $Q6(Y),await PQ6(Y),J.mcpConfig){let q=await PK9(J.mcpConfig);Y=TK9(Y,q)}let K=await Y.get("url","global");if(!K)K=YZ;if(!lH(K))n.info("Targeting custom Amp server",{ampURL:K});return Y=Cd1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:IQ6(await Gx1(J,Y))}}function xK9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function yK9(){let J=xK9(process.argv);if(Y56({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),wK9(n),n.info("Starting Amp CLI.",{version:"0.0.
|
5985
|
+
`),await VO(),process.exit(1);if(J.executeMode&&Q.remote)await RQ6(K,q),await G.asyncDispose(),process.exit(0);let B=await F();if(J.executeMode)await T56(B,B.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1;if(Q.jetbrains||Q.ide){await Nr1();let j=await Wc();if(j.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(j.length===1){let R=j[0];if(R)SJ.selectConfig(R)}else M=!0}let N=Ax1("0.0.1759377701-g6ad5b4",G.settingsStorage),L=Z0.of([P0.file(process.cwd())]),A=DC(void 0,L);if(K)B.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let O=await U9();await DF6({stdin:X,stdout:process.stdout,history:new db1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:B.threadID,worker:B,workerDeps:z,configService:G.configService,internalAPIClient:MZ,ampURL:J.ampURL,useGpt5:O.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{n.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:SJ,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,startWithPicker:Q.startWithPicker,updateService:N,debugWidgetTree:Q.debugWidgetTree}),await G.asyncDispose(),process.exit(0)}async function fK(J){if(J.interactive)t2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
5986
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=SU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await $Q6(Y),await PQ6(Y),J.mcpConfig){let q=await PK9(J.mcpConfig);Y=TK9(Y,q)}let K=await Y.get("url","global");if(!K)K=YZ;if(!lH(K))n.info("Targeting custom Amp server",{ampURL:K});return Y=Cd1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:IQ6(await Gx1(J,Y))}}function xK9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function yK9(){let J=xK9(process.argv);if(Y56({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),wK9(n),n.info("Starting Amp CLI.",{version:"0.0.1759377701-g6ad5b4",buildTimestamp:"2025-10-02T04:06:46.623Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new $2(kK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await bK9().parseAsync(process.argv)}async function fK9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),m2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
5987
5987
|
`);else if(!lH(J.ampURL))m2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
5988
5988
|
`);let Z=process.env.AMP_API_KEY;if(Z)m2.write(`API key found in environment variable, storing...
|
5989
5989
|
`),await Q.set("apiKey",Z,J.ampURL),m2.write(`API key successfully stored.
|
@@ -5999,7 +5999,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMo
|
|
5999
5999
|
`));try{let Q;if(J)Q=J,t2.write(Z8.blue(`Updating to version ${J}...
|
6000
6000
|
`)),await TT(J),t2.write(Z8.green(`✓ Successfully updated to version ${J}
|
6001
6001
|
`));else{t2.write(Z8.blue(`Checking for updates...
|
6002
|
-
`));let{hasUpdate:X,latestVersion:Y}=await mR("0.0.
|
6002
|
+
`));let{hasUpdate:X,latestVersion:Y}=await mR("0.0.1759377701-g6ad5b4");if(!X)t2.write(Z8.green(`✓ Amp CLI is already up to date.
|
6003
6003
|
`)),process.exit(0);if(!Y)t2.write(Z8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,t2.write(Z8.blue(`Updating to version ${Y}...
|
6004
6004
|
`)),await TT(Y),t2.write(Z8.green(`✓ Successfully updated to version ${Y}
|
6005
6005
|
`))}let Z=await RO(Q);if(Z.warning)t2.write(`
|
package/package.json
CHANGED