@sourcegraph/amp 0.0.1760127338-g8601e4 → 0.0.1760140901-g5719d0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -5867,10 +5867,10 @@ Available parameters:`),W.push(d79(Q));return W.join(`
5867
5867
  `)}catch(X){return`Failed to validate input for tool '${Z}': ${X instanceof Error?X.message:"Unknown validation error"}`}}function VZ6(){return!process.stdin.isTTY&&process.stdin.readable}function l79(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X&&X.startsWith("--")){let Y=X.slice(2),K=J[Z+1];if(K&&!K.startsWith("--")){if(Q[Y])if(Array.isArray(Q[Y]))Q[Y].push(K);else Q[Y]=[Q[Y],K];else Q[Y]=K;Z++}}}return Q}function i79(){let J=process.env.AMP_TOOLBOX;if(!J)return kw;let Q=J.split(":").map((X)=>X.trim()).filter(Boolean),Z=Q.filter((X)=>!NZ6.isAbsolute(X));if(Z.length>0)throw Error(`AMP_TOOLBOX must contain absolute paths only. Found relative paths: ${Z.join(", ")}
5868
5868
  See https://ampcode.com/manual#toolboxes`);return Q[0]||kw}function LZ6(J,Q){let Z=J.command("tools").alias("tool").description("Tool management commands");return n79(Z,Q),a79(Z,Q),r79(Z,Q),s79(Z,Q),Z}function n79(J,Q){J.command("list").alias("ls").description("List all active tools (including MCP tools)").option("--json","output as a single JSON array").action(async function(Z,X){let Y=X.optsWithGlobals(),K=await Q(X,Y),q=0;await K.mcpService.initialized,await QZ6({json:Y.json,isTTY:K.context.isTTY,toolService:K.toolService,mcpService:K.mcpService,stderr:process.stderr,stdout:process.stdout,exit:(G)=>{q=G}}),await K.asyncDispose(),K.cleanupTerminal(),process.exit(q)})}function a79(J,Q){J.command("show").argument("<tool>","The tool for which to show details").description("Show details about an active tool").option("--json","output as a single JSON object").action(async function(Z,X,Y){let K=Y.optsWithGlobals(),q=await Q(Y,K);await q.mcpService.initialized;let G=0;await KZ6({toolName:Z,json:K.json,isTTY:q.context.isTTY,toolService:q.toolService,stdout:process.stdout,exit:(z)=>{G=z}}),await q.asyncDispose(),q.cleanupTerminal(),process.exit(G)})}function r79(J,Q){J.command("make").argument("<tool-name>","A descriptive name like run-tests or build-project").description("Sets up a skeleton tool in your toolbox").option("--force","Overwrite an existing tool if it already exists").option("--bun","Create a Bun/TypeScript tool (default)").option("--zsh","Create a Zsh shell script tool").option("--bash","Create a Bash shell script tool").action(async function(Z,X,Y){let K="bun";if(X.zsh)K="zsh";else if(X.bash)K="bash";else if(X.bun)K="bun";try{let q=i79();await YZ6({fs:XZ6,toolName:Z,toolboxDir:q,force:X.force,language:K,stdout:process.stdout,exit:process.exit})}catch(q){process.stdout.write(`${q instanceof Error?q.message:String(q)}
5869
5869
  `),process.exit(1)}})}function s79(J,Q){let Z=[G8.bold("Examples:"),""," # invoke the Read tool for README.md and the first ten lines"," amp tools use Read --path $PWD/README.md --read_range 0 --read_range 10",""," # invoke web_search with JSON input",` amp tools use web_search <<<'{"query":"Svelte 5"}'`,""," # invoke a toolbox tool"," amp tools use tb__run_test --workspace server","",`Use ${G8.green("amp tools list")} to get a list of all tools available in this environment.`,"",`Use ${G8.green("amp tools show <tool-name>")} to see the schema of a tool.`].join(`
5870
- `);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(VZ6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await DZ6({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)})}import{homedir as gW9}from"node:os";import Cp from"node:path";var AZ6=[{id:"e5f6ce3f-3eb0-4841-be9f-95d53fe773cc",advertiser_id:"baseten",advertiser_name:"Baseten",title:"Baseten model routing",text:"Baseten gives you one client for all providers.",button_text:"Get Started",destination_url:"https://www.baseten.co/",call_to_action:"link_to",ad_tool_tip:"Suggested because you're switching SDKs to call models.",keywords:["model","switching","routing","inference"],status:"active",demo_user_message:"We're switching models from gpt-4o to Claude 3.5 (and maybe Gemini). What's a clean way to do model routing and fallback across providers in our Node inference service without rewriting everything?",demo_assistant_message:"Create a provider-agnostic interface and a routing layer that selects the model based on cost, latency, or quality. Implement retries and fallback so if one provider errors or is slow, you can route inference to another model. Start with a simple rules-based router, log per-request metrics, and then evolve to latency-aware or A/B routing.",created_at:new Date("2024-01-15").toISOString(),updated_at:new Date("2024-01-15").toISOString()},{id:"46cf2889-eb7a-427f-8403-6dd9bb8f29a1",advertiser_id:"baseten",advertiser_name:"BaseTen",title:"No cold starts with BaseTen",text:"Keep models warm and call times down with Baseten",button_text:"Learn More",destination_url:"https://www.baseten.co/",call_to_action:"link_to",ad_tool_tip:"Suggested because you want to optimize model inference times.",keywords:["cold starts","models","fast"],status:"active",demo_user_message:"Our model endpoints have cold starts-the first request takes 8-12s but later ones are fast. How can we keep models warm and reduce time-to-first-token in production?",demo_assistant_message:"Keep a warm pool or set min replicas to avoid cold starts, preload weights at startup, and send periodic keep-alives so the models stay warm. Pin model weights in GPU memory, enable token streaming to improve perceived latency, and watch p50/p95 to ensure consistently fast responses under load.",created_at:new Date("2024-02-01").toISOString(),updated_at:new Date("2024-02-01").toISOString()},{id:"9009f4bf-8584-418a-ac87-43052d14e996",advertiser_id:"parallel",advertiser_name:"Parallel",title:"Web API built for AI agents",text:"Get accurate, verifiable web data with predictable costs.",button_text:"Get Started",destination_url:"https://parallel.ai/",call_to_action:"custom",custom_actions:[{text:"Start Free Trial",description:"Opens Parallel signup page"}],ad_tool_tip:"Suggested because you're building AI agents that need web data.",keywords:["web search","ai agents","web scraping","research"],status:"active",demo_user_message:"We're building an AI agent that needs to research companies and products on the web, but we keep getting hallucinated data or unpredictable API costs. How can we get reliable web data for our agent?",demo_assistant_message:"Use a purpose-built web API for AI agents that provides cross-referenced facts with provenance. Look for services that charge per query instead of per token for predictable costs, and ensure outputs are evidence-based so you can verify sources. This reduces hallucination and gives you an audit trail for the information your agent uses.",created_at:new Date("2024-03-01").toISOString(),updated_at:new Date("2024-03-01").toISOString()},{id:"9e91d62d-8f11-4634-8ffc-8af2a1cc78e2",advertiser_id:"parallel",advertiser_name:"Parallel",title:"Predictable costs for AI web search",text:"Pay per query, not per token. Budget compute by task complexity.",button_text:"Learn More",destination_url:"https://parallel.ai/",call_to_action:"link_to",ad_tool_tip:"Suggested because you need cost-effective web research for AI.",keywords:["cost","pricing","web search","budget","research"],status:"active",demo_user_message:"Our AI agent's web research costs are all over the place-some queries cost pennies, others cost dollars because of token usage. How can we make web API costs more predictable for budgeting?",demo_assistant_message:"Switch to a web API that charges per query instead of per token. This lets you flex compute budget based on task complexity and gives you predictable pricing regardless of how much text gets processed. Monitor cost per query type and set limits so you can forecast spend accurately.",created_at:new Date("2024-03-15").toISOString(),updated_at:new Date("2024-03-15").toISOString()},{id:"1755b522-ee2e-49c0-8337-de53211dc543",advertiser_id:"parallel",advertiser_name:"Parallel",title:"test ad for parallel",text:"Pay per query, not per token. Budget compute by task complexity.",button_text:"Learn More",destination_url:"https://parallel.ai/",call_to_action:"custom",custom_actions:[{text:"go do something crazy"},{text:"try another action",description:"This is a second custom action"}],ad_tool_tip:"Suggested because you need cost-effective web research for AI.",keywords:["cost","pricing","web search","budget","research"],status:"active",demo_user_message:"Our AI agent's web research costs are all over the place-some queries cost pennies, others cost dollars because of token usage. How can we make web API costs more predictable for budgeting?",demo_assistant_message:"Switch to a web API that charges per query instead of per token. This lets you flex compute budget based on task complexity and gives you predictable pricing regardless of how much text gets processed. Monitor cost per query type and set limits so you can forecast spend accurately.",created_at:new Date("2024-03-15").toISOString(),updated_at:new Date("2024-03-15").toISOString()}];W0();bE();Oj();a2();Q3();P2();XL();p6();S0();function RZ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}W0();Q3();import o79 from"node:fs";import wZ6 from"node:path";function OZ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!wZ6.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function jZ6(J){try{let Q=wZ6.extname(J).toLowerCase(),Z=Ze1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=o79.readFileSync(J);return t79(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function t79(J,Q){if(J.length>iO)return l.warn(`Image file too large: ${J.length} bytes (max: ${iO})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as nY6}from"node:child_process";import{rmdir as pX9}from"node:fs/promises";import{tmpdir as dX9}from"node:os";import aY6 from"node:path";cO();W0();import{spawn as e79}from"node:child_process";import{promises as J59}from"node:fs";function $Z6(J){return J.kind==="executable"}function EZ6(J){return J.kind==="markdown"}var yH=50000,IZ6=300000;async function By1(J,Q,Z,X={}){let{timeoutMs:Y=IZ6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),EZ6(q))return await Q59(q,Q);else if($Z6(q))return await Z59(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function Q59(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await J59.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>yH?Z.slice(0,yH)+`
5870
+ `);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(VZ6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await DZ6({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)})}import{homedir as gW9}from"node:os";import Cp from"node:path";var AZ6=[{id:"e5f6ce3f-3eb0-4841-be9f-95d53fe773cc",advertiser_id:"baseten",advertiser_name:"Baseten",title:"Baseten model routing",text:"Baseten gives you one client for all providers.",button_text:"Get Started",destination_url:"https://www.baseten.co/",call_to_action:"link_to",ad_tool_tip:"Suggested because you're switching SDKs to call models.",keywords:["model","switching","routing","inference"],status:"active",demo_user_message:"We're switching models from gpt-4o to Claude 3.5 (and maybe Gemini). What's a clean way to do model routing and fallback across providers in our Node inference service without rewriting everything?",demo_assistant_message:"Create a provider-agnostic interface and a routing layer that selects the model based on cost, latency, or quality. Implement retries and fallback so if one provider errors or is slow, you can route inference to another model. Start with a simple rules-based router, log per-request metrics, and then evolve to latency-aware or A/B routing.",created_at:new Date("2024-01-15").toISOString(),updated_at:new Date("2024-01-15").toISOString()},{id:"46cf2889-eb7a-427f-8403-6dd9bb8f29a1",advertiser_id:"baseten",advertiser_name:"Baseten",title:"No cold starts with Baseten",text:"Keep models warm and call times down with Baseten",button_text:"Learn More",destination_url:"https://www.baseten.co/",call_to_action:"link_to",ad_tool_tip:"Suggested because you want to optimize model inference times.",keywords:["cold starts","models","fast"],status:"active",demo_user_message:"Our model endpoints have cold starts-the first request takes 8-12s but later ones are fast. How can we keep models warm and reduce time-to-first-token in production?",demo_assistant_message:"Keep a warm pool or set min replicas to avoid cold starts, preload weights at startup, and send periodic keep-alives so the models stay warm. Pin model weights in GPU memory, enable token streaming to improve perceived latency, and watch p50/p95 to ensure consistently fast responses under load.",created_at:new Date("2024-02-01").toISOString(),updated_at:new Date("2024-02-01").toISOString()},{id:"9009f4bf-8584-418a-ac87-43052d14e996",advertiser_id:"parallel",advertiser_name:"Parallel",title:"Web API built for AI agents",text:"Get accurate, verifiable web data with predictable costs.",button_text:"Get Started",destination_url:"https://parallel.ai/",call_to_action:"custom",custom_actions:[{text:"Start Free Trial",description:"Opens Parallel signup page"}],ad_tool_tip:"Suggested because you're building AI agents that need web data.",keywords:["web search","ai agents","web scraping","research"],status:"active",demo_user_message:"We're building an AI agent that needs to research companies and products on the web, but we keep getting hallucinated data or unpredictable API costs. How can we get reliable web data for our agent?",demo_assistant_message:"Use a purpose-built web API for AI agents that provides cross-referenced facts with provenance. Look for services that charge per query instead of per token for predictable costs, and ensure outputs are evidence-based so you can verify sources. This reduces hallucination and gives you an audit trail for the information your agent uses.",created_at:new Date("2024-03-01").toISOString(),updated_at:new Date("2024-03-01").toISOString()},{id:"9e91d62d-8f11-4634-8ffc-8af2a1cc78e2",advertiser_id:"parallel",advertiser_name:"Parallel",title:"Predictable costs for AI web search",text:"Pay per query, not per token. Budget compute by task complexity.",button_text:"Learn More",destination_url:"https://parallel.ai/",call_to_action:"link_to",ad_tool_tip:"Suggested because you need cost-effective web research for AI.",keywords:["cost","pricing","web search","budget","research"],status:"active",demo_user_message:"Our AI agent's web research costs are all over the place-some queries cost pennies, others cost dollars because of token usage. How can we make web API costs more predictable for budgeting?",demo_assistant_message:"Switch to a web API that charges per query instead of per token. This lets you flex compute budget based on task complexity and gives you predictable pricing regardless of how much text gets processed. Monitor cost per query type and set limits so you can forecast spend accurately.",created_at:new Date("2024-03-15").toISOString(),updated_at:new Date("2024-03-15").toISOString()},{id:"1755b522-ee2e-49c0-8337-de53211dc543",advertiser_id:"parallel",advertiser_name:"Parallel",title:"test ad for parallel",text:"Pay per query, not per token. Budget compute by task complexity.",button_text:"Learn More",destination_url:"https://parallel.ai/",call_to_action:"custom",custom_actions:[{text:"go do something crazy"},{text:"try another action",description:"This is a second custom action"}],ad_tool_tip:"Suggested because you need cost-effective web research for AI.",keywords:["cost","pricing","web search","budget","research"],status:"active",demo_user_message:"Our AI agent's web research costs are all over the place-some queries cost pennies, others cost dollars because of token usage. How can we make web API costs more predictable for budgeting?",demo_assistant_message:"Switch to a web API that charges per query instead of per token. This lets you flex compute budget based on task complexity and gives you predictable pricing regardless of how much text gets processed. Monitor cost per query type and set limits so you can forecast spend accurately.",created_at:new Date("2024-03-15").toISOString(),updated_at:new Date("2024-03-15").toISOString()}];W0();bE();Oj();a2();Q3();P2();XL();p6();S0();function RZ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}W0();Q3();import o79 from"node:fs";import wZ6 from"node:path";function OZ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!wZ6.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function jZ6(J){try{let Q=wZ6.extname(J).toLowerCase(),Z=Ze1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=o79.readFileSync(J);return t79(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function t79(J,Q){if(J.length>iO)return l.warn(`Image file too large: ${J.length} bytes (max: ${iO})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as nY6}from"node:child_process";import{rmdir as pX9}from"node:fs/promises";import{tmpdir as dX9}from"node:os";import aY6 from"node:path";cO();W0();import{spawn as e79}from"node:child_process";import{promises as J59}from"node:fs";function $Z6(J){return J.kind==="executable"}function EZ6(J){return J.kind==="markdown"}var yH=50000,IZ6=300000;async function By1(J,Q,Z,X={}){let{timeoutMs:Y=IZ6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),EZ6(q))return await Q59(q,Q);else if($Z6(q))return await Z59(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function Q59(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await J59.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>yH?Z.slice(0,yH)+`
5871
5871
  ... (output truncated at ${yH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function Z59(J,Q,Z=IZ6,X){return new Promise((Y)=>{let[K,q]=X59(J,Q);l.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=tt1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),l.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=e79(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<=yH)F.push(V);else{let N=yH-(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<=yH)H.push(V);else{let N=yH-(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?`
5872
5872
  ${L}`:L;if(B>yH)A+=`
5873
- ... (output truncated at ${yH} 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 X59(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return K59(Z,X?[...X]:null,Y,Q);else return Y59(Z,X?[...X]:null,Y,Q)}function Y59(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function K59(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]}}W0();bE();Oj();a2();PN();qq();kW();p6();S0();import{mkdtemp as cX9,readFile as lX9,unlink as iX9,writeFile as XR2}from"fs/promises";var n71={};A6(n71,{scrollUp:()=>E59,scrollDown:()=>I59,link:()=>k59,image:()=>_59,iTerm:()=>x59,exitAlternativeScreen:()=>S59,eraseUp:()=>$59,eraseStartLine:()=>O59,eraseScreen:()=>Dy1,eraseLines:()=>R59,eraseLine:()=>SZ6,eraseEndLine:()=>w59,eraseDown:()=>j59,enterAlternativeScreen:()=>C59,cursorUp:()=>TZ6,cursorTo:()=>z59,cursorShow:()=>A59,cursorSavePosition:()=>B59,cursorRestorePosition:()=>D59,cursorPrevLine:()=>N59,cursorNextLine:()=>V59,cursorMove:()=>U59,cursorLeft:()=>CZ6,cursorHide:()=>L59,cursorGetPosition:()=>M59,cursorForward:()=>F59,cursorDown:()=>W59,cursorBackward:()=>H59,clearTerminal:()=>T59,clearScreen:()=>P59,beep:()=>v59});import My1 from"node:process";var i71=globalThis.window?.document!==void 0,GL2=globalThis.process?.versions?.node!==void 0,zL2=globalThis.process?.versions?.bun!==void 0,UL2=globalThis.Deno?.version?.deno!==void 0,WL2=globalThis.process?.versions?.electron!==void 0,FL2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,HL2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,BL2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,DL2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,ML2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Eu=globalThis.navigator?.userAgentData?.platform,VL2=Eu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",NL2=Eu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",LL2=Eu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",AL2=Eu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),RL2=Eu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var U2="\x1B[",Pu="\x1B]",GC="\x07",Iu=";",PZ6=!i71&&My1.env.TERM_PROGRAM==="Apple_Terminal",q59=!i71&&My1.platform==="win32",G59=i71?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:My1.cwd,z59=(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)+Iu+(J+1)+"H"},U59=(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},TZ6=(J=1)=>U2+J+"A",W59=(J=1)=>U2+J+"B",F59=(J=1)=>U2+J+"C",H59=(J=1)=>U2+J+"D",CZ6=U2+"G",B59=PZ6?"\x1B7":U2+"s",D59=PZ6?"\x1B8":U2+"u",M59=U2+"6n",V59=U2+"E",N59=U2+"F",L59=U2+"?25l",A59=U2+"?25h",R59=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=SZ6+(Z<J-1?TZ6():"");if(J)Q+=CZ6;return Q},w59=U2+"K",O59=U2+"1K",SZ6=U2+"2K",j59=U2+"J",$59=U2+"1J",Dy1=U2+"2J",E59=U2+"S",I59=U2+"T",P59="\x1Bc",T59=q59?`${Dy1}${U2}0f`:`${Dy1}${U2}3J${U2}H`,C59=U2+"?1049h",S59=U2+"?1049l",v59=GC,k59=(J,Q)=>[Pu,"8",Iu,Iu,Q,GC,J,Pu,"8",Iu,Iu,GC].join(""),_59=(J,Q={})=>{let Z=`${Pu}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")+GC},x59={setCwd:(J=G59())=>`${Pu}50;CurrentDir=${J}${GC}`,annotation(J,Q={}){let Z=`${Pu}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+GC}};var a71=P6(fZ6(),1);function hV(J,Q,{target:Z="stdout",...X}={}){if(!a71.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return n71.link(J,Q)}hV.isSupported=a71.default.stdout;hV.stderr=(J,Q,Z={})=>hV(J,Q,{target:"stderr",...Z});hV.stderr.isSupported=a71.default.stderr;W0();qq();class Ry1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1760127338-g8601e4"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await E80(Q,this.configService)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}W0();class r71 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class zQ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function hZ6(J){if(J instanceof r71)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zQ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var lV=null,nX9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(lV)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (_b1(),LJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{lV=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});lV=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{lV=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/clients/${Y}/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => P6(Df1(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){l.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new zQ(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!lV)return new zQ("Not connected to Amp web interface");try{lV.disconnect();let Z=lV.clientID;return lV=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new zQ(`Disconnected from Amp web interface
5873
+ ... (output truncated at ${yH} 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 X59(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return K59(Z,X?[...X]:null,Y,Q);else return Y59(Z,X?[...X]:null,Y,Q)}function Y59(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function K59(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]}}W0();bE();Oj();a2();PN();qq();kW();p6();S0();import{mkdtemp as cX9,readFile as lX9,unlink as iX9,writeFile as XR2}from"fs/promises";var n71={};A6(n71,{scrollUp:()=>E59,scrollDown:()=>I59,link:()=>k59,image:()=>_59,iTerm:()=>x59,exitAlternativeScreen:()=>S59,eraseUp:()=>$59,eraseStartLine:()=>O59,eraseScreen:()=>Dy1,eraseLines:()=>R59,eraseLine:()=>SZ6,eraseEndLine:()=>w59,eraseDown:()=>j59,enterAlternativeScreen:()=>C59,cursorUp:()=>TZ6,cursorTo:()=>z59,cursorShow:()=>A59,cursorSavePosition:()=>B59,cursorRestorePosition:()=>D59,cursorPrevLine:()=>N59,cursorNextLine:()=>V59,cursorMove:()=>U59,cursorLeft:()=>CZ6,cursorHide:()=>L59,cursorGetPosition:()=>M59,cursorForward:()=>F59,cursorDown:()=>W59,cursorBackward:()=>H59,clearTerminal:()=>T59,clearScreen:()=>P59,beep:()=>v59});import My1 from"node:process";var i71=globalThis.window?.document!==void 0,GL2=globalThis.process?.versions?.node!==void 0,zL2=globalThis.process?.versions?.bun!==void 0,UL2=globalThis.Deno?.version?.deno!==void 0,WL2=globalThis.process?.versions?.electron!==void 0,FL2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,HL2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,BL2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,DL2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,ML2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Eu=globalThis.navigator?.userAgentData?.platform,VL2=Eu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",NL2=Eu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",LL2=Eu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",AL2=Eu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),RL2=Eu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var U2="\x1B[",Pu="\x1B]",GC="\x07",Iu=";",PZ6=!i71&&My1.env.TERM_PROGRAM==="Apple_Terminal",q59=!i71&&My1.platform==="win32",G59=i71?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:My1.cwd,z59=(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)+Iu+(J+1)+"H"},U59=(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},TZ6=(J=1)=>U2+J+"A",W59=(J=1)=>U2+J+"B",F59=(J=1)=>U2+J+"C",H59=(J=1)=>U2+J+"D",CZ6=U2+"G",B59=PZ6?"\x1B7":U2+"s",D59=PZ6?"\x1B8":U2+"u",M59=U2+"6n",V59=U2+"E",N59=U2+"F",L59=U2+"?25l",A59=U2+"?25h",R59=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=SZ6+(Z<J-1?TZ6():"");if(J)Q+=CZ6;return Q},w59=U2+"K",O59=U2+"1K",SZ6=U2+"2K",j59=U2+"J",$59=U2+"1J",Dy1=U2+"2J",E59=U2+"S",I59=U2+"T",P59="\x1Bc",T59=q59?`${Dy1}${U2}0f`:`${Dy1}${U2}3J${U2}H`,C59=U2+"?1049h",S59=U2+"?1049l",v59=GC,k59=(J,Q)=>[Pu,"8",Iu,Iu,Q,GC,J,Pu,"8",Iu,Iu,GC].join(""),_59=(J,Q={})=>{let Z=`${Pu}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")+GC},x59={setCwd:(J=G59())=>`${Pu}50;CurrentDir=${J}${GC}`,annotation(J,Q={}){let Z=`${Pu}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+GC}};var a71=P6(fZ6(),1);function hV(J,Q,{target:Z="stdout",...X}={}){if(!a71.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return n71.link(J,Q)}hV.isSupported=a71.default.stdout;hV.stderr=(J,Q,Z={})=>hV(J,Q,{target:"stderr",...Z});hV.stderr.isSupported=a71.default.stderr;W0();qq();class Ry1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1760140901-g5719d0"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await E80(Q,this.configService)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}W0();class r71 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class zQ{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function hZ6(J){if(J instanceof r71)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zQ)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var lV=null,nX9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(lV)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (_b1(),LJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{lV=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});lV=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{lV=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/clients/${Y}/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => P6(Df1(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){l.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new zQ(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!lV)return new zQ("Not connected to Amp web interface");try{lV.disconnect();let Z=lV.clientID;return lV=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new zQ(`Disconnected from Amp web interface
5874
5874
  Client ID: ${Z}
5875
5875
  Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Mf1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=lC(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Ry1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(I0((Z)=>Z.settings["internal.modes"]),U8()).subscribe((Z)=>{this._initBaseCommands(Z??!1)})}_initBaseCommands(J){if(this.commands={...aX9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,nX9);if(J)Object.assign(this.commands,rX9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{l.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await By1(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 aX9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${T5} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:f80}]}});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 r71;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(new AbortController().signal)}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 cX9(aY6.join(dX9(),"amp-edit-")),Y=aY6.join(X,"message.amp.md");nY6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await lX9(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return l.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await iX9(Y),await pX9(X)}catch(K){l.warn("Failed to clean up temporary file",K)}return}catch(Z){return l.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return oU("dangerouslyAllowAll",!1),new zQ("Amp is now following permissions rules for this session")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return oU("dangerouslyAllowAll",!0),new zQ("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await KC();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw l.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:KC};await d71(Y);return}catch(Y){l.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return l.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zQ(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return l.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
5876
5876
  `).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=lk(new URL(Y),Z.id).toString(),G=`Thread URL: ${hV(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 zQ(`${G}
@@ -6066,13 +6066,13 @@ ${this.stateNotifier.value.getDownloadPath()}.`,new v1({color:Q.colorScheme.fore
6066
6066
  https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_disk`,new v1({color:Q.colorScheme.foreground}))}),new _0({height:1}),new Z0({text:new O1(`Finally restart your JetBrains IDE${!OG()&&" and Amp"}.`,new v1({color:Q.colorScheme.foreground}))}),new _0({height:1}),new Z0({text:new O1("Press any key to exit...",new v1({color:Q.colorScheme.foreground,dim:!0}))})]})})});return new Y9({autofocus:!0,onKey:(U)=>{return this.widget.onExit(),"handled"},child:z})}return new S6({decoration:new c9(Q.colorScheme.background),child:new l6({padding:a0.all(2),child:new Z0({text:new O1("Discovering JetBrains IDEs...",new v1({color:Q.colorScheme.foreground}))})})})}}function _W9(J){let Q=J.reduce((Z,X)=>{return(Z[X.name]??=[]).push(X),Z},{});return Object.entries(Q).map(([Z,X])=>({name:Z,versions:X.map((Y)=>Y.version).sort()}))}function xW9(J){if(J.length<=1)return"";if(J.length>=3)return` (${J[0]}-${J.at(-1)})`;return` (${J.join(", ")})`}F9();_9();class bm1 extends G6{color;trigger;trail;fps;speed;leftOffset;constructor({key:J,color:Q,trigger:Z,trail:X=5,fps:Y=60,speed:K=1,leftOffset:q=0}){super(J?{key:J}:{});this.color=Q,this.trigger=Z,this.trail=X,this.fps=Y,this.speed=K,this.leftOffset=q}createState(){return new CU6}}class CU6 extends q6{progress=0;timer=null;initState(){this.restart()}didUpdateWidget(J){if(J.trigger!==this.widget.trigger)this.restart()}dispose(){this.stop()}restart(){this.stop(),this.progress=-this.widget.trail,this.start()}start(){if(this.timer)return;let J=Math.max(16,Math.round(1000/Math.max(1,this.widget.fps)));this.timer=setInterval(()=>{this.setState(()=>{this.progress+=this.widget.speed})},J)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}build(J){return new SU6({color:this.widget.color,trail:this.widget.trail,head:this.progress,leftOffset:this.widget.leftOffset},this.widget.key)}}class SU6 extends mH{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new aV(this)}createRenderObject(){return new vU6(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}updateRenderObject(J){J.update(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}}class vU6 extends o6{_color;_trail;_head;_leftOffset;constructor(J,Q,Z,X){super();this._color=J;this._trail=Q;this._head=Z;this._leftOffset=X}update(J,Q,Z,X){let Y=!1;if(Q!==this._trail)this._trail=Q,Y=!0;if(this._color=J,this._head=Z,this._leftOffset=X,Y)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Q=J.constrain(J.biggest.width,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y),K=Math.floor(this.size.width),q=[1,0.7,0.5,0.35,0.25,0.15];for(let G=0;G<=this._trail&&G<q.length;G++){let z=Math.floor(this._head)-G+this._leftOffset;if(z<this._leftOffset||z>=K)continue;let U=bW9(this._color,q[G]);J.setChar(X+z,Y,"━",{fg:U},1)}super.paint(J,Q,Z)}}function bW9(J,Q){if(J.type==="rgb")return k1.rgb(J.value.r,J.value.g,J.value.b,Q);if(J.type==="index")return k1.index(J.value,Q);return k1.default(Q)}class ym1 extends b6{message;onDismiss;constructor({key:J,message:Q,onDismiss:Z}){super({key:J});this.message=Q,this.onDismiss=Z}build(J){let Z=z8.of(J).colorScheme,X=hZ6(this.message),Y=[{value:"dismiss",label:"Dismiss"}],K=X.type==="error"?Z.destructive:Z.primary;return new GY({title:X.title,body:nf1({text:X.description}),options:Y,onSelect:(q)=>{this.onDismiss()},borderColor:K,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}}F9();class fm1 extends b6{url;qrCode;constructor({key:J,url:Q,qrCode:Z}){super(J?{key:J}:{});this.url=Q,this.qrCode=Z}build(J){let Z=z8.of(J).colorScheme,X=v8.of(J),Y=new v1({color:k1.rgb(0,0,0)}),K=new v1({color:Z.foreground}),q=new v1({color:Z.foreground}),G=new v1({color:Z.secondary,bold:!0}),z=X.size.width,U=X.size.height,W=z-4,F=Math.min(U-4,Math.floor(U*0.8)),H=Math.min(60,W),B=new CG({autofocus:!0,child:new l6({padding:a0.only({left:2,right:2}),child:new V6({crossAxisAlignment:"center",children:[new _2({child:new S6({decoration:new c9(k1.rgb(255,255,255)),padding:a0.all(2),child:new Z0({text:new O1(this.qrCode,Y),textAlign:"left"})})}),new _0({height:1}),new _2({child:new Z0({text:new O1(`Continue at ${this.url}`,K)})}),new _0({height:1})]})})}),M=new _2({child:new Z0({text:new O1("",q,[new O1("Press ",q),new O1("Escape",G),new O1(" to close",q)])})}),V=new V6({crossAxisAlignment:"stretch",children:[new t9({child:B}),M]});return new _2({child:new S6({constraints:new E6(H,H,0,F),decoration:new c9(Z.background,W2.all(new F2(Z.primary,1,"rounded"))),child:V})})}}_9();class hm1 extends G6{props;constructor(J){super({key:J.key});this.props=J}createState(){return new kU6}}class kU6 extends q6{build(J){let{queuedMessages:Q,title:Z="Queue"}=this.widget.props;if(!Array.isArray(Q)||Q.length===0)return new _0({width:0,height:0});let X=Q.map((Y)=>this.buildQueueItem(Y));return new S6({child:new l6({padding:a0.symmetric(1,0),child:new V6({crossAxisAlignment:"stretch",children:[new Z0({text:new O1(Z,new v1({bold:!0}))}),...X]})})})}buildQueueItem(J){let Z=J.queuedMessage.content.filter((q)=>q.type==="text").map((q)=>q.text).join(" ").trim(),X=Z.split(`
6067
6067
  `)[0],Y=Z.includes(`
6068
6068
  `)?`${X}...`:Z,K=new v1({color:k1.index(8)});return new l6({padding:a0.only({bottom:0}),child:new o8({crossAxisAlignment:"start",children:[new l6({padding:a0.only({right:1}),child:new Z0({text:new O1("•",new v1({color:k1.index(8)}))})}),new t9({child:new Z0({text:new O1(Y,K)})})]})})}}QW();var yW9=Q1.string(),_U6=Q1.object({id:yW9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","public","thread_workspace_shared"]),sharedGroupIDs:Q1.array(Q1.string())})});W0();qq();QW();var fW9=Q1.object({id:Q1.string()});function hW9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/3600000),Y=Math.floor(X/24),K=Math.floor(Y/7),q=Math.floor(Y/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Y<7)return`${Y}d ago`;if(K<=4)return`${K}w ago`;return`${q}mo ago`}class SJ1{configService;constructor(J){this.configService=J}async fetchThreadSummaries(J="",Q=0,Z=20){try{let X=await C5("/api/user",void 0,this.configService);if(!X.ok)return{ok:!1,errorMsg:`Failed to get user info (${X.status})`};let Y;try{Y=fW9.parse(await X.json())}catch(W){return{ok:!1,errorMsg:"Invalid user data format from server"}}let K=new URLSearchParams({createdByUserID:Y.id,limit:String(Z),offset:String(Q*Z)}),q=await C5(`/api/threads?${K}`,void 0,this.configService);if(!q.ok)return{ok:!1,errorMsg:`Failed to fetch threads (${q.status})`};let G;try{G=Q1.array(_U6).parse(await q.json())}catch(W){return l.error("failed to parse thread data from server",{error:W}),{ok:!1,errorMsg:"Invalid thread data format from server"}}return{ok:!0,threads:G.filter((W)=>W.messageCount>0).filter((W)=>{if(!J.trim())return!0;let F=W.title?.toLowerCase()||"untitled",H=W.id.toLowerCase(),B=J.toLowerCase();return F.includes(B)||H.includes(B)}).slice(0,Z).map((W)=>{let F=W.title||"Untitled",H=new Date(W.updatedAt),B=hW9(H),M=W.id.slice(-8);return{id:W.id,title:F,messageCount:W.messageCount,updatedAt:W.updatedAt,description:{timeAgo:B,title:F,shortThreadID:M}}})}}catch(X){return{ok:!1,errorMsg:X instanceof Error?X.message:"An unexpected error occurred"}}}}_9();class gm1 extends G6{props;constructor(J){super();this.props=J}createState(){return new xU6(this.props.pageSize,this.props.loadBuffer,this.props.autofocus??!0)}}class xU6 extends q6{pageSize;loadBuffer;autofocus;allThreads=[];isLoading=!1;currentPage=0;hasMoreToLoad=!0;error=null;constructor(J=20,Q=J*2,Z){super();this.pageSize=J;this.loadBuffer=Q;this.autofocus=Z}async initState(){await this.loadThreads()}async loadThreads(){if(this.isLoading||!this.hasMoreToLoad)return;this.isLoading=!0,this.error=null;try{let J=await this.widget.props.threadFetcher.fetchThreadSummaries("",this.currentPage,this.pageSize);if(!this.mounted)return;if(!J.ok){this.error=J.errorMsg,this.hasMoreToLoad=!1,this.setState();return}let Q=J.threads;if(Q.length===0)this.hasMoreToLoad=!1;else{let Z=new Set(this.allThreads.map((Y)=>Y.id)),X=Q.filter((Y)=>!Z.has(Y.id));this.allThreads=[...this.allThreads,...X],this.currentPage++}this.setState()}finally{this.isLoading=!1}}onChange=async(J)=>{if(this.allThreads.length-J<=this.loadBuffer&&this.hasMoreToLoad&&!this.isLoading)await this.loadThreads()};formatThreadDescription(J){let Z=`${String(J.messageCount)} msgs`.padEnd(8),X=J.description.timeAgo.padEnd(9);return`${Z} │ ${X}│ ${J.description.shortThreadID}`}build(J){let Q=(q)=>{if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"};if(this.error)return new Y9({autofocus:this.autofocus,onKey:Q,child:new Z0({text:new O1(this.error)})});if(this.isLoading&&this.allThreads.length===0)return new Y9({autofocus:this.autofocus,onKey:Q,child:new Z0({text:new O1("Loading threads...")})});let Z=v8.sizeOf(J);if(this.allThreads.length===0&&!this.isLoading)return new Y9({autofocus:this.autofocus,onKey:Q,child:new Z0({text:new O1("No threads found.")})});let X=this.allThreads.map((q)=>({value:q.id,label:q.title,description:this.formatThreadDescription(q)})),Y=Math.max(5,Z.height);Y-=6;let K=Math.floor(Math.max(1,Y/2));return new Y9({autofocus:this.autofocus,onKey:Q,child:new $p({title:"Select a thread to continue:",options:X,onSelect:(q)=>{this.widget.props.onSelect(q)},onChange:this.onChange,maxVisibleItems:K,autofocus:this.autofocus})})}}w71();var bU6="You have invoked an experimental model. To use this model, you must enable training mode, which will allow all of your threads to be used for model training. Do not accept this if you would prefer your data not be used for training.";var yU6="https://ampcode.com/security#model-training";_9();class mm1 extends G6{onResponse;constructor({key:J,onResponse:Q}){super({key:J});this.onResponse=Q}createState(){return new fU6}}class fU6 extends q6{initState(){super.initState()}dispose(){super.dispose()}build(J){let Z=z8.of(J).colorScheme,X="Experimental Model Warning",Y=`${bU6} See ${yU6} for details.`;return new hU6({title:"Experimental Model Warning",body:Y,options:[{value:"reject",label:"Reject"},{value:"accept",label:"Turn on Training Mode"}],onSelect:(q)=>{this.widget.onResponse(q==="accept")},borderColor:Z.warning,selectedIndex:0,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}}class hU6 extends G6{options;onSelect;title;body;borderColor;selectedIndex;autofocus;showDismissalMessage;enableMouseInteraction;constructor({key:J,options:Q,onSelect:Z,title:X,body:Y,borderColor:K=k1.index(8),selectedIndex:q=0,autofocus:G=!0,showDismissalMessage:z=!0,enableMouseInteraction:U=!0}){super({key:J});this.options=Q,this.onSelect=Z,this.title=X,this.body=Y,this.borderColor=K,this.selectedIndex=q,this.autofocus=G,this.showDismissalMessage=z,this.enableMouseInteraction=U}createState(){return new gU6}}class gU6 extends q6{focusNode=new N2({debugLabel:"TrainingModeSelect"});initState(){super.initState(),this.focusNode.addKeyHandler(this.handleKeyEvent.bind(this))}dispose(){this.focusNode.dispose(),super.dispose()}handleKeyEvent(J){if(J.key==="Escape"&&!J.shiftKey&&!J.ctrlKey&&!J.altKey&&!J.metaKey)return this.widget.onSelect("reject"),"handled";return"ignored"}build(J){let Q=new GY({title:this.widget.title,body:this.widget.body,options:this.widget.options,onSelect:this.widget.onSelect,borderColor:this.widget.borderColor,selectedIndex:this.widget.selectedIndex,autofocus:this.widget.autofocus,showDismissalMessage:this.widget.showDismissalMessage,enableMouseInteraction:this.widget.enableMouseInteraction});return new Y9({focusNode:this.focusNode,child:Q,autofocus:this.widget.autofocus})}}class um1{detect(J,Q){if(!J||Q<1)return null;let Z=E2(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
6069
- `))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class pm1{detect(J,Q){if(!J||Q<1)return null;let Z=E2(J);if(Q>Z.length)return null;if(Z[0]!=="/")return null;let X=Z.slice(1,Q).join("");return{start:0,end:Q,query:X,trigger:"/"}}}class mU6{triggers;constructor(J){this.triggers=J}detect(J,Q){for(let Z of this.triggers){let X=Z.detect(J,Q);if(X)return X}return null}}function dm1(){return new mU6([new um1,new pm1])}function uU6(J,Q){switch(J){case"update-available":return[new O1("A newer Amp is available. Run ",new v1({color:Q.foreground,dim:!0})),new O1("amp update",new v1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new O1("Update complete, run ",new v1({color:Q.foreground,dim:!0})),new O1("amp update",new v1({color:Q.warning})),new O1(" to see warnings",new v1({color:Q.foreground,dim:!0}))];case"update-error":return[new O1("Update failed, run ",new v1({color:Q.foreground,dim:!0})),new O1("amp update",new v1({color:Q.warning})),new O1(" to see warnings",new v1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function mW9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new v1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new v1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class dU6 extends G6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new cU6}}class cU6 extends q6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;hasBanner=!1;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingAdActionModal=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;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;agentModePulseSeq=0;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;currentAgentMode=void 0;agentModeSubscription=null;hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;updateState="hidden";updateServiceSubscription=null;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;return[...J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued"),...J.subagentActiveTools].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 O1(this.submitDisabledHint,new v1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new O1("",void 0,[new O1("Ctrl+C",new v1({color:Q.keybind})),new O1(" again to exit",new v1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new O1("",void 0,[new O1("Esc",new v1({color:Q.keybind})),new O1(" again to clear input",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new O1("",void 0,[new O1("Escape",new v1({color:Q.keybind})),new O1(" to close help",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingAdActionModal)return new O1("",void 0,[new O1("Escape",new v1({color:Q.keybind})),new O1(" to close",new v1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new O1("",void 0,[new O1("Esc",new v1({color:Q.keybind})),new O1(" to cancel",new v1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new O1("Selection copied to clipboard",new v1({color:J.foreground,dim:!0}));let Z=uU6(this.updateState,J);if(Z)return new O1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new E51;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new CC);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(jf1(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 u4("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=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 Mf1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Dm1(this.getCommands(),this.widget.dependencies.fuzzyServer,new SJ1(this.widget.dependencies.configService));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,!0)}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"};onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{GX.instance.tuiInstance.suspend();let W=await Z(z.join(G(),"amp-edit-")),F=z.join(W,"message.amp.md");await q(F,J,"utf-8"),Q(`${U} "${F}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(F,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")l.error("Failed to read temporary file",H)}try{await Y(F),await K(W)}catch(H){l.warn("Failed to clean up temporary file",H)}GX.instance.tuiInstance.resume()}catch(W){try{GX.instance.tuiInstance.resume()}catch{}l.error("Error opening editor:",W)}};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=RZ6(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();R71(z);return}if(J.launchesWindow)GX.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,configService:this.widget.dependencies.configService,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})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,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 Sn({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}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z})}},Q,X.signal);if(J.launchesWindow)GX.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){l.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=dm1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(SG.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;if(this.widget.dependencies.freeTui){let J=AZ6.filter((Q)=>Q.status==="active");this.randomAd=J[Math.floor(Math.random()*J.length)]??null,this.hasBanner=!0}this.checkFreeTierStatus()}getAdActions(J){let Q=[];if(J.call_to_action==="link_to")Q.push({id:"open_link",label:`Open ${J.destination_url}`});if(J.call_to_action==="custom"&&J.custom_actions)for(let Z of J.custom_actions)Q.push({id:"custom_action",label:Z.text,description:Z.description});return Q.push({id:"dismiss",label:"Dismiss ad"}),Q}handleAdAction(J,Q){if(J==="open_link")import("node:child_process").then(({exec:X})=>{let Y=Q.destination_url,K=process.platform==="darwin"?`open "${Y}"`:process.platform==="win32"?`start "${Y}"`:`xdg-open "${Y}"`;X(K)});else if(J==="custom_action")import("node:child_process").then(({exec:X})=>{let Y=Q.destination_url,K=process.platform==="darwin"?`open "${Y}"`:process.platform==="win32"?`start "${Y}"`:`xdg-open "${Y}"`;X(K)});R71(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((X)=>{this.setState(()=>{this.ideStatus=X})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(X)=>{let Y=xV();if(!Y){l.warn("No active thread worker found to handle IDE message");return}await new Promise((K)=>setTimeout(K,50)),await Y.handle({type:"user:message",message:{content:[{type:"text",text:X}]}}),l.debug("Message sent from IDE to agent",{message:X.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((X)=>{this.textController.insertText(X),l.debug("Appended text to CLI prompt from IDE",{text:X.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((X)=>{this.setState(()=>{this.connectedClientsStatus=X})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((X)=>{this.setState(()=>{this.updateState=X})}),this.agentModeSubscription=this.widget.dependencies.configService.config.pipe(I0((X)=>X.settings["internal.modes"]?fz(X.settings):void 0),U8()).subscribe((X)=>{this.setState(()=>{this.currentAgentMode=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(X,Y)=>{if(X.length<=3)return!0;let K=OZ6(X);if(!K)return!0;if(this.imageAttachments.length>=Xe1)return!1;let q=jZ6(K);if(q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,q]}),!1;return!0},this.updateTerminalTitle();let Z=this.widget.dependencies.ideClient.getSelectedConfig();if(Z)this.connectToSelectedIde(Z).catch((X)=>{let Y=X instanceof Error?X.message:String(X);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})});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.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.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)=>{l.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(jf1("")),this.shouldUseProgressBar())process.stdout.write($f1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((G)=>G.type==="toolResult").map((G)=>({toolUse:G.toolUse,toolRun:G.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((G)=>G.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],q=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:q}}shouldUseProgressBar(){return v8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let J=this.getCurrentConfirmation(),Q="off";if(J)Q="paused";else if(this.isProcessing())Q="indeterminate";if(Q!==this.currentProgressBarState)this.currentProgressBarState=Q,this.sendProgressReport(Q),this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(VK6());break;case"paused":process.stdout.write(NK6());break;case"off":process.stdout.write($f1());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"){l.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){l.error("No tool use block found in confirmation");return}if(J==="allow-all-session")oU("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 l.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)}if(J==="connect-github"){let Y=new URL("/settings#github-app",this.widget.dependencies.ampURL).toString();try{await gU(Y)}catch(K){l.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}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 fJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){l.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=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(new AbortController().signal);break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await fJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J)=>{try{let Q=await this.widget.dependencies.switchToThread(J);this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,R71(Q),A71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{})}catch(Q){throw l.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=xV()||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.inMemoryAgentModeOverride&&{agentMode:this.inMemoryAgentModeOverride}}}),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},{config:this.widget.dependencies.configService});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:
6069
+ `))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class pm1{detect(J,Q){if(!J||Q<1)return null;let Z=E2(J);if(Q>Z.length)return null;if(Z[0]!=="/")return null;let X=Z.slice(1,Q).join("");return{start:0,end:Q,query:X,trigger:"/"}}}class mU6{triggers;constructor(J){this.triggers=J}detect(J,Q){for(let Z of this.triggers){let X=Z.detect(J,Q);if(X)return X}return null}}function dm1(){return new mU6([new um1,new pm1])}function uU6(J,Q){switch(J){case"update-available":return[new O1("A newer Amp is available. Run ",new v1({color:Q.foreground,dim:!0})),new O1("amp update",new v1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new O1("Update complete, run ",new v1({color:Q.foreground,dim:!0})),new O1("amp update",new v1({color:Q.warning})),new O1(" to see warnings",new v1({color:Q.foreground,dim:!0}))];case"update-error":return[new O1("Update failed, run ",new v1({color:Q.foreground,dim:!0})),new O1("amp update",new v1({color:Q.warning})),new O1(" to see warnings",new v1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function mW9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new v1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new v1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class dU6 extends G6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new cU6}}class cU6 extends q6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;hasBanner=!1;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingAdActionModal=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;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;agentModePulseSeq=0;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;currentAgentMode=void 0;agentModeSubscription=null;hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;updateState="hidden";updateServiceSubscription=null;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;return[...J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued"),...J.subagentActiveTools].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 O1(this.submitDisabledHint,new v1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new O1("",void 0,[new O1("Ctrl+C",new v1({color:Q.keybind})),new O1(" again to exit",new v1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new O1("",void 0,[new O1("Esc",new v1({color:Q.keybind})),new O1(" again to clear input",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new O1("",void 0,[new O1("Escape",new v1({color:Q.keybind})),new O1(" to close help",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingAdActionModal)return new O1("",void 0,[new O1("Escape",new v1({color:Q.keybind})),new O1(" to close",new v1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new O1("",void 0,[new O1("Esc",new v1({color:Q.keybind})),new O1(" to cancel",new v1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new O1("Selection copied to clipboard",new v1({color:J.foreground,dim:!0}));let Z=uU6(this.updateState,J);if(Z)return new O1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new E51;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new CC);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(jf1(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 u4("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=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 Mf1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Dm1(this.getCommands(),this.widget.dependencies.fuzzyServer,new SJ1(this.widget.dependencies.configService));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,!0)}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"};onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{GX.instance.tuiInstance.suspend();let W=await Z(z.join(G(),"amp-edit-")),F=z.join(W,"message.amp.md");await q(F,J,"utf-8"),Q(`${U} "${F}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(F,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")l.error("Failed to read temporary file",H)}try{await Y(F),await K(W)}catch(H){l.warn("Failed to clean up temporary file",H)}GX.instance.tuiInstance.resume()}catch(W){try{GX.instance.tuiInstance.resume()}catch{}l.error("Error opening editor:",W)}};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=RZ6(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();R71(z);return}if(J.launchesWindow)GX.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,configService:this.widget.dependencies.configService,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})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,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 Sn({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}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z})}},Q,X.signal);if(J.launchesWindow)GX.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){l.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=dm1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(SG.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;if(this.widget.dependencies.freeTui){let J=AZ6.filter((Q)=>Q.status==="active");this.randomAd=J[Math.floor(Math.random()*J.length)]??null,this.hasBanner=!0}this.checkFreeTierStatus()}getAdActions(J){let Q=[];if(J.call_to_action==="link_to")Q.push({id:"open_link",label:`Open ${J.destination_url}`});if(J.call_to_action==="custom"&&J.custom_actions)for(let Z of J.custom_actions)Q.push({id:"custom_action",label:Z.text,description:Z.description});return Q.push({id:"dismiss",label:"Dismiss ad"}),Q}handleAdAction(J,Q){if(J==="open_link")import("node:child_process").then(({exec:X})=>{let Y=Q.destination_url,K=process.platform==="darwin"?`open "${Y}"`:process.platform==="win32"?`start "${Y}"`:`xdg-open "${Y}"`;X(K)});else if(J==="custom_action")import("node:child_process").then(({exec:X})=>{let Y=Q.destination_url,K=process.platform==="darwin"?`open "${Y}"`:process.platform==="win32"?`start "${Y}"`:`xdg-open "${Y}"`;X(K)});R71(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((X)=>{this.setState(()=>{this.ideStatus=X})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(X)=>{let Y=xV();if(!Y){l.warn("No active thread worker found to handle IDE message");return}await new Promise((K)=>setTimeout(K,50)),await Y.handle({type:"user:message",message:{content:[{type:"text",text:X}]}}),l.debug("Message sent from IDE to agent",{message:X.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((X)=>{this.textController.insertText(X),l.debug("Appended text to CLI prompt from IDE",{text:X.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((X)=>{this.setState(()=>{this.connectedClientsStatus=X})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((X)=>{this.setState(()=>{this.updateState=X})}),this.agentModeSubscription=this.widget.dependencies.configService.config.pipe(I0((X)=>X.settings["internal.modes"]?fz(X.settings):void 0),U8()).subscribe((X)=>{this.setState(()=>{this.currentAgentMode=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(X,Y)=>{if(X.length<=3)return!0;let K=OZ6(X);if(!K)return!0;if(this.imageAttachments.length>=Xe1)return!1;let q=jZ6(K);if(q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,q]}),!1;return!0},this.updateTerminalTitle();let Z=this.widget.dependencies.ideClient.getSelectedConfig();if(Z)this.connectToSelectedIde(Z).catch((X)=>{let Y=X instanceof Error?X.message:String(X);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})});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.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.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)=>{l.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(jf1("")),this.shouldUseProgressBar())process.stdout.write($f1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((G)=>G.type==="toolResult").map((G)=>({toolUse:G.toolUse,toolRun:G.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((G)=>G.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],q=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:q}}shouldUseProgressBar(){return v8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let J=this.getCurrentConfirmation(),Q="off";if(J)Q="paused";else if(this.isProcessing())Q="indeterminate";if(Q!==this.currentProgressBarState)this.currentProgressBarState=Q,this.sendProgressReport(Q),this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(VK6());break;case"paused":process.stdout.write(NK6());break;case"off":process.stdout.write($f1());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"){l.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){l.error("No tool use block found in confirmation");return}if(J==="allow-all-session")oU("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 l.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)}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await gU(Y)}catch(K){l.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}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 fJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){l.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=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(new AbortController().signal);break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await fJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J)=>{try{let Q=await this.widget.dependencies.switchToThread(J);this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,R71(Q),A71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{})}catch(Q){throw l.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=xV()||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.inMemoryAgentModeOverride&&{agentMode:this.inMemoryAgentModeOverride}}}),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},{config:this.widget.dependencies.configService});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:
6070
6070
 
6071
6071
  ${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({},{config:this.widget.dependencies.configService});if(J.ok)await Xj({enabled:J.result.enabled,eligible:J.result.eligible}),this.setState(()=>{})}catch(J){l.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;GX.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=gW9();if(J===Q)return"~";if(J.startsWith(Q+Cp.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Cp.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Cp.sep),"…",Q.slice(-2).join(Cp.sep)].join(Cp.sep)}build(J){let Q=v8.of(J),Z=Q8.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 cH({child:new gm1({onSelect:async(i)=>{if(i)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(i);else process.exit(0)},pageSize:50,threadFetcher:new SJ1(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,W=q.mainThread||void 0,H=this.isTranscriptEmpty()?new BJ1({agentMode:this.inMemoryAgentModeOverride??this.currentAgentMode}):new Um1({key:U?new u4(`message-view-${U}`):void 0,items:q.items,subagentToolsByParentID:q.subagentToolsByParentID,controller:U?this.getMessageScrollController(U):new CC,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:W}),B=Math.max(Math.floor(Q.size.height*0.4),12),M=this.getCurrentEphemeralError(),V=this.buildBottomWidget(M,G,Y,Z,q,z,B),N=Q.size.width<40,L=q.mainThread?qi1(q.mainThread):void 0,A=new h51({threadViewState:q.viewState,threadTokenUsage:L,threadID:U??null,thread:q.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:N,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,isFreeTierEnabled:cm1,isFreeTierEligible:lm1}),R=new f51({bashInvocations:this.bashInvocations}),w=[];if(jY()&&MZ())w.push(new S6({decoration:new c9(Y.secondary),child:new l6({padding:a0.horizontal(1),child:new Z0({text:new O1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:k1.black})),textAlign:"center"})})}));let O=this.inMemoryAgentModeOverride??this.currentAgentMode,j=this.currentShellModeStatus,$=O?pU6(O):void 0,E=O&&!j?O.length+1:0,P=Q.capabilities.animationSupport,T=P==="disabled"?0:P==="slow"?30:60,S=O==="fast"?3:1,x=$&&T>0&&this.agentModePulseSeq>0?new n5({children:[V,new PG({top:0,left:1,right:1,height:1,child:new bm1({color:$,trigger:this.agentModePulseSeq,fps:T,speed:S,leftOffset:E})})]}):V;if(w.push(new t9({child:H}),R),this.hasBanner&&this.randomAd)w.push(new Fm1({ad:this.randomAd,onButtonClick:()=>{this.isShowingAdActionModal=!0,this.setState()}}));w.push(new S6({constraints:new E6(0,Q.size.width,0,B),child:x}),new _0({height:1,child:new l6({padding:a0.horizontal(1),child:A})}));let h=new V6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:w}),v=new j7(()=>{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.isShowingAdActionModal)return this.setState(()=>{this.isShowingAdActionModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingQRCodeOverlay)return this.setState(()=>{this.isShowingQRCodeOverlay=!1,this.qrCodeOverlayData=null}),"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 l.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((a)=>{l.error("Failed to mark message as interrupted:",a)}),this.cancelStreamingMessage().catch((a)=>{l.error("Failed to cancel streaming message:",a)}),"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"}),_=new j7(()=>{return this.onExitPressed(),"handled"}),y=new j7(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),g=new j7(()=>{return _G.instance.toggleAll(),"handled"}),k=new j7(()=>{return this.widget.dependencies.configService.getLatest().then((i)=>{oU("internal.showCost",!(i.settings["internal.showCost"]??!0))}),"handled"}),f=new j7(()=>{return GX.instance.toggleFrameStatsOverlay(),"handled"}),b=new j7(()=>{return GX.instance.tuiInstance.getScreen().markForRefresh(),ZZ.instance.requestFrame(),"handled"}),m=new j7(()=>{let i=this.inMemoryAgentModeOverride??this.currentAgentMode,a=Ai1(i);return this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=a,this.agentModePulseSeq++}),"handled"}),n=new j7(()=>{let i=this.findElementByKey("message-view-selection-area");if(i?.state){let a=i.state,o=a.controller?.copySelection();if(o&&o.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{a.controller.endCopyHighlight(),a.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),u=new j7(()=>{let{threadState:i}=this.widget.dependencies,a=i.mainThread?.id;if(a){let o=this.getMessageScrollController(a),X1=Math.max(Math.floor(Q.size.height*0.4),10),J1=Q.size.height-X1;o.animatePageUp(J1,100)}return"handled"}),e=new j7(()=>{let{threadState:i}=this.widget.dependencies,a=i.mainThread?.id;if(a){let o=this.getMessageScrollController(a),X1=Math.max(Math.floor(Q.size.height*0.4),10),J1=Q.size.height-X1;o.animatePageDown(J1,100)}return"handled"}),G1=new j7(()=>{let{threadState:i}=this.widget.dependencies,a=i.mainThread?.id;if(a)this.getMessageScrollController(a).animateTo(0,100);return"handled"}),F1=new j7(()=>{let{threadState:i}=this.widget.dependencies,a=i.mainThread?.id;if(a)this.getMessageScrollController(a).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),Z1=new Map([[L2.key("Escape"),new eu],[L2.ctrl("c"),new AC],[L2.ctrl("l"),new Yp],[L2.alt("m"),new RC],[L2.ctrl("m"),new RC],[L2.alt("c"),new Jp],[L2.alt("p"),new Xp],[L2.ctrl("r"),new Qp],[L2.alt("d"),new Zp],[L2.key("PageUp"),new L51],[L2.key("PageDown"),new A51],[L2.key("Home"),new R51],[L2.key("End"),new w51]]);if(process.platform==="darwin")Z1.set(L2.meta("c"),new AC);let W1=new Map([[eu,v],[M51,_],[Yp,b],[RC,m],[Jp,y],[Qp,g],[Zp,k],[Xp,f],[AC,n],[L51,u],[A51,e],[R51,G1],[w51,F1]]),p=h;if(this.isShowingConsoleOverlay)p=new n5({children:[p,new Nm1]});if(this.isShowingHelp)p=new n5({children:[p,new Rm1]});if(this.isShowingAdActionModal&&this.randomAd){let i=this.getAdActions(this.randomAd);p=new n5({children:[p,new Hm1({actions:i,onSelect:(a)=>{if(this.isShowingAdActionModal=!1,this.setState(),a&&a!=="dismiss")this.handleAdAction(a,this.randomAd)}})]})}if(this.isShowingFileChangesOverlay)p=new n5({children:[p,new Sh1]});if(this.isShowingCostBreakdownOverlay&&q.mainThread)p=new n5({children:[p,new Lm1({thread:q.mainThread})]});if(this.isShowingConfirmationOverlay)p=new n5({children:[p,new Mm1({details:this.confirmationOverlayContent})]});if(this.isShowingQRCodeOverlay&&this.qrCodeOverlayData)p=new n5({children:[p,new fm1({url:this.qrCodeOverlayData.url,qrCode:this.qrCodeOverlayData.qrCode})]});if(this.isShowingIdePicker)return new cH({child:new hK({actions:W1,child:new rV({shortcuts:Z1,debugLabel:"ide-picker-shortcuts",child:new wm1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode})})})});if(this.isShowingJetBrainsInstaller)return new cH({child:new hK({actions:W1,child:new rV({shortcuts:Z1,debugLabel:"jetbrains-installer-shortcuts",child:new xm1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let d=new oV({onError:(i)=>{this.showErrorMessage(i.message)},child:p});return new cH({child:new hK({actions:W1,child:new rV({shortcuts:Z1,debugLabel:"main-app-shortcuts",child:d})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new Am1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new mm1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Vm1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ym1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=mW9(X),U=new P51({key:this.textFieldKey,controller:this.textController,triggers:[dm1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(T)=>Bm1(T),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,onOpenInEditor:this.onOpenInEditor,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:GX.instance.tuiInstance.clipboard},optionViewBuilder:(T,S,x)=>{let h=x?Z.selection:void 0,v=S.type==="command"?Z.warning:Z.secondary,_=Z.foreground,y=Z.foreground,g,k;switch(S.type){case"command":g="/",k=S.name;break;case"file":g="@",k=S.path;break;case"thread":g="",k=S.title;break;default:g="",k=Bm1(S);break}let f=az6(S),b=new O1(g,new v1({color:v})),m=new O1(k,new v1({color:_})),n=[b,m];if(f){let u=new O1(" - ",new v1({color:y,dim:!0})),e=new O1(f,new v1({color:y,dim:!0}));n.push(u,e)}return new S6({decoration:new c9(h),child:new Z0({text:new O1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),W=Y.mainThread?.queuedMessages??[],F=new Y9({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,B=this.imageAttachments.length>0?new S6({padding:a0.only({bottom:1,left:1}),child:new Z0({text:new O1("",void 0,[new O1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((T,S)=>[new O1(`[image ${S+1}]`,new v1({color:Z.success})),...S<this.imageAttachments.length-1?[new O1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(W)&&W.length>0,N=B?new V6({crossAxisAlignment:"start",children:[B,new t9({child:F})]}):F,L=V?new hm1({queuedMessages:W}):void 0,A=M?new hf1(new Wm1({todos:K}),{clipBehavior:"antiAlias"}):void 0,R=[],w=Y.viewState;if(!this.isSummarizing(w))R.push({text:new O1("",void 0,[new O1("Enter",new v1({color:G.keybind})),new O1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)R.push({text:new O1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:B?1:0});let O=this.inMemoryAgentModeOverride??this.currentAgentMode;if(O&&!H){let T=pU6(O),S=this.hasToggledAgentMode?new O1(O,new v1({color:T})):new O1("",void 0,[new O1(O,new v1({color:T})),new O1(" (toggle with ",new v1({color:Z.foreground,dim:!0})),new O1("Ctrl+M",new v1({color:G.keybind})),new O1(")",new v1({color:Z.foreground,dim:!0}))]);R.push({text:S,position:"top-left",offsetY:0})}let j=Y.mainThread?.metadata?.treeInfo?.uri,$;if(j)$=P0.isUri(j)?j.fsPath:j;else $=process.cwd();let E=this.toHomeRelative($),P=this.shorten(E);return R.push({text:new O1(P,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Rh1({leftChild:N,rightChild1:L,rightChild2:A,maxHeight:q,overlayTexts:R,borderColor:Z.border,hasBanner:this.hasBanner})}}var cm1=void 0,lm1=void 0;async function lU6(J){let X=new fH(!1);q10({getEnabled:()=>cm1??!1,getEligible:()=>lm1??!1,updateState:(H)=>{if(H.enabled!==void 0)cm1=H.enabled;if(H.eligible!==void 0)lm1=H.eligible}});let Y=new Cb1({threadService:J.threadService,worker:J.worker,builder:(H,B)=>{let M=xV(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new dU6({...N,threadState:B})}}),K=new Ih1({configService:J.configService,child:Y}),q=new jh1({configService:J.configService,child:K}),G=new z8({data:dH.default(),child:q}),z=new Q8({data:wC.fromBaseTheme(dH.default()),child:G});try{await yf1(z,{onRootElementMounted:void 0})}finally{}let W=xV()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let H=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
6072
6072
  `),J.stdout.write(`Thread: ${H}
6073
6073
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
6074
6074
  `)}}function pU6(J){return J==="smart"?k1.rgb(3,197,97):J==="fast"?k1.rgb(228,180,2):J==="free"?k1.rgb(59,91,143):uW9(J)}function uW9(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 k1.index(Z[X])}bf1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){X4.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6075
- `)}var nm1=im1.join(Oc1||im1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function iW9(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 eH(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")oU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new $2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${G8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")oU("experimental.agentMode",Q.agentMode)}var nW9=A0.union([A0.object({command:A0.string(),args:A0.array(A0.string()).optional(),env:A0.record(A0.string(),A0.string()).optional()}).strict(),A0.object({url:A0.string()}).strict()]),aW9=A0.record(A0.string(),nW9);async function rm1(J){try{await dW9(im1.dirname(nm1),{recursive:!0}),await cW9(nm1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function rW9(){try{return(await rU6(nm1,"utf-8")).trim()}catch(J){return null}}async function sW9(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 aW9.parse(Q)}catch(Z){if(Z instanceof A0.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 oW9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var iU6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??N5,description:`Custom settings file path (overrides the default location ${N5})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ob1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:OG(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:Qy1(),hidden:!0,description:(J)=>J?"Enable IDE connection. When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:xd}],nU6=(J)=>("deprecated"in J)&&J.deprecated===!0,tW9=(J)=>("hidden"in J)&&J.hidden===!0,eW9=(J)=>("default"in J),JF9=(J)=>("default"in J)?J.default:void 0;function QF9(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(_K.unknownCommand(Z),1,q)}}var sU6=null;function er2(){return sU6}function kJ1(J){return{...J,getThreadEnvironment:M71,vfs:R20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Z_(J.fileSystem),generateThreadTitle:uq0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var sm1=P0.file(lW9.homedir()),oU6=process.env.XDG_CONFIG_HOME?P0.file(process.env.XDG_CONFIG_HOME):d0.joinPath(sm1,".config");async function JB(J,Q){Ni1("0.0.1760127338-g8601e4");let Z=_Z1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([P0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:wb1,homeDir:sm1,userConfigDir:oU6}),X=await Z.getLatest();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=rn(XO({configService:Z})),K=s90({configService:Z,toolService:Y}),q=Lw0(Y,f9,Ee).catch((A)=>{l.warn("Toolbox registration failed, continuing anyway:",A)}),G=K.initialized.catch((A)=>{l.warn("MCP service initialization failed, continuing anyway:",A)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)qO("JetBrains");else if(Q.ide&&Qy1())qO("VS Code");else if(Q.ide&&wQ6())qO("Neovim");N96(Y,{configService:Z});let z,U=l7.status.pipe(I0((A)=>Boolean(A.connected&&A.authenticated)),U8()).subscribe((A)=>{if(A){if(!z)z=Y.registerTool(cr)}else z?.dispose(),z=void 0}),W;if(!J.executeMode)W=new S71(process.cwd(),{},!0);else W=new class extends S71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(i2.write(`No API key found. Starting login flow...
6075
+ `)}var nm1=im1.join(Oc1||im1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function iW9(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 eH(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")oU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new $2("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${G8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")oU("experimental.agentMode",Q.agentMode)}var nW9=A0.union([A0.object({command:A0.string(),args:A0.array(A0.string()).optional(),env:A0.record(A0.string(),A0.string()).optional()}).strict(),A0.object({url:A0.string()}).strict()]),aW9=A0.record(A0.string(),nW9);async function rm1(J){try{await dW9(im1.dirname(nm1),{recursive:!0}),await cW9(nm1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function rW9(){try{return(await rU6(nm1,"utf-8")).trim()}catch(J){return null}}async function sW9(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 aW9.parse(Q)}catch(Z){if(Z instanceof A0.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 oW9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var iU6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??N5,description:`Custom settings file path (overrides the default location ${N5})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ob1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:OG(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:Qy1(),hidden:!0,description:(J)=>J?"Enable IDE connection. When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:xd}],nU6=(J)=>("deprecated"in J)&&J.deprecated===!0,tW9=(J)=>("hidden"in J)&&J.hidden===!0,eW9=(J)=>("default"in J),JF9=(J)=>("default"in J)?J.default:void 0;function QF9(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(_K.unknownCommand(Z),1,q)}}var sU6=null;function er2(){return sU6}function kJ1(J){return{...J,getThreadEnvironment:M71,vfs:R20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Z_(J.fileSystem),generateThreadTitle:uq0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var sm1=P0.file(lW9.homedir()),oU6=process.env.XDG_CONFIG_HOME?P0.file(process.env.XDG_CONFIG_HOME):d0.joinPath(sm1,".config");async function JB(J,Q){Ni1("0.0.1760140901-g5719d0");let Z=_Z1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([P0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:wb1,homeDir:sm1,userConfigDir:oU6}),X=await Z.getLatest();l.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=rn(XO({configService:Z})),K=s90({configService:Z,toolService:Y}),q=Lw0(Y,f9,Ee).catch((A)=>{l.warn("Toolbox registration failed, continuing anyway:",A)}),G=K.initialized.catch((A)=>{l.warn("MCP service initialization failed, continuing anyway:",A)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)qO("JetBrains");else if(Q.ide&&Qy1())qO("VS Code");else if(Q.ide&&wQ6())qO("Neovim");N96(Y,{configService:Z});let z,U=l7.status.pipe(I0((A)=>Boolean(A.connected&&A.authenticated)),U8()).subscribe((A)=>{if(A){if(!z)z=Y.registerTool(cr)}else z?.dispose(),z=void 0}),W;if(!J.executeMode)W=new S71(process.cwd(),{},!0);else W=new class extends S71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(i2.write(`No API key found. Starting login flow...
6076
6076
  `),!await ZF9(J))await iR(),process.exit(1)}let F=await E20({isDevelopment:!1}),H=new RH1(F),B=new LH1(F,Z,{lazy:!0}),M=Q.notifications!==void 0?Q.notifications:!J.executeMode,V=A96({playNotificationSound:async(A)=>{if(M){L96(A);let R=_f1(),w=xf1();if((!R||w)&&X.settings["notifications.system.enabled"]!==!1){if(A==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(A==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:H,configService:Z});l.info("Starting Amp background services");let N=_20({threadService:H,threadHistoryService:B,configService:Z,isExtensionDevelopment:!1}),L={configService:Z,toolService:Y,mcpService:K,threadService:H,threadHistoryService:B,threadSyncService:N,threadStorage:F,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:W,notificationService:V,fileSystem:Q.jetbrains||Q.ide?N20:f9};return{...L,async asyncDispose(){await L.mcpService.dispose(),await L.threadService.asyncDispose(),L.configService.unsubscribe(),L.toolService.dispose(),L.fuzzyServer.dispose(),L.threadSyncService.dispose(),L.settingsStorage[Symbol.dispose](),U.unsubscribe(),z?.dispose()}}}async function ZF9(J){if(!J.executeMode){if(!await Uy1("Would you like to log in to Amp? [(y)es, (n)o]: "))return i2.write(`Login cancelled. Run the command again to retry.
6077
6077
  `),!1}return await tU6(J)}async function tU6(J){let Q=pW9(32).toString("hex"),Z=await zy1(J.ampURL,Q);try{await gU(Z)}catch(Y){l.error("Failed to open browser",{error:Y})}let X=await zy1(J.ampURL,Q,!1);i2.write(`If your browser did not open automatically, visit:
6078
6078
 
@@ -6082,12 +6082,12 @@ ${G8.blue.bold(X)}
6082
6082
  Login successful! You can now use the Amp CLI.
6083
6083
  `),!0}catch(Y){return l.error("Login failed",{error:Y}),X4.write(`
6084
6084
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6085
- `),!1}}function XF9(){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)aR(),process.exit(0);let H=F.originalError??F;wJ6(H)}),J.option("-V, --version","output the version number",()=>{i2.write(`0.0.1760127338-g8601e4 (released 2025-10-10T20:20:42.562Z)
6086
- `),process.exit(0)}),J.addHelpText("after",LQ6()),J.configureHelp({formatHelp:AQ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await zY(B);await GF9(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 zY(B);await qF9(M,await rb1(B,M.settings))});let Q=async(F,H,B)=>{_Z1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:e1.of([P0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:sm1,userConfigDir:oU6});let M={...H,executeMode:!1};await am1(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 zY(B);await aU6(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 zY(B);await DF9(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 zY(M);if(H.pick)await Q(M,V,B);else await BF9(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 zY(M);await HF9(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 zY(B);await aU6(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 zY(M);await FF9(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 zY(M);await WF9(M,V,F,B)}),LZ6(J,async(F,H)=>{let B=await zY(H);eH(F,H);let M=await JB(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:aR,asyncDispose:M.asyncDispose.bind(M)}}),aQ6(J),uQ6(J,async(F)=>{let H=await zY(F);return{settings:H.settings,getThreadDeps:async(B)=>{eH(B,F);let M=await JB(H,F);return{mcpService:M.mcpService,asyncDispose:M.asyncDispose.bind(M)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await zY(B);eH(H,B);let V=await JB(M,B);try{await kb1(V,V.configService,{})}finally{await V.asyncDispose(),await aR()}});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 Xy1(F.force||!1,F.verbose||!1,"0.0.1760127338-g8601e4"),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 EV(H,V),L=JF9(F);if(L)N.default(L);if(N.hidden=tW9(F)||nU6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of iU6)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 EV("-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 EV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new EV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let G=new EV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(G);let z=new EV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new EV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await zY(B);if(Object.keys(B).forEach((V)=>{let N=iU6.find((L)=>L.name===V);if(N&&nU6(N)&&!eW9(N))X4.write(G8.yellow(`Warning: '--${V}' flag is deprecated
6085
+ `),!1}}function XF9(){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)aR(),process.exit(0);let H=F.originalError??F;wJ6(H)}),J.option("-V, --version","output the version number",()=>{i2.write(`0.0.1760140901-g5719d0 (released 2025-10-11T00:07:44.809Z)
6086
+ `),process.exit(0)}),J.addHelpText("after",LQ6()),J.configureHelp({formatHelp:AQ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await zY(B);await GF9(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 zY(B);await qF9(M,await rb1(B,M.settings))});let Q=async(F,H,B)=>{_Z1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:e1.of([P0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:sm1,userConfigDir:oU6});let M={...H,executeMode:!1};await am1(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 zY(B);await aU6(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 zY(B);await DF9(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 zY(M);if(H.pick)await Q(M,V,B);else await BF9(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 zY(M);await HF9(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 zY(B);await aU6(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 zY(M);await FF9(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 zY(M);await WF9(M,V,F,B)}),LZ6(J,async(F,H)=>{let B=await zY(H);eH(F,H);let M=await JB(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:aR,asyncDispose:M.asyncDispose.bind(M)}}),aQ6(J),uQ6(J,async(F)=>{let H=await zY(F);return{settings:H.settings,getThreadDeps:async(B)=>{eH(B,F);let M=await JB(H,F);return{mcpService:M.mcpService,asyncDispose:M.asyncDispose.bind(M)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await zY(B);eH(H,B);let V=await JB(M,B);try{await kb1(V,V.configService,{})}finally{await V.asyncDispose(),await aR()}});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 Xy1(F.force||!1,F.verbose||!1,"0.0.1760140901-g5719d0"),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 EV(H,V),L=JF9(F);if(L)N.default(L);if(N.hidden=tW9(F)||nU6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of iU6)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 EV("-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 EV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new EV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let G=new EV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(G);let z=new EV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let F=new EV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await zY(B);if(Object.keys(B).forEach((V)=>{let N=iU6.find((L)=>L.name===V);if(N&&nU6(N)&&!eW9(N))X4.write(G8.yellow(`Warning: '--${V}' flag is deprecated
6087
6087
  `))}),H.args.length>0)QF9(M,H);await am1(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 UF9(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 zF9(F.version)});return J.addCommand(W),J}async function vJ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??rK(),K=kJ1(J);if(Z)await J.threadStorage.set(Y,Z);let q=await fJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,u71(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(d7(z,"assistant"))await rm1(Y),G.unsubscribe()});return await q.resume(),q}async function am1(J,Q,Z){let X=m71(Q);if(X instanceof Error)zX(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let R=(await Wy1()).trimEnd();if(R)K=R}else Y=(await Wy1()).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&&Y===""&&!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"
6088
6088
  Or pipe via stdin: echo "your message" | amp --execute`);eH(Z,Q);let q=await JB(J,Q);sU6=q;let G=kJ1(q),z=async(R)=>{let w=await rU6(R,"utf-8"),O=JSON.parse(w);if(!XW(O.id))throw new $2(_K.invalidThreadId);return vJ1(q,{visibility:X,thread:O})},U=async(R)=>{if(!XW(R))throw new $2(_K.invalidThreadId);let w=await q.threadService.get(R)??void 0;return vJ1(q,{visibility:X,thread:w})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return vJ1(q,{visibility:X})}catch(R){if(R instanceof $2)throw R;throw await O71(R,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return vJ1(q,{visibility:X})};if(Q.format==="jsonl")X4.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6089
- `),await iR(),process.exit(1);if(J.executeMode&&Q.remote)await rQ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await vJ6(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await ha1();let R=await wO({jetbrainsOnly:Q.jetbrains});if(R.length===0)if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall");else l7.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(R.length===1){let w=R[0];if(w)l7.selectConfig(w)}else B=!0}let V=qy1("0.0.1760127338-g8601e4",q.settingsStorage),N=e1.of([P0.file(process.cwd())]),L=lC(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await q.configService.getLatest();await lU6({stdout:process.stdout,history:new yb1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:_J,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:l7,connectedClientsService:new yd,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,freeTui:"freeTui"in Q?Boolean(Q.freeTui):!1}),await q.asyncDispose(),process.exit(0)}async function zY(J){if(J.interactive)X4.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6090
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=await yU(J.settingsFile),K=fU({...J,settingsFile:Y,getHook:process.env.AMP_URL?(z,U)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(await oQ6(K),await tQ6(K),J.mcpConfig){let z=await sW9(J.mcpConfig);K=oW9(K,z)}let q=await K.get("url","global");if(!q)q=qZ;if(!qB(q))l.info("Targeting custom Amp server",{ampURL:q});if(K=cc1(K),await K.get("debug.httpLogging"))uc1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:q,settings:K,secrets:sQ6(await rb1(J,K))}}function YF9(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 KF9(){let J=YF9(process.argv);if(XJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),iW9(l),l.info("Starting Amp CLI.",{version:"0.0.1760127338-g8601e4",buildTimestamp:"2025-10-10T20:20:42.562Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new $2(_K.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await XF9().parseAsync(process.argv)}KF9().catch(O71);async function qF9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),i2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6089
+ `),await iR(),process.exit(1);if(J.executeMode&&Q.remote)await rQ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await vJ6(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await ha1();let R=await wO({jetbrainsOnly:Q.jetbrains});if(R.length===0)if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall");else l7.sendStatus({enabled:!0,connected:!1,authenticated:!1});else if(R.length===1){let w=R[0];if(w)l7.selectConfig(w)}else B=!0}let V=qy1("0.0.1760140901-g5719d0",q.settingsStorage),N=e1.of([P0.file(process.cwd())]),L=lC(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await q.configService.getLatest();await lU6({stdout:process.stdout,history:new yb1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:_J,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:l7,connectedClientsService:new yd,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,debugWidgetTree:Q.debugWidgetTree,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,freeTui:"freeTui"in Q?Boolean(Q.freeTui):!1}),await q.asyncDispose(),process.exit(0)}async function zY(J){if(J.interactive)X4.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6090
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=await yU(J.settingsFile),K=fU({...J,settingsFile:Y,getHook:process.env.AMP_URL?(z,U)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return U()}:void 0});if(await oQ6(K),await tQ6(K),J.mcpConfig){let z=await sW9(J.mcpConfig);K=oW9(K,z)}let q=await K.get("url","global");if(!q)q=qZ;if(!qB(q))l.info("Targeting custom Amp server",{ampURL:q});if(K=cc1(K),await K.get("debug.httpLogging"))uc1();return{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:q,settings:K,secrets:sQ6(await rb1(J,K))}}function YF9(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 KF9(){let J=YF9(process.argv);if(XJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),iW9(l),l.info("Starting Amp CLI.",{version:"0.0.1760140901-g5719d0",buildTimestamp:"2025-10-11T00:07:44.809Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new $2(_K.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await XF9().parseAsync(process.argv)}KF9().catch(O71);async function qF9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),i2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6091
6091
  `);else if(!qB(J.ampURL))i2.write(`Logging in to ${new URL(J.ampURL).hostname}
6092
6092
  `);let Z=process.env.AMP_API_KEY;if(Z)i2.write(`API key found in environment variable, storing...
6093
6093
  `),await Q.set("apiKey",Z,J.ampURL),i2.write(`API key successfully stored.
@@ -6103,7 +6103,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);eH(Z,Q);let q=await JB(
6103
6103
  `));try{let Q;if(J)Q=J,X4.write(G8.blue(`Updating to version ${J}...
6104
6104
  `)),await XC(J),X4.write(G8.green(`✓ Successfully updated to version ${J}
6105
6105
  `));else{X4.write(G8.blue(`Checking for updates...
6106
- `));let{hasUpdate:X,latestVersion:Y}=await vj("0.0.1760127338-g8601e4");if(!X)X4.write(G8.green(`✓ Amp CLI is already up to date.
6106
+ `));let{hasUpdate:X,latestVersion:Y}=await vj("0.0.1760140901-g5719d0");if(!X)X4.write(G8.green(`✓ Amp CLI is already up to date.
6107
6107
  `)),process.exit(0);if(!Y)X4.write(G8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,X4.write(G8.blue(`Updating to version ${Y}...
6108
6108
  `)),await XC(Y),X4.write(G8.green(`✓ Successfully updated to version ${Y}
6109
6109
  `))}let Z=await tR(Q);if(Z.warning)X4.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1760127338-g8601e4",
3
+ "version": "0.0.1760140901-g5719d0",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {