@sourcegraph/amp 0.0.1780580310-g6c808e → 0.0.1780592276-g890982

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -228,7 +228,7 @@ Expected format:
228
228
  `).length:A.split(`
229
229
  `).length,deleted:0,changed:0}}var HyA;var qyA=z0(()=>{HyA=v4(CyA(),1)});function Fh1(A,Q){let $=URL.parse(A);if(!$)throw Error(Q);return $}function PO(A){let Q=typeof A==="string"?A:A.toString();return Q===j8||Q===j8.slice(0,-1)}function vO(A){return PO(A)?j8:A}function OyA(A){let Q=typeof A==="string"?URL.parse(A):A;if(!Q)return!1;let $=Q.hostname,B=URL.parse(process.env.AMP_URL??"")??wyA;return $===B.hostname||$===uyA||$.endsWith(Xh1)||$===MyA||$.endsWith(Ih1)}var wyA,j8,uyA="ampcode.app",Xh1,MyA="ampcodedev.org",Ih1;var VF=z0(()=>{wyA=Fh1("https://ampcode.com/","invalid AMP_URL env var");j8=wyA.toString();Xh1=`.${uyA}`,Ih1=`.${MyA}`});function Vh1(A){return A.trim().replace(Gh1,"")}function Kh1(A){let Q=A.split("/").filter(Boolean);for(let $=Q.length-1;$>=0;$--){let B=Q[$];if(B&&O7(B))return B}return null}function eB(A){let Q=Vh1(A);if(!Q)return null;if(O7(Q))return Q;let $;try{$=new URL(Q)}catch{return null}if(!OyA($))return null;return Kh1($.pathname)}var Gh1;var jy=z0(()=>{VF();A3();Gh1=/^[<("'`]+|[>")'`,.]+$/g});function TO(){return`T-${OO()}`}function O7(A){return WxA.safeParse(A).success}function de(){return`toolu_${crypto.randomUUID()}`}function ce(A){if(!A||typeof A!=="object")return!1;let Q=A;return Q.type==="image"&&typeof Q.source==="object"&&Q.source!==null}function pe(A){if(!A||typeof A!=="object")return!1;return A.type==="text"}function LyA(A){if("complete"in A)return A.complete;return!("inputPartialJSON"in A)}function le(A){if(!A||typeof A!=="object")return;let Q=A,$=typeof Q.sentAt==="number"?Q.sentAt:void 0,B=Q.fromAggman===!0||"aggman"in Q&&!!Q.aggman?!0:void 0,E=typeof Q.fromExecutorThreadID==="string"&&O7(Q.fromExecutorThreadID)?Q.fromExecutorThreadID:void 0;if($===void 0&&B===void 0&&E===void 0)return;return{...$!==void 0?{sentAt:$}:{},...B===!0?{fromAggman:B}:{},...E!==void 0?{fromExecutorThreadID:E}:{}}}function ZN0(A,Q){for(let $ of A.messages){if($.role!=="user")continue;for(let B of $.content)if(B.type==="tool_result"&&B.toolUseID===Q)return B}return}function jyA(A,Q="Untitled"){if(A?.title)return pxA(A.title,300);return Q}function zh1(A){return A.replace(/u([0-9A-Fa-f]{4})(\s)/gi,(Q,$,B)=>{try{return String.fromCodePoint(parseInt($,16))+B}catch{return`u${$}${B}`}})}function RyA(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="info"){if($.content.some((E)=>E.type==="summary"&&E.summary.type==="message"))break}if($?.role!=="assistant"||!$.state||$.state.type!=="complete"||$.state.stopReason!=="tool_use")continue;for(let B of $.content)if(B.type==="tool_use"&&B.name===oxA&&B.input){let E=B.input.todos;if(Array.isArray(E))return E;let D=B.input.content;if(typeof D==="string")return zh1(D)}}return}function PyA(A){return A.map((Q)=>Q.type==="text"?Q.text:null).filter((Q)=>Q!==null).join(`
230
230
 
231
- `)}function vyA(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($&&"role"in $&&$.role==="info"){for(let B of $.content)if(B.type==="summary"&&B.summary.type==="message")return{summaryBlock:B,index:Q}}}return}function FN0(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="user"&&$.agentMode)return $.agentMode}return}var A3=z0(()=>{rH0();tH0();w1()});function SO(A){if(!A)return{};return{[Wh1]:A.id}}var LG="x-amp-feature",Wh1="x-amp-thread-id",_O="x-amp-message-id",TyA="X-Amp-Client-Application",_yA="X-Amp-Client-Type",SyA="X-Amp-Client-Version",kyA="X-Amp-Installation-ID",fyA="X-Amp-Device-Fingerprint";var kO=()=>{};function byA(A){xyA=A}function jC(A){Ry=A}function hyA(A){yyA=A}function gyA(A){Py=A.installationID,vy=A.deviceFingerprint}function myA(){if(!Py||!vy)return;return{installationID:Py,deviceFingerprint:vy}}function R8(){let A=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(A)return{type:"cli",name:"AmpSDK",version:A};let Q;if(!Ry)Q="CLI";else if(["Neovim","JetBrains","Zed"].includes(Ry))Q=Ry;else Q=`${Ry} CLI`;return{type:"cli",name:yyA?`${Q} Execute Mode`:Q,version:xyA}}function fO(A){let Q={};if(Q[TyA]=A.name,Q[_yA]=A.type,Py)Q[kyA]=Py;if(vy)Q[fyA]=vy;if(A.version)Q[SyA]=A.version;return Q}var xyA=null,Ry=null,yyA=!1,Py=null,vy=null;var rU=z0(()=>{kO()});function Ch1(A){if(A.proxy&&!process.env.HTTP_PROXY&&!process.env.http_proxy)process.env.HTTP_PROXY=A.proxy;if(A.proxy&&!process.env.HTTPS_PROXY&&!process.env.https_proxy)process.env.HTTPS_PROXY=A.proxy}function xO(A,Q,$){let B=$?`/threads/${Q}/${$}`:`/threads/${Q}`;return new URL(B,A)}async function J5(A,Q,$){let B=await $.getLatest(Q?.signal??void 0),E=await cyA(A,Q,B);return fetch(E)}async function dyA(A,Q,$){let B=await cyA(Q,$,A);return fetch(B)}async function cyA(A,Q,$){if(A.startsWith("http:")||A.startsWith("https:"))throw Error("input must be a path, not an absolute URL");if(!A.startsWith("/"))throw Error("pathAndQuery must start with /");let B=$.settings.url;if(!B)throw Error("amp.url is not set");let E=await $.secrets.getToken("apiKey",B);Ch1({proxy:$.settings.proxy});let D=new URL(A,B);return new Request(D,{...Q,duplex:"half",headers:{"Content-Type":"application/json",...Q?.headers,...fO(R8()),...E?{Authorization:`Bearer ${E}`}:{}}})}async function pyA(A,Q,$,B){let E=await M4.shareThreadWithOperator({threadID:A,message:$||void 0,ephemeralError:B||void 0},{config:Q});if(!E.ok)throw Error(`Failed to share thread: ${E.error.message}`)}async function lyA(A,Q){let $=await J5("/api/telemetry",{method:"POST",redirect:"manual",body:A},Q);if(!$.ok){let B=await $.text(),E;try{E=JSON.parse(B).error||`HTTP ${$.status}`}catch{E=B||`HTTP ${$.status}`}throw Error(`Failed to submit telemetry: ${E}`)}}var y9=z0(()=>{rU();B$()});function Nh1(A){if(new Blob([A]).size<=Hh1)return{body:A};return{body:DfA.gzip(A),headers:{"Content-Encoding":"gzip"}}}function qh1(){return new Proxy({},{get:(A,Q)=>{return async(...$)=>{let B=$.at(1),E=$.at(0);if(!B?.config)throw Error("Internal API client requires configService in options. Call with { config: configService }");let{body:D,headers:J={}}=Nh1(JSON.stringify({method:Q,params:E})),U=await J5("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:D,headers:J,signal:B?.signal},B.config);if(!U.ok)throw Error(`API request for ${Q} failed: ${U.status}`);return await U.json()}}})}var Hh1=25600,M4;var B$=z0(()=>{JfA();y9();M4=qh1()});function wh1(A){return A.config.pipe(O1(({settings:Q,secrets:$})=>M1(async()=>({url:Q.url,proxy:Q.proxy,apiKey:await $.getToken("apiKey",Q.url)}))),UQ(dU),O1(()=>UO(600000).pipe(zQ(void 0),Ae(()=>M1(async(Q)=>{let $=await M4.getUserInfo({},{signal:Q,config:A});if($.ok)return $.result;if($.error&&$.error.code==="auth-required")return null;throw S.error("getUserInfo failed",{error:$.error}),Error(`getUserInfo error: ${$.error.code}`)})))),sA((Q)=>{return Q instanceof Error?{error:{message:String(Q)}}:Q===mU?"pending":Q?{user:Q,features:Q.features,workspace:Q?.team,mysteriousMessage:Q?.mysteriousMessage}:{error:{message:"User not found"}}}),UQ((Q,$)=>dU(Q,$)),L$({shouldCountRefs:!0}))}function yO(A){let Q=iyA.get(A);if(Q)return Q;let $=wh1(A);return iyA.set(A,$),$}function b9(A){return Boolean(typeof A==="object"&&"user"in A&&A.user)}function RC(A){return typeof A==="object"&&"error"in A}var iyA;var ie=z0(()=>{bA();s0();B$();iyA=new WeakMap});function L7(A){let Q=e1[A];return`${Q.provider}/${Q.name}`}function bO(A){let Q=A.indexOf("/");if(Q===-1)throw Error(`Invalid provider/model format: ${A}`);return{provider:A.slice(0,Q),model:A.slice(Q+1)}}function uh1(A){return Object.values(f4).includes(A)}function nyA(A){let Q=A.trim(),{provider:$,model:B}=bO(Q);if(!uh1($))throw Error(`Unknown model provider: ${$}`);if(!B.trim())throw Error(`Invalid provider/model format: ${Q}`)}function XN0(A){let Q=Mh1[A];if(Q===void 0)throw Error(`Unknown provider: ${A}`);let $={provider:Q.provider,contextWindow:Q.contextWindow,maxOutputTokens:Q.maxOutputTokens};if(Q.pricing!==void 0)$.pricing=Q.pricing;if(Q.capabilities!==void 0)$.capabilities=Q.capabilities;return $}function jG(A){let{provider:Q,model:$}=bO(A);for(let E of Object.values(e1))if(E.provider===Q&&E.name===$)return E;return{...XN0(Q),name:$,displayName:$}}function ne(A){for(let $ of Object.values(e1))if($.name===A)return $;let Q=A.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Q){let $=Q[1];for(let B of Object.values(e1))if(B.name===$)return B}return}function PC(A){let Q=A.indexOf("/");if(Q===-1)return A;return A.slice(Q+1)}function IN0(A){let Q=jG(A);return Q.contextWindow-Q.maxOutputTokens}var f4,e1,Mh1,GN0;var UD=z0(()=>{f4={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},e1={CLAUDE_SONNET_4:{provider:f4.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:f4.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:f4.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:f4.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:f4.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:f4.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:f4.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_7:{provider:f4.ANTHROPIC,name:"claude-opus-4-7",displayName:"Claude Opus 4.7",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_8:{provider:f4.ANTHROPIC,name:"claude-opus-4-8",displayName:"Claude Opus 4.8",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:2},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:f4.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:f4.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:f4.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:f4.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:f4.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5:{provider:f4.OPENAI,name:"gpt-5.5",displayName:"GPT-5.5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:5,output:30,cached:0.5},capabilities:{reasoning:!0,vision:!0,tools:!0}},AMP_NOSTROMO:{provider:f4.OPENAI,name:"amp-nostromo-v1",displayName:"nostromo",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0,output:0,cached:0},capabilities:{tools:!0}},GPT_5_4_PRO:{provider:f4.OPENAI,name:"gpt-5.4-pro",displayName:"GPT-5.4-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5_PRO:{provider:f4.OPENAI,name:"gpt-5.5-pro",displayName:"GPT-5.5-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:f4.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:f4.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:f4.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:f4.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:f4.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:f4.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:f4.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:f4.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:f4.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:f4.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_BUILD_0_1:{provider:f4.XAI,name:"grok-build-0.1",displayName:"Grok Build 0.1",contextWindow:256000,maxOutputTokens:32000,pricing:{input:1,output:2,cached:0.2},capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:f4.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:f4.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:f4.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_5_FLASH:{provider:f4.VERTEXAI,name:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:f4.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:f4.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:f4.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:f4.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:f4.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:f4.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:f4.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:f4.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:f4.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};Mh1={anthropic:e1.CLAUDE_SONNET_4_5,openai:e1.GPT_5_4,xai:e1.GROK_BUILD_0_1,cerebras:e1.Z_AI_GLM_4_7,fireworks:e1.FIREWORKS_GLM_4P6,baseten:e1.BASETEN_KIMI_K2P5,moonshotai:e1.KIMI_K2_INSTRUCT,openrouter:e1.SONOMA_SKY_ALPHA,groq:e1.GPT_OSS_120B,vertexai:e1.GEMINI_3_1_PRO_PREVIEW};GN0={FINDER:"finder"}});function Ty(A){return typeof A==="string"&&jh1.includes(A)}function tyA(A){return A===syA}function oe(A,Q){if(!tyA(A))return!0;return Boolean(Q&&WG(Q))}function $bA(A){if(typeof A!=="string")return!1;return QbA.includes(A)}function BbA(A,Q){let $=E$(Q);if(!$)return!1;if(Oh1.has(A)){let B=$.finder??GN0.FINDER,E=Lh1[B];if(A!==E)return!1}if($.includeTools){if($.deferredTools?.includes(A))return!0;return $.includeTools.includes(A)}return!0}function EbA(A,Q){let $=E$(Q);if(!$)return!1;return $.deferredTools?.includes(A)??!1}function _h1(A){if(A?.isInternalUser!==void 0)return A.isInternalUser;return Boolean(A?.userEmail&&WG(A.userEmail))}function RG(A,Q){let $=A?.["internal.visibleModes"]??[],B=A?.["experimental.modes"]??[],E=[...$,...B];return Object.values(h9).filter((D)=>{if(tyA(D.key)&&!_h1(Q))return!1;if(D.key===AbA)return!1;if(E.includes(`!${D.key}`))return!1;if(Q?.v2&&!(("visibleInV2"in D)&&D.visibleInV2))return!1;let U="visible"in D?D.visible:!1,Y=E.includes(D.key);return U||Y}).map((D)=>({mode:D.key,description:"description"in D?D.description:void 0})).sort((D,J)=>D.mode.localeCompare(J.mode))}function E$(A){return Object.values(h9).find((Q)=>Q.key===A)}function vC(A){if(!A)return;return E$(A)?.reasoningEffortControl}function DbA(A,Q){let{levels:$}=A,B=Q?$.indexOf(Q):-1;if(B===-1)return $[0];return $[(B+1)%$.length]??$[0]}function ae(A,Q){return vC(A)?.levels.includes(Q)??!1}function hO(A,Q={}){if(!A||!$bA(A)||!vC(A))return;let $=Q["reasoning.effort"];if($!==void 0&&Ty($))return $;let B=E$(A)?.reasoningEffort;return B&&ae(A,B)?B:void 0}function re(A,Q,$){let B=E$(A),E=$??B?.displayName??A;if(Q!==void 0){let D=B?.reasoningEffortControl?.levels.indexOf(Q);if(D===1)return{base:E,superscript:"²",plainReasoningIndex:"2",text:`${E}²`};if(D===2)return{base:E,superscript:"³",plainReasoningIndex:"3",text:`${E}³`};if(D===3)return{base:E,superscript:"⁴",plainReasoningIndex:"4",text:`${E}⁴`}}return{base:E,superscript:"",plainReasoningIndex:void 0,text:E}}function KN0(A,Q){let B=(Q.findIndex((D)=>D.mode===A)+1)%Q.length;return Q[B]?.mode??"smart"}var Oh1,Lh1,jh1,ayA,ryA,syA="nostromo",Rh1,VN0,oyA,Ph1,vh1,eyA,Th1,h9,AbA,QbA;var j7=z0(()=>{UD();Oh1=new Set(["finder"]),Lh1={finder:"finder"},jh1=["none","minimal","low","medium","high","xhigh","max"];ayA={r:0,g:55,b:0},ryA={r:0,g:255,b:136};Rh1=["finder","shell_command","apply_patch","web_search","read_web_page","read_mcp_resource","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter"],VN0=["Read","finder","Bash","create_file","edit_file","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter","read_mcp_resource"],oyA=["code_review"],Ph1=["code_review"],vh1=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","archive_threads","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],eyA=["shell_command","apply_patch","web_search","read_web_page","Task","skill","read_thread","find_thread","librarian","oracle","finder","view_media","painter","send_message_to_aggman"],Th1=Array.from(new Set([...VN0,...eyA])),h9={DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.5",primaryModel:L7("GPT_5_5"),systemPrompt:"deep",promptFragments:["diagrams","toolConnectionError","guidanceFiles"],includeTools:eyA,deferredTools:Ph1,visible:!0,visibleInV2:!0,reasoningEffort:"medium",reasoningEffortControl:{levels:["low","medium","xhigh"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:L7("CLAUDE_OPUS_4_7"),systemPrompt:"smart",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:VN0,deferredTools:oyA,visible:!0,visibleInV2:!0,reasoningEffort:"high",reasoningEffortControl:{levels:["high","xhigh","max"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},RUSH:{key:"rush",displayName:"Rush",description:"Fast, low-token GPT-5.5 for small, well-defined tasks",primaryModel:L7("GPT_5_5"),systemPrompt:"rush",promptFragments:["toolConnectionError","guidanceFiles"],includeTools:Rh1,visible:!0,reasoningEffort:"none",subagents:{"task-subagent":{model:L7("GPT_5_5"),reasoningEffort:"none"}},uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:L7("CLAUDE_OPUS_4_6"),systemPrompt:"aggman",promptFragments:[],includeTools:vh1,visible:!1,serverOnly:!0,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:L7("CLAUDE_OPUS_4_6"),systemPrompt:"large",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:VN0,deferredTools:oyA,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},NOSTROMO:{key:syA,displayName:"nostromo",description:"Internal-only deterministic test mode with scripted tool scenarios",primaryModel:L7("AMP_NOSTROMO"),systemPrompt:"nostromo",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:Th1,visible:!0,visibleInV2:!0,reasoningEffort:"low",uiHints:{labelAnimation:"jitter",primaryColor:{r:0,g:46,b:77},secondaryColor:{r:48,g:213,b:200}}}},AbA=h9.AGG.key,QbA=Object.values(h9).map((A)=>A.key)});var PG=z0(()=>{j7();UD()});var zF=P((zl6,QhA)=>{var ebA=["nodebuffer","arraybuffer","fragments"],AhA=typeof Blob<"u";if(AhA)ebA.push("blob");QhA.exports={BINARY_TYPES:ebA,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:AhA,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var by=P((Wl6,G00)=>{var{EMPTY_BUFFER:Mm1}=zF(),fN0=Buffer[Symbol.species];function Om1(A,Q){if(A.length===0)return Mm1;if(A.length===1)return A[0];let $=Buffer.allocUnsafe(Q),B=0;for(let E=0;E<A.length;E++){let D=A[E];$.set(D,B),B+=D.length}if(B<Q)return new fN0($.buffer,$.byteOffset,B);return $}function $hA(A,Q,$,B,E){for(let D=0;D<E;D++)$[B+D]=A[D]^Q[D&3]}function BhA(A,Q){for(let $=0;$<A.length;$++)A[$]^=Q[$&3]}function Lm1(A){if(A.length===A.buffer.byteLength)return A.buffer;return A.buffer.slice(A.byteOffset,A.byteOffset+A.length)}function xN0(A){if(xN0.readOnly=!0,Buffer.isBuffer(A))return A;let Q;if(A instanceof ArrayBuffer)Q=new fN0(A);else if(ArrayBuffer.isView(A))Q=new fN0(A.buffer,A.byteOffset,A.byteLength);else Q=Buffer.from(A),xN0.readOnly=!1;return Q}G00.exports={concat:Om1,mask:$hA,toArrayBuffer:Lm1,toBuffer:xN0,unmask:BhA};if(!process.env.WS_NO_BUFFER_UTIL)try{let A=(()=>{throw new Error("Cannot require module "+"bufferutil");})();G00.exports.mask=function(Q,$,B,E,D){if(D<48)$hA(Q,$,B,E,D);else A.mask(Q,$,B,E,D)},G00.exports.unmask=function(Q,$){if(Q.length<32)BhA(Q,$);else A.unmask(Q,$)}}catch(A){}});var UhA=P((Cl6,JhA)=>{var EhA=Symbol("kDone"),yN0=Symbol("kRun");class DhA{constructor(A){this[EhA]=()=>{this.pending--,this[yN0]()},this.concurrency=A||1/0,this.jobs=[],this.pending=0}add(A){this.jobs.push(A),this[yN0]()}[yN0](){if(this.pending===this.concurrency)return;if(this.jobs.length){let A=this.jobs.shift();this.pending++,A(this[EhA])}}}JhA.exports=DhA});var iO=P((Hl6,IhA)=>{var hy=Y0("zlib"),YhA=by(),jm1=UhA(),{kStatusCode:ZhA}=zF(),Rm1=Buffer[Symbol.species],Pm1=Buffer.from([0,0,255,255]),K00=Symbol("permessage-deflate"),WF=Symbol("total-length"),pO=Symbol("callback"),TG=Symbol("buffers"),lO=Symbol("error"),V00;class FhA{constructor(A){if(this._options=A||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!V00){let Q=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;V00=new jm1(Q)}}static get extensionName(){return"permessage-deflate"}offer(){let A={};if(this._options.serverNoContextTakeover)A.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)A.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)A.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)A.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)A.client_max_window_bits=!0;return A}accept(A){return A=this.normalizeParams(A),this.params=this._isServer?this.acceptAsServer(A):this.acceptAsClient(A),this.params}cleanup(){if(this._inflate)this._inflate.close(),this._inflate=null;if(this._deflate){let A=this._deflate[pO];if(this._deflate.close(),this._deflate=null,A)A(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(A){let Q=this._options,$=A.find((B)=>{if(Q.serverNoContextTakeover===!1&&B.server_no_context_takeover||B.server_max_window_bits&&(Q.serverMaxWindowBits===!1||typeof Q.serverMaxWindowBits==="number"&&Q.serverMaxWindowBits>B.server_max_window_bits)||typeof Q.clientMaxWindowBits==="number"&&!B.client_max_window_bits)return!1;return!0});if(!$)throw Error("None of the extension offers can be accepted");if(Q.serverNoContextTakeover)$.server_no_context_takeover=!0;if(Q.clientNoContextTakeover)$.client_no_context_takeover=!0;if(typeof Q.serverMaxWindowBits==="number")$.server_max_window_bits=Q.serverMaxWindowBits;if(typeof Q.clientMaxWindowBits==="number")$.client_max_window_bits=Q.clientMaxWindowBits;else if($.client_max_window_bits===!0||Q.clientMaxWindowBits===!1)delete $.client_max_window_bits;return $}acceptAsClient(A){let Q=A[0];if(this._options.clientNoContextTakeover===!1&&Q.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(!Q.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")Q.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&Q.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"');return Q}normalizeParams(A){return A.forEach((Q)=>{Object.keys(Q).forEach(($)=>{let B=Q[$];if(B.length>1)throw Error(`Parameter "${$}" must have only a single value`);if(B=B[0],$==="client_max_window_bits"){if(B!==!0){let E=+B;if(!Number.isInteger(E)||E<8||E>15)throw TypeError(`Invalid value for parameter "${$}": ${B}`);B=E}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${$}": ${B}`)}else if($==="server_max_window_bits"){let E=+B;if(!Number.isInteger(E)||E<8||E>15)throw TypeError(`Invalid value for parameter "${$}": ${B}`);B=E}else if($==="client_no_context_takeover"||$==="server_no_context_takeover"){if(B!==!0)throw TypeError(`Invalid value for parameter "${$}": ${B}`)}else throw Error(`Unknown parameter "${$}"`);Q[$]=B})}),A}decompress(A,Q,$){V00.add((B)=>{this._decompress(A,Q,(E,D)=>{B(),$(E,D)})})}compress(A,Q,$){V00.add((B)=>{this._compress(A,Q,(E,D)=>{B(),$(E,D)})})}_decompress(A,Q,$){let B=this._isServer?"client":"server";if(!this._inflate){let E=`${B}_max_window_bits`,D=typeof this.params[E]!=="number"?hy.Z_DEFAULT_WINDOWBITS:this.params[E];this._inflate=hy.createInflateRaw({...this._options.zlibInflateOptions,windowBits:D}),this._inflate[K00]=this,this._inflate[WF]=0,this._inflate[TG]=[],this._inflate.on("error",Tm1),this._inflate.on("data",XhA)}if(this._inflate[pO]=$,this._inflate.write(A),Q)this._inflate.write(Pm1);this._inflate.flush(()=>{let E=this._inflate[lO];if(E){this._inflate.close(),this._inflate=null,$(E);return}let D=YhA.concat(this._inflate[TG],this._inflate[WF]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[WF]=0,this._inflate[TG]=[],Q&&this.params[`${B}_no_context_takeover`])this._inflate.reset();$(null,D)})}_compress(A,Q,$){let B=this._isServer?"server":"client";if(!this._deflate){let E=`${B}_max_window_bits`,D=typeof this.params[E]!=="number"?hy.Z_DEFAULT_WINDOWBITS:this.params[E];this._deflate=hy.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:D}),this._deflate[WF]=0,this._deflate[TG]=[],this._deflate.on("data",vm1)}this._deflate[pO]=$,this._deflate.write(A),this._deflate.flush(hy.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let E=YhA.concat(this._deflate[TG],this._deflate[WF]);if(Q)E=new Rm1(E.buffer,E.byteOffset,E.length-4);if(this._deflate[pO]=null,this._deflate[WF]=0,this._deflate[TG]=[],Q&&this.params[`${B}_no_context_takeover`])this._deflate.reset();$(null,E)})}}IhA.exports=FhA;function vm1(A){this[TG].push(A),this[WF]+=A.length}function XhA(A){if(this[WF]+=A.length,this[K00]._maxPayload<1||this[WF]<=this[K00]._maxPayload){this[TG].push(A);return}this[lO]=RangeError("Max payload size exceeded"),this[lO].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[lO][ZhA]=1009,this.removeListener("data",XhA),this.reset()}function Tm1(A){if(this[K00]._inflate=null,this[lO]){this[pO](this[lO]);return}A[ZhA]=1007,this[pO](A)}});var nO=P((Nl6,z00)=>{var{isUtf8:GhA}=Y0("buffer"),{hasBlob:_m1}=zF(),Sm1=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function km1(A){return A>=1000&&A<=1014&&A!==1004&&A!==1005&&A!==1006||A>=3000&&A<=4999}function bN0(A){let Q=A.length,$=0;while($<Q)if((A[$]&128)===0)$++;else if((A[$]&224)===192){if($+1===Q||(A[$+1]&192)!==128||(A[$]&254)===192)return!1;$+=2}else if((A[$]&240)===224){if($+2>=Q||(A[$+1]&192)!==128||(A[$+2]&192)!==128||A[$]===224&&(A[$+1]&224)===128||A[$]===237&&(A[$+1]&224)===160)return!1;$+=3}else if((A[$]&248)===240){if($+3>=Q||(A[$+1]&192)!==128||(A[$+2]&192)!==128||(A[$+3]&192)!==128||A[$]===240&&(A[$+1]&240)===128||A[$]===244&&A[$+1]>143||A[$]>244)return!1;$+=4}else return!1;return!0}function fm1(A){return _m1&&typeof A==="object"&&typeof A.arrayBuffer==="function"&&typeof A.type==="string"&&typeof A.stream==="function"&&(A[Symbol.toStringTag]==="Blob"||A[Symbol.toStringTag]==="File")}z00.exports={isBlob:fm1,isValidStatusCode:km1,isValidUTF8:bN0,tokenChars:Sm1};if(GhA)z00.exports.isValidUTF8=function(A){return A.length<24?bN0(A):GhA(A)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let A=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();z00.exports.isValidUTF8=function(Q){return Q.length<32?bN0(Q):A(Q)}}catch(A){}});var gN0=P((ql6,ChA)=>{var{Writable:xm1}=Y0("stream"),VhA=iO(),{BINARY_TYPES:ym1,EMPTY_BUFFER:KhA,kStatusCode:bm1,kWebSocket:hm1}=zF(),{concat:hN0,toArrayBuffer:gm1,unmask:mm1}=by(),{isValidStatusCode:dm1,isValidUTF8:zhA}=nO(),W00=Buffer[Symbol.species];class WhA extends xm1{constructor(A={}){super();this._allowSynchronousEvents=A.allowSynchronousEvents!==void 0?A.allowSynchronousEvents:!0,this._binaryType=A.binaryType||ym1[0],this._extensions=A.extensions||{},this._isServer=!!A.isServer,this._maxPayload=A.maxPayload|0,this._skipUTF8Validation=!!A.skipUTF8Validation,this[hm1]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(A,Q,$){if(this._opcode===8&&this._state==0)return $();this._bufferedBytes+=A.length,this._buffers.push(A),this.startLoop($)}consume(A){if(this._bufferedBytes-=A,A===this._buffers[0].length)return this._buffers.shift();if(A<this._buffers[0].length){let $=this._buffers[0];return this._buffers[0]=new W00($.buffer,$.byteOffset+A,$.length-A),new W00($.buffer,$.byteOffset,A)}let Q=Buffer.allocUnsafe(A);do{let $=this._buffers[0],B=Q.length-A;if(A>=$.length)Q.set(this._buffers.shift(),B);else Q.set(new Uint8Array($.buffer,$.byteOffset,A),B),this._buffers[0]=new W00($.buffer,$.byteOffset+A,$.length-A);A-=$.length}while(A>0);return Q}startLoop(A){this._loop=!0;do switch(this._state){case 0:this.getInfo(A);break;case 1:this.getPayloadLength16(A);break;case 2:this.getPayloadLength64(A);break;case 3:this.getMask();break;case 4:this.getData(A);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)A()}getInfo(A){if(this._bufferedBytes<2){this._loop=!1;return}let Q=this.consume(2);if((Q[0]&48)!==0){let B=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");A(B);return}let $=(Q[0]&64)===64;if($&&!this._extensions[VhA.extensionName]){let B=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(B);return}if(this._fin=(Q[0]&128)===128,this._opcode=Q[0]&15,this._payloadLength=Q[1]&127,this._opcode===0){if($){let B=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(B);return}if(!this._fragmented){let B=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");A(B);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let B=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(B);return}this._compressed=$}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let B=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");A(B);return}if($){let B=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(B);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let B=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");A(B);return}}else{let B=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(B);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(Q[1]&128)===128,this._isServer){if(!this._masked){let B=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");A(B);return}}else if(this._masked){let B=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");A(B);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else this.haveLength(A)}getPayloadLength16(A){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(A)}getPayloadLength64(A){if(this._bufferedBytes<8){this._loop=!1;return}let Q=this.consume(8),$=Q.readUInt32BE(0);if($>Math.pow(2,21)-1){let B=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");A(B);return}this._payloadLength=$*Math.pow(2,32)+Q.readUInt32BE(4),this.haveLength(A)}haveLength(A){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let Q=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");A(Q);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(A){let Q=KhA;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(Q=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)mm1(Q,this._mask)}if(this._opcode>7){this.controlMessage(Q,A);return}if(this._compressed){this._state=5,this.decompress(Q,A);return}if(Q.length)this._messageLength=this._totalPayloadLength,this._fragments.push(Q);this.dataMessage(A)}decompress(A,Q){this._extensions[VhA.extensionName].decompress(A,this._fin,(B,E)=>{if(B)return Q(B);if(E.length){if(this._messageLength+=E.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let D=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");Q(D);return}this._fragments.push(E)}if(this.dataMessage(Q),this._state===0)this.startLoop(Q)})}dataMessage(A){if(!this._fin){this._state=0;return}let Q=this._messageLength,$=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let B;if(this._binaryType==="nodebuffer")B=hN0($,Q);else if(this._binaryType==="arraybuffer")B=gm1(hN0($,Q));else if(this._binaryType==="blob")B=new Blob($);else B=$;if(this._allowSynchronousEvents)this.emit("message",B,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",B,!0),this._state=0,this.startLoop(A)})}else{let B=hN0($,Q);if(!this._skipUTF8Validation&&!zhA(B)){let E=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");A(E);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",B,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",B,!1),this._state=0,this.startLoop(A)})}}controlMessage(A,Q){if(this._opcode===8){if(A.length===0)this._loop=!1,this.emit("conclude",1005,KhA),this.end();else{let $=A.readUInt16BE(0);if(!dm1($)){let E=this.createError(RangeError,`invalid status code ${$}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");Q(E);return}let B=new W00(A.buffer,A.byteOffset+2,A.length-2);if(!this._skipUTF8Validation&&!zhA(B)){let E=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");Q(E);return}this._loop=!1,this.emit("conclude",$,B),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",A),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",A),this._state=0,this.startLoop(Q)})}createError(A,Q,$,B,E){this._loop=!1,this._errored=!0;let D=new A($?`Invalid WebSocket frame: ${Q}`:Q);return Error.captureStackTrace(D,this.createError),D.code=E,D[bm1]=B,D}}ChA.exports=WhA});var dN0=P((ul6,qhA)=>{var{Duplex:wl6}=Y0("stream"),{randomFillSync:cm1}=Y0("crypto"),HhA=iO(),{EMPTY_BUFFER:pm1,kWebSocket:lm1,NOOP:im1}=zF(),{isBlob:oO,isValidStatusCode:nm1}=nO(),{mask:NhA,toBuffer:fC}=by(),YD=Symbol("kByteLength"),om1=Buffer.alloc(4),xC,aO=8192,iJ=0,am1=1,rm1=2;class _G{constructor(A,Q,$){if(this._extensions=Q||{},$)this._generateMask=$,this._maskBuffer=Buffer.alloc(4);this._socket=A,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=iJ,this.onerror=im1,this[lm1]=void 0}static frame(A,Q){let $,B=!1,E=2,D=!1;if(Q.mask){if($=Q.maskBuffer||om1,Q.generateMask)Q.generateMask($);else{if(aO===8192){if(xC===void 0)xC=Buffer.alloc(8192);cm1(xC,0,8192),aO=0}$[0]=xC[aO++],$[1]=xC[aO++],$[2]=xC[aO++],$[3]=xC[aO++]}D=($[0]|$[1]|$[2]|$[3])===0,E=6}let J;if(typeof A==="string")if((!Q.mask||D)&&Q[YD]!==void 0)J=Q[YD];else A=Buffer.from(A),J=A.length;else J=A.length,B=Q.mask&&Q.readOnly&&!D;let U=J;if(J>=65536)E+=8,U=127;else if(J>125)E+=2,U=126;let Y=Buffer.allocUnsafe(B?J+E:E);if(Y[0]=Q.fin?Q.opcode|128:Q.opcode,Q.rsv1)Y[0]|=64;if(Y[1]=U,U===126)Y.writeUInt16BE(J,2);else if(U===127)Y[2]=Y[3]=0,Y.writeUIntBE(J,4,6);if(!Q.mask)return[Y,A];if(Y[1]|=128,Y[E-4]=$[0],Y[E-3]=$[1],Y[E-2]=$[2],Y[E-1]=$[3],D)return[Y,A];if(B)return NhA(A,$,Y,E,J),[Y];return NhA(A,$,A,0,J),[Y,A]}close(A,Q,$,B){let E;if(A===void 0)E=pm1;else if(typeof A!=="number"||!nm1(A))throw TypeError("First argument must be a valid error code number");else if(Q===void 0||!Q.length)E=Buffer.allocUnsafe(2),E.writeUInt16BE(A,0);else{let J=Buffer.byteLength(Q);if(J>123)throw RangeError("The message must not be greater than 123 bytes");if(E=Buffer.allocUnsafe(2+J),E.writeUInt16BE(A,0),typeof Q==="string")E.write(Q,2);else E.set(Q,2)}let D={[YD]:E.length,fin:!0,generateMask:this._generateMask,mask:$,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==iJ)this.enqueue([this.dispatch,E,!1,D,B]);else this.sendFrame(_G.frame(E,D),B)}ping(A,Q,$){let B,E;if(typeof A==="string")B=Buffer.byteLength(A),E=!1;else if(oO(A))B=A.size,E=!1;else A=fC(A),B=A.length,E=fC.readOnly;if(B>125)throw RangeError("The data size must not be greater than 125 bytes");let D={[YD]:B,fin:!0,generateMask:this._generateMask,mask:Q,maskBuffer:this._maskBuffer,opcode:9,readOnly:E,rsv1:!1};if(oO(A))if(this._state!==iJ)this.enqueue([this.getBlobData,A,!1,D,$]);else this.getBlobData(A,!1,D,$);else if(this._state!==iJ)this.enqueue([this.dispatch,A,!1,D,$]);else this.sendFrame(_G.frame(A,D),$)}pong(A,Q,$){let B,E;if(typeof A==="string")B=Buffer.byteLength(A),E=!1;else if(oO(A))B=A.size,E=!1;else A=fC(A),B=A.length,E=fC.readOnly;if(B>125)throw RangeError("The data size must not be greater than 125 bytes");let D={[YD]:B,fin:!0,generateMask:this._generateMask,mask:Q,maskBuffer:this._maskBuffer,opcode:10,readOnly:E,rsv1:!1};if(oO(A))if(this._state!==iJ)this.enqueue([this.getBlobData,A,!1,D,$]);else this.getBlobData(A,!1,D,$);else if(this._state!==iJ)this.enqueue([this.dispatch,A,!1,D,$]);else this.sendFrame(_G.frame(A,D),$)}send(A,Q,$){let B=this._extensions[HhA.extensionName],E=Q.binary?2:1,D=Q.compress,J,U;if(typeof A==="string")J=Buffer.byteLength(A),U=!1;else if(oO(A))J=A.size,U=!1;else A=fC(A),J=A.length,U=fC.readOnly;if(this._firstFragment){if(this._firstFragment=!1,D&&B&&B.params[B._isServer?"server_no_context_takeover":"client_no_context_takeover"])D=J>=B._threshold;this._compress=D}else D=!1,E=0;if(Q.fin)this._firstFragment=!0;let Y={[YD]:J,fin:Q.fin,generateMask:this._generateMask,mask:Q.mask,maskBuffer:this._maskBuffer,opcode:E,readOnly:U,rsv1:D};if(oO(A))if(this._state!==iJ)this.enqueue([this.getBlobData,A,this._compress,Y,$]);else this.getBlobData(A,this._compress,Y,$);else if(this._state!==iJ)this.enqueue([this.dispatch,A,this._compress,Y,$]);else this.dispatch(A,this._compress,Y,$)}getBlobData(A,Q,$,B){this._bufferedBytes+=$[YD],this._state=rm1,A.arrayBuffer().then((E)=>{if(this._socket.destroyed){let J=Error("The socket was closed while the blob was being read");process.nextTick(mN0,this,J,B);return}this._bufferedBytes-=$[YD];let D=fC(E);if(!Q)this._state=iJ,this.sendFrame(_G.frame(D,$),B),this.dequeue();else this.dispatch(D,Q,$,B)}).catch((E)=>{process.nextTick(sm1,this,E,B)})}dispatch(A,Q,$,B){if(!Q){this.sendFrame(_G.frame(A,$),B);return}let E=this._extensions[HhA.extensionName];this._bufferedBytes+=$[YD],this._state=am1,E.compress(A,$.fin,(D,J)=>{if(this._socket.destroyed){let U=Error("The socket was closed while data was being compressed");mN0(this,U,B);return}this._bufferedBytes-=$[YD],this._state=iJ,$.readOnly=!1,this.sendFrame(_G.frame(J,$),B),this.dequeue()})}dequeue(){while(this._state===iJ&&this._queue.length){let A=this._queue.shift();this._bufferedBytes-=A[3][YD],Reflect.apply(A[0],this,A.slice(1))}}enqueue(A){this._bufferedBytes+=A[3][YD],this._queue.push(A)}sendFrame(A,Q){if(A.length===2)this._socket.cork(),this._socket.write(A[0]),this._socket.write(A[1],Q),this._socket.uncork();else this._socket.write(A[0],Q)}}qhA.exports=_G;function mN0(A,Q,$){if(typeof $==="function")$(Q);for(let B=0;B<A._queue.length;B++){let E=A._queue[B],D=E[E.length-1];if(typeof D==="function")D(Q)}}function sm1(A,Q,$){mN0(A,Q,$),A.onerror(Q)}});var vhA=P((Ml6,PhA)=>{var{kForOnEventAttribute:gy,kListener:cN0}=zF(),whA=Symbol("kCode"),uhA=Symbol("kData"),MhA=Symbol("kError"),OhA=Symbol("kMessage"),LhA=Symbol("kReason"),rO=Symbol("kTarget"),jhA=Symbol("kType"),RhA=Symbol("kWasClean");class SG{constructor(A){this[rO]=null,this[jhA]=A}get target(){return this[rO]}get type(){return this[jhA]}}Object.defineProperty(SG.prototype,"target",{enumerable:!0});Object.defineProperty(SG.prototype,"type",{enumerable:!0});class sO extends SG{constructor(A,Q={}){super(A);this[whA]=Q.code===void 0?0:Q.code,this[LhA]=Q.reason===void 0?"":Q.reason,this[RhA]=Q.wasClean===void 0?!1:Q.wasClean}get code(){return this[whA]}get reason(){return this[LhA]}get wasClean(){return this[RhA]}}Object.defineProperty(sO.prototype,"code",{enumerable:!0});Object.defineProperty(sO.prototype,"reason",{enumerable:!0});Object.defineProperty(sO.prototype,"wasClean",{enumerable:!0});class my extends SG{constructor(A,Q={}){super(A);this[MhA]=Q.error===void 0?null:Q.error,this[OhA]=Q.message===void 0?"":Q.message}get error(){return this[MhA]}get message(){return this[OhA]}}Object.defineProperty(my.prototype,"error",{enumerable:!0});Object.defineProperty(my.prototype,"message",{enumerable:!0});class H00 extends SG{constructor(A,Q={}){super(A);this[uhA]=Q.data===void 0?null:Q.data}get data(){return this[uhA]}}Object.defineProperty(H00.prototype,"data",{enumerable:!0});var tm1={addEventListener(A,Q,$={}){for(let E of this.listeners(A))if(!$[gy]&&E[cN0]===Q&&!E[gy])return;let B;if(A==="message")B=function(D,J){let U=new H00("message",{data:J?D:D.toString()});U[rO]=this,C00(Q,this,U)};else if(A==="close")B=function(D,J){let U=new sO("close",{code:D,reason:J.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});U[rO]=this,C00(Q,this,U)};else if(A==="error")B=function(D){let J=new my("error",{error:D,message:D.message});J[rO]=this,C00(Q,this,J)};else if(A==="open")B=function(){let D=new SG("open");D[rO]=this,C00(Q,this,D)};else return;if(B[gy]=!!$[gy],B[cN0]=Q,$.once)this.once(A,B);else this.on(A,B)},removeEventListener(A,Q){for(let $ of this.listeners(A))if($[cN0]===Q&&!$[gy]){this.removeListener(A,$);break}}};PhA.exports={CloseEvent:sO,ErrorEvent:my,Event:SG,EventTarget:tm1,MessageEvent:H00};function C00(A,Q,$){if(typeof A==="object"&&A.handleEvent)A.handleEvent.call(A,$);else A.call(Q,$)}});var N00=P((Ol6,ThA)=>{var{tokenChars:dy}=nO();function sU(A,Q,$){if(A[Q]===void 0)A[Q]=[$];else A[Q].push($)}function em1(A){let Q=Object.create(null),$=Object.create(null),B=!1,E=!1,D=!1,J,U,Y=-1,Z=-1,F=-1,X=0;for(;X<A.length;X++)if(Z=A.charCodeAt(X),J===void 0)if(F===-1&&dy[Z]===1){if(Y===-1)Y=X}else if(X!==0&&(Z===32||Z===9)){if(F===-1&&Y!==-1)F=X}else if(Z===59||Z===44){if(Y===-1)throw SyntaxError(`Unexpected character at index ${X}`);if(F===-1)F=X;let G=A.slice(Y,F);if(Z===44)sU(Q,G,$),$=Object.create(null);else J=G;Y=F=-1}else throw SyntaxError(`Unexpected character at index ${X}`);else if(U===void 0)if(F===-1&&dy[Z]===1){if(Y===-1)Y=X}else if(Z===32||Z===9){if(F===-1&&Y!==-1)F=X}else if(Z===59||Z===44){if(Y===-1)throw SyntaxError(`Unexpected character at index ${X}`);if(F===-1)F=X;if(sU($,A.slice(Y,F),!0),Z===44)sU(Q,J,$),$=Object.create(null),J=void 0;Y=F=-1}else if(Z===61&&Y!==-1&&F===-1)U=A.slice(Y,X),Y=F=-1;else throw SyntaxError(`Unexpected character at index ${X}`);else if(E){if(dy[Z]!==1)throw SyntaxError(`Unexpected character at index ${X}`);if(Y===-1)Y=X;else if(!B)B=!0;E=!1}else if(D)if(dy[Z]===1){if(Y===-1)Y=X}else if(Z===34&&Y!==-1)D=!1,F=X;else if(Z===92)E=!0;else throw SyntaxError(`Unexpected character at index ${X}`);else if(Z===34&&A.charCodeAt(X-1)===61)D=!0;else if(F===-1&&dy[Z]===1){if(Y===-1)Y=X}else if(Y!==-1&&(Z===32||Z===9)){if(F===-1)F=X}else if(Z===59||Z===44){if(Y===-1)throw SyntaxError(`Unexpected character at index ${X}`);if(F===-1)F=X;let G=A.slice(Y,F);if(B)G=G.replace(/\\/g,""),B=!1;if(sU($,U,G),Z===44)sU(Q,J,$),$=Object.create(null),J=void 0;U=void 0,Y=F=-1}else throw SyntaxError(`Unexpected character at index ${X}`);if(Y===-1||D||Z===32||Z===9)throw SyntaxError("Unexpected end of input");if(F===-1)F=X;let I=A.slice(Y,F);if(J===void 0)sU(Q,I,$);else{if(U===void 0)sU($,I,!0);else if(B)sU($,U,I.replace(/\\/g,""));else sU($,U,I);sU(Q,J,$)}return Q}function Ad1(A){return Object.keys(A).map((Q)=>{let $=A[Q];if(!Array.isArray($))$=[$];return $.map((B)=>{return[Q].concat(Object.keys(B).map((E)=>{let D=B[E];if(!Array.isArray(D))D=[D];return D.map((J)=>J===!0?E:`${E}=${J}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}ThA.exports={format:Ad1,parse:em1}});var M00=P((Rl6,chA)=>{var Qd1=Y0("events"),$d1=Y0("https"),Bd1=Y0("http"),khA=Y0("net"),Ed1=Y0("tls"),{randomBytes:Dd1,createHash:Jd1}=Y0("crypto"),{Duplex:Ll6,Readable:jl6}=Y0("stream"),{URL:pN0}=Y0("url"),kG=iO(),Ud1=gN0(),Yd1=dN0(),{isBlob:Zd1}=nO(),{BINARY_TYPES:_hA,CLOSE_TIMEOUT:Fd1,EMPTY_BUFFER:q00,GUID:Xd1,kForOnEventAttribute:lN0,kListener:Id1,kStatusCode:Gd1,kWebSocket:R3,NOOP:fhA}=zF(),{EventTarget:{addEventListener:Vd1,removeEventListener:Kd1}}=vhA(),{format:zd1,parse:Wd1}=N00(),{toBuffer:Cd1}=by(),xhA=Symbol("kAborted"),iN0=[8,13],CF=["CONNECTING","OPEN","CLOSING","CLOSED"],Hd1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class S1 extends Qd1{constructor(A,Q,$){super();if(this._binaryType=_hA[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=q00,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=S1.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,A!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,Q===void 0)Q=[];else if(!Array.isArray(Q))if(typeof Q==="object"&&Q!==null)$=Q,Q=[];else Q=[Q];yhA(this,A,Q,$)}else this._autoPong=$.autoPong,this._closeTimeout=$.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(A){if(!_hA.includes(A))return;if(this._binaryType=A,this._receiver)this._receiver._binaryType=A}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(A,Q,$){let B=new Ud1({allowSynchronousEvents:$.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:$.maxPayload,skipUTF8Validation:$.skipUTF8Validation}),E=new Yd1(A,this._extensions,$.generateMask);if(this._receiver=B,this._sender=E,this._socket=A,B[R3]=this,E[R3]=this,A[R3]=this,B.on("conclude",wd1),B.on("drain",ud1),B.on("error",Md1),B.on("message",Od1),B.on("ping",Ld1),B.on("pong",jd1),E.onerror=Rd1,A.setTimeout)A.setTimeout(0);if(A.setNoDelay)A.setNoDelay();if(Q.length>0)A.unshift(Q);A.on("close",ghA),A.on("data",u00),A.on("end",mhA),A.on("error",dhA),this._readyState=S1.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=S1.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[kG.extensionName])this._extensions[kG.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=S1.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(A,Q){if(this.readyState===S1.CLOSED)return;if(this.readyState===S1.CONNECTING){m9(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===S1.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=S1.CLOSING,this._sender.close(A,Q,!this._isServer,($)=>{if($)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),hhA(this)}pause(){if(this.readyState===S1.CONNECTING||this.readyState===S1.CLOSED)return;this._paused=!0,this._socket.pause()}ping(A,Q,$){if(this.readyState===S1.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof A==="function")$=A,A=Q=void 0;else if(typeof Q==="function")$=Q,Q=void 0;if(typeof A==="number")A=A.toString();if(this.readyState!==S1.OPEN){nN0(this,A,$);return}if(Q===void 0)Q=!this._isServer;this._sender.ping(A||q00,Q,$)}pong(A,Q,$){if(this.readyState===S1.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof A==="function")$=A,A=Q=void 0;else if(typeof Q==="function")$=Q,Q=void 0;if(typeof A==="number")A=A.toString();if(this.readyState!==S1.OPEN){nN0(this,A,$);return}if(Q===void 0)Q=!this._isServer;this._sender.pong(A||q00,Q,$)}resume(){if(this.readyState===S1.CONNECTING||this.readyState===S1.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(A,Q,$){if(this.readyState===S1.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Q==="function")$=Q,Q={};if(typeof A==="number")A=A.toString();if(this.readyState!==S1.OPEN){nN0(this,A,$);return}let B={binary:typeof A!=="string",mask:!this._isServer,compress:!0,fin:!0,...Q};if(!this._extensions[kG.extensionName])B.compress=!1;this._sender.send(A||q00,B,$)}terminate(){if(this.readyState===S1.CLOSED)return;if(this.readyState===S1.CONNECTING){m9(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=S1.CLOSING,this._socket.destroy()}}Object.defineProperty(S1,"CONNECTING",{enumerable:!0,value:CF.indexOf("CONNECTING")});Object.defineProperty(S1.prototype,"CONNECTING",{enumerable:!0,value:CF.indexOf("CONNECTING")});Object.defineProperty(S1,"OPEN",{enumerable:!0,value:CF.indexOf("OPEN")});Object.defineProperty(S1.prototype,"OPEN",{enumerable:!0,value:CF.indexOf("OPEN")});Object.defineProperty(S1,"CLOSING",{enumerable:!0,value:CF.indexOf("CLOSING")});Object.defineProperty(S1.prototype,"CLOSING",{enumerable:!0,value:CF.indexOf("CLOSING")});Object.defineProperty(S1,"CLOSED",{enumerable:!0,value:CF.indexOf("CLOSED")});Object.defineProperty(S1.prototype,"CLOSED",{enumerable:!0,value:CF.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((A)=>{Object.defineProperty(S1.prototype,A,{enumerable:!0})});["open","error","close","message"].forEach((A)=>{Object.defineProperty(S1.prototype,`on${A}`,{enumerable:!0,get(){for(let Q of this.listeners(A))if(Q[lN0])return Q[Id1];return null},set(Q){for(let $ of this.listeners(A))if($[lN0]){this.removeListener(A,$);break}if(typeof Q!=="function")return;this.addEventListener(A,Q,{[lN0]:!0})}})});S1.prototype.addEventListener=Vd1;S1.prototype.removeEventListener=Kd1;chA.exports=S1;function yhA(A,Q,$,B){let E={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Fd1,protocolVersion:iN0[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...B,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(A._autoPong=E.autoPong,A._closeTimeout=E.closeTimeout,!iN0.includes(E.protocolVersion))throw RangeError(`Unsupported protocol version: ${E.protocolVersion} (supported versions: ${iN0.join(", ")})`);let D;if(Q instanceof pN0)D=Q;else try{D=new pN0(Q)}catch{throw SyntaxError(`Invalid URL: ${Q}`)}if(D.protocol==="http:")D.protocol="ws:";else if(D.protocol==="https:")D.protocol="wss:";A._url=D.href;let J=D.protocol==="wss:",U=D.protocol==="ws+unix:",Y;if(D.protocol!=="ws:"&&!J&&!U)Y=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(U&&!D.pathname)Y="The URL's pathname is empty";else if(D.hash)Y="The URL contains a fragment identifier";if(Y){let K=SyntaxError(Y);if(A._redirects===0)throw K;else{w00(A,K);return}}let Z=J?443:80,F=Dd1(16).toString("base64"),X=J?$d1.request:Bd1.request,I=new Set,G;if(E.createConnection=E.createConnection||(J?qd1:Nd1),E.defaultPort=E.defaultPort||Z,E.port=D.port||Z,E.host=D.hostname.startsWith("[")?D.hostname.slice(1,-1):D.hostname,E.headers={...E.headers,"Sec-WebSocket-Version":E.protocolVersion,"Sec-WebSocket-Key":F,Connection:"Upgrade",Upgrade:"websocket"},E.path=D.pathname+D.search,E.timeout=E.handshakeTimeout,E.perMessageDeflate)G=new kG({...E.perMessageDeflate,isServer:!1,maxPayload:E.maxPayload}),E.headers["Sec-WebSocket-Extensions"]=zd1({[kG.extensionName]:G.offer()});if($.length){for(let K of $){if(typeof K!=="string"||!Hd1.test(K)||I.has(K))throw SyntaxError("An invalid or duplicated subprotocol was specified");I.add(K)}E.headers["Sec-WebSocket-Protocol"]=$.join(",")}if(E.origin)if(E.protocolVersion<13)E.headers["Sec-WebSocket-Origin"]=E.origin;else E.headers.Origin=E.origin;if(D.username||D.password)E.auth=`${D.username}:${D.password}`;if(U){let K=E.path.split(":");E.socketPath=K[0],E.path=K[1]}let V;if(E.followRedirects){if(A._redirects===0){A._originalIpc=U,A._originalSecure=J,A._originalHostOrSocketPath=U?E.socketPath:D.host;let K=B&&B.headers;if(B={...B,headers:{}},K)for(let[z,W]of Object.entries(K))B.headers[z.toLowerCase()]=W}else if(A.listenerCount("redirect")===0){let K=U?A._originalIpc?E.socketPath===A._originalHostOrSocketPath:!1:A._originalIpc?!1:D.host===A._originalHostOrSocketPath;if(!K||A._originalSecure&&!J){if(delete E.headers.authorization,delete E.headers.cookie,!K)delete E.headers.host;E.auth=void 0}}if(E.auth&&!B.headers.authorization)B.headers.authorization="Basic "+Buffer.from(E.auth).toString("base64");if(V=A._req=X(E),A._redirects)A.emit("redirect",A.url,V)}else V=A._req=X(E);if(E.timeout)V.on("timeout",()=>{m9(A,V,"Opening handshake has timed out")});if(V.on("error",(K)=>{if(V===null||V[xhA])return;V=A._req=null,w00(A,K)}),V.on("response",(K)=>{let z=K.headers.location,W=K.statusCode;if(z&&E.followRedirects&&W>=300&&W<400){if(++A._redirects>E.maxRedirects){m9(A,V,"Maximum redirects exceeded");return}V.abort();let C;try{C=new pN0(z,Q)}catch(H){let N=SyntaxError(`Invalid URL: ${z}`);w00(A,N);return}yhA(A,C,$,B)}else if(!A.emit("unexpected-response",V,K))m9(A,V,`Unexpected server response: ${K.statusCode}`)}),V.on("upgrade",(K,z,W)=>{if(A.emit("upgrade",K),A.readyState!==S1.CONNECTING)return;V=A._req=null;let C=K.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){m9(A,z,"Invalid Upgrade header");return}let H=Jd1("sha1").update(F+Xd1).digest("base64");if(K.headers["sec-websocket-accept"]!==H){m9(A,z,"Invalid Sec-WebSocket-Accept header");return}let N=K.headers["sec-websocket-protocol"],q;if(N!==void 0){if(!I.size)q="Server sent a subprotocol but none was requested";else if(!I.has(N))q="Server sent an invalid subprotocol"}else if(I.size)q="Server sent no subprotocol";if(q){m9(A,z,q);return}if(N)A._protocol=N;let u=K.headers["sec-websocket-extensions"];if(u!==void 0){if(!G){m9(A,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let L;try{L=Wd1(u)}catch(_){m9(A,z,"Invalid Sec-WebSocket-Extensions header");return}let R=Object.keys(L);if(R.length!==1||R[0]!==kG.extensionName){m9(A,z,"Server indicated an extension that was not requested");return}try{G.accept(L[kG.extensionName])}catch(_){m9(A,z,"Invalid Sec-WebSocket-Extensions header");return}A._extensions[kG.extensionName]=G}A.setSocket(z,W,{allowSynchronousEvents:E.allowSynchronousEvents,generateMask:E.generateMask,maxPayload:E.maxPayload,skipUTF8Validation:E.skipUTF8Validation})}),E.finishRequest)E.finishRequest(V,A);else V.end()}function w00(A,Q){A._readyState=S1.CLOSING,A._errorEmitted=!0,A.emit("error",Q),A.emitClose()}function Nd1(A){return A.path=A.socketPath,khA.connect(A)}function qd1(A){if(A.path=void 0,!A.servername&&A.servername!=="")A.servername=khA.isIP(A.host)?"":A.host;return Ed1.connect(A)}function m9(A,Q,$){A._readyState=S1.CLOSING;let B=Error($);if(Error.captureStackTrace(B,m9),Q.setHeader){if(Q[xhA]=!0,Q.abort(),Q.socket&&!Q.socket.destroyed)Q.socket.destroy();process.nextTick(w00,A,B)}else Q.destroy(B),Q.once("error",A.emit.bind(A,"error")),Q.once("close",A.emitClose.bind(A))}function nN0(A,Q,$){if(Q){let B=Zd1(Q)?Q.size:Cd1(Q).length;if(A._socket)A._sender._bufferedBytes+=B;else A._bufferedAmount+=B}if($){let B=Error(`WebSocket is not open: readyState ${A.readyState} (${CF[A.readyState]})`);process.nextTick($,B)}}function wd1(A,Q){let $=this[R3];if($._closeFrameReceived=!0,$._closeMessage=Q,$._closeCode=A,$._socket[R3]===void 0)return;if($._socket.removeListener("data",u00),process.nextTick(bhA,$._socket),A===1005)$.close();else $.close(A,Q)}function ud1(){let A=this[R3];if(!A.isPaused)A._socket.resume()}function Md1(A){let Q=this[R3];if(Q._socket[R3]!==void 0)Q._socket.removeListener("data",u00),process.nextTick(bhA,Q._socket),Q.close(A[Gd1]);if(!Q._errorEmitted)Q._errorEmitted=!0,Q.emit("error",A)}function ShA(){this[R3].emitClose()}function Od1(A,Q){this[R3].emit("message",A,Q)}function Ld1(A){let Q=this[R3];if(Q._autoPong)Q.pong(A,!this._isServer,fhA);Q.emit("ping",A)}function jd1(A){this[R3].emit("pong",A)}function bhA(A){A.resume()}function Rd1(A){let Q=this[R3];if(Q.readyState===S1.CLOSED)return;if(Q.readyState===S1.OPEN)Q._readyState=S1.CLOSING,hhA(Q);if(this._socket.end(),!Q._errorEmitted)Q._errorEmitted=!0,Q.emit("error",A)}function hhA(A){A._closeTimer=setTimeout(A._socket.destroy.bind(A._socket),A._closeTimeout)}function ghA(){let A=this[R3];if(this.removeListener("close",ghA),this.removeListener("data",u00),this.removeListener("end",mhA),A._readyState=S1.CLOSING,!this._readableState.endEmitted&&!A._closeFrameReceived&&!A._receiver._writableState.errorEmitted&&this._readableState.length!==0){let Q=this.read(this._readableState.length);A._receiver.write(Q)}if(A._receiver.end(),this[R3]=void 0,clearTimeout(A._closeTimer),A._receiver._writableState.finished||A._receiver._writableState.errorEmitted)A.emitClose();else A._receiver.on("error",ShA),A._receiver.on("finish",ShA)}function u00(A){if(!this[R3]._receiver.write(A))this.pause()}function mhA(){let A=this[R3];A._readyState=S1.CLOSING,A._receiver.end(),this.end()}function dhA(){let A=this[R3];if(this.removeListener("error",dhA),this.on("error",fhA),A)A._readyState=S1.CLOSING,this.destroy()}});var nhA=P((vl6,ihA)=>{var Pl6=M00(),{Duplex:Pd1}=Y0("stream");function phA(A){A.emit("close")}function vd1(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function lhA(A){if(this.removeListener("error",lhA),this.destroy(),this.listenerCount("error")===0)this.emit("error",A)}function Td1(A,Q){let $=!0,B=new Pd1({...Q,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return A.on("message",function(D,J){let U=!J&&B._readableState.objectMode?D.toString():D;if(!B.push(U))A.pause()}),A.once("error",function(D){if(B.destroyed)return;$=!1,B.destroy(D)}),A.once("close",function(){if(B.destroyed)return;B.push(null)}),B._destroy=function(E,D){if(A.readyState===A.CLOSED){D(E),process.nextTick(phA,B);return}let J=!1;if(A.once("error",function(Y){J=!0,D(Y)}),A.once("close",function(){if(!J)D(E);process.nextTick(phA,B)}),$)A.terminate()},B._final=function(E){if(A.readyState===A.CONNECTING){A.once("open",function(){B._final(E)});return}if(A._socket===null)return;if(A._socket._writableState.finished){if(E(),B._readableState.endEmitted)B.destroy()}else A._socket.once("finish",function(){E()}),A.close()},B._read=function(){if(A.isPaused)A.resume()},B._write=function(E,D,J){if(A.readyState===A.CONNECTING){A.once("open",function(){B._write(E,D,J)});return}A.send(E,J)},B.on("end",vd1),B.on("error",lhA),B}ihA.exports=Td1});var oN0=P((Tl6,ohA)=>{var{tokenChars:_d1}=nO();function Sd1(A){let Q=new Set,$=-1,B=-1,E=0;for(E;E<A.length;E++){let J=A.charCodeAt(E);if(B===-1&&_d1[J]===1){if($===-1)$=E}else if(E!==0&&(J===32||J===9)){if(B===-1&&$!==-1)B=E}else if(J===44){if($===-1)throw SyntaxError(`Unexpected character at index ${E}`);if(B===-1)B=E;let U=A.slice($,B);if(Q.has(U))throw SyntaxError(`The "${U}" subprotocol is duplicated`);Q.add(U),$=B=-1}else throw SyntaxError(`Unexpected character at index ${E}`)}if($===-1||B!==-1)throw SyntaxError("Unexpected end of input");let D=A.slice($,E);if(Q.has(D))throw SyntaxError(`The "${D}" subprotocol is duplicated`);return Q.add(D),Q}ohA.exports={parse:Sd1}});var ehA=P((Sl6,thA)=>{var kd1=Y0("events"),O00=Y0("http"),{Duplex:_l6}=Y0("stream"),{createHash:fd1}=Y0("crypto"),ahA=N00(),yC=iO(),xd1=oN0(),yd1=M00(),{CLOSE_TIMEOUT:bd1,GUID:hd1,kWebSocket:gd1}=zF(),md1=/^[+/0-9A-Za-z]{22}==$/;class shA extends kd1{constructor(A,Q){super();if(A={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:bd1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:yd1,...A},A.port==null&&!A.server&&!A.noServer||A.port!=null&&(A.server||A.noServer)||A.server&&A.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(A.port!=null)this._server=O00.createServer(($,B)=>{let E=O00.STATUS_CODES[426];B.writeHead(426,{"Content-Length":E.length,"Content-Type":"text/plain"}),B.end(E)}),this._server.listen(A.port,A.host,A.backlog,Q);else if(A.server)this._server=A.server;if(this._server){let $=this.emit.bind(this,"connection");this._removeListeners=dd1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(B,E,D)=>{this.handleUpgrade(B,E,D,$)}})}if(A.perMessageDeflate===!0)A.perMessageDeflate={};if(A.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=A,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(A){if(this._state===2){if(A)this.once("close",()=>{A(Error("The server is not running"))});process.nextTick(cy,this);return}if(A)this.once("close",A);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick(cy,this);else this._shouldEmitClose=!0;else process.nextTick(cy,this)}else{let Q=this._server;this._removeListeners(),this._removeListeners=this._server=null,Q.close(()=>{cy(this)})}}shouldHandle(A){if(this.options.path){let Q=A.url.indexOf("?");if((Q!==-1?A.url.slice(0,Q):A.url)!==this.options.path)return!1}return!0}handleUpgrade(A,Q,$,B){Q.on("error",rhA);let E=A.headers["sec-websocket-key"],D=A.headers.upgrade,J=+A.headers["sec-websocket-version"];if(A.method!=="GET"){bC(this,A,Q,405,"Invalid HTTP method");return}if(D===void 0||D.toLowerCase()!=="websocket"){bC(this,A,Q,400,"Invalid Upgrade header");return}if(E===void 0||!md1.test(E)){bC(this,A,Q,400,"Missing or invalid Sec-WebSocket-Key header");return}if(J!==13&&J!==8){bC(this,A,Q,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(A)){py(Q,400);return}let U=A.headers["sec-websocket-protocol"],Y=new Set;if(U!==void 0)try{Y=xd1.parse(U)}catch(X){bC(this,A,Q,400,"Invalid Sec-WebSocket-Protocol header");return}let Z=A.headers["sec-websocket-extensions"],F={};if(this.options.perMessageDeflate&&Z!==void 0){let X=new yC({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let I=ahA.parse(Z);if(I[yC.extensionName])X.accept(I[yC.extensionName]),F[yC.extensionName]=X}catch(I){bC(this,A,Q,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let X={origin:A.headers[`${J===8?"sec-websocket-origin":"origin"}`],secure:!!(A.socket.authorized||A.socket.encrypted),req:A};if(this.options.verifyClient.length===2){this.options.verifyClient(X,(I,G,V,K)=>{if(!I)return py(Q,G||401,V,K);this.completeUpgrade(F,E,Y,A,Q,$,B)});return}if(!this.options.verifyClient(X))return py(Q,401)}this.completeUpgrade(F,E,Y,A,Q,$,B)}completeUpgrade(A,Q,$,B,E,D,J){if(!E.readable||!E.writable)return E.destroy();if(E[gd1])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return py(E,503);let Y=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fd1("sha1").update(Q+hd1).digest("base64")}`],Z=new this.options.WebSocket(null,void 0,this.options);if($.size){let F=this.options.handleProtocols?this.options.handleProtocols($,B):$.values().next().value;if(F)Y.push(`Sec-WebSocket-Protocol: ${F}`),Z._protocol=F}if(A[yC.extensionName]){let F=A[yC.extensionName].params,X=ahA.format({[yC.extensionName]:[F]});Y.push(`Sec-WebSocket-Extensions: ${X}`),Z._extensions=A}if(this.emit("headers",Y,B),E.write(Y.concat(`\r
231
+ `)}function vyA(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($&&"role"in $&&$.role==="info"){for(let B of $.content)if(B.type==="summary"&&B.summary.type==="message")return{summaryBlock:B,index:Q}}}return}function FN0(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="user"&&$.agentMode)return $.agentMode}return}var A3=z0(()=>{rH0();tH0();w1()});function SO(A){if(!A)return{};return{[Wh1]:A.id}}var LG="x-amp-feature",Wh1="x-amp-thread-id",_O="x-amp-message-id",TyA="X-Amp-Client-Application",_yA="X-Amp-Client-Type",SyA="X-Amp-Client-Version",kyA="X-Amp-Installation-ID",fyA="X-Amp-Device-Fingerprint";var kO=()=>{};function byA(A){xyA=A}function jC(A){Ry=A}function hyA(A){yyA=A}function gyA(A){Py=A.installationID,vy=A.deviceFingerprint}function myA(){if(!Py||!vy)return;return{installationID:Py,deviceFingerprint:vy}}function R8(){let A=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(A)return{type:"cli",name:"AmpSDK",version:A};let Q;if(!Ry)Q="CLI";else if(["Neovim","JetBrains","Zed"].includes(Ry))Q=Ry;else Q=`${Ry} CLI`;return{type:"cli",name:yyA?`${Q} Execute Mode`:Q,version:xyA}}function fO(A){let Q={};if(Q[TyA]=A.name,Q[_yA]=A.type,Py)Q[kyA]=Py;if(vy)Q[fyA]=vy;if(A.version)Q[SyA]=A.version;return Q}var xyA=null,Ry=null,yyA=!1,Py=null,vy=null;var rU=z0(()=>{kO()});function Ch1(A){if(A.proxy&&!process.env.HTTP_PROXY&&!process.env.http_proxy)process.env.HTTP_PROXY=A.proxy;if(A.proxy&&!process.env.HTTPS_PROXY&&!process.env.https_proxy)process.env.HTTPS_PROXY=A.proxy}function xO(A,Q,$){let B=$?`/threads/${Q}/${$}`:`/threads/${Q}`;return new URL(B,A)}async function J5(A,Q,$){let B=await $.getLatest(Q?.signal??void 0),E=await cyA(A,Q,B);return fetch(E)}async function dyA(A,Q,$){let B=await cyA(Q,$,A);return fetch(B)}async function cyA(A,Q,$){if(A.startsWith("http:")||A.startsWith("https:"))throw Error("input must be a path, not an absolute URL");if(!A.startsWith("/"))throw Error("pathAndQuery must start with /");let B=$.settings.url;if(!B)throw Error("amp.url is not set");let E=await $.secrets.getToken("apiKey",B);Ch1({proxy:$.settings.proxy});let D=new URL(A,B);return new Request(D,{...Q,duplex:"half",headers:{"Content-Type":"application/json",...Q?.headers,...fO(R8()),...E?{Authorization:`Bearer ${E}`}:{}}})}async function pyA(A,Q,$,B){let E=await M4.shareThreadWithOperator({threadID:A,message:$||void 0,ephemeralError:B||void 0},{config:Q});if(!E.ok)throw Error(`Failed to share thread: ${E.error.message}`)}async function lyA(A,Q){let $=await J5("/api/telemetry",{method:"POST",redirect:"manual",body:A},Q);if(!$.ok){let B=await $.text(),E;try{E=JSON.parse(B).error||`HTTP ${$.status}`}catch{E=B||`HTTP ${$.status}`}throw Error(`Failed to submit telemetry: ${E}`)}}var y9=z0(()=>{rU();B$()});function Nh1(A){if(new Blob([A]).size<=Hh1)return{body:A};return{body:DfA.gzip(A),headers:{"Content-Encoding":"gzip"}}}function qh1(){return new Proxy({},{get:(A,Q)=>{return async(...$)=>{let B=$.at(1),E=$.at(0);if(!B?.config)throw Error("Internal API client requires configService in options. Call with { config: configService }");let{body:D,headers:J={}}=Nh1(JSON.stringify({method:Q,params:E})),U=await J5("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:D,headers:J,signal:B?.signal},B.config);if(!U.ok)throw Error(`API request for ${Q} failed: ${U.status}`);return await U.json()}}})}var Hh1=25600,M4;var B$=z0(()=>{JfA();y9();M4=qh1()});function wh1(A){return A.config.pipe(O1(({settings:Q,secrets:$})=>M1(async()=>({url:Q.url,proxy:Q.proxy,apiKey:await $.getToken("apiKey",Q.url)}))),UQ(dU),O1(()=>UO(600000).pipe(zQ(void 0),Ae(()=>M1(async(Q)=>{let $=await M4.getUserInfo({},{signal:Q,config:A});if($.ok)return $.result;if($.error&&$.error.code==="auth-required")return null;throw S.error("getUserInfo failed",{error:$.error}),Error(`getUserInfo error: ${$.error.code}`)})))),sA((Q)=>{return Q instanceof Error?{error:{message:String(Q)}}:Q===mU?"pending":Q?{user:Q,features:Q.features,workspace:Q?.team,mysteriousMessage:Q?.mysteriousMessage}:{error:{message:"User not found"}}}),UQ((Q,$)=>dU(Q,$)),L$({shouldCountRefs:!0}))}function yO(A){let Q=iyA.get(A);if(Q)return Q;let $=wh1(A);return iyA.set(A,$),$}function b9(A){return Boolean(typeof A==="object"&&"user"in A&&A.user)}function RC(A){return typeof A==="object"&&"error"in A}var iyA;var ie=z0(()=>{bA();s0();B$();iyA=new WeakMap});function L7(A){let Q=e1[A];return`${Q.provider}/${Q.name}`}function bO(A){let Q=A.indexOf("/");if(Q===-1)throw Error(`Invalid provider/model format: ${A}`);return{provider:A.slice(0,Q),model:A.slice(Q+1)}}function uh1(A){return Object.values(f4).includes(A)}function nyA(A){let Q=A.trim(),{provider:$,model:B}=bO(Q);if(!uh1($))throw Error(`Unknown model provider: ${$}`);if(!B.trim())throw Error(`Invalid provider/model format: ${Q}`)}function XN0(A){let Q=Mh1[A];if(Q===void 0)throw Error(`Unknown provider: ${A}`);let $={provider:Q.provider,contextWindow:Q.contextWindow,maxOutputTokens:Q.maxOutputTokens};if(Q.pricing!==void 0)$.pricing=Q.pricing;if(Q.capabilities!==void 0)$.capabilities=Q.capabilities;return $}function jG(A){let{provider:Q,model:$}=bO(A);for(let E of Object.values(e1))if(E.provider===Q&&E.name===$)return E;return{...XN0(Q),name:$,displayName:$}}function ne(A){for(let $ of Object.values(e1))if($.name===A)return $;let Q=A.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Q){let $=Q[1];for(let B of Object.values(e1))if(B.name===$)return B}return}function PC(A){let Q=A.indexOf("/");if(Q===-1)return A;return A.slice(Q+1)}function IN0(A){let Q=jG(A);return Q.contextWindow-Q.maxOutputTokens}var f4,e1,Mh1,GN0;var UD=z0(()=>{f4={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},e1={CLAUDE_SONNET_4:{provider:f4.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:f4.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:f4.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:f4.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:f4.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:f4.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:f4.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_7:{provider:f4.ANTHROPIC,name:"claude-opus-4-7",displayName:"Claude Opus 4.7",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_8:{provider:f4.ANTHROPIC,name:"claude-opus-4-8",displayName:"Claude Opus 4.8",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:2},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:f4.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:f4.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:f4.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:f4.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:f4.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5:{provider:f4.OPENAI,name:"gpt-5.5",displayName:"GPT-5.5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:5,output:30,cached:0.5},capabilities:{reasoning:!0,vision:!0,tools:!0}},AMP_NOSTROMO:{provider:f4.OPENAI,name:"amp-nostromo-v1",displayName:"nostromo",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0,output:0,cached:0},capabilities:{tools:!0}},GPT_5_4_PRO:{provider:f4.OPENAI,name:"gpt-5.4-pro",displayName:"GPT-5.4-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5_PRO:{provider:f4.OPENAI,name:"gpt-5.5-pro",displayName:"GPT-5.5-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:f4.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:f4.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:f4.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:f4.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:f4.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:f4.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:f4.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:f4.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:f4.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:f4.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_BUILD_0_1:{provider:f4.XAI,name:"grok-build-0.1",displayName:"Grok Build 0.1",contextWindow:256000,maxOutputTokens:32000,pricing:{input:1,output:2,cached:0.2},capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:f4.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:f4.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:f4.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_5_FLASH:{provider:f4.VERTEXAI,name:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:f4.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:f4.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:f4.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:f4.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:f4.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:f4.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:f4.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:f4.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:f4.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:f4.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};Mh1={anthropic:e1.CLAUDE_SONNET_4_5,openai:e1.GPT_5_4,xai:e1.GROK_BUILD_0_1,cerebras:e1.Z_AI_GLM_4_7,fireworks:e1.FIREWORKS_GLM_4P6,baseten:e1.BASETEN_KIMI_K2P5,moonshotai:e1.KIMI_K2_INSTRUCT,openrouter:e1.SONOMA_SKY_ALPHA,groq:e1.GPT_OSS_120B,vertexai:e1.GEMINI_3_1_PRO_PREVIEW};GN0={FINDER:"finder"}});function Ty(A){return typeof A==="string"&&jh1.includes(A)}function tyA(A){return A===syA}function oe(A,Q){if(!tyA(A))return!0;return Boolean(Q&&WG(Q))}function $bA(A){if(typeof A!=="string")return!1;return QbA.includes(A)}function BbA(A,Q){let $=E$(Q);if(!$)return!1;if(Oh1.has(A)){let B=$.finder??GN0.FINDER,E=Lh1[B];if(A!==E)return!1}if($.includeTools){if($.deferredTools?.includes(A))return!0;return $.includeTools.includes(A)}return!0}function EbA(A,Q){let $=E$(Q);if(!$)return!1;return $.deferredTools?.includes(A)??!1}function _h1(A){if(A?.isInternalUser!==void 0)return A.isInternalUser;return Boolean(A?.userEmail&&WG(A.userEmail))}function RG(A,Q){let $=A?.["internal.visibleModes"]??[],B=A?.["experimental.modes"]??[],E=[...$,...B];return Object.values(h9).filter((D)=>{if(tyA(D.key)&&!_h1(Q))return!1;if(D.key===AbA)return!1;if(E.includes(`!${D.key}`))return!1;if(Q?.v2&&!(("visibleInV2"in D)&&D.visibleInV2))return!1;let U="visible"in D?D.visible:!1,Y=E.includes(D.key);return U||Y}).map((D)=>({mode:D.key,description:"description"in D?D.description:void 0})).sort((D,J)=>D.mode.localeCompare(J.mode))}function E$(A){return Object.values(h9).find((Q)=>Q.key===A)}function vC(A){if(!A)return;return E$(A)?.reasoningEffortControl}function DbA(A,Q){let{levels:$}=A,B=Q?$.indexOf(Q):-1;if(B===-1)return $[0];return $[(B+1)%$.length]??$[0]}function ae(A,Q){return vC(A)?.levels.includes(Q)??!1}function hO(A,Q={}){if(!A||!$bA(A)||!vC(A))return;let $=Q["reasoning.effort"];if($!==void 0&&Ty($))return $;let B=E$(A)?.reasoningEffort;return B&&ae(A,B)?B:void 0}function re(A,Q,$){let B=E$(A),E=$??B?.displayName??A;if(Q!==void 0){let D=B?.reasoningEffortControl?.levels.indexOf(Q);if(D===1)return{base:E,superscript:"²",plainReasoningIndex:"2",text:`${E}²`};if(D===2)return{base:E,superscript:"³",plainReasoningIndex:"3",text:`${E}³`};if(D===3)return{base:E,superscript:"⁴",plainReasoningIndex:"4",text:`${E}⁴`}}return{base:E,superscript:"",plainReasoningIndex:void 0,text:E}}function KN0(A,Q){let B=(Q.findIndex((D)=>D.mode===A)+1)%Q.length;return Q[B]?.mode??"smart"}var Oh1,Lh1,jh1,ayA,ryA,syA="nostromo",Rh1,VN0,oyA,Ph1,vh1,eyA,Th1,h9,AbA,QbA;var j7=z0(()=>{UD();Oh1=new Set(["finder"]),Lh1={finder:"finder"},jh1=["none","minimal","low","medium","high","xhigh","max"];ayA={r:0,g:55,b:0},ryA={r:0,g:255,b:136};Rh1=["finder","shell_command","apply_patch","web_search","read_web_page","read_mcp_resource","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter"],VN0=["Read","finder","Bash","create_file","edit_file","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter","read_mcp_resource"],oyA=["code_review"],Ph1=["code_review"],vh1=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","archive_threads","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],eyA=["shell_command","apply_patch","web_search","read_web_page","Task","skill","read_thread","find_thread","librarian","oracle","finder","view_media","painter","send_message_to_aggman"],Th1=Array.from(new Set([...VN0,...eyA])),h9={DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.5",primaryModel:L7("GPT_5_5"),systemPrompt:"deep",promptFragments:["diagrams","toolConnectionError","guidanceFiles"],includeTools:eyA,deferredTools:Ph1,visible:!0,visibleInV2:!0,reasoningEffort:"medium",reasoningEffortControl:{levels:["low","medium","xhigh"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:L7("CLAUDE_OPUS_4_8"),systemPrompt:"smart",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:VN0,deferredTools:oyA,visible:!0,visibleInV2:!0,reasoningEffort:"high",reasoningEffortControl:{levels:["high","xhigh","max"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},RUSH:{key:"rush",displayName:"Rush",description:"Fast, low-token GPT-5.5 for small, well-defined tasks",primaryModel:L7("GPT_5_5"),systemPrompt:"rush",promptFragments:["toolConnectionError","guidanceFiles"],includeTools:Rh1,visible:!0,reasoningEffort:"none",subagents:{"task-subagent":{model:L7("GPT_5_5"),reasoningEffort:"none"}},uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:L7("CLAUDE_OPUS_4_6"),systemPrompt:"aggman",promptFragments:[],includeTools:vh1,visible:!1,serverOnly:!0,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:L7("CLAUDE_OPUS_4_6"),systemPrompt:"large",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:VN0,deferredTools:oyA,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},NOSTROMO:{key:syA,displayName:"nostromo",description:"Internal-only deterministic test mode with scripted tool scenarios",primaryModel:L7("AMP_NOSTROMO"),systemPrompt:"nostromo",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:Th1,visible:!0,visibleInV2:!0,reasoningEffort:"low",uiHints:{labelAnimation:"jitter",primaryColor:{r:0,g:46,b:77},secondaryColor:{r:48,g:213,b:200}}}},AbA=h9.AGG.key,QbA=Object.values(h9).map((A)=>A.key)});var PG=z0(()=>{j7();UD()});var zF=P((zl6,QhA)=>{var ebA=["nodebuffer","arraybuffer","fragments"],AhA=typeof Blob<"u";if(AhA)ebA.push("blob");QhA.exports={BINARY_TYPES:ebA,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:AhA,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var by=P((Wl6,G00)=>{var{EMPTY_BUFFER:Mm1}=zF(),fN0=Buffer[Symbol.species];function Om1(A,Q){if(A.length===0)return Mm1;if(A.length===1)return A[0];let $=Buffer.allocUnsafe(Q),B=0;for(let E=0;E<A.length;E++){let D=A[E];$.set(D,B),B+=D.length}if(B<Q)return new fN0($.buffer,$.byteOffset,B);return $}function $hA(A,Q,$,B,E){for(let D=0;D<E;D++)$[B+D]=A[D]^Q[D&3]}function BhA(A,Q){for(let $=0;$<A.length;$++)A[$]^=Q[$&3]}function Lm1(A){if(A.length===A.buffer.byteLength)return A.buffer;return A.buffer.slice(A.byteOffset,A.byteOffset+A.length)}function xN0(A){if(xN0.readOnly=!0,Buffer.isBuffer(A))return A;let Q;if(A instanceof ArrayBuffer)Q=new fN0(A);else if(ArrayBuffer.isView(A))Q=new fN0(A.buffer,A.byteOffset,A.byteLength);else Q=Buffer.from(A),xN0.readOnly=!1;return Q}G00.exports={concat:Om1,mask:$hA,toArrayBuffer:Lm1,toBuffer:xN0,unmask:BhA};if(!process.env.WS_NO_BUFFER_UTIL)try{let A=(()=>{throw new Error("Cannot require module "+"bufferutil");})();G00.exports.mask=function(Q,$,B,E,D){if(D<48)$hA(Q,$,B,E,D);else A.mask(Q,$,B,E,D)},G00.exports.unmask=function(Q,$){if(Q.length<32)BhA(Q,$);else A.unmask(Q,$)}}catch(A){}});var UhA=P((Cl6,JhA)=>{var EhA=Symbol("kDone"),yN0=Symbol("kRun");class DhA{constructor(A){this[EhA]=()=>{this.pending--,this[yN0]()},this.concurrency=A||1/0,this.jobs=[],this.pending=0}add(A){this.jobs.push(A),this[yN0]()}[yN0](){if(this.pending===this.concurrency)return;if(this.jobs.length){let A=this.jobs.shift();this.pending++,A(this[EhA])}}}JhA.exports=DhA});var iO=P((Hl6,IhA)=>{var hy=Y0("zlib"),YhA=by(),jm1=UhA(),{kStatusCode:ZhA}=zF(),Rm1=Buffer[Symbol.species],Pm1=Buffer.from([0,0,255,255]),K00=Symbol("permessage-deflate"),WF=Symbol("total-length"),pO=Symbol("callback"),TG=Symbol("buffers"),lO=Symbol("error"),V00;class FhA{constructor(A){if(this._options=A||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!V00){let Q=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;V00=new jm1(Q)}}static get extensionName(){return"permessage-deflate"}offer(){let A={};if(this._options.serverNoContextTakeover)A.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)A.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)A.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)A.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)A.client_max_window_bits=!0;return A}accept(A){return A=this.normalizeParams(A),this.params=this._isServer?this.acceptAsServer(A):this.acceptAsClient(A),this.params}cleanup(){if(this._inflate)this._inflate.close(),this._inflate=null;if(this._deflate){let A=this._deflate[pO];if(this._deflate.close(),this._deflate=null,A)A(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(A){let Q=this._options,$=A.find((B)=>{if(Q.serverNoContextTakeover===!1&&B.server_no_context_takeover||B.server_max_window_bits&&(Q.serverMaxWindowBits===!1||typeof Q.serverMaxWindowBits==="number"&&Q.serverMaxWindowBits>B.server_max_window_bits)||typeof Q.clientMaxWindowBits==="number"&&!B.client_max_window_bits)return!1;return!0});if(!$)throw Error("None of the extension offers can be accepted");if(Q.serverNoContextTakeover)$.server_no_context_takeover=!0;if(Q.clientNoContextTakeover)$.client_no_context_takeover=!0;if(typeof Q.serverMaxWindowBits==="number")$.server_max_window_bits=Q.serverMaxWindowBits;if(typeof Q.clientMaxWindowBits==="number")$.client_max_window_bits=Q.clientMaxWindowBits;else if($.client_max_window_bits===!0||Q.clientMaxWindowBits===!1)delete $.client_max_window_bits;return $}acceptAsClient(A){let Q=A[0];if(this._options.clientNoContextTakeover===!1&&Q.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(!Q.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")Q.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&Q.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"');return Q}normalizeParams(A){return A.forEach((Q)=>{Object.keys(Q).forEach(($)=>{let B=Q[$];if(B.length>1)throw Error(`Parameter "${$}" must have only a single value`);if(B=B[0],$==="client_max_window_bits"){if(B!==!0){let E=+B;if(!Number.isInteger(E)||E<8||E>15)throw TypeError(`Invalid value for parameter "${$}": ${B}`);B=E}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${$}": ${B}`)}else if($==="server_max_window_bits"){let E=+B;if(!Number.isInteger(E)||E<8||E>15)throw TypeError(`Invalid value for parameter "${$}": ${B}`);B=E}else if($==="client_no_context_takeover"||$==="server_no_context_takeover"){if(B!==!0)throw TypeError(`Invalid value for parameter "${$}": ${B}`)}else throw Error(`Unknown parameter "${$}"`);Q[$]=B})}),A}decompress(A,Q,$){V00.add((B)=>{this._decompress(A,Q,(E,D)=>{B(),$(E,D)})})}compress(A,Q,$){V00.add((B)=>{this._compress(A,Q,(E,D)=>{B(),$(E,D)})})}_decompress(A,Q,$){let B=this._isServer?"client":"server";if(!this._inflate){let E=`${B}_max_window_bits`,D=typeof this.params[E]!=="number"?hy.Z_DEFAULT_WINDOWBITS:this.params[E];this._inflate=hy.createInflateRaw({...this._options.zlibInflateOptions,windowBits:D}),this._inflate[K00]=this,this._inflate[WF]=0,this._inflate[TG]=[],this._inflate.on("error",Tm1),this._inflate.on("data",XhA)}if(this._inflate[pO]=$,this._inflate.write(A),Q)this._inflate.write(Pm1);this._inflate.flush(()=>{let E=this._inflate[lO];if(E){this._inflate.close(),this._inflate=null,$(E);return}let D=YhA.concat(this._inflate[TG],this._inflate[WF]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[WF]=0,this._inflate[TG]=[],Q&&this.params[`${B}_no_context_takeover`])this._inflate.reset();$(null,D)})}_compress(A,Q,$){let B=this._isServer?"server":"client";if(!this._deflate){let E=`${B}_max_window_bits`,D=typeof this.params[E]!=="number"?hy.Z_DEFAULT_WINDOWBITS:this.params[E];this._deflate=hy.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:D}),this._deflate[WF]=0,this._deflate[TG]=[],this._deflate.on("data",vm1)}this._deflate[pO]=$,this._deflate.write(A),this._deflate.flush(hy.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let E=YhA.concat(this._deflate[TG],this._deflate[WF]);if(Q)E=new Rm1(E.buffer,E.byteOffset,E.length-4);if(this._deflate[pO]=null,this._deflate[WF]=0,this._deflate[TG]=[],Q&&this.params[`${B}_no_context_takeover`])this._deflate.reset();$(null,E)})}}IhA.exports=FhA;function vm1(A){this[TG].push(A),this[WF]+=A.length}function XhA(A){if(this[WF]+=A.length,this[K00]._maxPayload<1||this[WF]<=this[K00]._maxPayload){this[TG].push(A);return}this[lO]=RangeError("Max payload size exceeded"),this[lO].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[lO][ZhA]=1009,this.removeListener("data",XhA),this.reset()}function Tm1(A){if(this[K00]._inflate=null,this[lO]){this[pO](this[lO]);return}A[ZhA]=1007,this[pO](A)}});var nO=P((Nl6,z00)=>{var{isUtf8:GhA}=Y0("buffer"),{hasBlob:_m1}=zF(),Sm1=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function km1(A){return A>=1000&&A<=1014&&A!==1004&&A!==1005&&A!==1006||A>=3000&&A<=4999}function bN0(A){let Q=A.length,$=0;while($<Q)if((A[$]&128)===0)$++;else if((A[$]&224)===192){if($+1===Q||(A[$+1]&192)!==128||(A[$]&254)===192)return!1;$+=2}else if((A[$]&240)===224){if($+2>=Q||(A[$+1]&192)!==128||(A[$+2]&192)!==128||A[$]===224&&(A[$+1]&224)===128||A[$]===237&&(A[$+1]&224)===160)return!1;$+=3}else if((A[$]&248)===240){if($+3>=Q||(A[$+1]&192)!==128||(A[$+2]&192)!==128||(A[$+3]&192)!==128||A[$]===240&&(A[$+1]&240)===128||A[$]===244&&A[$+1]>143||A[$]>244)return!1;$+=4}else return!1;return!0}function fm1(A){return _m1&&typeof A==="object"&&typeof A.arrayBuffer==="function"&&typeof A.type==="string"&&typeof A.stream==="function"&&(A[Symbol.toStringTag]==="Blob"||A[Symbol.toStringTag]==="File")}z00.exports={isBlob:fm1,isValidStatusCode:km1,isValidUTF8:bN0,tokenChars:Sm1};if(GhA)z00.exports.isValidUTF8=function(A){return A.length<24?bN0(A):GhA(A)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let A=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();z00.exports.isValidUTF8=function(Q){return Q.length<32?bN0(Q):A(Q)}}catch(A){}});var gN0=P((ql6,ChA)=>{var{Writable:xm1}=Y0("stream"),VhA=iO(),{BINARY_TYPES:ym1,EMPTY_BUFFER:KhA,kStatusCode:bm1,kWebSocket:hm1}=zF(),{concat:hN0,toArrayBuffer:gm1,unmask:mm1}=by(),{isValidStatusCode:dm1,isValidUTF8:zhA}=nO(),W00=Buffer[Symbol.species];class WhA extends xm1{constructor(A={}){super();this._allowSynchronousEvents=A.allowSynchronousEvents!==void 0?A.allowSynchronousEvents:!0,this._binaryType=A.binaryType||ym1[0],this._extensions=A.extensions||{},this._isServer=!!A.isServer,this._maxPayload=A.maxPayload|0,this._skipUTF8Validation=!!A.skipUTF8Validation,this[hm1]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(A,Q,$){if(this._opcode===8&&this._state==0)return $();this._bufferedBytes+=A.length,this._buffers.push(A),this.startLoop($)}consume(A){if(this._bufferedBytes-=A,A===this._buffers[0].length)return this._buffers.shift();if(A<this._buffers[0].length){let $=this._buffers[0];return this._buffers[0]=new W00($.buffer,$.byteOffset+A,$.length-A),new W00($.buffer,$.byteOffset,A)}let Q=Buffer.allocUnsafe(A);do{let $=this._buffers[0],B=Q.length-A;if(A>=$.length)Q.set(this._buffers.shift(),B);else Q.set(new Uint8Array($.buffer,$.byteOffset,A),B),this._buffers[0]=new W00($.buffer,$.byteOffset+A,$.length-A);A-=$.length}while(A>0);return Q}startLoop(A){this._loop=!0;do switch(this._state){case 0:this.getInfo(A);break;case 1:this.getPayloadLength16(A);break;case 2:this.getPayloadLength64(A);break;case 3:this.getMask();break;case 4:this.getData(A);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)A()}getInfo(A){if(this._bufferedBytes<2){this._loop=!1;return}let Q=this.consume(2);if((Q[0]&48)!==0){let B=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");A(B);return}let $=(Q[0]&64)===64;if($&&!this._extensions[VhA.extensionName]){let B=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(B);return}if(this._fin=(Q[0]&128)===128,this._opcode=Q[0]&15,this._payloadLength=Q[1]&127,this._opcode===0){if($){let B=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(B);return}if(!this._fragmented){let B=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");A(B);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let B=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(B);return}this._compressed=$}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let B=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");A(B);return}if($){let B=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(B);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let B=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");A(B);return}}else{let B=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(B);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(Q[1]&128)===128,this._isServer){if(!this._masked){let B=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");A(B);return}}else if(this._masked){let B=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");A(B);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else this.haveLength(A)}getPayloadLength16(A){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(A)}getPayloadLength64(A){if(this._bufferedBytes<8){this._loop=!1;return}let Q=this.consume(8),$=Q.readUInt32BE(0);if($>Math.pow(2,21)-1){let B=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");A(B);return}this._payloadLength=$*Math.pow(2,32)+Q.readUInt32BE(4),this.haveLength(A)}haveLength(A){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let Q=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");A(Q);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(A){let Q=KhA;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(Q=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)mm1(Q,this._mask)}if(this._opcode>7){this.controlMessage(Q,A);return}if(this._compressed){this._state=5,this.decompress(Q,A);return}if(Q.length)this._messageLength=this._totalPayloadLength,this._fragments.push(Q);this.dataMessage(A)}decompress(A,Q){this._extensions[VhA.extensionName].decompress(A,this._fin,(B,E)=>{if(B)return Q(B);if(E.length){if(this._messageLength+=E.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let D=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");Q(D);return}this._fragments.push(E)}if(this.dataMessage(Q),this._state===0)this.startLoop(Q)})}dataMessage(A){if(!this._fin){this._state=0;return}let Q=this._messageLength,$=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let B;if(this._binaryType==="nodebuffer")B=hN0($,Q);else if(this._binaryType==="arraybuffer")B=gm1(hN0($,Q));else if(this._binaryType==="blob")B=new Blob($);else B=$;if(this._allowSynchronousEvents)this.emit("message",B,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",B,!0),this._state=0,this.startLoop(A)})}else{let B=hN0($,Q);if(!this._skipUTF8Validation&&!zhA(B)){let E=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");A(E);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",B,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",B,!1),this._state=0,this.startLoop(A)})}}controlMessage(A,Q){if(this._opcode===8){if(A.length===0)this._loop=!1,this.emit("conclude",1005,KhA),this.end();else{let $=A.readUInt16BE(0);if(!dm1($)){let E=this.createError(RangeError,`invalid status code ${$}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");Q(E);return}let B=new W00(A.buffer,A.byteOffset+2,A.length-2);if(!this._skipUTF8Validation&&!zhA(B)){let E=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");Q(E);return}this._loop=!1,this.emit("conclude",$,B),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",A),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",A),this._state=0,this.startLoop(Q)})}createError(A,Q,$,B,E){this._loop=!1,this._errored=!0;let D=new A($?`Invalid WebSocket frame: ${Q}`:Q);return Error.captureStackTrace(D,this.createError),D.code=E,D[bm1]=B,D}}ChA.exports=WhA});var dN0=P((ul6,qhA)=>{var{Duplex:wl6}=Y0("stream"),{randomFillSync:cm1}=Y0("crypto"),HhA=iO(),{EMPTY_BUFFER:pm1,kWebSocket:lm1,NOOP:im1}=zF(),{isBlob:oO,isValidStatusCode:nm1}=nO(),{mask:NhA,toBuffer:fC}=by(),YD=Symbol("kByteLength"),om1=Buffer.alloc(4),xC,aO=8192,iJ=0,am1=1,rm1=2;class _G{constructor(A,Q,$){if(this._extensions=Q||{},$)this._generateMask=$,this._maskBuffer=Buffer.alloc(4);this._socket=A,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=iJ,this.onerror=im1,this[lm1]=void 0}static frame(A,Q){let $,B=!1,E=2,D=!1;if(Q.mask){if($=Q.maskBuffer||om1,Q.generateMask)Q.generateMask($);else{if(aO===8192){if(xC===void 0)xC=Buffer.alloc(8192);cm1(xC,0,8192),aO=0}$[0]=xC[aO++],$[1]=xC[aO++],$[2]=xC[aO++],$[3]=xC[aO++]}D=($[0]|$[1]|$[2]|$[3])===0,E=6}let J;if(typeof A==="string")if((!Q.mask||D)&&Q[YD]!==void 0)J=Q[YD];else A=Buffer.from(A),J=A.length;else J=A.length,B=Q.mask&&Q.readOnly&&!D;let U=J;if(J>=65536)E+=8,U=127;else if(J>125)E+=2,U=126;let Y=Buffer.allocUnsafe(B?J+E:E);if(Y[0]=Q.fin?Q.opcode|128:Q.opcode,Q.rsv1)Y[0]|=64;if(Y[1]=U,U===126)Y.writeUInt16BE(J,2);else if(U===127)Y[2]=Y[3]=0,Y.writeUIntBE(J,4,6);if(!Q.mask)return[Y,A];if(Y[1]|=128,Y[E-4]=$[0],Y[E-3]=$[1],Y[E-2]=$[2],Y[E-1]=$[3],D)return[Y,A];if(B)return NhA(A,$,Y,E,J),[Y];return NhA(A,$,A,0,J),[Y,A]}close(A,Q,$,B){let E;if(A===void 0)E=pm1;else if(typeof A!=="number"||!nm1(A))throw TypeError("First argument must be a valid error code number");else if(Q===void 0||!Q.length)E=Buffer.allocUnsafe(2),E.writeUInt16BE(A,0);else{let J=Buffer.byteLength(Q);if(J>123)throw RangeError("The message must not be greater than 123 bytes");if(E=Buffer.allocUnsafe(2+J),E.writeUInt16BE(A,0),typeof Q==="string")E.write(Q,2);else E.set(Q,2)}let D={[YD]:E.length,fin:!0,generateMask:this._generateMask,mask:$,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==iJ)this.enqueue([this.dispatch,E,!1,D,B]);else this.sendFrame(_G.frame(E,D),B)}ping(A,Q,$){let B,E;if(typeof A==="string")B=Buffer.byteLength(A),E=!1;else if(oO(A))B=A.size,E=!1;else A=fC(A),B=A.length,E=fC.readOnly;if(B>125)throw RangeError("The data size must not be greater than 125 bytes");let D={[YD]:B,fin:!0,generateMask:this._generateMask,mask:Q,maskBuffer:this._maskBuffer,opcode:9,readOnly:E,rsv1:!1};if(oO(A))if(this._state!==iJ)this.enqueue([this.getBlobData,A,!1,D,$]);else this.getBlobData(A,!1,D,$);else if(this._state!==iJ)this.enqueue([this.dispatch,A,!1,D,$]);else this.sendFrame(_G.frame(A,D),$)}pong(A,Q,$){let B,E;if(typeof A==="string")B=Buffer.byteLength(A),E=!1;else if(oO(A))B=A.size,E=!1;else A=fC(A),B=A.length,E=fC.readOnly;if(B>125)throw RangeError("The data size must not be greater than 125 bytes");let D={[YD]:B,fin:!0,generateMask:this._generateMask,mask:Q,maskBuffer:this._maskBuffer,opcode:10,readOnly:E,rsv1:!1};if(oO(A))if(this._state!==iJ)this.enqueue([this.getBlobData,A,!1,D,$]);else this.getBlobData(A,!1,D,$);else if(this._state!==iJ)this.enqueue([this.dispatch,A,!1,D,$]);else this.sendFrame(_G.frame(A,D),$)}send(A,Q,$){let B=this._extensions[HhA.extensionName],E=Q.binary?2:1,D=Q.compress,J,U;if(typeof A==="string")J=Buffer.byteLength(A),U=!1;else if(oO(A))J=A.size,U=!1;else A=fC(A),J=A.length,U=fC.readOnly;if(this._firstFragment){if(this._firstFragment=!1,D&&B&&B.params[B._isServer?"server_no_context_takeover":"client_no_context_takeover"])D=J>=B._threshold;this._compress=D}else D=!1,E=0;if(Q.fin)this._firstFragment=!0;let Y={[YD]:J,fin:Q.fin,generateMask:this._generateMask,mask:Q.mask,maskBuffer:this._maskBuffer,opcode:E,readOnly:U,rsv1:D};if(oO(A))if(this._state!==iJ)this.enqueue([this.getBlobData,A,this._compress,Y,$]);else this.getBlobData(A,this._compress,Y,$);else if(this._state!==iJ)this.enqueue([this.dispatch,A,this._compress,Y,$]);else this.dispatch(A,this._compress,Y,$)}getBlobData(A,Q,$,B){this._bufferedBytes+=$[YD],this._state=rm1,A.arrayBuffer().then((E)=>{if(this._socket.destroyed){let J=Error("The socket was closed while the blob was being read");process.nextTick(mN0,this,J,B);return}this._bufferedBytes-=$[YD];let D=fC(E);if(!Q)this._state=iJ,this.sendFrame(_G.frame(D,$),B),this.dequeue();else this.dispatch(D,Q,$,B)}).catch((E)=>{process.nextTick(sm1,this,E,B)})}dispatch(A,Q,$,B){if(!Q){this.sendFrame(_G.frame(A,$),B);return}let E=this._extensions[HhA.extensionName];this._bufferedBytes+=$[YD],this._state=am1,E.compress(A,$.fin,(D,J)=>{if(this._socket.destroyed){let U=Error("The socket was closed while data was being compressed");mN0(this,U,B);return}this._bufferedBytes-=$[YD],this._state=iJ,$.readOnly=!1,this.sendFrame(_G.frame(J,$),B),this.dequeue()})}dequeue(){while(this._state===iJ&&this._queue.length){let A=this._queue.shift();this._bufferedBytes-=A[3][YD],Reflect.apply(A[0],this,A.slice(1))}}enqueue(A){this._bufferedBytes+=A[3][YD],this._queue.push(A)}sendFrame(A,Q){if(A.length===2)this._socket.cork(),this._socket.write(A[0]),this._socket.write(A[1],Q),this._socket.uncork();else this._socket.write(A[0],Q)}}qhA.exports=_G;function mN0(A,Q,$){if(typeof $==="function")$(Q);for(let B=0;B<A._queue.length;B++){let E=A._queue[B],D=E[E.length-1];if(typeof D==="function")D(Q)}}function sm1(A,Q,$){mN0(A,Q,$),A.onerror(Q)}});var vhA=P((Ml6,PhA)=>{var{kForOnEventAttribute:gy,kListener:cN0}=zF(),whA=Symbol("kCode"),uhA=Symbol("kData"),MhA=Symbol("kError"),OhA=Symbol("kMessage"),LhA=Symbol("kReason"),rO=Symbol("kTarget"),jhA=Symbol("kType"),RhA=Symbol("kWasClean");class SG{constructor(A){this[rO]=null,this[jhA]=A}get target(){return this[rO]}get type(){return this[jhA]}}Object.defineProperty(SG.prototype,"target",{enumerable:!0});Object.defineProperty(SG.prototype,"type",{enumerable:!0});class sO extends SG{constructor(A,Q={}){super(A);this[whA]=Q.code===void 0?0:Q.code,this[LhA]=Q.reason===void 0?"":Q.reason,this[RhA]=Q.wasClean===void 0?!1:Q.wasClean}get code(){return this[whA]}get reason(){return this[LhA]}get wasClean(){return this[RhA]}}Object.defineProperty(sO.prototype,"code",{enumerable:!0});Object.defineProperty(sO.prototype,"reason",{enumerable:!0});Object.defineProperty(sO.prototype,"wasClean",{enumerable:!0});class my extends SG{constructor(A,Q={}){super(A);this[MhA]=Q.error===void 0?null:Q.error,this[OhA]=Q.message===void 0?"":Q.message}get error(){return this[MhA]}get message(){return this[OhA]}}Object.defineProperty(my.prototype,"error",{enumerable:!0});Object.defineProperty(my.prototype,"message",{enumerable:!0});class H00 extends SG{constructor(A,Q={}){super(A);this[uhA]=Q.data===void 0?null:Q.data}get data(){return this[uhA]}}Object.defineProperty(H00.prototype,"data",{enumerable:!0});var tm1={addEventListener(A,Q,$={}){for(let E of this.listeners(A))if(!$[gy]&&E[cN0]===Q&&!E[gy])return;let B;if(A==="message")B=function(D,J){let U=new H00("message",{data:J?D:D.toString()});U[rO]=this,C00(Q,this,U)};else if(A==="close")B=function(D,J){let U=new sO("close",{code:D,reason:J.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});U[rO]=this,C00(Q,this,U)};else if(A==="error")B=function(D){let J=new my("error",{error:D,message:D.message});J[rO]=this,C00(Q,this,J)};else if(A==="open")B=function(){let D=new SG("open");D[rO]=this,C00(Q,this,D)};else return;if(B[gy]=!!$[gy],B[cN0]=Q,$.once)this.once(A,B);else this.on(A,B)},removeEventListener(A,Q){for(let $ of this.listeners(A))if($[cN0]===Q&&!$[gy]){this.removeListener(A,$);break}}};PhA.exports={CloseEvent:sO,ErrorEvent:my,Event:SG,EventTarget:tm1,MessageEvent:H00};function C00(A,Q,$){if(typeof A==="object"&&A.handleEvent)A.handleEvent.call(A,$);else A.call(Q,$)}});var N00=P((Ol6,ThA)=>{var{tokenChars:dy}=nO();function sU(A,Q,$){if(A[Q]===void 0)A[Q]=[$];else A[Q].push($)}function em1(A){let Q=Object.create(null),$=Object.create(null),B=!1,E=!1,D=!1,J,U,Y=-1,Z=-1,F=-1,X=0;for(;X<A.length;X++)if(Z=A.charCodeAt(X),J===void 0)if(F===-1&&dy[Z]===1){if(Y===-1)Y=X}else if(X!==0&&(Z===32||Z===9)){if(F===-1&&Y!==-1)F=X}else if(Z===59||Z===44){if(Y===-1)throw SyntaxError(`Unexpected character at index ${X}`);if(F===-1)F=X;let G=A.slice(Y,F);if(Z===44)sU(Q,G,$),$=Object.create(null);else J=G;Y=F=-1}else throw SyntaxError(`Unexpected character at index ${X}`);else if(U===void 0)if(F===-1&&dy[Z]===1){if(Y===-1)Y=X}else if(Z===32||Z===9){if(F===-1&&Y!==-1)F=X}else if(Z===59||Z===44){if(Y===-1)throw SyntaxError(`Unexpected character at index ${X}`);if(F===-1)F=X;if(sU($,A.slice(Y,F),!0),Z===44)sU(Q,J,$),$=Object.create(null),J=void 0;Y=F=-1}else if(Z===61&&Y!==-1&&F===-1)U=A.slice(Y,X),Y=F=-1;else throw SyntaxError(`Unexpected character at index ${X}`);else if(E){if(dy[Z]!==1)throw SyntaxError(`Unexpected character at index ${X}`);if(Y===-1)Y=X;else if(!B)B=!0;E=!1}else if(D)if(dy[Z]===1){if(Y===-1)Y=X}else if(Z===34&&Y!==-1)D=!1,F=X;else if(Z===92)E=!0;else throw SyntaxError(`Unexpected character at index ${X}`);else if(Z===34&&A.charCodeAt(X-1)===61)D=!0;else if(F===-1&&dy[Z]===1){if(Y===-1)Y=X}else if(Y!==-1&&(Z===32||Z===9)){if(F===-1)F=X}else if(Z===59||Z===44){if(Y===-1)throw SyntaxError(`Unexpected character at index ${X}`);if(F===-1)F=X;let G=A.slice(Y,F);if(B)G=G.replace(/\\/g,""),B=!1;if(sU($,U,G),Z===44)sU(Q,J,$),$=Object.create(null),J=void 0;U=void 0,Y=F=-1}else throw SyntaxError(`Unexpected character at index ${X}`);if(Y===-1||D||Z===32||Z===9)throw SyntaxError("Unexpected end of input");if(F===-1)F=X;let I=A.slice(Y,F);if(J===void 0)sU(Q,I,$);else{if(U===void 0)sU($,I,!0);else if(B)sU($,U,I.replace(/\\/g,""));else sU($,U,I);sU(Q,J,$)}return Q}function Ad1(A){return Object.keys(A).map((Q)=>{let $=A[Q];if(!Array.isArray($))$=[$];return $.map((B)=>{return[Q].concat(Object.keys(B).map((E)=>{let D=B[E];if(!Array.isArray(D))D=[D];return D.map((J)=>J===!0?E:`${E}=${J}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}ThA.exports={format:Ad1,parse:em1}});var M00=P((Rl6,chA)=>{var Qd1=Y0("events"),$d1=Y0("https"),Bd1=Y0("http"),khA=Y0("net"),Ed1=Y0("tls"),{randomBytes:Dd1,createHash:Jd1}=Y0("crypto"),{Duplex:Ll6,Readable:jl6}=Y0("stream"),{URL:pN0}=Y0("url"),kG=iO(),Ud1=gN0(),Yd1=dN0(),{isBlob:Zd1}=nO(),{BINARY_TYPES:_hA,CLOSE_TIMEOUT:Fd1,EMPTY_BUFFER:q00,GUID:Xd1,kForOnEventAttribute:lN0,kListener:Id1,kStatusCode:Gd1,kWebSocket:R3,NOOP:fhA}=zF(),{EventTarget:{addEventListener:Vd1,removeEventListener:Kd1}}=vhA(),{format:zd1,parse:Wd1}=N00(),{toBuffer:Cd1}=by(),xhA=Symbol("kAborted"),iN0=[8,13],CF=["CONNECTING","OPEN","CLOSING","CLOSED"],Hd1=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class S1 extends Qd1{constructor(A,Q,$){super();if(this._binaryType=_hA[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=q00,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=S1.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,A!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,Q===void 0)Q=[];else if(!Array.isArray(Q))if(typeof Q==="object"&&Q!==null)$=Q,Q=[];else Q=[Q];yhA(this,A,Q,$)}else this._autoPong=$.autoPong,this._closeTimeout=$.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(A){if(!_hA.includes(A))return;if(this._binaryType=A,this._receiver)this._receiver._binaryType=A}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(A,Q,$){let B=new Ud1({allowSynchronousEvents:$.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:$.maxPayload,skipUTF8Validation:$.skipUTF8Validation}),E=new Yd1(A,this._extensions,$.generateMask);if(this._receiver=B,this._sender=E,this._socket=A,B[R3]=this,E[R3]=this,A[R3]=this,B.on("conclude",wd1),B.on("drain",ud1),B.on("error",Md1),B.on("message",Od1),B.on("ping",Ld1),B.on("pong",jd1),E.onerror=Rd1,A.setTimeout)A.setTimeout(0);if(A.setNoDelay)A.setNoDelay();if(Q.length>0)A.unshift(Q);A.on("close",ghA),A.on("data",u00),A.on("end",mhA),A.on("error",dhA),this._readyState=S1.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=S1.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[kG.extensionName])this._extensions[kG.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=S1.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(A,Q){if(this.readyState===S1.CLOSED)return;if(this.readyState===S1.CONNECTING){m9(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===S1.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=S1.CLOSING,this._sender.close(A,Q,!this._isServer,($)=>{if($)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),hhA(this)}pause(){if(this.readyState===S1.CONNECTING||this.readyState===S1.CLOSED)return;this._paused=!0,this._socket.pause()}ping(A,Q,$){if(this.readyState===S1.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof A==="function")$=A,A=Q=void 0;else if(typeof Q==="function")$=Q,Q=void 0;if(typeof A==="number")A=A.toString();if(this.readyState!==S1.OPEN){nN0(this,A,$);return}if(Q===void 0)Q=!this._isServer;this._sender.ping(A||q00,Q,$)}pong(A,Q,$){if(this.readyState===S1.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof A==="function")$=A,A=Q=void 0;else if(typeof Q==="function")$=Q,Q=void 0;if(typeof A==="number")A=A.toString();if(this.readyState!==S1.OPEN){nN0(this,A,$);return}if(Q===void 0)Q=!this._isServer;this._sender.pong(A||q00,Q,$)}resume(){if(this.readyState===S1.CONNECTING||this.readyState===S1.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(A,Q,$){if(this.readyState===S1.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Q==="function")$=Q,Q={};if(typeof A==="number")A=A.toString();if(this.readyState!==S1.OPEN){nN0(this,A,$);return}let B={binary:typeof A!=="string",mask:!this._isServer,compress:!0,fin:!0,...Q};if(!this._extensions[kG.extensionName])B.compress=!1;this._sender.send(A||q00,B,$)}terminate(){if(this.readyState===S1.CLOSED)return;if(this.readyState===S1.CONNECTING){m9(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=S1.CLOSING,this._socket.destroy()}}Object.defineProperty(S1,"CONNECTING",{enumerable:!0,value:CF.indexOf("CONNECTING")});Object.defineProperty(S1.prototype,"CONNECTING",{enumerable:!0,value:CF.indexOf("CONNECTING")});Object.defineProperty(S1,"OPEN",{enumerable:!0,value:CF.indexOf("OPEN")});Object.defineProperty(S1.prototype,"OPEN",{enumerable:!0,value:CF.indexOf("OPEN")});Object.defineProperty(S1,"CLOSING",{enumerable:!0,value:CF.indexOf("CLOSING")});Object.defineProperty(S1.prototype,"CLOSING",{enumerable:!0,value:CF.indexOf("CLOSING")});Object.defineProperty(S1,"CLOSED",{enumerable:!0,value:CF.indexOf("CLOSED")});Object.defineProperty(S1.prototype,"CLOSED",{enumerable:!0,value:CF.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((A)=>{Object.defineProperty(S1.prototype,A,{enumerable:!0})});["open","error","close","message"].forEach((A)=>{Object.defineProperty(S1.prototype,`on${A}`,{enumerable:!0,get(){for(let Q of this.listeners(A))if(Q[lN0])return Q[Id1];return null},set(Q){for(let $ of this.listeners(A))if($[lN0]){this.removeListener(A,$);break}if(typeof Q!=="function")return;this.addEventListener(A,Q,{[lN0]:!0})}})});S1.prototype.addEventListener=Vd1;S1.prototype.removeEventListener=Kd1;chA.exports=S1;function yhA(A,Q,$,B){let E={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Fd1,protocolVersion:iN0[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...B,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(A._autoPong=E.autoPong,A._closeTimeout=E.closeTimeout,!iN0.includes(E.protocolVersion))throw RangeError(`Unsupported protocol version: ${E.protocolVersion} (supported versions: ${iN0.join(", ")})`);let D;if(Q instanceof pN0)D=Q;else try{D=new pN0(Q)}catch{throw SyntaxError(`Invalid URL: ${Q}`)}if(D.protocol==="http:")D.protocol="ws:";else if(D.protocol==="https:")D.protocol="wss:";A._url=D.href;let J=D.protocol==="wss:",U=D.protocol==="ws+unix:",Y;if(D.protocol!=="ws:"&&!J&&!U)Y=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(U&&!D.pathname)Y="The URL's pathname is empty";else if(D.hash)Y="The URL contains a fragment identifier";if(Y){let K=SyntaxError(Y);if(A._redirects===0)throw K;else{w00(A,K);return}}let Z=J?443:80,F=Dd1(16).toString("base64"),X=J?$d1.request:Bd1.request,I=new Set,G;if(E.createConnection=E.createConnection||(J?qd1:Nd1),E.defaultPort=E.defaultPort||Z,E.port=D.port||Z,E.host=D.hostname.startsWith("[")?D.hostname.slice(1,-1):D.hostname,E.headers={...E.headers,"Sec-WebSocket-Version":E.protocolVersion,"Sec-WebSocket-Key":F,Connection:"Upgrade",Upgrade:"websocket"},E.path=D.pathname+D.search,E.timeout=E.handshakeTimeout,E.perMessageDeflate)G=new kG({...E.perMessageDeflate,isServer:!1,maxPayload:E.maxPayload}),E.headers["Sec-WebSocket-Extensions"]=zd1({[kG.extensionName]:G.offer()});if($.length){for(let K of $){if(typeof K!=="string"||!Hd1.test(K)||I.has(K))throw SyntaxError("An invalid or duplicated subprotocol was specified");I.add(K)}E.headers["Sec-WebSocket-Protocol"]=$.join(",")}if(E.origin)if(E.protocolVersion<13)E.headers["Sec-WebSocket-Origin"]=E.origin;else E.headers.Origin=E.origin;if(D.username||D.password)E.auth=`${D.username}:${D.password}`;if(U){let K=E.path.split(":");E.socketPath=K[0],E.path=K[1]}let V;if(E.followRedirects){if(A._redirects===0){A._originalIpc=U,A._originalSecure=J,A._originalHostOrSocketPath=U?E.socketPath:D.host;let K=B&&B.headers;if(B={...B,headers:{}},K)for(let[z,W]of Object.entries(K))B.headers[z.toLowerCase()]=W}else if(A.listenerCount("redirect")===0){let K=U?A._originalIpc?E.socketPath===A._originalHostOrSocketPath:!1:A._originalIpc?!1:D.host===A._originalHostOrSocketPath;if(!K||A._originalSecure&&!J){if(delete E.headers.authorization,delete E.headers.cookie,!K)delete E.headers.host;E.auth=void 0}}if(E.auth&&!B.headers.authorization)B.headers.authorization="Basic "+Buffer.from(E.auth).toString("base64");if(V=A._req=X(E),A._redirects)A.emit("redirect",A.url,V)}else V=A._req=X(E);if(E.timeout)V.on("timeout",()=>{m9(A,V,"Opening handshake has timed out")});if(V.on("error",(K)=>{if(V===null||V[xhA])return;V=A._req=null,w00(A,K)}),V.on("response",(K)=>{let z=K.headers.location,W=K.statusCode;if(z&&E.followRedirects&&W>=300&&W<400){if(++A._redirects>E.maxRedirects){m9(A,V,"Maximum redirects exceeded");return}V.abort();let C;try{C=new pN0(z,Q)}catch(H){let N=SyntaxError(`Invalid URL: ${z}`);w00(A,N);return}yhA(A,C,$,B)}else if(!A.emit("unexpected-response",V,K))m9(A,V,`Unexpected server response: ${K.statusCode}`)}),V.on("upgrade",(K,z,W)=>{if(A.emit("upgrade",K),A.readyState!==S1.CONNECTING)return;V=A._req=null;let C=K.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){m9(A,z,"Invalid Upgrade header");return}let H=Jd1("sha1").update(F+Xd1).digest("base64");if(K.headers["sec-websocket-accept"]!==H){m9(A,z,"Invalid Sec-WebSocket-Accept header");return}let N=K.headers["sec-websocket-protocol"],q;if(N!==void 0){if(!I.size)q="Server sent a subprotocol but none was requested";else if(!I.has(N))q="Server sent an invalid subprotocol"}else if(I.size)q="Server sent no subprotocol";if(q){m9(A,z,q);return}if(N)A._protocol=N;let u=K.headers["sec-websocket-extensions"];if(u!==void 0){if(!G){m9(A,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let L;try{L=Wd1(u)}catch(_){m9(A,z,"Invalid Sec-WebSocket-Extensions header");return}let R=Object.keys(L);if(R.length!==1||R[0]!==kG.extensionName){m9(A,z,"Server indicated an extension that was not requested");return}try{G.accept(L[kG.extensionName])}catch(_){m9(A,z,"Invalid Sec-WebSocket-Extensions header");return}A._extensions[kG.extensionName]=G}A.setSocket(z,W,{allowSynchronousEvents:E.allowSynchronousEvents,generateMask:E.generateMask,maxPayload:E.maxPayload,skipUTF8Validation:E.skipUTF8Validation})}),E.finishRequest)E.finishRequest(V,A);else V.end()}function w00(A,Q){A._readyState=S1.CLOSING,A._errorEmitted=!0,A.emit("error",Q),A.emitClose()}function Nd1(A){return A.path=A.socketPath,khA.connect(A)}function qd1(A){if(A.path=void 0,!A.servername&&A.servername!=="")A.servername=khA.isIP(A.host)?"":A.host;return Ed1.connect(A)}function m9(A,Q,$){A._readyState=S1.CLOSING;let B=Error($);if(Error.captureStackTrace(B,m9),Q.setHeader){if(Q[xhA]=!0,Q.abort(),Q.socket&&!Q.socket.destroyed)Q.socket.destroy();process.nextTick(w00,A,B)}else Q.destroy(B),Q.once("error",A.emit.bind(A,"error")),Q.once("close",A.emitClose.bind(A))}function nN0(A,Q,$){if(Q){let B=Zd1(Q)?Q.size:Cd1(Q).length;if(A._socket)A._sender._bufferedBytes+=B;else A._bufferedAmount+=B}if($){let B=Error(`WebSocket is not open: readyState ${A.readyState} (${CF[A.readyState]})`);process.nextTick($,B)}}function wd1(A,Q){let $=this[R3];if($._closeFrameReceived=!0,$._closeMessage=Q,$._closeCode=A,$._socket[R3]===void 0)return;if($._socket.removeListener("data",u00),process.nextTick(bhA,$._socket),A===1005)$.close();else $.close(A,Q)}function ud1(){let A=this[R3];if(!A.isPaused)A._socket.resume()}function Md1(A){let Q=this[R3];if(Q._socket[R3]!==void 0)Q._socket.removeListener("data",u00),process.nextTick(bhA,Q._socket),Q.close(A[Gd1]);if(!Q._errorEmitted)Q._errorEmitted=!0,Q.emit("error",A)}function ShA(){this[R3].emitClose()}function Od1(A,Q){this[R3].emit("message",A,Q)}function Ld1(A){let Q=this[R3];if(Q._autoPong)Q.pong(A,!this._isServer,fhA);Q.emit("ping",A)}function jd1(A){this[R3].emit("pong",A)}function bhA(A){A.resume()}function Rd1(A){let Q=this[R3];if(Q.readyState===S1.CLOSED)return;if(Q.readyState===S1.OPEN)Q._readyState=S1.CLOSING,hhA(Q);if(this._socket.end(),!Q._errorEmitted)Q._errorEmitted=!0,Q.emit("error",A)}function hhA(A){A._closeTimer=setTimeout(A._socket.destroy.bind(A._socket),A._closeTimeout)}function ghA(){let A=this[R3];if(this.removeListener("close",ghA),this.removeListener("data",u00),this.removeListener("end",mhA),A._readyState=S1.CLOSING,!this._readableState.endEmitted&&!A._closeFrameReceived&&!A._receiver._writableState.errorEmitted&&this._readableState.length!==0){let Q=this.read(this._readableState.length);A._receiver.write(Q)}if(A._receiver.end(),this[R3]=void 0,clearTimeout(A._closeTimer),A._receiver._writableState.finished||A._receiver._writableState.errorEmitted)A.emitClose();else A._receiver.on("error",ShA),A._receiver.on("finish",ShA)}function u00(A){if(!this[R3]._receiver.write(A))this.pause()}function mhA(){let A=this[R3];A._readyState=S1.CLOSING,A._receiver.end(),this.end()}function dhA(){let A=this[R3];if(this.removeListener("error",dhA),this.on("error",fhA),A)A._readyState=S1.CLOSING,this.destroy()}});var nhA=P((vl6,ihA)=>{var Pl6=M00(),{Duplex:Pd1}=Y0("stream");function phA(A){A.emit("close")}function vd1(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function lhA(A){if(this.removeListener("error",lhA),this.destroy(),this.listenerCount("error")===0)this.emit("error",A)}function Td1(A,Q){let $=!0,B=new Pd1({...Q,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return A.on("message",function(D,J){let U=!J&&B._readableState.objectMode?D.toString():D;if(!B.push(U))A.pause()}),A.once("error",function(D){if(B.destroyed)return;$=!1,B.destroy(D)}),A.once("close",function(){if(B.destroyed)return;B.push(null)}),B._destroy=function(E,D){if(A.readyState===A.CLOSED){D(E),process.nextTick(phA,B);return}let J=!1;if(A.once("error",function(Y){J=!0,D(Y)}),A.once("close",function(){if(!J)D(E);process.nextTick(phA,B)}),$)A.terminate()},B._final=function(E){if(A.readyState===A.CONNECTING){A.once("open",function(){B._final(E)});return}if(A._socket===null)return;if(A._socket._writableState.finished){if(E(),B._readableState.endEmitted)B.destroy()}else A._socket.once("finish",function(){E()}),A.close()},B._read=function(){if(A.isPaused)A.resume()},B._write=function(E,D,J){if(A.readyState===A.CONNECTING){A.once("open",function(){B._write(E,D,J)});return}A.send(E,J)},B.on("end",vd1),B.on("error",lhA),B}ihA.exports=Td1});var oN0=P((Tl6,ohA)=>{var{tokenChars:_d1}=nO();function Sd1(A){let Q=new Set,$=-1,B=-1,E=0;for(E;E<A.length;E++){let J=A.charCodeAt(E);if(B===-1&&_d1[J]===1){if($===-1)$=E}else if(E!==0&&(J===32||J===9)){if(B===-1&&$!==-1)B=E}else if(J===44){if($===-1)throw SyntaxError(`Unexpected character at index ${E}`);if(B===-1)B=E;let U=A.slice($,B);if(Q.has(U))throw SyntaxError(`The "${U}" subprotocol is duplicated`);Q.add(U),$=B=-1}else throw SyntaxError(`Unexpected character at index ${E}`)}if($===-1||B!==-1)throw SyntaxError("Unexpected end of input");let D=A.slice($,E);if(Q.has(D))throw SyntaxError(`The "${D}" subprotocol is duplicated`);return Q.add(D),Q}ohA.exports={parse:Sd1}});var ehA=P((Sl6,thA)=>{var kd1=Y0("events"),O00=Y0("http"),{Duplex:_l6}=Y0("stream"),{createHash:fd1}=Y0("crypto"),ahA=N00(),yC=iO(),xd1=oN0(),yd1=M00(),{CLOSE_TIMEOUT:bd1,GUID:hd1,kWebSocket:gd1}=zF(),md1=/^[+/0-9A-Za-z]{22}==$/;class shA extends kd1{constructor(A,Q){super();if(A={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:bd1,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:yd1,...A},A.port==null&&!A.server&&!A.noServer||A.port!=null&&(A.server||A.noServer)||A.server&&A.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(A.port!=null)this._server=O00.createServer(($,B)=>{let E=O00.STATUS_CODES[426];B.writeHead(426,{"Content-Length":E.length,"Content-Type":"text/plain"}),B.end(E)}),this._server.listen(A.port,A.host,A.backlog,Q);else if(A.server)this._server=A.server;if(this._server){let $=this.emit.bind(this,"connection");this._removeListeners=dd1(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(B,E,D)=>{this.handleUpgrade(B,E,D,$)}})}if(A.perMessageDeflate===!0)A.perMessageDeflate={};if(A.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=A,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(A){if(this._state===2){if(A)this.once("close",()=>{A(Error("The server is not running"))});process.nextTick(cy,this);return}if(A)this.once("close",A);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick(cy,this);else this._shouldEmitClose=!0;else process.nextTick(cy,this)}else{let Q=this._server;this._removeListeners(),this._removeListeners=this._server=null,Q.close(()=>{cy(this)})}}shouldHandle(A){if(this.options.path){let Q=A.url.indexOf("?");if((Q!==-1?A.url.slice(0,Q):A.url)!==this.options.path)return!1}return!0}handleUpgrade(A,Q,$,B){Q.on("error",rhA);let E=A.headers["sec-websocket-key"],D=A.headers.upgrade,J=+A.headers["sec-websocket-version"];if(A.method!=="GET"){bC(this,A,Q,405,"Invalid HTTP method");return}if(D===void 0||D.toLowerCase()!=="websocket"){bC(this,A,Q,400,"Invalid Upgrade header");return}if(E===void 0||!md1.test(E)){bC(this,A,Q,400,"Missing or invalid Sec-WebSocket-Key header");return}if(J!==13&&J!==8){bC(this,A,Q,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(A)){py(Q,400);return}let U=A.headers["sec-websocket-protocol"],Y=new Set;if(U!==void 0)try{Y=xd1.parse(U)}catch(X){bC(this,A,Q,400,"Invalid Sec-WebSocket-Protocol header");return}let Z=A.headers["sec-websocket-extensions"],F={};if(this.options.perMessageDeflate&&Z!==void 0){let X=new yC({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let I=ahA.parse(Z);if(I[yC.extensionName])X.accept(I[yC.extensionName]),F[yC.extensionName]=X}catch(I){bC(this,A,Q,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let X={origin:A.headers[`${J===8?"sec-websocket-origin":"origin"}`],secure:!!(A.socket.authorized||A.socket.encrypted),req:A};if(this.options.verifyClient.length===2){this.options.verifyClient(X,(I,G,V,K)=>{if(!I)return py(Q,G||401,V,K);this.completeUpgrade(F,E,Y,A,Q,$,B)});return}if(!this.options.verifyClient(X))return py(Q,401)}this.completeUpgrade(F,E,Y,A,Q,$,B)}completeUpgrade(A,Q,$,B,E,D,J){if(!E.readable||!E.writable)return E.destroy();if(E[gd1])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return py(E,503);let Y=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fd1("sha1").update(Q+hd1).digest("base64")}`],Z=new this.options.WebSocket(null,void 0,this.options);if($.size){let F=this.options.handleProtocols?this.options.handleProtocols($,B):$.values().next().value;if(F)Y.push(`Sec-WebSocket-Protocol: ${F}`),Z._protocol=F}if(A[yC.extensionName]){let F=A[yC.extensionName].params,X=ahA.format({[yC.extensionName]:[F]});Y.push(`Sec-WebSocket-Extensions: ${X}`),Z._extensions=A}if(this.emit("headers",Y,B),E.write(Y.concat(`\r
232
232
  `).join(`\r
233
233
  `)),E.removeListener("error",rhA),Z.setSocket(E,D,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(Z),Z.on("close",()=>{if(this.clients.delete(Z),this._shouldEmitClose&&!this.clients.size)process.nextTick(cy,this)});J(Z,B)}}thA.exports=shA;function dd1(A,Q){for(let $ of Object.keys(Q))A.on($,Q[$]);return function(){for(let B of Object.keys(Q))A.removeListener(B,Q[B])}}function cy(A){A._state=2,A.emit("close")}function rhA(){this.destroy()}function py(A,Q,$,B){$=$||O00.STATUS_CODES[Q],B={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength($),...B},A.once("finish",A.destroy),A.end(`HTTP/1.1 ${Q} ${O00.STATUS_CODES[Q]}\r
234
234
  `+Object.keys(B).map((E)=>`${E}: ${B[E]}`).join(`\r
@@ -805,7 +805,7 @@ Expected format:
805
805
  *** Begin Patch
806
806
  *** Add File: path/to/file.ts
807
807
  +file contents
808
- *** End Patch\`);if(g===-1)throw Error('Invalid patch format: missing *** Begin Patch marker. Patch must start with "*** Begin Patch"');if(t===-1)throw Error('Invalid patch format: missing *** End Patch marker. Patch must end with "*** End Patch"');if(t<g)throw Error("Invalid patch format: *** End Patch appears before *** Begin Patch. Check marker ordering.");let I=i.slice(0,g).filter((l)=>l.trim()!=="");if(I.length>0)n.push(\`Warning: \${I.length} non-empty line(s) before *** Begin Patch were ignored. First ignored: "\${I[0].slice(0,40)}\${I[0].length>40?"...":""}"\`);let b=i.findIndex((l,q)=>q>g&&l.trim()==="*** Begin Patch");if(b!==-1&&b<t)n.push(\`Warning: duplicate "*** Begin Patch" found at line \${b+1}. Only the first marker is used.\`);let D=i.slice(t+1).filter((l)=>l.trim()!=="");if(D.length>0)n.push(\`Warning: \${D.length} non-empty line(s) after *** End Patch were ignored. First ignored: "\${D[0].slice(0,40)}\${D[0].length>40?"...":""}"\`);let k=g+1;while(k<t){let l=WD(i,k);if(!l){k++;continue}let q=i[k];if(q.startsWith("*** Add File:")){let{content:W,nextIdx:Z}=SD(i,l.nextIdx);o.push({type:"add",path:l.filePath,contents:W}),k=Z}else if(q.startsWith("*** Delete File:"))o.push({type:"delete",path:l.filePath}),k=l.nextIdx;else if(q.startsWith("*** Update File:")){let{chunks:W,nextIdx:Z}=ND(i,l.nextIdx);o.push({type:"update",path:l.filePath,movePath:l.movePath,chunks:W}),k=Z}else k++}return{hunks:o,warnings:n.length>0?n:void 0}}var w6="Bash",Qb="shell_command";var Wb="create_file";var Sb="edit_file";var Nb="apply_patch";function Vb(r){return r==="done"||r==="error"||r==="rejected-by-user"||r==="cancelled"}var K={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},ur={CLAUDE_SONNET_4:{provider:K.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:K.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:K.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:K.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:K.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:K.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:K.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_7:{provider:K.ANTHROPIC,name:"claude-opus-4-7",displayName:"Claude Opus 4.7",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_8:{provider:K.ANTHROPIC,name:"claude-opus-4-8",displayName:"Claude Opus 4.8",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:2},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:K.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:K.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:K.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:K.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:K.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5:{provider:K.OPENAI,name:"gpt-5.5",displayName:"GPT-5.5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:5,output:30,cached:0.5},capabilities:{reasoning:!0,vision:!0,tools:!0}},AMP_NOSTROMO:{provider:K.OPENAI,name:"amp-nostromo-v1",displayName:"nostromo",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0,output:0,cached:0},capabilities:{tools:!0}},GPT_5_4_PRO:{provider:K.OPENAI,name:"gpt-5.4-pro",displayName:"GPT-5.4-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5_PRO:{provider:K.OPENAI,name:"gpt-5.5-pro",displayName:"GPT-5.5-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:K.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:K.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:K.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:K.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:K.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:K.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:K.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:K.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:K.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:K.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_BUILD_0_1:{provider:K.XAI,name:"grok-build-0.1",displayName:"Grok Build 0.1",contextWindow:256000,maxOutputTokens:32000,pricing:{input:1,output:2,cached:0.2},capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:K.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:K.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:K.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_5_FLASH:{provider:K.VERTEXAI,name:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:K.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:K.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:K.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:K.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:K.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:K.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:K.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:K.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:K.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:K.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:K.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:K.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:K.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:K.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:K.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};function Nr(r){let v=ur[r];return\`\${v.provider}/\${v.name}\`}function Hb(r){let v=r.indexOf("/");if(v===-1)throw Error(\`Invalid provider/model format: \${r}\`);return{provider:r.slice(0,v),model:r.slice(v+1)}}function HD(r){return Object.values(K).includes(r)}function Bb(r){let v=r.trim(),{provider:i,model:o}=Hb(v);if(!HD(i))throw Error(\`Unknown model provider: \${i}\`);if(!o.trim())throw Error(\`Invalid provider/model format: \${v}\`)}var Wc={anthropic:ur.CLAUDE_SONNET_4_5,openai:ur.GPT_5_4,xai:ur.GROK_BUILD_0_1,cerebras:ur.Z_AI_GLM_4_7,fireworks:ur.FIREWORKS_GLM_4P6,baseten:ur.BASETEN_KIMI_K2P5,moonshotai:ur.KIMI_K2_INSTRUCT,openrouter:ur.SONOMA_SKY_ALPHA,groq:ur.GPT_OSS_120B,vertexai:ur.GEMINI_3_1_PRO_PREVIEW};var Bc=new Set(["finder"]),Fc={finder:"finder"};var BD="nostromo";var FD=["finder","shell_command","apply_patch","web_search","read_web_page","read_mcp_resource","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter"],D6=["Read","finder","Bash","create_file","edit_file","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter","read_mcp_resource"],Fb=["code_review"],AD=["code_review"],PD=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","archive_threads","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],Ab=["shell_command","apply_patch","web_search","read_web_page","Task","skill","read_thread","find_thread","librarian","oracle","finder","view_media","painter","send_message_to_aggman"],TD=Array.from(new Set([...D6,...Ab])),ei={DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.5",primaryModel:Nr("GPT_5_5"),systemPrompt:"deep",promptFragments:["diagrams","toolConnectionError","guidanceFiles"],includeTools:Ab,deferredTools:AD,visible:!0,visibleInV2:!0,reasoningEffort:"medium",reasoningEffortControl:{levels:["low","medium","xhigh"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:Nr("CLAUDE_OPUS_4_7"),systemPrompt:"smart",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:D6,deferredTools:Fb,visible:!0,visibleInV2:!0,reasoningEffort:"high",reasoningEffortControl:{levels:["high","xhigh","max"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},RUSH:{key:"rush",displayName:"Rush",description:"Fast, low-token GPT-5.5 for small, well-defined tasks",primaryModel:Nr("GPT_5_5"),systemPrompt:"rush",promptFragments:["toolConnectionError","guidanceFiles"],includeTools:FD,visible:!0,reasoningEffort:"none",subagents:{"task-subagent":{model:Nr("GPT_5_5"),reasoningEffort:"none"}},uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:Nr("CLAUDE_OPUS_4_6"),systemPrompt:"aggman",promptFragments:[],includeTools:PD,visible:!1,serverOnly:!0,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:Nr("CLAUDE_OPUS_4_6"),systemPrompt:"large",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:D6,deferredTools:Fb,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},NOSTROMO:{key:BD,displayName:"nostromo",description:"Internal-only deterministic test mode with scripted tool scenarios",primaryModel:Nr("AMP_NOSTROMO"),systemPrompt:"nostromo",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:TD,visible:!0,visibleInV2:!0,reasoningEffort:"low",uiHints:{labelAnimation:"jitter",primaryColor:{r:0,g:46,b:77},secondaryColor:{r:48,g:213,b:200}}}};var Ac=ei.AGG.key,Pc=Object.values(ei).map((r)=>r.key);import Dv from"path";function Pb(){if(typeof process==="object")return process.platform==="win32"?"windows":"posix";else if(typeof navigator==="object")return navigator.userAgent.indexOf("Windows")>=0?"windows":"posix";return"posix"}var ZD=/^\\w[\\w\\d+.-]*$/,LD=/^\\//,ED=/^\\/\\//;function Tb(r,v){if(!r.scheme&&v)throw Error(\`[UriError]: Scheme is missing: {scheme: "", authority: "\${r.authority}", path: "\${r.path}", query: "\${r.query}", fragment: "\${r.fragment}"}\`);if(r.scheme&&!ZD.test(r.scheme))throw Error("[UriError]: Scheme contains illegal characters.");if(r.path){if(r.authority){if(!LD.test(r.path))throw Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(ED.test(r.path))throw Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function OD(r,v){if(!r&&!v)return"file";return r}function MD(r,v){switch(r){case"https":case"http":case"file":if(!v)v=gr;else if(v[0]!==gr)v=gr+v;break}return v}var A="",gr="/",RD=/^(([^:/?#]+?):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/;class ir{static isUri(r){if(r instanceof ir)return!0;if(!r)return!1;let v=r;return typeof v.authority==="string"&&typeof v.fragment==="string"&&typeof v.path==="string"&&typeof v.query==="string"&&typeof v.scheme==="string"&&typeof v.fsPath==="string"&&typeof v.with==="function"&&typeof v.toString==="function"}scheme;authority;path;query;fragment;platform;constructor(r,v,i,o,n,$=!1,u){if(typeof r==="object")this.scheme=r.scheme||A,this.authority=r.authority||A,this.path=r.path||A,this.query=r.query||A,this.fragment=r.fragment||A,this.platform=r.platform;else this.scheme=OD(r,$),this.authority=v||A,this.path=MD(this.scheme,i||A),this.query=o||A,this.fragment=n||A,this.platform=u,Tb(this,$)}get fsPath(){return Mb(this,!1)}with(r){if(!r)return this;let{scheme:v,authority:i,path:o,query:n,fragment:$,platform:u}=r;if(v===void 0)v=this.scheme;else if(v===null)v=A;if(i===void 0)i=this.authority;else if(i===null)i=A;if(o===void 0)o=this.path;else if(o===null)o=A;if(n===void 0)n=this.query;else if(n===null)n=A;if($===void 0)$=this.fragment;else if($===null)$=A;if(u===void 0)u=this.platform;else if(u===null)u=void 0;if(v===this.scheme&&i===this.authority&&o===this.path&&n===this.query&&$===this.fragment&&u===this.platform)return this;return new Rr(v,i,o,n,$,!1,u)}static parse(r,v=!1){let i=RD.exec(r);if(!i)return new Rr(A,A,A,A,A);return new Rr(i[2]||A,pi(i[4]||A),pi(i[5]||A),pi(i[7]||A),pi(i[9]||A),v)}static file(r,v=Pb()){let i=A;if(v==="windows")r=r.replace(/\\\\/g,gr);if(r[0]===gr&&r[1]===gr){let o=r.indexOf(gr,2);if(o===-1)i=r.substring(2),r=gr;else i=r.substring(2,o),r=r.substring(o)||gr}return new Rr("file",i,r,A,A,!1,v)}static from(r){let v=new Rr(r.scheme,r.authority,r.path,r.query,r.fragment,!0,r.platform);return Tb(v,!0),v}toString(r=!1){return k6(this,r)}toJSON(){return this}static revive(r){if(!r)return r;if(r instanceof ir)return r;let v=new Rr(r),i=r;return v._formatted=i.external,v._fsPath=i._sep===Eb(v.platform)?i.fsPath:null,v}}function Eb(r){return r==="windows"?1:void 0}class Rr extends ir{_formatted=null;_fsPath=null;get fsPath(){if(!this._fsPath)this._fsPath=Mb(this,!1);return this._fsPath}toString(r=!1){if(!r){if(!this._formatted)this._formatted=k6(this,!1);return this._formatted}return k6(this,!0)}toJSON(){let r={};if(this._fsPath)r.fsPath=this._fsPath,r._sep=Eb(this.platform);if(this._formatted)r.external=this._formatted;if(r.scheme=this.scheme,r.authority=this.authority,r.path=this.path,r.query=this.query,r.fragment=this.fragment,this.platform)r.platform=this.platform;return r}}var Ob={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function Zb(r,v,i){let o;for(let n=0;n<r.length;n++){let $=r.charCodeAt(n);if($>=97&&$<=122||$>=65&&$<=90||$>=48&&$<=57||$===45||$===46||$===95||$===126||v&&$===47||i&&$===91||i&&$===93||i&&$===58){if(o!==void 0)o+=r.charAt(n)}else{if(o===void 0)o=r.substring(0,n);let u=Ob[$];if(u!==void 0)o+=u;else o+=encodeURIComponent(r.charAt(n))}}return o!==void 0?o:r}function CD(r){let v;for(let i=0;i<r.length;i++){let o=r.charCodeAt(i);if(o===35||o===63){if(v===void 0)v=r.substring(0,i);v+=Ob[o]}else if(v!==void 0)v+=r[i]}return v!==void 0?v:r}function Mb(r,v){let i;if(r.authority&&r.path.length>1&&r.scheme==="file")i=\`//\${r.authority}\${r.path}\`;else if(r.path.charCodeAt(0)===47&&(r.path.charCodeAt(1)>=65&&r.path.charCodeAt(1)<=90||r.path.charCodeAt(1)>=97&&r.path.charCodeAt(1)<=122)&&r.path.charCodeAt(2)===58)if(!v)i=r.path[1].toLowerCase()+r.path.substring(2);else i=r.path.substring(1);else i=r.path;if(r.platform==="windows")i=i.replace(/\\//g,"\\\\");return i}function k6(r,v){let i=!v?Zb:CD,o="",{scheme:n,authority:$,path:u,query:g,fragment:t}=r;if(n)o+=n,o+=":";if($||n==="file")o+=gr,o+=gr;if($){let I=$.indexOf("@");if(I!==-1){let b=$.substring(0,I);if($=$.substring(I+1),I=b.lastIndexOf(":"),I===-1)o+=i(b,!1,!1);else o+=i(b.substring(0,I),!1,!1),o+=":",o+=i(b.substring(I+1),!1,!0);o+="@"}if($=$.toLowerCase(),I=$.lastIndexOf(":"),I===-1)o+=i($,!1,!0);else o+=i($.substring(0,I),!1,!0),o+=$.substring(I)}if(u){if(u.length>=3&&u.charCodeAt(0)===47&&u.charCodeAt(2)===58){let I=u.charCodeAt(1);if(I>=65&&I<=90)u=\`/\${String.fromCharCode(I+32)}:\${u.substring(3)}\`}else if(u.length>=2&&u.charCodeAt(1)===58){let I=u.charCodeAt(0);if(I>=65&&I<=90)u=\`\${String.fromCharCode(I+32)}:\${u.substring(2)}\`}o+=i(u,!0,!1)}if(g)o+="?",o+=i(g,!1,!1);if(t)o+="#",o+=!v?Zb(t,!1,!1):t;return o}function Rb(r){try{return decodeURIComponent(r)}catch{if(r.length>3)return r.substring(0,3)+Rb(r.substring(3));else return r}}var Lb=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function pi(r){if(!r.match(Lb))return r;return r.replace(Lb,(v)=>Rb(v))}var xD=hi.string().brand();var j=TU(oU(),1),{optWhitespace:Tk}=j.default;function uU(r,v){return r.then(v).skip(r)}function Zk(r){return j.default((v,i)=>{let o=v.indexOf(r,i);if(o!==-1)return j.default.makeSuccess(o+r.length,v.substring(i,o));return j.default.makeFailure(i,[r])})}function s(r,v){let i=r;return j.default((o,n)=>{for(let $ of i){let u=$._(o,n);if(u.status)return u}return j.default.makeFailure(n,[v])})}function Lk(r,v,i){return j.default((o,n)=>{let $=[],u=n;if(i._(o,u).status)return j.default.makeFailure(u,["at least one match before terminator"]);let t=r._(o,u);if(!t.status)return t;$.push(t.value),u=t.index;while(!0){if(i._(o,u).status)break;let b=v._(o,u);if(!b.status)break;u=b.index;let D=r._(o,u);if(!D.status)break;$.push(D.value),u=D.index}return j.default.makeSuccess(u,$)})}var Ek=new Set('\\\\|&<>(); "[]');function Ok(){return j.default((r,v)=>{let i=v,o="";while(i<r.length){let n=r[i];if(n==="\\\\"){let $=r[i+1];if($===void 0||!Ek.has($))break;o+=$,i+=2;continue}if(Mk(n)){o+=n,i++;continue}if(n==="$"&&!Rk(r[i+1])){o+=n,i++;continue}if(n==="("){let $=Ck(r,i);if($===void 0)break;o+=r.slice(i,$),i=$;continue}break}if(i===v)return j.default.makeFailure(v,["unquoted string"]);return j.default.makeSuccess(i,o)})}function Mk(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_"||r==="-"||r===":"||r==="/"||r==="."||r==="*"||r==="~"||r==="@"||r==="="||r==="+"||r==="^"||r===","||r==="["||r==="]"||r==="#"||r==="!"}function Rk(r){return r==="{"||r==="("||r==="_"||r!==void 0&&r>="a"&&r<="z"||r!==void 0&&r>="A"&&r<="Z"}function Ck(r,v){let i=v+1;while(i<r.length){let o=r[i];if(o===")")return i+1;if(!xk(o))return;i++}return}function xk(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_"||r==="-"}function fk(){return j.default((r,v)=>{let i=v,o="";while(i<r.length){let n=r[i];if(mk(n)){o+=n,i++;continue}let $=r[i+1];if(n==="\\\\"&&$!==void 0&&yk($)){o+=$,i+=2;continue}break}return j.default.makeSuccess(i,o)})}function mk(r){return r===" "||r==="\\t"||r===\`
808
+ *** End Patch\`);if(g===-1)throw Error('Invalid patch format: missing *** Begin Patch marker. Patch must start with "*** Begin Patch"');if(t===-1)throw Error('Invalid patch format: missing *** End Patch marker. Patch must end with "*** End Patch"');if(t<g)throw Error("Invalid patch format: *** End Patch appears before *** Begin Patch. Check marker ordering.");let I=i.slice(0,g).filter((l)=>l.trim()!=="");if(I.length>0)n.push(\`Warning: \${I.length} non-empty line(s) before *** Begin Patch were ignored. First ignored: "\${I[0].slice(0,40)}\${I[0].length>40?"...":""}"\`);let b=i.findIndex((l,q)=>q>g&&l.trim()==="*** Begin Patch");if(b!==-1&&b<t)n.push(\`Warning: duplicate "*** Begin Patch" found at line \${b+1}. Only the first marker is used.\`);let D=i.slice(t+1).filter((l)=>l.trim()!=="");if(D.length>0)n.push(\`Warning: \${D.length} non-empty line(s) after *** End Patch were ignored. First ignored: "\${D[0].slice(0,40)}\${D[0].length>40?"...":""}"\`);let k=g+1;while(k<t){let l=WD(i,k);if(!l){k++;continue}let q=i[k];if(q.startsWith("*** Add File:")){let{content:W,nextIdx:Z}=SD(i,l.nextIdx);o.push({type:"add",path:l.filePath,contents:W}),k=Z}else if(q.startsWith("*** Delete File:"))o.push({type:"delete",path:l.filePath}),k=l.nextIdx;else if(q.startsWith("*** Update File:")){let{chunks:W,nextIdx:Z}=ND(i,l.nextIdx);o.push({type:"update",path:l.filePath,movePath:l.movePath,chunks:W}),k=Z}else k++}return{hunks:o,warnings:n.length>0?n:void 0}}var w6="Bash",Qb="shell_command";var Wb="create_file";var Sb="edit_file";var Nb="apply_patch";function Vb(r){return r==="done"||r==="error"||r==="rejected-by-user"||r==="cancelled"}var K={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},ur={CLAUDE_SONNET_4:{provider:K.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:K.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:K.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:K.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:K.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:K.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:K.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_7:{provider:K.ANTHROPIC,name:"claude-opus-4-7",displayName:"Claude Opus 4.7",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:6},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_8:{provider:K.ANTHROPIC,name:"claude-opus-4-8",displayName:"Claude Opus 4.8",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300,fastModeMultiplier:2},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:K.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:K.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:K.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:K.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:K.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5:{provider:K.OPENAI,name:"gpt-5.5",displayName:"GPT-5.5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:5,output:30,cached:0.5},capabilities:{reasoning:!0,vision:!0,tools:!0}},AMP_NOSTROMO:{provider:K.OPENAI,name:"amp-nostromo-v1",displayName:"nostromo",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0,output:0,cached:0},capabilities:{tools:!0}},GPT_5_4_PRO:{provider:K.OPENAI,name:"gpt-5.4-pro",displayName:"GPT-5.4-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_5_PRO:{provider:K.OPENAI,name:"gpt-5.5-pro",displayName:"GPT-5.5-Pro",contextWindow:1050000,maxOutputTokens:128000,pricing:{input:30,output:180,cached:30},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:K.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:K.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:K.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:K.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:K.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:K.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:K.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:K.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:K.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:K.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_BUILD_0_1:{provider:K.XAI,name:"grok-build-0.1",displayName:"Grok Build 0.1",contextWindow:256000,maxOutputTokens:32000,pricing:{input:1,output:2,cached:0.2},capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:K.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:K.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:K.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_5_FLASH:{provider:K.VERTEXAI,name:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:K.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:K.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:K.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:K.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:K.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:K.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:K.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:K.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:K.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:K.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:K.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:K.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:K.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:K.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:K.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};function Nr(r){let v=ur[r];return\`\${v.provider}/\${v.name}\`}function Hb(r){let v=r.indexOf("/");if(v===-1)throw Error(\`Invalid provider/model format: \${r}\`);return{provider:r.slice(0,v),model:r.slice(v+1)}}function HD(r){return Object.values(K).includes(r)}function Bb(r){let v=r.trim(),{provider:i,model:o}=Hb(v);if(!HD(i))throw Error(\`Unknown model provider: \${i}\`);if(!o.trim())throw Error(\`Invalid provider/model format: \${v}\`)}var Wc={anthropic:ur.CLAUDE_SONNET_4_5,openai:ur.GPT_5_4,xai:ur.GROK_BUILD_0_1,cerebras:ur.Z_AI_GLM_4_7,fireworks:ur.FIREWORKS_GLM_4P6,baseten:ur.BASETEN_KIMI_K2P5,moonshotai:ur.KIMI_K2_INSTRUCT,openrouter:ur.SONOMA_SKY_ALPHA,groq:ur.GPT_OSS_120B,vertexai:ur.GEMINI_3_1_PRO_PREVIEW};var Bc=new Set(["finder"]),Fc={finder:"finder"};var BD="nostromo";var FD=["finder","shell_command","apply_patch","web_search","read_web_page","read_mcp_resource","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter"],D6=["Read","finder","Bash","create_file","edit_file","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","Task","view_media","painter","read_mcp_resource"],Fb=["code_review"],AD=["code_review"],PD=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","archive_threads","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],Ab=["shell_command","apply_patch","web_search","read_web_page","Task","skill","read_thread","find_thread","librarian","oracle","finder","view_media","painter","send_message_to_aggman"],TD=Array.from(new Set([...D6,...Ab])),ei={DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.5",primaryModel:Nr("GPT_5_5"),systemPrompt:"deep",promptFragments:["diagrams","toolConnectionError","guidanceFiles"],includeTools:Ab,deferredTools:AD,visible:!0,visibleInV2:!0,reasoningEffort:"medium",reasoningEffortControl:{levels:["low","medium","xhigh"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:Nr("CLAUDE_OPUS_4_8"),systemPrompt:"smart",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:D6,deferredTools:Fb,visible:!0,visibleInV2:!0,reasoningEffort:"high",reasoningEffortControl:{levels:["high","xhigh","max"]},uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},RUSH:{key:"rush",displayName:"Rush",description:"Fast, low-token GPT-5.5 for small, well-defined tasks",primaryModel:Nr("GPT_5_5"),systemPrompt:"rush",promptFragments:["toolConnectionError","guidanceFiles"],includeTools:FD,visible:!0,reasoningEffort:"none",subagents:{"task-subagent":{model:Nr("GPT_5_5"),reasoningEffort:"none"}},uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:Nr("CLAUDE_OPUS_4_6"),systemPrompt:"aggman",promptFragments:[],includeTools:PD,visible:!1,serverOnly:!0,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:Nr("CLAUDE_OPUS_4_6"),systemPrompt:"large",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:D6,deferredTools:Fb,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},NOSTROMO:{key:BD,displayName:"nostromo",description:"Internal-only deterministic test mode with scripted tool scenarios",primaryModel:Nr("AMP_NOSTROMO"),systemPrompt:"nostromo",promptFragments:["diagrams","fileLinks","toolConnectionError","guidanceFiles"],includeTools:TD,visible:!0,visibleInV2:!0,reasoningEffort:"low",uiHints:{labelAnimation:"jitter",primaryColor:{r:0,g:46,b:77},secondaryColor:{r:48,g:213,b:200}}}};var Ac=ei.AGG.key,Pc=Object.values(ei).map((r)=>r.key);import Dv from"path";function Pb(){if(typeof process==="object")return process.platform==="win32"?"windows":"posix";else if(typeof navigator==="object")return navigator.userAgent.indexOf("Windows")>=0?"windows":"posix";return"posix"}var ZD=/^\\w[\\w\\d+.-]*$/,LD=/^\\//,ED=/^\\/\\//;function Tb(r,v){if(!r.scheme&&v)throw Error(\`[UriError]: Scheme is missing: {scheme: "", authority: "\${r.authority}", path: "\${r.path}", query: "\${r.query}", fragment: "\${r.fragment}"}\`);if(r.scheme&&!ZD.test(r.scheme))throw Error("[UriError]: Scheme contains illegal characters.");if(r.path){if(r.authority){if(!LD.test(r.path))throw Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(ED.test(r.path))throw Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}function OD(r,v){if(!r&&!v)return"file";return r}function MD(r,v){switch(r){case"https":case"http":case"file":if(!v)v=gr;else if(v[0]!==gr)v=gr+v;break}return v}var A="",gr="/",RD=/^(([^:/?#]+?):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/;class ir{static isUri(r){if(r instanceof ir)return!0;if(!r)return!1;let v=r;return typeof v.authority==="string"&&typeof v.fragment==="string"&&typeof v.path==="string"&&typeof v.query==="string"&&typeof v.scheme==="string"&&typeof v.fsPath==="string"&&typeof v.with==="function"&&typeof v.toString==="function"}scheme;authority;path;query;fragment;platform;constructor(r,v,i,o,n,$=!1,u){if(typeof r==="object")this.scheme=r.scheme||A,this.authority=r.authority||A,this.path=r.path||A,this.query=r.query||A,this.fragment=r.fragment||A,this.platform=r.platform;else this.scheme=OD(r,$),this.authority=v||A,this.path=MD(this.scheme,i||A),this.query=o||A,this.fragment=n||A,this.platform=u,Tb(this,$)}get fsPath(){return Mb(this,!1)}with(r){if(!r)return this;let{scheme:v,authority:i,path:o,query:n,fragment:$,platform:u}=r;if(v===void 0)v=this.scheme;else if(v===null)v=A;if(i===void 0)i=this.authority;else if(i===null)i=A;if(o===void 0)o=this.path;else if(o===null)o=A;if(n===void 0)n=this.query;else if(n===null)n=A;if($===void 0)$=this.fragment;else if($===null)$=A;if(u===void 0)u=this.platform;else if(u===null)u=void 0;if(v===this.scheme&&i===this.authority&&o===this.path&&n===this.query&&$===this.fragment&&u===this.platform)return this;return new Rr(v,i,o,n,$,!1,u)}static parse(r,v=!1){let i=RD.exec(r);if(!i)return new Rr(A,A,A,A,A);return new Rr(i[2]||A,pi(i[4]||A),pi(i[5]||A),pi(i[7]||A),pi(i[9]||A),v)}static file(r,v=Pb()){let i=A;if(v==="windows")r=r.replace(/\\\\/g,gr);if(r[0]===gr&&r[1]===gr){let o=r.indexOf(gr,2);if(o===-1)i=r.substring(2),r=gr;else i=r.substring(2,o),r=r.substring(o)||gr}return new Rr("file",i,r,A,A,!1,v)}static from(r){let v=new Rr(r.scheme,r.authority,r.path,r.query,r.fragment,!0,r.platform);return Tb(v,!0),v}toString(r=!1){return k6(this,r)}toJSON(){return this}static revive(r){if(!r)return r;if(r instanceof ir)return r;let v=new Rr(r),i=r;return v._formatted=i.external,v._fsPath=i._sep===Eb(v.platform)?i.fsPath:null,v}}function Eb(r){return r==="windows"?1:void 0}class Rr extends ir{_formatted=null;_fsPath=null;get fsPath(){if(!this._fsPath)this._fsPath=Mb(this,!1);return this._fsPath}toString(r=!1){if(!r){if(!this._formatted)this._formatted=k6(this,!1);return this._formatted}return k6(this,!0)}toJSON(){let r={};if(this._fsPath)r.fsPath=this._fsPath,r._sep=Eb(this.platform);if(this._formatted)r.external=this._formatted;if(r.scheme=this.scheme,r.authority=this.authority,r.path=this.path,r.query=this.query,r.fragment=this.fragment,this.platform)r.platform=this.platform;return r}}var Ob={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function Zb(r,v,i){let o;for(let n=0;n<r.length;n++){let $=r.charCodeAt(n);if($>=97&&$<=122||$>=65&&$<=90||$>=48&&$<=57||$===45||$===46||$===95||$===126||v&&$===47||i&&$===91||i&&$===93||i&&$===58){if(o!==void 0)o+=r.charAt(n)}else{if(o===void 0)o=r.substring(0,n);let u=Ob[$];if(u!==void 0)o+=u;else o+=encodeURIComponent(r.charAt(n))}}return o!==void 0?o:r}function CD(r){let v;for(let i=0;i<r.length;i++){let o=r.charCodeAt(i);if(o===35||o===63){if(v===void 0)v=r.substring(0,i);v+=Ob[o]}else if(v!==void 0)v+=r[i]}return v!==void 0?v:r}function Mb(r,v){let i;if(r.authority&&r.path.length>1&&r.scheme==="file")i=\`//\${r.authority}\${r.path}\`;else if(r.path.charCodeAt(0)===47&&(r.path.charCodeAt(1)>=65&&r.path.charCodeAt(1)<=90||r.path.charCodeAt(1)>=97&&r.path.charCodeAt(1)<=122)&&r.path.charCodeAt(2)===58)if(!v)i=r.path[1].toLowerCase()+r.path.substring(2);else i=r.path.substring(1);else i=r.path;if(r.platform==="windows")i=i.replace(/\\//g,"\\\\");return i}function k6(r,v){let i=!v?Zb:CD,o="",{scheme:n,authority:$,path:u,query:g,fragment:t}=r;if(n)o+=n,o+=":";if($||n==="file")o+=gr,o+=gr;if($){let I=$.indexOf("@");if(I!==-1){let b=$.substring(0,I);if($=$.substring(I+1),I=b.lastIndexOf(":"),I===-1)o+=i(b,!1,!1);else o+=i(b.substring(0,I),!1,!1),o+=":",o+=i(b.substring(I+1),!1,!0);o+="@"}if($=$.toLowerCase(),I=$.lastIndexOf(":"),I===-1)o+=i($,!1,!0);else o+=i($.substring(0,I),!1,!0),o+=$.substring(I)}if(u){if(u.length>=3&&u.charCodeAt(0)===47&&u.charCodeAt(2)===58){let I=u.charCodeAt(1);if(I>=65&&I<=90)u=\`/\${String.fromCharCode(I+32)}:\${u.substring(3)}\`}else if(u.length>=2&&u.charCodeAt(1)===58){let I=u.charCodeAt(0);if(I>=65&&I<=90)u=\`\${String.fromCharCode(I+32)}:\${u.substring(2)}\`}o+=i(u,!0,!1)}if(g)o+="?",o+=i(g,!1,!1);if(t)o+="#",o+=!v?Zb(t,!1,!1):t;return o}function Rb(r){try{return decodeURIComponent(r)}catch{if(r.length>3)return r.substring(0,3)+Rb(r.substring(3));else return r}}var Lb=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function pi(r){if(!r.match(Lb))return r;return r.replace(Lb,(v)=>Rb(v))}var xD=hi.string().brand();var j=TU(oU(),1),{optWhitespace:Tk}=j.default;function uU(r,v){return r.then(v).skip(r)}function Zk(r){return j.default((v,i)=>{let o=v.indexOf(r,i);if(o!==-1)return j.default.makeSuccess(o+r.length,v.substring(i,o));return j.default.makeFailure(i,[r])})}function s(r,v){let i=r;return j.default((o,n)=>{for(let $ of i){let u=$._(o,n);if(u.status)return u}return j.default.makeFailure(n,[v])})}function Lk(r,v,i){return j.default((o,n)=>{let $=[],u=n;if(i._(o,u).status)return j.default.makeFailure(u,["at least one match before terminator"]);let t=r._(o,u);if(!t.status)return t;$.push(t.value),u=t.index;while(!0){if(i._(o,u).status)break;let b=v._(o,u);if(!b.status)break;u=b.index;let D=r._(o,u);if(!D.status)break;$.push(D.value),u=D.index}return j.default.makeSuccess(u,$)})}var Ek=new Set('\\\\|&<>(); "[]');function Ok(){return j.default((r,v)=>{let i=v,o="";while(i<r.length){let n=r[i];if(n==="\\\\"){let $=r[i+1];if($===void 0||!Ek.has($))break;o+=$,i+=2;continue}if(Mk(n)){o+=n,i++;continue}if(n==="$"&&!Rk(r[i+1])){o+=n,i++;continue}if(n==="("){let $=Ck(r,i);if($===void 0)break;o+=r.slice(i,$),i=$;continue}break}if(i===v)return j.default.makeFailure(v,["unquoted string"]);return j.default.makeSuccess(i,o)})}function Mk(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_"||r==="-"||r===":"||r==="/"||r==="."||r==="*"||r==="~"||r==="@"||r==="="||r==="+"||r==="^"||r===","||r==="["||r==="]"||r==="#"||r==="!"}function Rk(r){return r==="{"||r==="("||r==="_"||r!==void 0&&r>="a"&&r<="z"||r!==void 0&&r>="A"&&r<="Z"}function Ck(r,v){let i=v+1;while(i<r.length){let o=r[i];if(o===")")return i+1;if(!xk(o))return;i++}return}function xk(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_"||r==="-"}function fk(){return j.default((r,v)=>{let i=v,o="";while(i<r.length){let n=r[i];if(mk(n)){o+=n,i++;continue}let $=r[i+1];if(n==="\\\\"&&$!==void 0&&yk($)){o+=$,i+=2;continue}break}return j.default.makeSuccess(i,o)})}function mk(r){return r===" "||r==="\\t"||r===\`
809
809
  \`||r==="\\r"}function yk(r){return/\\s/.test(r)}function dk(){return j.default((r,v)=>{let i=r[v];if(i===";")return j.default.makeSuccess(v+1,void 0);if(i==="&"||i==="|"){let o=r[v+1]===i?v+2:v+1;return j.default.makeSuccess(o,void 0)}return j.default.makeFailure(v,["operator"])})}function hk(r){let v=r;return j.default((i,o)=>{let n=[],$=o;while($<i.length){let u=!1;for(let g of v){let t=g._(i,$);if(!t.status)continue;n.push(t.value),$=t.index,u=!0;break}if(!u)break}if(n.length===0)return j.default.makeFailure(o,["word"]);return j.default.makeSuccess($,ek(n))})}function ek(r){let[v,...i]=r;if(v===void 0)throw Error("Expect non-empty array of parts in argument: "+JSON.stringify(r));else if(i.length===0)return v;else if(r.every((o)=>typeof o==="string"))return r.join("");else return{type:"concatenation",values:r}}function pk(r,v,i){let o=r,n=v,$=i;return j.default((u,g)=>{let t=o._(u,g);if(!t.status)return t;let I=[t.value],b=t.index;while(!0){let k=ak(u,b,n,$);if(!k.status)break;let l=o._(u,k.index);if(!l.status)break;I.push(l.value),b=l.index}let D=sk(u,b,$);if(D!==void 0)b=D;return j.default.makeSuccess(b,I)})}function ak(r,v,i,o){let n=o._(r,v);if(!n.status)return{status:!1};let $=i._(r,n.index);if(!$.status)return{status:!1};let u=o._(r,$.index);if(!u.status)return{status:!1};return{status:!0,index:u.index}}function sk(r,v,i){let o=i._(r,v);if(!o.status||r[o.index]!=="&")return;let n=i._(r,o.index+1);return n.status?n.index:void 0}class J6{platform;constructor(r){this.platform=r}whitespaceWithEscapes=fk();escapeSequences=j.default.string("\\\\").then(j.default.oneOf('\\\\|&<>();"'));unquotedEscapeSequences=j.default.string("\\\\").then(j.default.oneOf('\\\\|&<>(); "[]'));doubleQuotedString=uU(j.default.string('"'),s([this.escapeSequences,j.default.noneOf('"')],"double-quoted character").many().tie()).desc("double-quoted string");singleQuotedString=uU(j.default.string("'"),s([j.default.string("\\\\").then(j.default.any),j.default.noneOf("'\\\\")],"single-quoted character").many().tie()).desc("single-quoted string");braceExpansion=j.default.lazy(()=>{let r=j.default.lazy(()=>s([j.default.string("{").then(r).skip(j.default.string("}")).map((v)=>\`{\${v}}\`),j.default.noneOf("}")],"brace content").many().tie());return j.default.string("{").then(r).skip(j.default.string("}")).map((v)=>\`{\${v}}\`)}).desc("brace expansion");unquotedString=j.default.lazy(()=>{if(this.platform==="win32")return j.default.alt(j.default.regexp(/[a-zA-Z]:[\\\\/]\\S+/),j.default.regexp(/\\\\\\\\\\S+\\\\\\S*/),j.default.alt(this.unquotedEscapeSequences,j.default.regexp(/[a-zA-Z0-9_\\-:/.*~@=\\\\^,[\\]#!]/),j.default.regexp(/\\$(?![A-Za-z_{(])/),j.default.regexp(/\\([a-zA-Z0-9_-]*\\)/)).atLeast(1).tie()).desc("unquoted string");else return Ok().desc("unquoted string")});commandSubstitution=j.default.lazy(()=>j.default.string("$(").then(this.expression).skip(j.default.string(")")).map((r)=>({type:"invocations",trees:r})));word=j.default.lazy(()=>{return hk([this.doubleQuotedString,this.singleQuotedString,this.braceExpansion,this.unquotedString,this.commandSubstitution,this.envVariable])}).node("word");envVariable=j.default.regexp(/\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})/).map((r)=>Br).desc("environment variable");envVarAssignment=j.default.seqMap(j.default.regexp(/[A-Za-z_][A-Za-z0-9_]*/),j.default.string("="),s([this.doubleQuotedString,this.singleQuotedString,this.unquotedString],"environment variable value").or(j.default.succeed("")),(r,v,i)=>({name:r,value:i})).desc("environment variable assignment");heredoc=j.default.regex(/<<-?'?(\\w+)'?/).chain((r)=>Zk(r)).desc("heredoc");operator=dk();redirect=j.default.lazy(()=>{let r=s([j.default.string(">>"),j.default.string(">")],"output redirect"),v=s([j.default.string("&>>"),j.default.string("&>")],"output redirect"),i=j.default.string("<"),o=j.default.regexp(/\\d+>(&\\d+|\\S+)/);return s([j.default.seq(s([r,v],"output redirect"),j.default.optWhitespace,this.word).map((n)=>{return}),j.default.seq(r,j.default.optWhitespace,this.word,j.default.whitespace,j.default.string("&>"),j.default.optWhitespace,this.word).map((n)=>{return}),j.default.seq(i,j.default.optWhitespace,this.word).map((n)=>{return}),j.default.seq(j.default.digit,i,j.default.optWhitespace,this.word).map((n)=>{return}),o.map((n)=>{return}),this.heredoc.map((n)=>{return})],"redirect").desc("redirect")});args=Lk(j.default.notFollowedBy(s([this.operator,this.redirect],"operator or redirect")).then(this.word),this.whitespaceWithEscapes,s([this.operator,this.redirect],"operator or redirect"));invocationWithoutArgs=j.default.lazy(()=>j.default.seqMap(this.envVarAssignment.skip(this.whitespaceWithEscapes).many(),this.word,(r,v)=>({program:v,arguments:[],...r.length>0&&{envVars:r}})));invocationWithArgs=j.default.lazy(()=>j.default.seqMap(this.envVarAssignment.skip(this.whitespaceWithEscapes).many(),this.word.skip(this.whitespaceWithEscapes),this.args,(r,v,i)=>({program:v,arguments:i,...r.length>0&&{envVars:r}})));invocation=j.default.lazy(()=>{let r=s([this.invocationWithArgs,this.invocationWithoutArgs],"invocation");return s([r.skip(this.redirect.trim(Tk).many()),r],"invocation")});bareExpression=j.default.lazy(()=>pk(this.invocation,this.operator,this.whitespaceWithEscapes));subshellExpression=j.default.lazy(()=>j.default.string("(").then(this.expression).skip(j.default.string(")")));expression=j.default.lazy(()=>s([this.bareExpression,this.subshellExpression],"expression"));expressionWithEOF=this.expression.skip(j.default.eof);parseShellCommand(r){return this.expression.tryParse(r)}tryParseShellCommand(r){let i=this.expressionWithEOF._(r,0);return i.status?i.value:void 0}}var gU=new J6(typeof process<"u"?process.platform:"browser");function tU(r,v){return(v===void 0||v===gU.platform?gU:new J6(v)).parseShellCommand(r)}var Br=Symbol("Dynamic");function IU(r){let v=[],i=[...r];while(i.length>0){let o=i.shift(),n=[],$;if(typeof o.program.value==="object"){if(o.program.value.type==="invocations")i.push(...o.program.value.trees);$=Br}else $=o.program.value;for(let u of o.arguments)if(u.value===Br||typeof u.value==="string")n.push(u.value);else if(u.value.type==="invocations")i.push(...u.value.trees),n.push(Br);else for(let g of u.value.values)if(typeof g==="object"&&g.type==="invocations")i.push(...g.trees),n.push(Br);else if(g===Br||typeof g==="string")n.push(g);else throw Error("Unexpected word value: "+g);v.push({program:$,arguments:n})}return v}function bU(r){return{cmd:typeof r.command==="string"?r.command:"",cwd:typeof r.workdir==="string"?r.workdir:void 0,timeout_ms:typeof r.timeout_ms==="number"?r.timeout_ms:void 0}}function r1(r){if(!r)return;if(typeof r==="string"){if(r.startsWith("file://"))return ir.parse(r).fsPath;return Dv.isAbsolute(r)?r:void 0}return r.fsPath}function j6(r,v,i){if(r.startsWith("file://"))return ir.parse(r);if(v&&!Dv.isAbsolute(r))return ir.file(Dv.resolve(v,r));if(!Dv.isAbsolute(r)){let o=r1(i);if(o)return ir.file(Dv.resolve(o,r));return}return ir.file(r)}function X6(r){let v=Array.from(new Map(r.map((i)=>[i.toString(),i])).values());return v.length>0?v:null}function n1(r,v){let i=r?.path;if(typeof i!=="string")return null;let o=j6(i,void 0,v);return o?[o]:null}function v1(r){let v;try{v=IU(tU(r))}catch{return[]}if(v.length!==1)return[];let[i]=v;if(!i||i.program===Br||Array.isArray(i.program))return[];if(i.program.toLowerCase()!=="sed")return[];let o=i.arguments;if(!o.every((n)=>typeof n==="string"))return[];if(!o.some((n)=>i1(n)))return[];return $1(o).filter((n)=>n!==""&&n!=="-")}function i1(r){return r==="-i"||r.startsWith("-i")||r==="--in-place"||r.startsWith("--in-place=")}function $1(r){let v=[],i=!1,o=!1;for(let n=0;n<r.length;n++){let $=r[n];if(!$)continue;if($==="--"){for(let u of r.slice(n+1))if(i||o)v.push(u);else o=!0;break}if($.startsWith("-")&&$!=="-"){if($==="-i"||$==="--in-place"){if(r[n+1]==="")n++;continue}if($.startsWith("-i")||$.startsWith("--in-place="))continue;if($==="-e"||$==="--expression"||$==="-f"||$==="--file"){i=!0,n++;continue}continue}if(i||o)v.push($);else o=!0}return v}function o1(r,v){if(!r||typeof r==="string"||!("files"in r)||!Array.isArray(r.files))return null;let i=[];for(let o of r.files)if(typeof o?.uri==="string"&&o.uri.startsWith("file://")){let n=o.uri;i.push(ir.parse(n))}return X6(i)}function u1(r,v){let i=typeof r?.patchText==="string"?r.patchText:void 0;if(!i)return null;try{let n=Yb(i).hunks.flatMap(($)=>$.type==="update"&&$.movePath?[$.path,$.movePath]:[$.path]).map(($)=>j6($,void 0,v)).filter(($)=>$!==void 0);return X6(n)}catch{return null}}function g1(r){switch(r){case"running":return"in-progress";case"pending":return"queued";default:return r}}function q6(r){if(r.tool===w6){let v=r.input;if(v&&typeof v.cmd==="string")return{command:v.cmd,dir:v.cwd}}if(r.tool==="shell_command"){let v=r.input,i=bU(v);if(i.cmd)return{command:i.cmd,dir:i.cwd}}return null}function UU(r){let v=new Map,i=[];for(let o of r){if(o.role==="assistant"){for(let n of o.content)if(n.type==="tool_use")v.set(n.id,{toolUseID:n.id,tool:n.name,input:n.input})}if(o.role==="user")for(let n of o.content){if(n.type!=="tool_result")continue;let $={status:g1(n.status)};if(Vb($.status)){let u=v.get(n.toolUseID);if(u){let g={toolUseID:n.toolUseID,tool:u.tool,input:u.input,status:$.status==="rejected-by-user"?"cancelled":$.status,...n.output!==void 0?{output:n.output}:{},...n.status==="error"&&typeof n.output==="string"?{error:n.output}:{}};i.push({call:u,result:g})}}}}return i}function lU(r,v){if(r.tool===Sb||r.tool===Wb){let i=r.input;return n1(i,v)}if(r.tool===Nb){let i=r.input;if("output"in r){let o=o1(r.output,v);if(o)return o}return u1(i,v)}if(r.tool===w6||r.tool===Qb){let i=q6(r);if(!i)return null;let o=v1(i.command);if(o.length>0){let n=o.map(($)=>j6($,i.dir,v)).filter(($)=>$!==void 0);return X6(n)}}return null}function wU(r){return r.fsPath}function DU(r){return r.name==="PluginUIUnavailableError"}function kU(r,v){if(r.type!==v.type)return!1;if(r.type==="disabled"&&v.type==="disabled")return r.reason===v.reason;return!0}function I1(r){if(typeof r==="string")return r;if(G6(r))return Object.freeze([...r]);let v={};if(r.include!==void 0)v.include=G6(r.include)?Object.freeze([...r.include]):r.include;if(r.exclude!==void 0)v.exclude=Object.freeze([...r.exclude]);return Object.freeze(v)}function b1(r,v){if(typeof r==="string")return Object.freeze({include:r,exclude:Object.freeze([v])});if(G6(r))return Object.freeze(r.filter((n)=>n!==v));let i=new Set(r.exclude??[]);i.add(v);let o={exclude:Object.freeze([...i])};if(r.include!==void 0)o.include=r.include;return Object.freeze(o)}function G6(r){return Array.isArray(r)}var U1=new Set(["tool.call","tool.result","agent.start","agent.end"]),zU=new Set(Object.values(ei).flatMap((r)=>[r.key.toLowerCase(),r.displayName.toLowerCase()]));function l1(r){switch(r){case"tool.call":return{action:"allow"};case"tool.result":return;case"agent.start":return{};case"agent.end":return{action:"done"};default:return}}function _U(r,v){if(r==="tool.call"||r==="tool.result")return\`\${r}#\${v.toolUseID}\`;return r}function w1(r){if(!r||typeof r!=="object")return;let v=r.thread;if(!v||typeof v!=="object")return;let i=v.id;return typeof i==="string"?i:void 0}function D1(r,v){if(r!=="tool.call"&&r!=="tool.result"||!v||typeof v!=="object")return;let i=v.toolUseID;return typeof i==="string"?{kind:"tool",id:i}:void 0}function cU(r){if(r===void 0)return;return{invocation:r}}class JU{bridge;currentValue=null;subscribers=new Set;constructor(r){this.bridge=r}subscribe(r){let v=typeof r==="function"?{next:r}:r;if(this.subscribers.add(v),this.currentValue!==null)v.next?.(this.currentValue);else this.get().then((i)=>{if(this.subscribers.has(v))v.next?.(i)});return{unsubscribe:()=>{this.subscribers.delete(v)}}}pipe(r){return r(this)}async get(){if(this.currentValue!==null)return this.currentValue;let r=await this.bridge.request("configuration.get",{});return this.currentValue=r,r}async update(r,v){await this.bridge.request("configuration.update",{partial:r,target:v})}async delete(r,v){await this.bridge.request("configuration.delete",{key:r,target:v})}[Symbol.observable](){return this}_handleConfigChange(r){this.currentValue=r;for(let v of this.subscribers)v.next?.(r)}}function w$(r,v,i,o,n){let $=o?\`[\${i}:\${o}]\`:\`[\${i}]\`;return{log(...u){let g=\`\${$} \${String(u[0]??"")}\${u.length>1?" "+u.slice(1).map(String).join(" "):""}\`;if(v.info(g),n)r.request("span.event",{span:n,message:g})}}}class jU{currentValue=null;subscribers=new Set;get current(){return this.currentValue}subscribe(r){let v=typeof r==="function"?{next:r}:r;return this.subscribers.add(v),v.next?.(this.currentValue),{unsubscribe:()=>{this.subscribers.delete(v)}}}pipe(r){return r(this)}[Symbol.observable](){return this}_handleActiveThreadChange(r){this.currentValue=r===null?null:{id:r};for(let v of this.subscribers)v.next?.(this.currentValue)}}class K6{pluginName;pluginURI;scopedLogger;baseCtx;bridge;handlers=new Map;requestHandlers=new Map;commands=new Map;tools=new Map;executingToolNames=[];agentModes=new Map;agentModeDisplays=new WeakMap;logger;configuration;system;$;ui;ai;experimental;helpers;constructor(r,v,i,o,n,$){this.pluginName=r;this.pluginURI=v;this.scopedLogger=i;this.baseCtx=o;this.bridge=n;this.logger=w$(n,i,r),this.configuration=new JU(n),this.system=o.system,this.$=o.$,this.ui=this.createUI(),this.ai=o.ai,this.createAgent=this.createAgent.bind(this),this.registerAgentMode=this.registerAgentMode.bind(this),this.experimental={createAgent:this.createAgent,registerAgentMode:this.registerAgentMode,createStatusItem:(u)=>this.createStatusItem(u),activeThread:new jU,threads:{get:(u)=>this.createThreadContext(u)}},this.helpers={filesModifiedByToolCall:(u,g)=>lU(u,g??$),filePathFromURI:wU,shellCommandFromToolCall:q6,toolCallsInMessages:UU,isPluginUINotAvailableError:DU}}createAgent(r){let v=this.createAgentDefinition(r);return Object.freeze({definition:v,run:(i,o)=>this.runAgent(v,i,o)})}createAgentDefinition(r){this.validateCreateAgentConfig(r);let v={kind:"agent-definition",model:r.model,instructions:r.instructions};if(r.name!==void 0)v.name=r.name;if(r.tools!==void 0)v.tools=I1(r.tools);if(r.reasoningEffort!==void 0)v.reasoningEffort=r.reasoningEffort;return Object.freeze(v)}validateCreateAgentConfig(r){if(!r.model.trim())throw Error("createAgent requires a non-empty model");if(Bb(r.model),!r.instructions.trim())throw Error("createAgent requires non-empty instructions")}runAgent(r,v,i={}){let o=i.timeoutMs,n=this.toAgentDefinition(r),$={message:v};if(o!==void 0)$.timeoutMs=o;if(i.parentThreadID!==void 0)$.parentThreadID=i.parentThreadID;let u=this.agentModeDisplays.get(n);if(u!==void 0)$.agentModeDisplay=u;return this.bridge.request("agent.run",{agent:this.excludeCurrentToolFromAgent(n),options:$})}toAgentDefinition(r){return"definition"in r?r.definition:r}excludeCurrentToolFromAgent(r){let v=this.executingToolNames.at(-1);if(!v)return r;return Object.freeze({...r,tools:b1(r.tools??"all",v)})}registerAgentMode(r){let v=this.validateAgentModeDefinition(r),i={label:v.label};if(r.color!==void 0)i.color=r.color;return this.agentModeDisplays.set(r.agent,i),this.agentModes.set(v.key,{...r,key:v.key,label:v.label,agent:r.agent,pluginName:this.pluginName}),this.bridge.emitEvent("agent-modes.changed",{pluginName:this.pluginName}),{unsubscribe:()=>{if(this.agentModes.delete(r.key))this.agentModeDisplays.delete(r.agent),this.bridge.emitEvent("agent-modes.changed",{pluginName:this.pluginName})}}}validateAgentModeDefinition(r){let v=r.key.trim(),i=r.label.trim();if(!v)throw Error("Plugin agent mode requires a non-empty key");if(v.length>16)throw Error("Plugin agent mode key must be 16 characters or less");if(!i)throw Error("Plugin agent mode requires a non-empty label");if(i.length>16)throw Error("Plugin agent mode label must be 16 characters or less");if(this.validateCreateAgentConfig(r.agent),zU.has(v.toLowerCase())||zU.has(i.toLowerCase()))throw Error(\`Plugin agent mode '\${r.label}' conflicts with a built-in agent mode\`);return{key:v,label:i}}createUI(r){let v=cU(r);return{notify:(i)=>this.bridge.request("ui.notify",{message:i},v).then(()=>{return}),input:(i)=>this.bridge.request("ui.input",{options:i},v),confirm:(i)=>this.bridge.request("ui.confirm",{options:i},v),select:(i)=>this.bridge.request("ui.select",{options:i},v)}}on(r,v){if(U1.has(r))return this.requestHandlers.set(r,v),{unsubscribe:()=>{if(this.requestHandlers.get(r)===v)this.requestHandlers.delete(r)}};let i=this.handlers.get(r)??[];return i.push(v),this.handlers.set(r,i),{unsubscribe:()=>{let o=this.handlers.get(r);if(o){let n=o.indexOf(v);if(n!==-1)o.splice(n,1)}}}}registerCommand(r,v,i){let o=v.availability??{type:"enabled"};return this.commands.set(r,{id:r,options:v,handler:i,availability:o}),this.bridge.emitEvent("commands.changed",{pluginName:this.pluginName}),{setAvailability:(n)=>{let $=this.commands.get(r);if(!$)return;if(kU($.availability,n))return;$.availability=n,this.bridge.emitEvent("commands.changed",{pluginName:this.pluginName})},unsubscribe:()=>{if(this.commands.has(r))this.commands.delete(r),this.bridge.emitEvent("commands.changed",{pluginName:this.pluginName})}}}registerTool(r){return this.tools.set(r.name,{name:r.name,description:r.description,inputSchema:r.inputSchema,execute:r.execute}),this.bridge.emitEvent("tools.changed",{pluginName:this.pluginName}),{unsubscribe:()=>{if(this.tools.has(r.name))this.tools.delete(r.name),this.bridge.emitEvent("tools.changed",{pluginName:this.pluginName})}}}createStatusItem(r){let v=!0,i=t1(),o={pluginURI:this.pluginURI,id:i};if(r!==void 0)o.value=r;return this.bridge.request("status.create",o),{update:(n)=>{if(!v)return;this.bridge.request("status.update",{pluginURI:this.pluginURI,id:i,value:n})},unsubscribe:()=>{if(!v)return;v=!1,this.bridge.request("status.remove",{pluginURI:this.pluginURI,id:i})}}}getRegisteredTools(){return Array.from(this.tools.values()).map((r)=>({name:r.name,description:r.description,inputSchema:r.inputSchema,pluginName:this.pluginName}))}getRegisteredAgentModes(){return[...this.agentModes.values()]}async executeTool(r,v,i){let o=this.tools.get(r);if(!o)throw Error(\`Tool not found: \${r}\`);let n={ui:this.createUI(i.invocation),logger:w$(this.bridge,this.scopedLogger,this.pluginName,\`tool:\${r}\`),thread:this.createThreadContext(i.threadID,i.invocation)};this.executingToolNames.push(r);try{return await o.execute(v,n)}finally{this.executingToolNames.pop()}}async executeCommand(r,v){let i=this.commands.get(r);if(!i)throw Error(\`Command not found: \${r}\`);let o={ui:this.createUI(v?.invocation),system:this.baseCtx.system,ai:this.baseCtx.ai,$:this.baseCtx.$,thread:v?.threadID?this.createThreadContext(v.threadID,v.invocation):void 0};await i.handler(o)}getRegisteredCommands(){return Array.from(this.commands.values()).map((r)=>{let v={id:r.id,category:r.options.category??this.pluginName,title:r.options.title,pluginName:this.pluginName,availability:r.availability};if(r.options.description!==void 0)v.description=r.options.description;return v})}createSharedEventContext(r,v,i){return{$:this.baseCtx.$,ui:v===void 0?this.ui:this.createUI(v),ai:this.baseCtx.ai,system:this.baseCtx.system,logger:r,span:i}}createThreadContext(r,v){let i=cU(v);return{id:r,messages:(o)=>{let n={threadID:r};if(o!==void 0)n.options=o;return this.bridge.request("thread.messages",n,i)},append:(o)=>this.bridge.request("thread.append",{messages:o,threadID:r}).then(()=>{return}),appendUserMessage:(o,n)=>this.bridge.request("thread.append",{messages:[o],threadID:r,options:n},i).then(()=>{return})}}createEventContext(r,v,i,o){let n=D1(r,v),$=this.createSharedEventContext(i,n,o),u=w1(v);if(u===void 0)throw Error(\`Plugin event \${r} is missing thread.id\`);return{...$,thread:this.createThreadContext(u,n)}}async emit(r,v,i){let o=this.handlers.get(r);if(!o)return;let n=_U(r,v),$=w$(this.bridge,this.scopedLogger,this.pluginName,n,i),u=this.createEventContext(r,v,$,i);for(let g of o)await g(v,u)}async handleRequest(r,v,i){let o=this.requestHandlers.get(r);if(!o)return l1(r);let n=_U(r,v),$=w$(this.bridge,this.scopedLogger,this.pluginName,n,i),u=this.createEventContext(r,v,$,i);return o(v,u)}hasRequestHandler(r){return this.requestHandlers.has(r)}get registeredEvents(){return[...this.handlers.keys(),...this.requestHandlers.keys()]}}function XU(){let r={...process.env};return delete r.BUN_BE_BUN,r}var SU=process.env.AMP_PLUGIN_RUNTIME_LOG_FILE??WU(YU(),"amp-plugin-runtime.log");j1(QU(SU),{recursive:!0});var Y1=Bun.file(SU),qU=Y1.writer();function h(r,v){let i=new Date().toISOString(),o=v?\`[\${i}] \${r} \${JSON.stringify(v)}
810
810
  \`:\`[\${i}] \${r}
811
811
  \`;qU.write(o),qU.flush()}var GU="ampcode-plugin-types";Bun.plugin({name:"ampcode-plugin-resolver",setup(r){r.onResolve({filter:/^@ampcode\\/plugin(?:\\/.*)?$/},(v)=>{return h("Resolving @ampcode/plugin to virtual empty module",{request:v.path}),{path:v.path,namespace:GU}}),r.onLoad({filter:/.*/,namespace:GU},(v)=>{return h("Loading virtual empty module for @ampcode/plugin",{request:v.path}),{contents:"export {}",loader:"ts"}})}});function rr(r,v,i){let o={type:"response",id:r};if(i)o.error=i;else o.result=v;console.log(JSON.stringify(o))}var Q1=\`p-\${_1()}\`,W1=0,Y6=new Map;function Wn(r,v,i){let o=\`\${Q1}-\${++W1}\`;if(r==="span.event")h("Span event sent to host",{id:o,params:v});return new Promise((n,$)=>{Y6.set(o,{resolve:(g)=>n(g),reject:$});let u={type:"request",id:o,method:r,params:v};if(i?.invocation!==void 0)u.invocation=i.invocation;console.log(JSON.stringify(u))})}function KU(r,v){console.log(JSON.stringify({type:"event",event:r,data:v}))}function S1(r){let v=r.length-1,i=[...r.slice(0,v),\`\${r[v]} < \`,""],o=[...r.raw.slice(0,v),\`\${r.raw[v]} < \`,""];return Object.assign(i,{raw:o})}async function N1(r,...v){h("shellWrapper executing command",{strings:Array.from(r),values:v});try{let i=await K1(S1(r),...v,new Response("")).env(XU());return h("shellWrapper result",{exitCode:i.exitCode,stdout:i.stdout.toString(),stderr:i.stderr.toString()}),{exitCode:i.exitCode,stdout:i.stdout.toString(),stderr:i.stderr.toString()}}catch(i){let o=i;return h("shellWrapper error",{error:o.message,exitCode:o.exitCode}),{exitCode:o.exitCode??1,stdout:o.stdout?.toString()??"",stderr:o.stderr?.toString()??""}}}function V1(r,v){let o=\`\${k1.from(r,"base64").toString("utf8")}
@@ -2815,13 +2815,13 @@ ${K}`))}},error:(V)=>{if(!G)G=!0,Z(Error(`Failed to spawn brew: ${V.message}`))}
2815
2815
  ${K}`;if(J==="pnpm"&&K.includes("Unable to find the global bin directory"))z+=`
2816
2816
 
2817
2817
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
2818
- npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}s0();s0();ah();var TsQ="@ampcode/cli";async function l30(A,Q,$=TsQ){let E=`${Q||"https://registry.npmjs.org"}/${$}/latest`,D=new AbortController,J=setTimeout(()=>D.abort(),5000);try{let U=await fetch(E,{signal:D.signal});if(!U.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await U.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=dc(A,Z),X=F<0,I,G;if(Y.time){let V=Y.time[A],K=Y.time[Z],z=Date.now();if(V)I=Math.floor((z-new Date(V).getTime())/3600000);if(K)G=Math.floor((z-new Date(K).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:F,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(U){return S.debug("Error checking npm version",{error:U}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(J)}}var _sQ="https://static.ampcode.com/cli/cli-version.txt";async function i30(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${_sQ}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=(await B.text()).trim();if(!E||!/^\d+\.\d+\.\d+/.test(E))return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=dc(A,E),J=D<0;return S.info("Bin version comparison",{currentVersion:A,latestVersion:E,compareResult:D,hasUpdate:J}),{hasUpdate:J,latestVersion:E,currentVersion:A,source:"bin"}}catch(B){return S.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function dc(A,Q){let $=(J)=>{let[U,Y]=J.split("-");return{parts:U?.split(".").map(Number)||[],label:Y}},B=$(A),E=$(Q),D=Math.max(B.parts.length,E.parts.length);for(let J=0;J<D;J++){let U=B.parts[J]||0,Y=E.parts[J]||0;if(U<Y)return-1;if(U>Y)return 1}if(B.label===E.label)return 0;if(!B.label&&E.label)return 1;if(B.label&&!E.label)return-1;if(B.label&&E.label)return B.label<E.label?-1:1;return 0}function cc(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,D=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],J=B!==void 0?GV(B):void 0;return{sha:D,timestamp:B,age:J}}catch{return null}}bA();s0();import{readFile as SsQ,realpath as ksQ}from"node:fs/promises";import{dirname as uG4,join as fsQ}from"node:path";async function MG4(A){switch(A){case"binary":case"brew":return xsQ(gc());case"npm":case"pnpm":case"yarn":case"bun":return ysQ()}}async function xsQ(A){let Q=await VK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function ysQ(){try{let A=process.argv[1];if(!A)return null;let Q=await ksQ(A),$=uG4(uG4(Q));return await bsQ(fsQ($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function bsQ(A){let Q=await SsQ(A,"utf8"),$=JSON.parse(Q);if(!$.name||!gx0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}s0();import{spawn as hsQ}from"node:child_process";function nx0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var n30=null,pc=null;function OG4(A){return new Promise((Q)=>{let $=hsQ("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function o30(){if(n30)return n30;if(pc)return pc;pc=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return nx0(A);let Q=await OG4("@sourcegraph:registry");if(Q)return nx0(Q);let $=await OG4("registry");if($)return nx0($);return"https://registry.npmjs.org"})();try{return n30=await pc,n30}finally{pc=null}}var gsQ=3600000,msQ=5000;function ox0(A,Q,$={}){let B=new u4,E=B.pipe(L$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??gsQ,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await KV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await dsQ(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await KV(msQ),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await KV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function dsQ(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await dY(),U=J==="binary"||J==="brew",Y=U?void 0:await KK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await i30(A);else{let I=await o30();Z=await l30(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await MG4(J);if(I&&dc(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,dc(A,I)<0){let G=await WX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==gc()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await mc(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await WX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}ah();import{stderr as pD}from"node:process";function LG4(A){let Q=new GX().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(B)=>{await bx0(B.force||!1,B.verbose||!1,"0.0.1780580310-g6c808e"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new GX("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(B)=>{await lsQ(B.targetVersion)});A.addCommand($)}function csQ(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
2818
+ npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}s0();s0();ah();var TsQ="@ampcode/cli";async function l30(A,Q,$=TsQ){let E=`${Q||"https://registry.npmjs.org"}/${$}/latest`,D=new AbortController,J=setTimeout(()=>D.abort(),5000);try{let U=await fetch(E,{signal:D.signal});if(!U.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await U.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=dc(A,Z),X=F<0,I,G;if(Y.time){let V=Y.time[A],K=Y.time[Z],z=Date.now();if(V)I=Math.floor((z-new Date(V).getTime())/3600000);if(K)G=Math.floor((z-new Date(K).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:F,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(U){return S.debug("Error checking npm version",{error:U}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(J)}}var _sQ="https://static.ampcode.com/cli/cli-version.txt";async function i30(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${_sQ}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=(await B.text()).trim();if(!E||!/^\d+\.\d+\.\d+/.test(E))return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=dc(A,E),J=D<0;return S.info("Bin version comparison",{currentVersion:A,latestVersion:E,compareResult:D,hasUpdate:J}),{hasUpdate:J,latestVersion:E,currentVersion:A,source:"bin"}}catch(B){return S.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function dc(A,Q){let $=(J)=>{let[U,Y]=J.split("-");return{parts:U?.split(".").map(Number)||[],label:Y}},B=$(A),E=$(Q),D=Math.max(B.parts.length,E.parts.length);for(let J=0;J<D;J++){let U=B.parts[J]||0,Y=E.parts[J]||0;if(U<Y)return-1;if(U>Y)return 1}if(B.label===E.label)return 0;if(!B.label&&E.label)return 1;if(B.label&&!E.label)return-1;if(B.label&&E.label)return B.label<E.label?-1:1;return 0}function cc(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,D=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],J=B!==void 0?GV(B):void 0;return{sha:D,timestamp:B,age:J}}catch{return null}}bA();s0();import{readFile as SsQ,realpath as ksQ}from"node:fs/promises";import{dirname as uG4,join as fsQ}from"node:path";async function MG4(A){switch(A){case"binary":case"brew":return xsQ(gc());case"npm":case"pnpm":case"yarn":case"bun":return ysQ()}}async function xsQ(A){let Q=await VK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function ysQ(){try{let A=process.argv[1];if(!A)return null;let Q=await ksQ(A),$=uG4(uG4(Q));return await bsQ(fsQ($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function bsQ(A){let Q=await SsQ(A,"utf8"),$=JSON.parse(Q);if(!$.name||!gx0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}s0();import{spawn as hsQ}from"node:child_process";function nx0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var n30=null,pc=null;function OG4(A){return new Promise((Q)=>{let $=hsQ("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function o30(){if(n30)return n30;if(pc)return pc;pc=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return nx0(A);let Q=await OG4("@sourcegraph:registry");if(Q)return nx0(Q);let $=await OG4("registry");if($)return nx0($);return"https://registry.npmjs.org"})();try{return n30=await pc,n30}finally{pc=null}}var gsQ=3600000,msQ=5000;function ox0(A,Q,$={}){let B=new u4,E=B.pipe(L$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??gsQ,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await KV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await dsQ(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await KV(msQ),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await KV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function dsQ(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await dY(),U=J==="binary"||J==="brew",Y=U?void 0:await KK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await i30(A);else{let I=await o30();Z=await l30(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await MG4(J);if(I&&dc(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,dc(A,I)<0){let G=await WX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==gc()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await mc(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await WX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}ah();import{stderr as pD}from"node:process";function LG4(A){let Q=new GX().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(B)=>{await bx0(B.force||!1,B.verbose||!1,"0.0.1780592276-g890982"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new GX("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(B)=>{await lsQ(B.targetVersion)});A.addCommand($)}function csQ(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
2819
2819
  `),B=!1,$=0}function D(J){if(!Q)return;let U=J.padEnd($," ");A.write(`\r${U}`),B=!0,$=U.length}return{flushProgressLine:E,renderProgress:D}}function psQ(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)pD.write(k0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
2820
2820
  `))}async function lsQ(A){let $=process.platform==="win32"&&lN()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:E}=csQ(pD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")pD.write(k0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
2821
2821
 
2822
2822
  `));try{if(!A){pD.write(k0.blue(`Checking for updates...
2823
- `));let U=!1,Y;if(lN()){let Z=await i30("0.0.1780580310-g6c808e");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await o30(),F=await KK(),X=await l30("0.0.1780580310-g6c808e",Z,F);psQ(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=cc("0.0.1780580310-g6c808e"),F=Z?.age?`released ${Z.age} ago`:`built ${GV(new Date("2026-06-04T13:43:38.391Z"))} ago`;pD.write(k0.green(`✓ Amp is already up to date on version ${"0.0.1780580310-g6c808e"} (${F})
2824
- `));let X=await WX("0.0.1780580310-g6c808e",$);if(X.warning)pD.write(`
2823
+ `));let U=!1,Y;if(lN()){let Z=await i30("0.0.1780592276-g890982");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await o30(),F=await KK(),X=await l30("0.0.1780592276-g890982",Z,F);psQ(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=cc("0.0.1780592276-g890982"),F=Z?.age?`released ${Z.age} ago`:`built ${GV(new Date("2026-06-04T17:02:44.679Z"))} ago`;pD.write(k0.green(`✓ Amp is already up to date on version ${"0.0.1780592276-g890982"} (${F})
2824
+ `));let X=await WX("0.0.1780592276-g890982",$);if(X.warning)pD.write(`
2825
2825
  `+k0.yellow(X.warning)+`
2826
2826
  `);process.exit(0)}if(!Y)pD.write(k0.yellow("[WARN] could not find latest version")),process.exit(0);A=Y}pD.write(k0.blue(`Updating to version ${A}...
2827
2827
  `)),await mc(A,void 0,(U)=>{B(),pD.write(k0.dim(`Running: ${U}
@@ -2989,7 +2989,7 @@ ${B}`}async function G66(A,Q){if(!Q?.forceExternal&&Q?.onShowImagePreview&&bC4(A
2989
2989
  `).length,E=new J0({text:new g(A,new Q0({color:$}))});if(B<=Y80)return E;return new y0({width:1/0,height:Y80,child:new LB({autofocus:!1,controller:Q,child:E})})}function L76(){return new Map([[HA.key("PageUp"),new Z80],[HA.key("PageDown"),new Lg0],[HA.ctrl("u"),new Z80],[HA.shift("Home"),new jg0],[HA.shift("End"),new Rg0]])}function j76(A,Q,$){return Math.max(Q,Math.min(A,$))}var Pg0=8,Zw4=1,Fw4=Pg0-1;class vg0 extends G4{}class Tg0 extends G4{}class F80 extends G4{}class X80 extends G4{}class _g0 extends G4{}class Sg0 extends G4{}class kg0 extends c0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Xw4}}class Xw4 extends d0{messageScroll=new F$;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=R76(Q,this.messageScroll),B=P76(Q.options.message),E=B?new q4({actions:this.buildScrollActions(),child:new pQ({debugLabel:"SelectDialogScrollShortcuts",shortcuts:T76(),child:$})}):$,D=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)D.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return D.push({keys:["Esc"],label:"cancel"}),new $1({header:Q.options.title,minWidth:64,maxWidth:80,footer:D,autofocus:!1,onDismiss:Q.onCancel,child:E})}buildScrollActions(){let A=(Q)=>{let $=_76(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[vg0,new cA(()=>A(-Zw4))],[Tg0,new cA(()=>A(Zw4))],[F80,new cA(()=>A(-Fw4))],[X80,new cA(()=>A(Fw4))],[_g0,new cA(()=>this.messageScroll.jumpTo(0))],[Sg0,new cA(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function R76(A,Q){let $=A.options.options.map((E)=>({value:E,label:E})),B=Math.max(0,$.findIndex((E)=>E.value===A.options.initialValue));return new OX({options:$,selectedIndex:B,body:v76(A.options.message,Q),onSelect:(E)=>{if(E===null){A.onCancel();return}A.onSelect(E)},padding:n0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function P76(A){if(A===void 0)return!1;return A.split(`
2990
2990
  `).length>Pg0}function v76(A,Q){if(A===void 0)return;let $=A.split(`
2991
2991
  `).length,B=Math.min($,Pg0);return new y0({width:1/0,height:B,child:new LB({autofocus:!1,controller:Q,child:new J0({text:new g(A)})})})}function T76(){return new Map([[HA.key("PageUp"),new F80],[HA.key("PageDown"),new X80],[HA.ctrl("u"),new F80],[HA.ctrl("d"),new X80],[HA.ctrl("y"),new vg0],[HA.ctrl("e"),new Tg0],[HA.shift("Home"),new _g0],[HA.shift("End"),new Sg0]])}function _76(A,Q,$){return Math.max(Q,Math.min(A,$))}var S76=3,k76=2097152,f76=new BB("PluginDialogOverlay");function I80(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}function x76(A){let Q=new TextEncoder().encode(JSON.stringify(A)).byteLength;if(Q<=k76)return;throw Error(`thread.messages response is too large (${Q} bytes). Request fewer messages.`)}class fg0{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;blockingConfirmDialog=!1;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!mB0($.method)){if($.method==="thread.messages")this.handleThreadMessagesRequest($,Q);return}this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}hasBlockingConfirmDialog(){return this.activeDialog?.kind==="confirm"}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new z6({key:f76,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new Nl({key:new CK(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)});case"confirm":return new Og0({key:new CK(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new kg0({key:new CK(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.context.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,this.options.readThreadMessages)A.readThreadMessagesHandler=this.readThreadMessages;A.runAgentHandler=this.options.context.observerOnly?async()=>{throw Error("agent.run is only available from an executor-owned plugin runtime")}:this.options.runAgent??(async()=>{throw Error("agent.run is not available in this context")}),A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleThreadMessagesRequest(A,Q){try{let{options:$,threadID:B}=this.parseThreadMessagesRequestParams(A.params),E=await this.readThreadMessages($,B);x76(E),Q(I80(A.id,E))}catch($){Q(I80(A.id,void 0,$ instanceof Error?$.message:String($)))}}parseThreadMessagesRequestParams(A){if(!A||typeof A!=="object")return{options:void 0,threadID:void 0};let Q=A;return{options:Q.options,threadID:typeof Q.threadID==="string"?Q.threadID:void 0}}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(I80(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(I80(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let E=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,E))}catch(E){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,E instanceof Error?E.message:String(E)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=iY4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=nY4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=oY4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=aY4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.readThreadMessagesHandler===this.readThreadMessages)A.readThreadMessagesHandler=null;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null;if(A.runAgentHandler===this.options.runAgent)A.runAgentHandler=null}subscribePluginCommands(){let A=this.options.context.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(Uh($.errorMessage))continue;let B=`${$.uri.toString()}
2992
- ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=fG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=fG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=fG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,S76)}scheduleResolvingDialogAdvance(A,Q){K6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}s0();import{spawnSync as y76}from"node:child_process";import U9 from"node:process";var Iw4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function ql(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else X1.instance.stop()}function Gw4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:U9.env.NODE_ENV==="development"&&U9.platform==="darwin"?HA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),ql(A)}}}function b76(A,Q){let{command:$,args:B}=h76(A),E=U9.execve,D=U9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=y76($,B,{cwd:Q,env:U9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(U9.chdir(Q),$.includes("/"))return E($,[$,...B],U9.env);return E("/usr/bin/env",["env",$,...B],U9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class xg0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return b76(this.requestedThreadIDs,A)}}function h76(A){let Q=A.length>0?["threads","continue",...A]:[],$=g76(U9.argv),B=d76();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=U9.argv[1],D=E&&m76(E)?[E]:[];return{command:U9.execPath,args:[...D,...$,...Q]}}function g76(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(Iw4.booleans.has(Y)){Q.push(E);continue}if(!Iw4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function m76(A){return A!==U9.execPath&&!A.startsWith("/$bunfs/")}function d76(){if(U9.env.NODE_ENV!=="development")return null;let A=U9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=c76(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function c76(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var p76=48;class yg0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Wl({width:p76,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as o76}from"node:fs/promises";import hg0 from"node:os";var l76=["command","args","url","transport","_target"];function bg0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function i76(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function n76(A){if(!bg0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!bg0(B)){Q[$]=B;continue}let E={};for(let D of l76){if(!(D in B))continue;E[D]=D==="url"?i76(B[D]):B[D]}Q[$]=E}return Q}function Vw4(A){let Q=IO(A,[],{allowTrailingComma:!0});if(!bg0(Q))return JP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=n76($[B]);return JP(JSON.stringify($,null,2))}B$();function a76(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Kw4(A,Q,$=JP){try{return{path:Q,contents:$(await o76(A,"utf8"))}}catch{return null}}async function G80(A,Q){let $=[],B=a76(),E=await M4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(hD(D),null,2)});let J=await Kw4(CP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await Kw4(A.settingsFilePath,`${B}/settings/global.json`,Vw4);if(U)$.push(U);let Y=await dY()??"unknown",Z=await M4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780580310-g6c808e",clientOS:`${hg0.platform()} ${hg0.release()} ${hg0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class gg0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var r76=86400000;class mg0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??r76)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>ql(this.options))}}class V80 extends j6{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new dg0(this.offstage)}updateRenderObject(A){if(A instanceof dg0)A.offstage=this.offstage}}class dg0 extends yA{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class wl{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class cg0 extends c0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new zw4}}class zw4 extends d0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new SP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new SP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new V80({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],E=$===this.entries.length-1,D=E?new z6({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(J)=>{if(J.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new V80({key:B.key,offstage:!E,child:D}))}return new QQ({fit:"expand",children:Q})}}class lg0 extends F4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=t76(Q),B="";return new $1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:n0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new q5({items:Q,showBorder:!1,getLabel:(E)=>{let D=pg0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=Ww4(E.item,U),Z=Ww4(D.item,U);if(Y!==Z)return Y?-1:1;let F=Vq(E.item.verb.toLowerCase(),J),X=Vq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=Vq(pg0(E.item),J),G=Vq(pg0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=BA.of(D);return new J0({text:new g(E.status.reason,new Q0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new Cw4({command:E,isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class Cw4 extends F4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:E,query:D,buildContext:J}=this.props,U=BA.of(J),{colors:Y,app:Z}=U,F=$?Z.selectionBackground:void 0,X=$?Z.selectionForeground:Y.foreground,I=$?X:Y.mutedForeground,G=new J0({text:new g(Q.noun?.toLowerCase()??"",new Q0({color:I,dim:B||!$})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),V=Q.verb.toLowerCase();if(B)V+=" (unavailable)";let K=s76(Q,D);if(K)V+=` (alias: ${K})`;let z=new J0({text:new g(V,new Q0({color:X,bold:!0,dim:B})),maxLines:1,overflow:"ellipsis"}),W=[{child:G,fixedWidth:E},{child:z,expanded:!0}];if(Q.shortcut)W.push({child:e76(Q.shortcut,U,B)});return new Hw4({columns:W,padding:n0.horizontal(1),backgroundColor:F})}}function pg0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Ww4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function s76(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function t76(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,dA($.noun)):Q},0)}function e76(A,Q,$){let{app:B}=Q,E=new Q0({color:B.keybind,bold:!0,dim:$}),D=[],J=HX(A.toString()).split("+");for(let U=0;U<J.length;U++){if(U>0)D.push(new g("+",E));D.push(new g(J[U],E))}return J0.spans(D)}class Hw4 extends F4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new L4({child:Y.child}));else D.push(Y.child)}let J=new LA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new WA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class ig0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new wl,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class lB extends lQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=lB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(lB)?.commandRegistry??null}}class ng0 extends c0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Nw4}}class Nw4 extends d0{modalStack=new wl;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=lB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=lB.of(A).commands,$=new lg0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new cg0({root:$,controller:this.modalStack})}}var qw4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],ww4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class K80 extends F4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=z4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new hA({padding:n0.only({left:4}),child:J})]});else U=new LA({crossAxisAlignment:"start",children:[new L4({flex:1,child:D}),new y0({width:1}),new L4({flex:1,child:J})]});B.push(new hA({padding:n0.horizontal(6),child:U}))}return new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function A86(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return HX(Q.join("+"))}class og0 extends F4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=BA.of(A),{colors:$,app:B}=Q,E=z4.of(A),D=new Q0({color:$.secondary,bold:!0}),J=new Q0({color:B.keybind}),U=new Q0({color:B.command}),Y=new Q0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((V)=>{let K=V.noun?.toLowerCase();return K!=="dev"&&K!=="debug"&&V.status.type!=="hidden"})].sort((V,K)=>{let z=(V.noun??"").toLowerCase(),W=(K.noun??"").toLowerCase(),C=z.localeCompare(W);if(C!==0)return C;return V.verb.toLowerCase().localeCompare(K.verb.toLowerCase())}),I=(V)=>{let K=V.methods.map((z)=>A86(z)).join(", ");return[new J0({text:new g(K,J)}),new J0({text:new g(V.description,Y)})]},G=new LB({autofocus:!0,child:new WA({constraints:new Y4(Z,Z,0,Number.POSITIVE_INFINITY),child:new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new hA({padding:n0.horizontal(2),child:new J0({text:new g(`Editor Shortcuts
2992
+ ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=fG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=fG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=fG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,S76)}scheduleResolvingDialogAdvance(A,Q){K6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}s0();import{spawnSync as y76}from"node:child_process";import U9 from"node:process";var Iw4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function ql(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else X1.instance.stop()}function Gw4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:U9.env.NODE_ENV==="development"&&U9.platform==="darwin"?HA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),ql(A)}}}function b76(A,Q){let{command:$,args:B}=h76(A),E=U9.execve,D=U9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=y76($,B,{cwd:Q,env:U9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(U9.chdir(Q),$.includes("/"))return E($,[$,...B],U9.env);return E("/usr/bin/env",["env",$,...B],U9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class xg0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return b76(this.requestedThreadIDs,A)}}function h76(A){let Q=A.length>0?["threads","continue",...A]:[],$=g76(U9.argv),B=d76();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=U9.argv[1],D=E&&m76(E)?[E]:[];return{command:U9.execPath,args:[...D,...$,...Q]}}function g76(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(Iw4.booleans.has(Y)){Q.push(E);continue}if(!Iw4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function m76(A){return A!==U9.execPath&&!A.startsWith("/$bunfs/")}function d76(){if(U9.env.NODE_ENV!=="development")return null;let A=U9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=c76(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function c76(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var p76=48;class yg0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Wl({width:p76,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as o76}from"node:fs/promises";import hg0 from"node:os";var l76=["command","args","url","transport","_target"];function bg0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function i76(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function n76(A){if(!bg0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!bg0(B)){Q[$]=B;continue}let E={};for(let D of l76){if(!(D in B))continue;E[D]=D==="url"?i76(B[D]):B[D]}Q[$]=E}return Q}function Vw4(A){let Q=IO(A,[],{allowTrailingComma:!0});if(!bg0(Q))return JP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=n76($[B]);return JP(JSON.stringify($,null,2))}B$();function a76(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Kw4(A,Q,$=JP){try{return{path:Q,contents:$(await o76(A,"utf8"))}}catch{return null}}async function G80(A,Q){let $=[],B=a76(),E=await M4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(hD(D),null,2)});let J=await Kw4(CP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await Kw4(A.settingsFilePath,`${B}/settings/global.json`,Vw4);if(U)$.push(U);let Y=await dY()??"unknown",Z=await M4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780592276-g890982",clientOS:`${hg0.platform()} ${hg0.release()} ${hg0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class gg0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var r76=86400000;class mg0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??r76)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>ql(this.options))}}class V80 extends j6{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new dg0(this.offstage)}updateRenderObject(A){if(A instanceof dg0)A.offstage=this.offstage}}class dg0 extends yA{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class wl{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class cg0 extends c0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new zw4}}class zw4 extends d0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new SP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new SP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new V80({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],E=$===this.entries.length-1,D=E?new z6({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(J)=>{if(J.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new V80({key:B.key,offstage:!E,child:D}))}return new QQ({fit:"expand",children:Q})}}class lg0 extends F4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=t76(Q),B="";return new $1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:n0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new q5({items:Q,showBorder:!1,getLabel:(E)=>{let D=pg0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=Ww4(E.item,U),Z=Ww4(D.item,U);if(Y!==Z)return Y?-1:1;let F=Vq(E.item.verb.toLowerCase(),J),X=Vq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=Vq(pg0(E.item),J),G=Vq(pg0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=BA.of(D);return new J0({text:new g(E.status.reason,new Q0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new Cw4({command:E,isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class Cw4 extends F4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:E,query:D,buildContext:J}=this.props,U=BA.of(J),{colors:Y,app:Z}=U,F=$?Z.selectionBackground:void 0,X=$?Z.selectionForeground:Y.foreground,I=$?X:Y.mutedForeground,G=new J0({text:new g(Q.noun?.toLowerCase()??"",new Q0({color:I,dim:B||!$})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),V=Q.verb.toLowerCase();if(B)V+=" (unavailable)";let K=s76(Q,D);if(K)V+=` (alias: ${K})`;let z=new J0({text:new g(V,new Q0({color:X,bold:!0,dim:B})),maxLines:1,overflow:"ellipsis"}),W=[{child:G,fixedWidth:E},{child:z,expanded:!0}];if(Q.shortcut)W.push({child:e76(Q.shortcut,U,B)});return new Hw4({columns:W,padding:n0.horizontal(1),backgroundColor:F})}}function pg0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Ww4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function s76(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function t76(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,dA($.noun)):Q},0)}function e76(A,Q,$){let{app:B}=Q,E=new Q0({color:B.keybind,bold:!0,dim:$}),D=[],J=HX(A.toString()).split("+");for(let U=0;U<J.length;U++){if(U>0)D.push(new g("+",E));D.push(new g(J[U],E))}return J0.spans(D)}class Hw4 extends F4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new L4({child:Y.child}));else D.push(Y.child)}let J=new LA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new WA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class ig0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new wl,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class lB extends lQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=lB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(lB)?.commandRegistry??null}}class ng0 extends c0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Nw4}}class Nw4 extends d0{modalStack=new wl;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=lB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=lB.of(A).commands,$=new lg0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new cg0({root:$,controller:this.modalStack})}}var qw4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],ww4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class K80 extends F4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=z4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new hA({padding:n0.only({left:4}),child:J})]});else U=new LA({crossAxisAlignment:"start",children:[new L4({flex:1,child:D}),new y0({width:1}),new L4({flex:1,child:J})]});B.push(new hA({padding:n0.horizontal(6),child:U}))}return new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function A86(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return HX(Q.join("+"))}class og0 extends F4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=BA.of(A),{colors:$,app:B}=Q,E=z4.of(A),D=new Q0({color:$.secondary,bold:!0}),J=new Q0({color:B.keybind}),U=new Q0({color:B.command}),Y=new Q0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((V)=>{let K=V.noun?.toLowerCase();return K!=="dev"&&K!=="debug"&&V.status.type!=="hidden"})].sort((V,K)=>{let z=(V.noun??"").toLowerCase(),W=(K.noun??"").toLowerCase(),C=z.localeCompare(W);if(C!==0)return C;return V.verb.toLowerCase().localeCompare(K.verb.toLowerCase())}),I=(V)=>{let K=V.methods.map((z)=>A86(z)).join(", ");return[new J0({text:new g(K,J)}),new J0({text:new g(V.description,Y)})]},G=new LB({autofocus:!0,child:new WA({constraints:new Y4(Z,Z,0,Number.POSITIVE_INFINITY),child:new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new hA({padding:n0.horizontal(2),child:new J0({text:new g(`Editor Shortcuts
2993
2993
  `,D)})}),new K80({items:qw4.filter((V)=>V.submitOnEnterOnly===void 0||V.submitOnEnterOnly===!0),renderRow:I}),new y0({height:1}),new hA({padding:n0.horizontal(2),child:new J0({text:new g(`Scrolling & Navigation
2994
2994
  `,D)})}),new K80({items:ww4,renderRow:I}),new y0({height:1}),new hA({padding:n0.horizontal(2),child:new J0({text:new g(`Command Palette Commands
2995
2995
  `,D)})}),new K80({items:X,renderRow:(V)=>{let K=V.noun?`${V.noun}: ${V.verb}`:V.verb;return[new J0({text:new g(K,U)}),new J0({text:new g(V.description,Y)})]}}),new y0({height:1})]})})});return new $1({header:"Amp CLI — Help & Keyboard Shortcuts",minWidth:Z,maxWidth:Z,maxHeight:E.size.height,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.onDismiss,child:G})}}class Yv extends lQ{completionBuilder;constructor({completionBuilder:A,child:Q}){super({child:Q});this.completionBuilder=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(Yv);if(!Q)throw Error("No CompletionBuilderProvider found in widget tree");return Q.completionBuilder}}var Q86=250,$86=2000;class ag0 extends c0{configReloadEvents;toastController;child;constructor(A){super();this.configReloadEvents=A.configReloadEvents,this.toastController=A.toastController,this.child=A.child}createState(){return new uw4}}class uw4 extends d0{subscription=null;toastTimer=null;pendingToastType=null;lastToast=null;initState(){this.subscribeToConfigReloadEvents()}didUpdateWidget(A){if(A.configReloadEvents===this.widget.configReloadEvents)return;this.clearPendingToast(),this.subscribeToConfigReloadEvents()}dispose(){this.subscription?.unsubscribe(),this.subscription=null,this.clearPendingToast(),super.dispose()}build(A){return this.widget.child}subscribeToConfigReloadEvents(){this.subscription?.unsubscribe(),this.subscription=this.widget.configReloadEvents.subscribe((A)=>{this.scheduleToast(A)})}scheduleToast(A){if(this.pendingToastType=B86(this.pendingToastType,A),this.toastTimer)clearTimeout(this.toastTimer);this.toastTimer=setTimeout(()=>{if(!this.mounted)return;this.flushToast()},Q86),this.toastTimer.unref()}flushToast(){let A=this.pendingToastType;if(this.clearPendingToast(),!A)return;let Q=Date.now();if(E86(this.lastToast,A,Q))return;this.lastToast={type:A,shownAt:Q},D86(this.widget.toastController,A)}clearPendingToast(){if(this.toastTimer)clearTimeout(this.toastTimer),this.toastTimer=null;this.pendingToastType=null}}function B86(A,Q){return A==="failed"||Q.type==="failed"?"failed":"succeeded"}function E86(A,Q,$){return A?.type===Q&&$-A.shownAt<$86}function D86(A,Q){switch(Q){case"succeeded":A.show("Config reloaded","success",1500);break;case"failed":A.show("Config reload failed","error",5000);break}}class HQ extends lQ{context;constructor({context:A,child:Q}){super({child:Q});this.context=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(HQ);if(!Q)throw Error("No ContextProvider found in widget tree");return Q.context}}s0();y9();var W80=80,J86=15,U86=1,Mw4=-W80,Y86=16,Z86=$b0(W80,W80);function Ow4({ampURL:A,threadID:Q,logPath:$}){return[`Debug thread ${xO(new URL(A),Q).toString()} (cli log: ${$}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
@@ -3082,7 +3082,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)R=this.widget.centerContent
3082
3082
  `));if(U.tools.length===0)J.push(new g(` └─ No tools available
3083
3083
  `,E));else for(let F of U.tools)DZ6(J,F,$);J.push(new g(`
3084
3084
  `))}return J}function DZ6(A,Q,$){let{colors:B,app:E}=$,D=JZ6(Q.status,$);if(A.push(new g(` ${D.icon} `,new Q0({color:D.color}))),A.push(new g(Q.name,new Q0({color:Q.status==="pending"?B.warning:E.command}))),Q.status==="pending")A.push(new g(" discovering...",new Q0({color:B.foreground,dim:!0})));else if(Q.description)A.push(new g(` ${Oj4(Q.description,50)}`,new Q0({color:B.foreground,dim:!0})));if(Q.error)A.push(new g(` ${Oj4(Q.error,40)}`,new Q0({color:E.toolError})));A.push(new g(`
3085
- `))}function JZ6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function Oj4(A,Q){let $=A.replace(/\s+/g," ").trim();if(dA($)<=Q)return $;let B="...",E=dA(B);if(Q<=E)return d7(B,Q);return`${d7($,Q-E,!0,"")}${B}`}var Oc0="https://ampcode.com/news/neo",Lc0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:Oc0,href:Oc0}]}];function UZ6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:Oc0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function YZ6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var uv=50,yq=40,uc0=1000,ZZ6=420,FZ6=760,XZ6=-250,IZ6=1100,w90=33,Pj4=0.999,GZ6=2.1,VZ6=720,KZ6=420,yj4="Meet the new",bj4="Amp",hj4="CLI",jc0=B4(yj4).length,zZ6=B4(bj4).length,WZ6=B4(hj4).length,u90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},vj4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},Tj4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},_j4=[u90,vj4,Tj4,u90,vj4,Tj4,u90],CZ6=u90;class Rc0 extends c0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??YZ6(),this.introStages=this.variant==="npm-migration"?UZ6(this.binaryInstallCommand):Lc0,this.dismissible=this.variant!=="npm-migration"}createState(){return new gj4}}class gj4 extends d0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=uc0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new u5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=NE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=Pj4,this.firstStageHintVisible=this.animationProgress>=Pj4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:uc0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=NE(A/FZ6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},w90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=NE($/ZZ6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},w90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=NE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*Mv(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},w90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,uc0+XZ6),Q=A+IZ6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?NE((A-this.firstStageTitleRevealStartedAt)/VZ6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?NE((A-this.firstStageHintRevealStartedAt)/KZ6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},w90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Sj4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:kj4(Sj4(this.previousIntroStage),A,Mv(this.stageTransitionProgress));return this.dismissProgress>0?kj4(Q,CZ6,Mv(this.dismissProgress)):Q}build(A){let Q=d4.of(A).colorScheme,$=BA.of(A),B=this.currentOrbPalette(),E=B7(1,"deep",B),D=z4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/uv,D.height/yq)*GZ6,Z=Y+(1-Y)*U,F=Mv(this.dismissProgress),X=Math.max(uv,Math.round(uv*Z)),I=Math.max(yq,Math.round(yq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-uv)/2)),z=-Math.floor(yq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,q=HZ6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(uv,Math.round(uv*q.orbScale)),L=Math.max(yq,Math.round(yq*q.orbScale)),R=q.orbCenterX,_=q.orbCenterY,v=Math.round(R-u/2),f=Math.round(_-L/2),d=Math.max(3,Math.min(D.height-5,Math.floor(yq/2)+2)),x=Math.max(d+3,D.height-3),T=q.textDissolveProgress,k=this.isFinalIntroStage()?q.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&T<1,m=c&&this.firstStageHintVisible,b=m&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-d-6)),E0=Math.max(0,Math.floor((D.width-a)/2)),I0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),v0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new xK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new xK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new z6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new QQ({fit:"expand",children:[new mj4({color:Q.background,dissolveProgress:k}),new QQ({fit:"expand",children:[new aA({onClick:()=>{},child:y0.expand()}),new r1({left:v,top:f,width:u,height:L,child:v0}),...c?[new r1({left:E0,top:I0,width:a,height:X0,child:qZ6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:T,context:A})})]:[],...m?[...b?[new r1({left:E0,top:Math.max(0,x-1),width:a,height:1,child:new J0({text:jZ6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:T}),textAlign:"center"})})]:[],new r1({left:E0,top:x,width:a,height:1,child:PZ6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:T,context:A})})]:[]]})]})})}}class mj4 extends EB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new dj4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class dj4 extends yA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=NE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!NZ6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function NE(A){return Math.min(1,Math.max(0,A))}function Mv(A){return 1-(1-A)**3}function Sj4(A){return _j4[A]??_j4[0]}function kj4(A,Q,$){return{primary:Kq(A.primary,Q.primary,$),secondary:Kq(A.secondary,Q.secondary,$)}}function HZ6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:NE(A/0.52),backdropDissolveProgress:Mv(NE((A-0.12)/0.88))}}function NZ6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=cj4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function qZ6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return Mc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=Mv(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Aq(new QQ({fit:"expand",children:[new r1({left:W,top:0,width:D,height:J,child:Mc0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new r1({left:z,top:0,width:D,height:J,child:Mc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function Mc0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??Lc0[0],X=new Q0({color:E,bold:!0}),I=new Q0({color:$}),G=A===Lc0&&Q===0,V=[...F.title===null?[]:[new J0({text:G?M90(MZ6({progress:U,foreground:E,pulseColor:E}),Y):new g(r7(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[wZ6()]:[],...F.body.map((K)=>uZ6(K,I,B,D,J,Y,Z))];return new Q6({child:new hA({padding:n0.horizontal(1),child:new IA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function wZ6(){return y0.height(1)}function uZ6(A,Q,$,B,E,D,J){if(typeof A==="string")return new J0({text:new g(r7(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new H5({onCopy:(U,Y)=>{if(Y)EQ.success(J,"Copied to clipboard",2000)},child:new IA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new J0({text:new g(r7(U,D),new Q0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new J0({text:new g("",void 0,[new g(r7(A.text,D),new Q0({color:$,dim:!0})),new g(r7(A.keybind,D,B4(A.text).length),new Q0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new Q6({child:new H5({child:U})});return U}if("highlightText"in A){let U=q$.createSpan(A.href,A.linkText,new Q0({color:B,underline:!0})),Y=kX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new Q0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{d6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new J0({text:M90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new IA({mainAxisSize:"min",children:[new J0({text:new g(r7(A.text,D),Q),textAlign:"center"}),new Q6({child:new LA({mainAxisSize:"min",children:[q$.createWidget(J,A.href,r7(A.linkText,D),new Q0({color:B,underline:!0})),new J0({text:new g(r7(A.textAfter,D),Q)})]})})]});let U=q$.createSpan(A.href,A.linkText,new Q0({color:B,underline:!0})),Y=kX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{d6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new J0({text:M90(Z,D),textAlign:"center"})}if(D>0)return new J0({text:new g(r7(A.text,D),new Q0({color:B,underline:!0})),textAlign:"center"});return new Q6({child:q$.createWidget(J,A.href,A.text,new Q0({color:B,underline:!0}))})}function MZ6({progress:A,foreground:Q,pulseColor:$}){let B=new Q0({color:Q,bold:!0}),E=new Q0({color:LZ6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(OZ6(A).padEnd(jc0," "),B),new g(" ",B),new g(fj4(bj4,zZ6,A,0.72),B),new g(" ",B),new g(fj4(hj4,WZ6,A,0.88),E)])}function OZ6(A){let Q=B4(yj4),$=Math.min(jc0,Math.ceil(NE(A/0.62)*jc0));return Q.slice(0,$).join("")}function fj4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function LZ6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=NE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function jZ6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g(r7(`${A}/${Q}`,B),new Q0({color:$,dim:!0}))}function RZ6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new Q0({color:B}),U=new Q0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=xj4(Y,E),V=xj4(I,NE((E*(B4(Y).length+B4(I).length)-B4(Y).length)/B4(I).length));return new g("",void 0,[new g(r7(G,D),J),new g(r7(V.slice(0,Z.length),D),U),new g(r7(V.slice(Z.length,Z.length+0),D),J),new g(r7(V.slice(Z.length+0),D),U)])}function PZ6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new J0({text:RZ6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new Q0({color:B}),Y=new Q0({color:$,dim:!0});return new H5({onCopy:(Z,F)=>{if(F)EQ.success(J,"Copied to clipboard",2000)},child:new J0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function xj4(A,Q){let $=B4(A),B=Math.min($.length,Math.ceil(NE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function M90(A,Q,$=0){if(Q<=0)return A;let B=$+B4(A.text??"").length,E=A.children?.map((D)=>{let J=M90(D,Q,B);return B+=B4(D.toPlainText()).length,J});return new g(A.text?r7(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function r7(A,Q,$=0){if(Q<=0)return A;return B4(A).map((E,D)=>{if(E.trim()==="")return E;return cj4($+D)<Q?" ":E}).join("")}function cj4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function vZ6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function TZ6(A,Q={}){return new Promise(($,B)=>{let E=!1,D=setTimeout(()=>{J.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),J=A.observer.agentState().subscribe((U)=>{if(y3(U)){E=!0;return}if(!E)return;let Y=vZ6(A);if(Y===null)return;clearTimeout(D),J.unsubscribe(),$(Y)})})}class Pc0 extends c0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new lj4}}class lj4 extends d0{editorController=new rY;commandPalette=new sy0(this);commandRegistry=new ig0;toastController=new Ab0;relaunchNotificationController=new yg0;exitHintTimer=new Vp(this,1000);ideStatus=new m3(this,{});threadNavigationHistory=new gg0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new Tl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new p7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){K6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return kK4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new qc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>G80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await r50({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await bH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await hH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(CX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new Ng0(this.widget.configService,($)=>this.setState($)),K6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(se($.settings)))}),this.updateRelaunchIntegration=new mg0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new fg0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new Wh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=X1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?Dw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Gw4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(E,D,J)=>{E.pushWithDismiss((U)=>Hd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:U,onThreadSelected:J}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(E,D,J)=>{A.navigateBack(),J()}},UM4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(E,D,J)=>{A.navigateForward(),J()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(E,D,J)=>{E.push(new jm0({mcpServers:this.widget.context.mcpServers,onDismiss:J}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(E)=>{E.pushWithDismiss((D)=>new wc0({toolboxes:this.widget.context.toolboxes,onDismiss:D}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(E,D,J)=>{try{await d6(D,"https://ampcode.com/chronicle")}finally{J()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{NK(this.widget.context.settingsFilePath).catch((E)=>{S.error("Failed to open settings file in editor",{error:E})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(E,D,J)=>{E.pushWithDismiss((U)=>new Lm0({onCancel:U,onSelect:(Y)=>{this.handleIdeSelection(Y),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new og0({commands:lB.of(D).commands,onDismiss:J}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new $1({header:"Amp Version",maxWidth:72,onDismiss:J,child:new J0({text:new g(u50({version:"0.0.1780580310-g6c808e",buildTimestamp:"2026-06-04T13:43:38.391Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:HA.ctrl("c"),status:{type:"enabled"},run:(E,D)=>{q4.maybeInvoke(D,new PK)}},...Q,...yH4(this.widget.context.logFilePath)].map((E)=>this.commandRegistry.register(E));return()=>{for(let E of B)E()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new Kc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(I)=>this.notices.dismiss(I)}),D=z4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new WA({constraints:Y4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new z6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new ng0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(Hd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new z6({debugLabel:"WelcomeDialogOverlay",child:new Rc0({onDismiss:this.dismissWelcome,onQuit:()=>X1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new z6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Mm0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new rg0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:O90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new Om0);if(this.endCreditsVisible)F.push(new Cm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new HQ({context:this.widget.context,child:new lB({commandRegistry:this.commandRegistry,child:new Yv({completionBuilder:this.widget.completionBuilder,child:new EQ({controller:this.toastController,child:new q4({actions:this.buildActions(),child:new pQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new jQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Qb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new ag0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new yp({left:U,width:Y,child:new QQ({children:F})})})})})})})})})})})}buildShortcuts(){let A=new Map([[HA.ctrl("c"),new V70],[HA.ctrl("o"),new z70],[HA.alt("i"),new C70],[HA.alt("p"),new rc],[HA.ctrl("."),new q70],[HA.ctrl("t"),new M70],...this.threadListSidebar.shortcutEntries()]);if(O90.env.NODE_ENV==="development"&&O90.platform==="darwin")A.set(HA.meta("r"),new K70);return A}buildActions(){let A=new cA(()=>{if(v2.hasAnyCopyableSelection())return v2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA(()=>{return this.startNewDraftThread(),"handled"}),E=new cA(()=>{return X1.instance.stop(),"handled"}),D=new cA(()=>{return ql({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),J=new cA((I)=>{if(!I.text)return"ignored";return X1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{S.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),U=new cA(()=>{return X1.instance.toggleFrameStatsOverlay(),"handled"}),Y=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=Lw4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[V70,A],[zq,B],[PK,E],[K70,D],[DB,J],[op,$],[z70,Q],[C70,Z],...this.threadListSidebar.actionEntries(),[q70,Y],...F,[rc,U],[M70,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await PP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=iN(Q),E=s30(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return a30($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=pj4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dU(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=pj4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(RK);if(this.exitHintTimer.isActive())A.add(rP);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),X1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),iD((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")X1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(pe);if(U)this.widget.history.add(U.text,O90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=iN(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};iD((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=w50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return uoA(MoA($.observer.protocolMessages()),A)};runPluginAgent=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1});this.sendUserMessage($,[{type:"text",text:Q.message}]);try{let B=await TZ6($,{timeoutMs:Q.timeoutMs}),E=$.client.getThreadId();return E?{threadID:E,text:B}:{text:B}}finally{this.widget.clientPool.disconnect($)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function pj4(A,Q,$){let B={...A};for(let E of _Z6(Q,$)){if(!dU(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function _Z6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}A3();function ij4(A,Q,$,B){let E=jyA(A),D="\x1B[0m",J="\x1B[34m",U="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${E}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let F=14,X=7,I=new R2(F,X),G=new u5(42),V=new Zv(F,X,F,X,F,X,0,A.agentMode??"smart","intensity","ascii",void 0,void 0,m0.default(),G);V.layout(Y4.tight(F,X)),V.paint(I,0,0);let K=I.getBuffer().getCells(),z=0;for(let R=0;R<X;R++)if(K[R].some((_)=>_.char!==" ")){z=R;break}let W=X-1;for(let R=X-1;R>=0;R--)if(K[R].some((_)=>_.char!==" ")){W=R;break}function C(R,_){if(!R)return"";if(R.type==="rgb"){let{r:v,g:f,b:d}=R.value;if($.getColorDepth()>=24)return`\x1B[${_?38:48};2;${v};${f};${d}m`;let x=Ep(v,f,d);return`\x1B[${_?38:48};5;${x}m`}return""}let H=[];if(W>=z)for(let R=z;R<=W;R++){let _="";for(let v=0;v<F;v++){let f=K[R][v],d=f.char,x=C(f.style.fg,!0);_+=x+d+"\x1B[0m"}H.push(_)}let N=H.length,q=Math.max(N,Z.length),u=Math.floor((q-N)/2),L=Math.floor((q-Z.length)/2);for(let R=0;R<q;R++){let _=" ".repeat(F);if(R>=u&&R<u+N)_=H[R-u];let v=" ",f="";if(R>=L&&R<L+Z.length)f=Z[R-L];$.write(_+v+f+`
3085
+ `))}function JZ6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function Oj4(A,Q){let $=A.replace(/\s+/g," ").trim();if(dA($)<=Q)return $;let B="...",E=dA(B);if(Q<=E)return d7(B,Q);return`${d7($,Q-E,!0,"")}${B}`}var Oc0="https://ampcode.com/news/neo",Lc0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:Oc0,href:Oc0}]}];function UZ6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:Oc0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function YZ6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var uv=50,yq=40,uc0=1000,ZZ6=420,FZ6=760,XZ6=-250,IZ6=1100,w90=33,Pj4=0.999,GZ6=2.1,VZ6=720,KZ6=420,yj4="Meet the new",bj4="Amp",hj4="CLI",jc0=B4(yj4).length,zZ6=B4(bj4).length,WZ6=B4(hj4).length,u90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},vj4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},Tj4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},_j4=[u90,vj4,Tj4,u90,vj4,Tj4,u90],CZ6=u90;class Rc0 extends c0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??YZ6(),this.introStages=this.variant==="npm-migration"?UZ6(this.binaryInstallCommand):Lc0,this.dismissible=this.variant!=="npm-migration"}createState(){return new gj4}}class gj4 extends d0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=uc0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new u5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=NE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=Pj4,this.firstStageHintVisible=this.animationProgress>=Pj4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:uc0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=NE(A/FZ6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},w90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=NE($/ZZ6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},w90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=NE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*Mv(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},w90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,uc0+XZ6),Q=A+IZ6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?NE((A-this.firstStageTitleRevealStartedAt)/VZ6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?NE((A-this.firstStageHintRevealStartedAt)/KZ6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},w90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Sj4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:kj4(Sj4(this.previousIntroStage),A,Mv(this.stageTransitionProgress));return this.dismissProgress>0?kj4(Q,CZ6,Mv(this.dismissProgress)):Q}build(A){let Q=d4.of(A).colorScheme,$=BA.of(A),B=this.currentOrbPalette(),E=B7(1,"deep",B),D=z4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/uv,D.height/yq)*GZ6,Z=Y+(1-Y)*U,F=Mv(this.dismissProgress),X=Math.max(uv,Math.round(uv*Z)),I=Math.max(yq,Math.round(yq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-uv)/2)),z=-Math.floor(yq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,q=HZ6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(uv,Math.round(uv*q.orbScale)),L=Math.max(yq,Math.round(yq*q.orbScale)),R=q.orbCenterX,_=q.orbCenterY,v=Math.round(R-u/2),f=Math.round(_-L/2),d=Math.max(3,Math.min(D.height-5,Math.floor(yq/2)+2)),x=Math.max(d+3,D.height-3),T=q.textDissolveProgress,k=this.isFinalIntroStage()?q.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&T<1,m=c&&this.firstStageHintVisible,b=m&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-d-6)),E0=Math.max(0,Math.floor((D.width-a)/2)),I0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),v0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new xK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new xK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new z6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new QQ({fit:"expand",children:[new mj4({color:Q.background,dissolveProgress:k}),new QQ({fit:"expand",children:[new aA({onClick:()=>{},child:y0.expand()}),new r1({left:v,top:f,width:u,height:L,child:v0}),...c?[new r1({left:E0,top:I0,width:a,height:X0,child:qZ6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:T,context:A})})]:[],...m?[...b?[new r1({left:E0,top:Math.max(0,x-1),width:a,height:1,child:new J0({text:jZ6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:T}),textAlign:"center"})})]:[],new r1({left:E0,top:x,width:a,height:1,child:PZ6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:T,context:A})})]:[]]})]})})}}class mj4 extends EB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new dj4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class dj4 extends yA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=NE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!NZ6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function NE(A){return Math.min(1,Math.max(0,A))}function Mv(A){return 1-(1-A)**3}function Sj4(A){return _j4[A]??_j4[0]}function kj4(A,Q,$){return{primary:Kq(A.primary,Q.primary,$),secondary:Kq(A.secondary,Q.secondary,$)}}function HZ6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:NE(A/0.52),backdropDissolveProgress:Mv(NE((A-0.12)/0.88))}}function NZ6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=cj4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function qZ6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return Mc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=Mv(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Aq(new QQ({fit:"expand",children:[new r1({left:W,top:0,width:D,height:J,child:Mc0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new r1({left:z,top:0,width:D,height:J,child:Mc0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function Mc0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??Lc0[0],X=new Q0({color:E,bold:!0}),I=new Q0({color:$}),G=A===Lc0&&Q===0,V=[...F.title===null?[]:[new J0({text:G?M90(MZ6({progress:U,foreground:E,pulseColor:E}),Y):new g(r7(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[wZ6()]:[],...F.body.map((K)=>uZ6(K,I,B,D,J,Y,Z))];return new Q6({child:new hA({padding:n0.horizontal(1),child:new IA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function wZ6(){return y0.height(1)}function uZ6(A,Q,$,B,E,D,J){if(typeof A==="string")return new J0({text:new g(r7(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new H5({onCopy:(U,Y)=>{if(Y)EQ.success(J,"Copied to clipboard",2000)},child:new IA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new J0({text:new g(r7(U,D),new Q0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new J0({text:new g("",void 0,[new g(r7(A.text,D),new Q0({color:$,dim:!0})),new g(r7(A.keybind,D,B4(A.text).length),new Q0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new Q6({child:new H5({child:U})});return U}if("highlightText"in A){let U=q$.createSpan(A.href,A.linkText,new Q0({color:B,underline:!0})),Y=kX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new Q0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{d6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new J0({text:M90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new IA({mainAxisSize:"min",children:[new J0({text:new g(r7(A.text,D),Q),textAlign:"center"}),new Q6({child:new LA({mainAxisSize:"min",children:[q$.createWidget(J,A.href,r7(A.linkText,D),new Q0({color:B,underline:!0})),new J0({text:new g(r7(A.textAfter,D),Q)})]})})]});let U=q$.createSpan(A.href,A.linkText,new Q0({color:B,underline:!0})),Y=kX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{d6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new J0({text:M90(Z,D),textAlign:"center"})}if(D>0)return new J0({text:new g(r7(A.text,D),new Q0({color:B,underline:!0})),textAlign:"center"});return new Q6({child:q$.createWidget(J,A.href,A.text,new Q0({color:B,underline:!0}))})}function MZ6({progress:A,foreground:Q,pulseColor:$}){let B=new Q0({color:Q,bold:!0}),E=new Q0({color:LZ6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(OZ6(A).padEnd(jc0," "),B),new g(" ",B),new g(fj4(bj4,zZ6,A,0.72),B),new g(" ",B),new g(fj4(hj4,WZ6,A,0.88),E)])}function OZ6(A){let Q=B4(yj4),$=Math.min(jc0,Math.ceil(NE(A/0.62)*jc0));return Q.slice(0,$).join("")}function fj4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function LZ6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=NE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function jZ6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g(r7(`${A}/${Q}`,B),new Q0({color:$,dim:!0}))}function RZ6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new Q0({color:B}),U=new Q0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=xj4(Y,E),V=xj4(I,NE((E*(B4(Y).length+B4(I).length)-B4(Y).length)/B4(I).length));return new g("",void 0,[new g(r7(G,D),J),new g(r7(V.slice(0,Z.length),D),U),new g(r7(V.slice(Z.length,Z.length+0),D),J),new g(r7(V.slice(Z.length+0),D),U)])}function PZ6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new J0({text:RZ6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new Q0({color:B}),Y=new Q0({color:$,dim:!0});return new H5({onCopy:(Z,F)=>{if(F)EQ.success(J,"Copied to clipboard",2000)},child:new J0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function xj4(A,Q){let $=B4(A),B=Math.min($.length,Math.ceil(NE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function M90(A,Q,$=0){if(Q<=0)return A;let B=$+B4(A.text??"").length,E=A.children?.map((D)=>{let J=M90(D,Q,B);return B+=B4(D.toPlainText()).length,J});return new g(A.text?r7(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function r7(A,Q,$=0){if(Q<=0)return A;return B4(A).map((E,D)=>{if(E.trim()==="")return E;return cj4($+D)<Q?" ":E}).join("")}function cj4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function vZ6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function TZ6(A,Q={}){return new Promise(($,B)=>{let E=!1,D=setTimeout(()=>{J.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),J=A.observer.agentState().subscribe((U)=>{if(y3(U)){E=!0;return}if(!E)return;let Y=vZ6(A);if(Y===null)return;clearTimeout(D),J.unsubscribe(),$(Y)})})}class Pc0 extends c0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new lj4}}class lj4 extends d0{editorController=new rY;commandPalette=new sy0(this);commandRegistry=new ig0;toastController=new Ab0;relaunchNotificationController=new yg0;exitHintTimer=new Vp(this,1000);ideStatus=new m3(this,{});threadNavigationHistory=new gg0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new Tl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new p7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){K6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return kK4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new qc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>G80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await r50({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await bH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await hH4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(CX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new Ng0(this.widget.configService,($)=>this.setState($)),K6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(se($.settings)))}),this.updateRelaunchIntegration=new mg0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new fg0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new Wh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=X1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?Dw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Gw4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(E,D,J)=>{E.pushWithDismiss((U)=>Hd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:U,onThreadSelected:J}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(E,D,J)=>{A.navigateBack(),J()}},UM4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(E,D,J)=>{A.navigateForward(),J()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(E,D,J)=>{E.push(new jm0({mcpServers:this.widget.context.mcpServers,onDismiss:J}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(E)=>{E.pushWithDismiss((D)=>new wc0({toolboxes:this.widget.context.toolboxes,onDismiss:D}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(E,D,J)=>{try{await d6(D,"https://ampcode.com/chronicle")}finally{J()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{NK(this.widget.context.settingsFilePath).catch((E)=>{S.error("Failed to open settings file in editor",{error:E})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(E,D,J)=>{E.pushWithDismiss((U)=>new Lm0({onCancel:U,onSelect:(Y)=>{this.handleIdeSelection(Y),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new og0({commands:lB.of(D).commands,onDismiss:J}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new $1({header:"Amp Version",maxWidth:72,onDismiss:J,child:new J0({text:new g(u50({version:"0.0.1780592276-g890982",buildTimestamp:"2026-06-04T17:02:44.679Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:HA.ctrl("c"),status:{type:"enabled"},run:(E,D)=>{q4.maybeInvoke(D,new PK)}},...Q,...yH4(this.widget.context.logFilePath)].map((E)=>this.commandRegistry.register(E));return()=>{for(let E of B)E()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new Kc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(I)=>this.notices.dismiss(I)}),D=z4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new WA({constraints:Y4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new z6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new ng0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(Hd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new z6({debugLabel:"WelcomeDialogOverlay",child:new Rc0({onDismiss:this.dismissWelcome,onQuit:()=>X1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new z6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Mm0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new rg0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:O90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new Om0);if(this.endCreditsVisible)F.push(new Cm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new HQ({context:this.widget.context,child:new lB({commandRegistry:this.commandRegistry,child:new Yv({completionBuilder:this.widget.completionBuilder,child:new EQ({controller:this.toastController,child:new q4({actions:this.buildActions(),child:new pQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new jQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Qb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new ag0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new yp({left:U,width:Y,child:new QQ({children:F})})})})})})})})})})})}buildShortcuts(){let A=new Map([[HA.ctrl("c"),new V70],[HA.ctrl("o"),new z70],[HA.alt("i"),new C70],[HA.alt("p"),new rc],[HA.ctrl("."),new q70],[HA.ctrl("t"),new M70],...this.threadListSidebar.shortcutEntries()]);if(O90.env.NODE_ENV==="development"&&O90.platform==="darwin")A.set(HA.meta("r"),new K70);return A}buildActions(){let A=new cA(()=>{if(v2.hasAnyCopyableSelection())return v2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA(()=>{return this.startNewDraftThread(),"handled"}),E=new cA(()=>{return X1.instance.stop(),"handled"}),D=new cA(()=>{return ql({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),J=new cA((I)=>{if(!I.text)return"ignored";return X1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{S.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),U=new cA(()=>{return X1.instance.toggleFrameStatsOverlay(),"handled"}),Y=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=Lw4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[V70,A],[zq,B],[PK,E],[K70,D],[DB,J],[op,$],[z70,Q],[C70,Z],...this.threadListSidebar.actionEntries(),[q70,Y],...F,[rc,U],[M70,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await PP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=iN(Q),E=s30(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return a30($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=pj4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dU(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=pj4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(RK);if(this.exitHintTimer.isActive())A.add(rP);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),X1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),iD((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")X1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(pe);if(U)this.widget.history.add(U.text,O90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=iN(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};iD((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=w50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return uoA(MoA($.observer.protocolMessages()),A)};runPluginAgent=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1});this.sendUserMessage($,[{type:"text",text:Q.message}]);try{let B=await TZ6($,{timeoutMs:Q.timeoutMs}),E=$.client.getThreadId();return E?{threadID:E,text:B}:{text:B}}finally{this.widget.clientPool.disconnect($)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function pj4(A,Q,$){let B={...A};for(let E of _Z6(Q,$)){if(!dU(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function _Z6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}A3();function ij4(A,Q,$,B){let E=jyA(A),D="\x1B[0m",J="\x1B[34m",U="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${E}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let F=14,X=7,I=new R2(F,X),G=new u5(42),V=new Zv(F,X,F,X,F,X,0,A.agentMode??"smart","intensity","ascii",void 0,void 0,m0.default(),G);V.layout(Y4.tight(F,X)),V.paint(I,0,0);let K=I.getBuffer().getCells(),z=0;for(let R=0;R<X;R++)if(K[R].some((_)=>_.char!==" ")){z=R;break}let W=X-1;for(let R=X-1;R>=0;R--)if(K[R].some((_)=>_.char!==" ")){W=R;break}function C(R,_){if(!R)return"";if(R.type==="rgb"){let{r:v,g:f,b:d}=R.value;if($.getColorDepth()>=24)return`\x1B[${_?38:48};2;${v};${f};${d}m`;let x=Ep(v,f,d);return`\x1B[${_?38:48};5;${x}m`}return""}let H=[];if(W>=z)for(let R=z;R<=W;R++){let _="";for(let v=0;v<F;v++){let f=K[R][v],d=f.char,x=C(f.style.fg,!0);_+=x+d+"\x1B[0m"}H.push(_)}let N=H.length,q=Math.max(N,Z.length),u=Math.floor((q-N)/2),L=Math.floor((q-Z.length)/2);for(let R=0;R<q;R++){let _=" ".repeat(F);if(R>=u&&R<u+N)_=H[R-u];let v=" ",f="";if(R>=L&&R<L+Z.length)f=Z[R-L];$.write(_+v+f+`
3086
3086
  `)}if(B)$.write(`
3087
3087
  \x1B[90m${B}\x1B[0m
3088
3088
  `)}s0();class vc0{status=P3.status;constructor(){this.autoConnect()}async connect(A){await P3.start(A,!0,"user-initiated"),P3.selectConfig(A)}autoConnect(){let A=P3.getSelectedConfig();if(A){P3.start(A,!0,"auto-startup").catch((Q)=>{S.error("Failed to auto-connect to IDE",{error:Q})});return}this.discoverAndConnect()}async discoverAndConnect(){try{await rbA();let A=await kC({});if(A.length===1&&A[0])P3.selectConfig(A[0]),await P3.start(A[0],!0,"auto-startup")}catch(A){S.error("Failed to auto-discover IDE",{error:A})}}}s0();s0();import{exec as bq}from"node:child_process";function nj4(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")bq("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")bq("powershell [console]::beep(800,200)");else if(process.platform==="linux")bq("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")bq("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")bq("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")bq("powershell [console]::beep(1000,300)");else if(process.platform==="linux")bq("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){S.error(`Failed to play notification sound (${A}):`,Q)}}Zp();cy0();var SZ6=2000,kZ6="Agent is ready",fZ6="Waiting for approval";function oj4(A){let Q=!0,$=!0,B=A.configService.config.subscribe((W)=>{Q=W.settings["notifications.enabled"]??!0,$=W.settings["notifications.system.enabled"]!==!1}),E=0,D=()=>{let W=G?.prepareTerminalTitleForNotification();if(W!==void 0)process.stdout.write(yV4(W))},J=(W)=>{if(!Q)return;let C=Date.now();if(C-E<SZ6)return;if(E=C,HK())return;if(qI4())D(),setTimeout(wI4,Ry0);else nj4(W)},U=()=>{J("idle"),V(kZ6)},Y=()=>{J("requires-user-input"),V(fZ6)},Z=(W)=>W?.attempt===void 0||W.attempt===0,F=null,X=null,I=null,G,V=(W)=>{if(!Q||!$)return;if(HK()&&!dy0()&&!ec())return;D(),setTimeout(()=>{process.stdout.write(xV4(W))},Ry0)},K=()=>{F?.unsubscribe(),X?.unsubscribe(),F=null,X=null,I=null,G=void 0};return{attach:(W,C,H)=>{if(K(),G=H,C)X=C.subscribe({next:(N)=>{if(N===null)return;if(!Z(N))return;U()},error:(N)=>{S.debug("Neo notification active error stream errored",{error:N})}});F=W.subscribe({next:(N)=>{try{let q=I!==null&&y3(I),u=I==="awaiting_approval",L=q||u;if(N==="awaiting_approval"&&!u)Y();else if(N==="idle"&&L)U()}catch(q){S.debug("Neo notification handling failed",{error:q})}finally{I=N}},error:(N)=>{S.debug("Neo notification agent state stream errored",{error:N})}})},detach:K,unsubscribe(){K(),B.unsubscribe()}}}function xZ6({initialUserInput:A,showWelcome:Q,hideWelcome:$,welcomeVariant:B,welcomeDismissed:E}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let D=!A&&!E;return{show:D,markDismissedOnDismiss:D}}async function yZ6(A){await iD((Q)=>_P(Q,A,"interactive"))}async function aj4(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:D=!1,observerOnly:J=!1,initialAgentMode:U,initialPluginAgentModeKey:Y,initialReasoningEffort:Z,onFirstFrame:F,showWelcome:X=!1,hideWelcome:I=!1,welcomeVariant:G="intro"}=Q,V=G==="npm-migration";if($.length>1)S.info("Resuming multiple initial threads",{threadIDs:$});let K=async(d)=>{let x=await A.getThreadFromServer(d);if(!x)return null;return C30(x)},z=async(d)=>{let x=await A.getThreadFromServer(d);if(!x)throw Error(`Thread ${d} not found`);let T=await $B(d,A.configService,A.apiKey,{usesThreadActors:!0}),k=A7({endpoint:A.rivetEndpoint,poolName:T.poolName}),c={wsToken:T.wsToken,transport:"json-rpc"},b=await k.threadActor.get([T.threadId],{params:c}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:H30(x)}),skipReadyWait:!0});if(!b.ok&&b.status!==409)throw Error(`Thread import failed (${b.status}): ${await b.text()}`);try{await R30(d,A.configService,A.apiKey,{executorType:"local-client"})}catch(p){S.warn("failed to mark thread as imported on server",{threadID:d,error:p instanceof Error?p.message:String(p)})}},W=new Cy0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:EK.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(d)=>A.pluginService.event.toolCall(d),requestPluginToolResult:(d)=>A.pluginService.event.toolResult(d),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,canUseV2LocalThreadChanges:A.canUseV2LocalThreadChanges,invokeTool:async(d,x)=>{let T=typeof x.args==="object"&&x.args!==null?x.args:{},k=await IK({toolName:x.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:x.toolCallId,threadId:d});return A.toolService.invokeTool(x.toolName,{args:T},k)},persistLastThreadID:yZ6,readFileSystemDirectory:A.readFileSystemDirectory},K,z),C=await nN(),H=xZ6({initialUserInput:B,showWelcome:X,hideWelcome:I,welcomeVariant:G,welcomeDismissed:C.neoWelcomeDismissed}),N={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(d)=>{let x=await A.getThreadFromServer(d);return x?m10(x):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,loadThreadTail:A.getThreadTail,logFilePath:Oc,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:V?!1:J,invadersHighScore:C.neoInvadersHighScore,sessionAgentMode:U??C.agentMode,threadListSidebarVisible:C.threadListSidebarVisible,initialPluginAgentModeKey:Y,explicitReasoningEffort:Z,lastReasoningEffortByMode:C.lastReasoningEffortByMode,lastSpeedByMode:C.lastSpeedByMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},q=(d,x)=>{return HV4({ampURL:A.ampURL,configService:A.configService,threadID:d,signal:x})},u=()=>qV4({apiKey:A.apiKey,configService:A.configService,rivetEndpoint:A.rivetEndpoint}),L=new vc0,R=oj4({configService:A.configService}),_=await A.configService.getLatest();X1.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:_.settings["terminal.animation"]===!1}});let v=new Set,f=new xg0;try{await py0(new Pc0({clientPool:W,listSkillsForThread:q,completionBuilder:A.completionBuilder,history:new sx0,ideManager:L,configService:A.configService,updateService:A.updateService,initialThreadIDs:V?[]:$,notificationService:R,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:V?void 0:B,getDefaultNewThreadVisibility:E,observeThreadSummaries:u,openThreadPickerOnStart:V?!1:D,workspaceSettingsFilePath:A.workspaceSettingsFilePath,context:N,showWelcome:H.show,welcomeVariant:G,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:f.request,onWelcomeDismissed:H.markDismissedOnDismiss?()=>{iD(OV4).catch((x)=>{S.warn("Failed to mark Neo welcome as dismissed",{error:x})})}:void 0,onThreadArchived:(x)=>{v.add(x)},onFirstFrame:F}));let d=W.lastActiveObservingClient;if(d&&f.shouldShowExitSummary){let{client:x,observer:T}=d,k=x.getThreadId();if(k){let c={id:k,title:T.title().getValue(),agentMode:T.agentMode,archived:v.has(k)},m=`${A.ampURL.replace(/\/$/,"")}/threads/${k}`;ij4(c,m,process.stdout)}}}finally{process.stdout.write(X50("")),R.unsubscribe(),W.dispose(),await A.dispose?.()}process.exit(f.relaunchIfRequested(A.workspaceRoot)??0)}import{execFile as bZ6}from"node:child_process";import{closeSync as rj4,openSync as hZ6,writeSync as gZ6}from"node:fs";import mZ6 from"node:tty";var dZ6="\x1B[c",cZ6="\x1B[?1004h",pZ6="\x1B[?1004l",lZ6="\x1B[?u",sj4=200,iZ6="\x1B[>4;2m",nZ6="\x1B[?9001h",oZ6="\x1B[?9001l";function tj4(){let A=null;try{if(process.stdout.isTTY){let Q=process.stdout.getWindowSize();A=[Q[0],Q[1]]}}catch{}return{isTTY:process.stdout.isTTY,columns:process.stdout.columns??null,rows:process.stdout.rows??null,windowSize:A,hasRefreshSize:typeof process.stdout._refreshSize==="function"}}function aZ6(){if(process.stdout.isTTY)return{stream:process.stdout,target:"stdout",dispose:()=>{}};if(process.stderr.isTTY)return{stream:process.stderr,target:"stderr",dispose:()=>{}};if(process.platform!=="win32")try{let A=hZ6("/dev/tty","w");if(mZ6.isatty(A))return{stream:{write(Q){return gZ6(A,Q),!0}},target:"dev-tty",dispose:()=>{rj4(A)}};rj4(A)}catch{}return{stream:process.stdout,target:"stdout",dispose:()=>{}}}function w$(A,Q){if(!process.stdout.writable||process.stdout.destroyed){Q?.();return}let $=`${JSON.stringify(A)}
@@ -4998,7 +4998,7 @@ Start Amp from a smaller directory.`};function mX(A,Q){if(!FI4())return;S.debug(
4998
4998
  `)}function tP4(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let E=B.optsWithGlobals(),D=await Q(E),J=await LP(D),U=await M4.userDisplayBalanceInfo({},{config:J});if(!U.ok){if(U.error.code==="auth-required")process.stderr.write(k0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(k0.red("Error: ")+U.error.message+`
4999
4999
  `),process.exit(1)}process.stdout.write(await VV6(U.result.displayText)+`
5000
5000
  `),process.exit(0)})}var bC6=ui.join(gU,"logs","headless.log"),Pl0=ui.join(_y,"device-id.json");SF4();async function hC6(){let A=await Promise.all(SC.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return S.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function OS4(){hC6().then((A)=>{if(A){let Q=X00(A.ideName);if(Q)jC(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => v4(tv(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){I7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
5001
- `)}function gC6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function W3(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Sy("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli"&&ev(Q.mode))Sy("experimental.agentMode",Q.mode)}function mC6(A,Q){if(!b9(Q))return;if(!WG(Q.user.email)){if(A.model)throw new VA("The --model flag is only available for Amp employees.",1);Sy("internal.model",void 0);return}if(A.model)Sy("internal.model",pC6(A.model))}function HS4(A){let Q=A.indexOf(":");if(Q===-1)throw new VA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new VA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function dC6(A){if(A===void 0)return;let Q=A.trim();if(Ty(Q))return Q;throw new VA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function cC6(A,Q){if(vC(A))return;throw new VA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function pC6(A){if(!A.includes("="))return HS4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new VA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new VA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new VA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);HS4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new VA("No valid model overrides found in --model flag value.",1);return Q}function PE0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new B30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new B30(`${Q} must be an integer <= ${$.max}`);return B}function lC6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function iC6(A,Q){let $=await M4.getUserInfo({},{config:A});return $.ok?lC6($.result.features,Q):!1}function nC6(A){return A!=="pending"}function tq(A){if(!b9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function oC6(A){let Q=tq(A);if(Q)return Q.id;if(RC(A))throw Error(A.error.message);throw Error("unreachable")}function aC6(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function rC6(A){let B=aC6(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new VA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function _l0(A,Q){let $=Yx0(Error(A.error.message));if($.message===I3.networkOffline||$.message===I3.networkTimeout)return rC6(Q);if($.message!==I3.internalBug)return new VA($.message,1,$.suggestion);return new VA(A.error.message.replace(/^Error: /,""),1)}async function sC6(){if(process.versions.bun)return!1;try{return await dY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var NS4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??pJ,description:`Custom settings file path (overrides the default location ${pJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Oc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:e8(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"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:"mode",long:"mode",short:"m",type:"option",default:h9.SMART.key,description:`Set the agent mode (${RG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],qS4=(A)=>("deprecated"in A)&&A.deprecated===!0,tC6=(A)=>("hidden"in A)&&A.hidden===!0,eC6=(A)=>("default"in A),AH6=(A)=>("default"in A)?A.default:void 0;function wS4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=dC6(Q.effort);if($!==void 0){if(ev(Q.mode))cC6(Q.mode,$)}return $}var QH6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function ev(A){return Object.values(h9).some((Q)=>Q.key===A)}function $H6(A,Q){if(ev(A))return A;throw new VA(`${Q} does not support plugin-defined agent modes`,1)}function LS4(A,Q){if(ev(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=RG({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new VA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:h9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function BH6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,LS4(Q,$)}function EH6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new VA(I3.unknownCommand($),1,J)}}var vE0=p0.file(yC6.homedir()),vl0=process.env.XDG_CONFIG_HOME?p0.file(process.env.XDG_CONFIG_HOME):EA.joinPath(vE0,".config");async function jB(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;byA("0.0.1780580310-g6c808e");let D=E00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:vE0,userConfigDir:vl0}),J=A.secrets.get("apiKey",A.ampURL),U=yO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),l4(U.pipe($5(nC6)))});X.catch(()=>{return}),SP4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{TQ.write(`No API key found. Starting login flow...
5001
+ `)}function gC6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function W3(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Sy("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli"&&ev(Q.mode))Sy("experimental.agentMode",Q.mode)}function mC6(A,Q){if(!b9(Q))return;if(!WG(Q.user.email)){if(A.model)throw new VA("The --model flag is only available for Amp employees.",1);Sy("internal.model",void 0);return}if(A.model)Sy("internal.model",pC6(A.model))}function HS4(A){let Q=A.indexOf(":");if(Q===-1)throw new VA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new VA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function dC6(A){if(A===void 0)return;let Q=A.trim();if(Ty(Q))return Q;throw new VA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function cC6(A,Q){if(vC(A))return;throw new VA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function pC6(A){if(!A.includes("="))return HS4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new VA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new VA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new VA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);HS4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new VA("No valid model overrides found in --model flag value.",1);return Q}function PE0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new B30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new B30(`${Q} must be an integer <= ${$.max}`);return B}function lC6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function iC6(A,Q){let $=await M4.getUserInfo({},{config:A});return $.ok?lC6($.result.features,Q):!1}function nC6(A){return A!=="pending"}function tq(A){if(!b9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function oC6(A){let Q=tq(A);if(Q)return Q.id;if(RC(A))throw Error(A.error.message);throw Error("unreachable")}function aC6(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function rC6(A){let B=aC6(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new VA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function _l0(A,Q){let $=Yx0(Error(A.error.message));if($.message===I3.networkOffline||$.message===I3.networkTimeout)return rC6(Q);if($.message!==I3.internalBug)return new VA($.message,1,$.suggestion);return new VA(A.error.message.replace(/^Error: /,""),1)}async function sC6(){if(process.versions.bun)return!1;try{return await dY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var NS4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??pJ,description:`Custom settings file path (overrides the default location ${pJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Oc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:e8(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"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:"mode",long:"mode",short:"m",type:"option",default:h9.SMART.key,description:`Set the agent mode (${RG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],qS4=(A)=>("deprecated"in A)&&A.deprecated===!0,tC6=(A)=>("hidden"in A)&&A.hidden===!0,eC6=(A)=>("default"in A),AH6=(A)=>("default"in A)?A.default:void 0;function wS4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=dC6(Q.effort);if($!==void 0){if(ev(Q.mode))cC6(Q.mode,$)}return $}var QH6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function ev(A){return Object.values(h9).some((Q)=>Q.key===A)}function $H6(A,Q){if(ev(A))return A;throw new VA(`${Q} does not support plugin-defined agent modes`,1)}function LS4(A,Q){if(ev(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=RG({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new VA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:h9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function BH6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,LS4(Q,$)}function EH6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new VA(I3.unknownCommand($),1,J)}}var vE0=p0.file(yC6.homedir()),vl0=process.env.XDG_CONFIG_HOME?p0.file(process.env.XDG_CONFIG_HOME):EA.joinPath(vE0,".config");async function jB(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;byA("0.0.1780592276-g890982");let D=E00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:vE0,userConfigDir:vl0}),J=A.secrets.get("apiKey",A.ampURL),U=yO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),l4(U.pipe($5(nC6)))});X.catch(()=>{return}),SP4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{TQ.write(`No API key found. Starting login flow...
5002
5002
  `);let C0=await DH6(A),l=await A.secrets.get("apiKey",A.ampURL);if(S.info("Login flow completed",{success:C0,storedKeyPresent:Boolean(l),ampURL:A.ampURL}),!C0)await gY(),process.exit(1);G=!0,Z()}}{let B0=await D.getLatest(),C0=B0.settings.url,l=B0.secrets.isSet?.[C0];S.info("Config secrets state after login",{configURL:C0,apiKeySet:l?.apiKey??!1})}let V=B?"pending":await X;if(!B)S.info("Server status resolved",{status:"ready",isAuthenticated:b9(V),isError:RC(V),errorMessage:RC(V)?V.error.message:void 0});mC6(Q,V);let K=X.then((B0)=>oC6(B0));K.catch(()=>{return});let z=b9(V),W=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")S.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let C=W?"off":"all",{toolService:H,dispose:N}=JD4({configService:D}),q=new Map,u=()=>q.clear(),L=new FM0(D,A.settings.getWorkspaceRootPath()),R=rsA({configService:D}),_=inA({configService:D,trustStore:L,skillMCPServers:R.skillMCPServers,uploadImageAttachments:z,createOAuthProvider:async(B0,C0,l)=>{let i=`${B0}:${C0}`,A0=q.get(i);if(A0)return S.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:C0}),A0;S.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:C0});let s=(async()=>{let $0=new gC(A.secrets),e=await $0.getClientInfo(B0,C0),G0=l?.scopes??e?.scopes,V0=jI4();S.info("OAuth headless mode check",{useHeadless:V0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:TQ.isTTY});let u0;if(V0)u0=A.executeMode?LI4():OI4(B0);let F0=new $q0({storage:$0,serverName:B0,serverUrl:C0,clientId:l?.clientId??e?.clientId,clientSecret:l?.clientSecret??e?.clientSecret,authUrl:l?.authUrl??e?.authUrl,tokenUrl:l?.tokenUrl??e?.tokenUrl,scopes:G0,headlessAuthHandler:u0});return S.debug("OAuth provider created",{serverName:B0,serverUrl:C0,hasManualClientId:!!(l?.clientId??e?.clientId),willUseDCR:!(l?.clientId??e?.clientId),scopes:G0,headlessMode:V0,executeMode:A.executeMode}),F0})();return q.set(i,s),s}}),v=YL0({configService:D,spawn:p10}),f=Q.headless?aR4():void 0,d=f??new y90({configService:D}),x=d instanceof y90?d:void 0;if(x)x.pluginExecutorKind="local";let T=new W4(null),k=null,c=z&&!W?[...tR4(I.settings)?[{name:"permissions",entryPoint:ic0}]:[],{name:"thread-visibility",entryPoint:QP4(D,()=>X.then(tq),()=>k,(B0)=>{k=B0}),alwaysLoad:!0}]:[],m=uM0({configService:D,platform:d,loadGlobalPlugins:wx0(D),pluginFilter:C,activeThread$:T,internalPlugins:c}),b=loA(m),p=[_,v,b],n;if(E)n=new Map;else if(A.executeMode){let B0=await weA({toolService:H,providers:p,initialTimeout:15000});n=B0.registrations;for(let[C0,l]of B0.initErrors)S.warn(`${C0} provider initialization slow or failed:`,l)}else n=ZL0({toolService:H,providers:p});if(Q.jetbrains)jC("JetBrains");else if(Q.ide&&SI4())jC("VS Code");else if(Q.ide&&kI4())jC("Neovim");else if(Q.ide&&A.executeMode)OS4();if(A.executeMode)hyA(!0);let a,X0=P3.status.pipe(sA((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&cbA(B0.ideName))),UQ()).subscribe((B0)=>{if(B0){if(!a)a=H.registerTool(qeA)}else a?.dispose(),a=void 0}),E0;if(!A.executeMode){let B0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];E0=new v30(process.cwd(),{alwaysIncludePaths:B0},!0)}else E0=new class extends v30{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let I0=dh(D);S.info("Starting Amp background services");let W0=new ec0,v0={configService:D,toolService:H,mcpService:_,skillService:R,toolboxService:v,trustStore:L,threadRemote:I0,setThreadMeta:I0.setThreadMeta,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:E0,terminal:W0,pluginService:m,pluginPlatform:x,headlessPluginPlatform:f,activeThread$:T,serverStatus:V,serverStatusPromise:X,viewerUserIDPromise:K,hasAPIKeyAtStartup:G,consumeDraftNewThreadVisibility:()=>{let B0=k;return k=null,B0}};return{...v0,async asyncDispose(){if(v0.mcpService.hasAuthenticatingClients())S.info("Waiting for OAuth authentication to complete before exit..."),await v0.mcpService.waitForAuthentication();for(let B0 of n.values())B0.dispose();await v0.mcpService.dispose(),u(),v0.configService.unsubscribe(),Y?.unsubscribe(),N(),v0.fuzzyServer.dispose(),v0.settingsStorage[Symbol.dispose](),X0.unsubscribe(),a?.dispose(),await v0.pluginService.dispose()}}}async function DH6(A){if(!A.executeMode){if(!await k90("Would you like to log in to Amp? [(y)es, (n)o]: "))return TQ.write(`Login cancelled. Run the command again to retry.
5003
5003
  `),!1}return await jS4(A)}async function jS4(A){let Q=SC6(32).toString("hex"),$=await gc0(A.ampURL,Q),B=new AbortController;try{await gJ($,B.signal)}catch(D){S.error("Error opening browser",{error:D})}let E=await gc0(A.ampURL,Q,!1);TQ.write(`If your browser does not open automatically, visit:
5004
5004
 
@@ -5006,7 +5006,7 @@ ${k0.blue.bold(E)}
5006
5006
 
5007
5007
  `);try{return await TR4(A.ampURL,Q,A.secrets,B),TQ.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(D){return S.error("Login failed",{error:D}),I7.write(`
5008
5008
  Login failed: ${D instanceof Error?D.message:String(D)}
5009
- `),!1}}async function JH6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new VA("No Amp API key found. Run `amp login` first.",1);let E=_C6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function UH6(A){let Q=new GX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((C)=>{if(C.code==="commander.help"||C.code==="commander.version"||C.exitCode===0)kN(),process.exit(0);let H=C.originalError??C;eF4(H)}),xK4(Q,{version:"0.0.1780580310-g6c808e",buildTimestamp:"2026-06-04T13:43:38.391Z",buildType:"release"}),Q.addHelpText("after",sI4()),Q.configureHelp({formatHelp:tI4}),Q.command("logout").description("Log out by removing stored API key").action(async(C,H)=>{let N=H.optsWithGlobals(),q=await nQ(N);await CH6(q)}),Q.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(C,H)=>{let N=H.optsWithGlobals(),q=await nQ(N);await WH6(q,await oc0(N,q.settings))}),VP4(Q,nQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...C)=>{let H=C.find((L)=>typeof L==="object"&&L!==null&&typeof L.optsWithGlobals==="function")??B,N=C.filter((L)=>L!==H).flatMap((L)=>Array.isArray(L)?L:typeof L==="string"?[L]:[]),q=H.optsWithGlobals(),u=await nQ(q);await JH6(u.ampURL,u.secrets,N),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(C,H,N)=>{let q=N.optsWithGlobals(),u=await nQ(q);await GI4(C??"get",u.ampURL,u.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(C,H,N)=>{let q=N.optsWithGlobals(),u=await nQ(q);await KI4(u,C),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(C)=>{await QR4({raw:C.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
5009
+ `),!1}}async function JH6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new VA("No Amp API key found. Run `amp login` first.",1);let E=_C6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function UH6(A){let Q=new GX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((C)=>{if(C.code==="commander.help"||C.code==="commander.version"||C.exitCode===0)kN(),process.exit(0);let H=C.originalError??C;eF4(H)}),xK4(Q,{version:"0.0.1780592276-g890982",buildTimestamp:"2026-06-04T17:02:44.679Z",buildType:"release"}),Q.addHelpText("after",sI4()),Q.configureHelp({formatHelp:tI4}),Q.command("logout").description("Log out by removing stored API key").action(async(C,H)=>{let N=H.optsWithGlobals(),q=await nQ(N);await CH6(q)}),Q.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(C,H)=>{let N=H.optsWithGlobals(),q=await nQ(N);await WH6(q,await oc0(N,q.settings))}),VP4(Q,nQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...C)=>{let H=C.find((L)=>typeof L==="object"&&L!==null&&typeof L.optsWithGlobals==="function")??B,N=C.filter((L)=>L!==H).flatMap((L)=>Array.isArray(L)?L:typeof L==="string"?[L]:[]),q=H.optsWithGlobals(),u=await nQ(q);await JH6(u.ampURL,u.secrets,N),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(C,H,N)=>{let q=N.optsWithGlobals(),u=await nQ(q);await GI4(C??"get",u.ampURL,u.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(C,H,N)=>{let q=N.optsWithGlobals(),u=await nQ(q);await KI4(u,C),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(C)=>{await QR4({raw:C.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
5010
5010
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(C,H,N)=>{if(C&&H.apply)throw new VA("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let q=H.apply??C;if(!q||q.trim().length===0)TQ.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
5011
5011
 
5012
5012
  `),N.outputHelp(),process.exit(0);let u=eB(q)??m7(q),L=N.optsWithGlobals(),R=await nQ(L);W3(N,L);let _=await jB(R,L),v=!1;try{if(H.checkout&&H.skipCheckout)throw new VA("Choose either --checkout or --skip-checkout, not both.",1);if(RC(_.serverStatus))throw _l0(_.serverStatus,R.ampURL);await HR4({ampURL:R.ampURL,threadId:u,configService:_.configService,threadSnapshotReader:{get:_.threadRemote.getThread},apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:k90}),v=!0}finally{if(await _.asyncDispose(),v)process.exit(0)}});let E=async(C,H,N)=>{E00({storage:H.settings,secretStorage:H.secrets,workspaceRoot:process.cwd(),defaultAmpURL:H.ampURL,homeDir:vE0,userConfigDir:vl0});let q={...H,executeMode:!1};await Tl0(q,{...C,openThreadSwitcher:!0},N)},D=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").option("--limit <number>","Maximum number of threads to return",(C)=>PE0(C,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(C)=>PE0(C,"--offset",{min:0})).action(async(C,H)=>{let N=H.optsWithGlobals(),q=await nQ(N);await MS4(N,q,H)});D.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, unlisted, workspace, group)").action(async(C,H)=>{let N=H.optsWithGlobals(),q=await nQ(N);await TH6(N,q,H)}),D.command("continue [threadIDOrURLs...]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly. When multiple thread are given, all are resumed and the first is shown in the foreground.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(C,H,N)=>{let q=N.optsWithGlobals(),u=await nQ(q),L=Array.isArray(C)?C:[];if(H.pick)I7.write(`${k0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -5031,8 +5031,8 @@ ${R}
5031
5031
 
5032
5032
  `)},async input(){return},async confirm(){return!1},async select(){return},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},loadGlobalPlugins:wx0(q),pluginFilter:process.env.PLUGINS??"all"}),asyncDispose:async()=>{}}}),qP4(Q,async(C)=>{let H=C.optsWithGlobals(),N=await nQ(H);W3(C,H);let q=await jB(N,H),u=await q.secretStorage.get("apiKey",N.ampURL);if(!u)throw await q.asyncDispose(),new VA("API key required. Please run `amp login` first.",1);return{configService:q.configService,actorOptions:{apiKey:u,ampURL:N.ampURL,workspaceRoot:process.cwd(),dependencies:q},cleanupTerminal:kN,asyncDispose:q.asyncDispose.bind(q)}}),vP4(Q,async(C)=>{let H=C.optsWithGlobals(),N=await nQ(H);W3(C,H);let q=await jB(N,H);return{settings:N.settings,configService:q.configService,skillService:q.skillService,asyncDispose:q.asyncDispose.bind(q)}}),lR4(Q,async(C)=>{let H=C.optsWithGlobals();return await nQ(H)}),yR4(Q,async(C)=>{let H=await nQ(C);return{settings:H.settings,secretStorage:H.secrets,getThreadDeps:async(N)=>{W3(N,C);let q=await jB(H,C);return{mcpService:q.mcpService,settings:H.settings,asyncDispose:q.asyncDispose.bind(q)}}}}),vF4(Q,nQ),lF4(Q,nQ),tP4(Q,nQ),TP4(Q,nQ);function Z(C,H,N){let u=typeof C.description==="string"?C.description:N===void 0?C.description(!0):C.description(N),L=new L2(H,u),R=AH6(C);if(R)L.default(R);if(L.hidden=tC6(C)||qS4(C),"choices"in C&&Array.isArray(C.choices))if("hiddenChoices"in C){let _=[...C.choices],v=Array.isArray(C.hiddenChoices)?C.hiddenChoices:[],f=new Set([..._,...v]);L.argParser((d)=>{if(!f.has(d))throw new B30(`Allowed choices are ${_.join(", ")}.`);return d})}else L.choices([...C.choices]);return L}for(let C of NS4){switch(C.type){case"flag":{Q.addOption(Z(C,`--${C.long}`)),Q.addOption(Z(C,`--no-${C.long}`,!1));break}case"switch":{Q.addOption(Z(C,`--${C.long}`,!0));break}case"optional-option":{Q.addOption(Z(C,`${"short"in C?`-${C.short}, `:""}--${C.long} [value]`));break}default:{Q.addOption(Z(C,`${"short"in C?`-${C.short}, `:""}--${C.long} <value>`));break}}if("aliases"in C&&Array.isArray(C.aliases))for(let H of C.aliases){let N=new L2(`--${H}`,C.description);N.hidden=!0,N.implies({[C.name]:!0}),Q.addOption(N)}}Q.hook("preAction",(C,H)=>{if(H.optsWithGlobals().takeMeBack)U6(QH6)});let F=new L2("-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);Q.addOption(F);let X=new L2("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);Q.addOption(X);let I=new L2("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);Q.addOption(I);let G=new L2("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);Q.addOption(G);let V=new L2("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);Q.addOption(V);let K=new L2("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);Q.addOption(K);let z=new L2("--archive","When used with --execute, archive the thread after the command finishes.").default(!1);Q.addOption(z);let W=new L2("-l, --label <label>","When used with --execute, add a label to the thread. Repeat the flag for multiple labels.").argParser((C,H)=>{if(H===void 0)return[C];return[...H,C]});return Q.addOption(W),Q.action(async(C,H)=>{let N=C,q=await nQ(N);if(Object.keys(N).forEach((u)=>{let L=NS4.find((R)=>R.name===u);if(L&&qS4(L)&&!eC6(L))I7.write(k0.yellow(`Warning: '--${u}' flag is deprecated
5033
5033
  `))}),H.args.length>0)EH6(q,H);await Tl0(q,N,H)}),LG4(Q),Q}async function RS4(A,Q){await iD(($)=>_P($,A,Q))}async function YH6(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await ac0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await ac0()).trimEnd(),stdinInput:null}}function ZH6(A,Q,$){if(A.remote&&!Q)throw new VA("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(A.streamJson&&!Q)throw new VA("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new VA("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new VA("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new VA("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new VA("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new VA("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new VA("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"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&$===""&&!A.streamJsonInput&&!A.headless)throw new VA("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"
5034
- Or pipe via stdin: echo "your message" | amp --execute`)}function FH6(){KmA([$00.parse({tool:"*",action:"allow"})]),dgA({bypass:!0})}function XH6(A){if(A.threadId&&!O7(A.threadId))delete A.threadId}async function Tl0(A,Q,$){if(Q.headless)return IH6(A,Q,$);let B=await jB(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new VA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await sC6();return FH6(),XH6(Q),GH6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function IH6(A,Q,$){let B=(W,C)=>{let H=Number(process.hrtime.bigint()-C)/1e6,N=_F4();S.info("Startup phase",{phase:W,phaseMs:Math.round(H),sinceMainMs:N===null?void 0:Math.round(N)})};W3($,Q);let E=process.hrtime.bigint(),D=await jB(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(RC(J))throw _l0(J,A.ampURL);let U=b9(J)?J:null,Y=U?.user.email,Z=tq(J),F=sl(Q,Z);if(F instanceof Error)U6(F.message);if(U&&ev(Q.mode)&&!oe(Q.mode,Y))throw new VA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!WG(Y)))throw new VA("Headless executor mode is only available for Amp employees",1);Dx0();let I=await D.secretStorage.get("apiKey",A.ampURL);if(!I)throw new VA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!O7(G))throw new VA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await PH6({dependencies:D,apiKey:I,visibility:F??void 0}),K=G??V?.threadId;if(!K)throw new VA("Failed to resolve headless thread ID",1);let z=await TI4(K);if(z.status==="already-running")await D.asyncDispose(),await gY(),process.exit(0);try{await HI4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:K,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(W)=>D.activeThread$.next(W)})}finally{await z.release(),await D.asyncDispose()}await gY(),process.exit(0)}async function GH6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await YH6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;ZH6({...Q,streamJson:U},A.executeMode,D),W3($,Q),hF4(),Dx0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?eB(Q.observe)??m7(Q.observe):void 0,X=await B.serverStatusPromise;if(RC(X))throw _l0(X,A.ampURL);let I=tq(X),G=()=>iC6(B.configService,bSA.V2_LOCAL_THREAD_CHANGES),V=sl(Q,I);if(V instanceof Error)U6(V.message);if(A.executeMode&&Q.remote){if(!ev(Q.mode))throw new VA("Remote execute mode does not support plugin-defined agent modes",1);if(!b9(X)||!WG(X.user.email))throw new VA("Remote execute mode is only available for Amp employees",1);await UP4(D,J,B.configService,Q.mode),await B.asyncDispose(),await gY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await V30(A.settings,process.cwd(),I,V);if(N instanceof Error)U6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new VA("API key required. Please run `amp login` first.",1);let C=b9(X)&&WG(X.user.email);if(A.executeMode){if(Z.length>1)throw new VA("Execute mode can only resume one thread.",1);mR4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=LS4(B.pluginService,Q.mode),N=wS4($,Q),q=await nN(),u=Y?N:ex0({agentMode:H.agentMode,explicitEffort:N,sessionState:q}),L=Y?void 0:a30(await PP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:q}),R=Y?void 0:await z(),{threadID:_}=await P30({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await RS4(_,"execute"),Q.archive)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await gY(),process.exit(0)}else{let H=wS4($,Q),N=await BH6($,B.pluginService,Q.mode),q=E.showNpmMigrationWelcome?"npm-migration":"intro",u=ox0("0.0.1780580310-g6c808e",B.settingsStorage,{startDelayMs:3000}),L=new mc0(B.mcpService,A.settings.getWorkspaceRootPath()),R=dh(B.configService),_=new $p0(B.fuzzyServer),v=process.cwd();await aj4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??t8(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>qP({workspaceRoot:v},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:v,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,d)=>{let x=await M4.getThreadTail({thread:f,limit:d},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?OS4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:q,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function nQ(A){if(S.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)I7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5035
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await snA({get:async(U)=>{if(U!==eb)return;try{let Y=await fC6(Pl0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==eb)return;await kC6(ui.dirname(Pl0),{recursive:!0}),await xC6(Pl0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:C40()});gyA(B);let E=await RP4({...A,workspaceTrust:{current:!0,changes:px},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await hR4(A.mcpConfig);E=gR4(E,U)}let D=ui.dirname(E.getSettingsFilePath());FD4(_y,D),E=TSA(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=j8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!PO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:wP4(await oc0(A,E))}}function VH6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function KH6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=ui.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?bC6:Oc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function zH6(){TF4();let A=VH6(process.argv),Q=KH6(process.argv,A),$=gF4(Q);GB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)k0.level=0;if(gC6(S),S.info("Starting Amp CLI.",{version:"0.0.1780580310-g6c808e",buildTimestamp:"2026-06-04T13:43:38.391Z"}),process.platform==="win32"&&lN())qG4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new VA(I3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await UH6($).parseAsync(process.argv)}YD4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await zH6().catch(K30)});async function WH6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),TQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5034
+ Or pipe via stdin: echo "your message" | amp --execute`)}function FH6(){KmA([$00.parse({tool:"*",action:"allow"})]),dgA({bypass:!0})}function XH6(A){if(A.threadId&&!O7(A.threadId))delete A.threadId}async function Tl0(A,Q,$){if(Q.headless)return IH6(A,Q,$);let B=await jB(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new VA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await sC6();return FH6(),XH6(Q),GH6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function IH6(A,Q,$){let B=(W,C)=>{let H=Number(process.hrtime.bigint()-C)/1e6,N=_F4();S.info("Startup phase",{phase:W,phaseMs:Math.round(H),sinceMainMs:N===null?void 0:Math.round(N)})};W3($,Q);let E=process.hrtime.bigint(),D=await jB(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(RC(J))throw _l0(J,A.ampURL);let U=b9(J)?J:null,Y=U?.user.email,Z=tq(J),F=sl(Q,Z);if(F instanceof Error)U6(F.message);if(U&&ev(Q.mode)&&!oe(Q.mode,Y))throw new VA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!WG(Y)))throw new VA("Headless executor mode is only available for Amp employees",1);Dx0();let I=await D.secretStorage.get("apiKey",A.ampURL);if(!I)throw new VA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!O7(G))throw new VA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await PH6({dependencies:D,apiKey:I,visibility:F??void 0}),K=G??V?.threadId;if(!K)throw new VA("Failed to resolve headless thread ID",1);let z=await TI4(K);if(z.status==="already-running")await D.asyncDispose(),await gY(),process.exit(0);try{await HI4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:K,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(W)=>D.activeThread$.next(W)})}finally{await z.release(),await D.asyncDispose()}await gY(),process.exit(0)}async function GH6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await YH6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;ZH6({...Q,streamJson:U},A.executeMode,D),W3($,Q),hF4(),Dx0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?eB(Q.observe)??m7(Q.observe):void 0,X=await B.serverStatusPromise;if(RC(X))throw _l0(X,A.ampURL);let I=tq(X),G=()=>iC6(B.configService,bSA.V2_LOCAL_THREAD_CHANGES),V=sl(Q,I);if(V instanceof Error)U6(V.message);if(A.executeMode&&Q.remote){if(!ev(Q.mode))throw new VA("Remote execute mode does not support plugin-defined agent modes",1);if(!b9(X)||!WG(X.user.email))throw new VA("Remote execute mode is only available for Amp employees",1);await UP4(D,J,B.configService,Q.mode),await B.asyncDispose(),await gY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await V30(A.settings,process.cwd(),I,V);if(N instanceof Error)U6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new VA("API key required. Please run `amp login` first.",1);let C=b9(X)&&WG(X.user.email);if(A.executeMode){if(Z.length>1)throw new VA("Execute mode can only resume one thread.",1);mR4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=LS4(B.pluginService,Q.mode),N=wS4($,Q),q=await nN(),u=Y?N:ex0({agentMode:H.agentMode,explicitEffort:N,sessionState:q}),L=Y?void 0:a30(await PP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:q}),R=Y?void 0:await z(),{threadID:_}=await P30({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await RS4(_,"execute"),Q.archive)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await gY(),process.exit(0)}else{let H=wS4($,Q),N=await BH6($,B.pluginService,Q.mode),q=E.showNpmMigrationWelcome?"npm-migration":"intro",u=ox0("0.0.1780592276-g890982",B.settingsStorage,{startDelayMs:3000}),L=new mc0(B.mcpService,A.settings.getWorkspaceRootPath()),R=dh(B.configService),_=new $p0(B.fuzzyServer),v=process.cwd();await aj4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??t8(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>qP({workspaceRoot:v},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:v,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,d)=>{let x=await M4.getThreadTail({thread:f,limit:d},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?OS4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:q,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function nQ(A){if(S.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)I7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5035
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await snA({get:async(U)=>{if(U!==eb)return;try{let Y=await fC6(Pl0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==eb)return;await kC6(ui.dirname(Pl0),{recursive:!0}),await xC6(Pl0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:C40()});gyA(B);let E=await RP4({...A,workspaceTrust:{current:!0,changes:px},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await hR4(A.mcpConfig);E=gR4(E,U)}let D=ui.dirname(E.getSettingsFilePath());FD4(_y,D),E=TSA(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=j8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!PO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:wP4(await oc0(A,E))}}function VH6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function KH6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=ui.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?bC6:Oc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function zH6(){TF4();let A=VH6(process.argv),Q=KH6(process.argv,A),$=gF4(Q);GB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)k0.level=0;if(gC6(S),S.info("Starting Amp CLI.",{version:"0.0.1780592276-g890982",buildTimestamp:"2026-06-04T17:02:44.679Z"}),process.platform==="win32"&&lN())qG4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new VA(I3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await UH6($).parseAsync(process.argv)}YD4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await zH6().catch(K30)});async function WH6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),TQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5036
5036
  `);else if(!PO(A.ampURL))TQ.write(`Logging in to ${new URL(A.ampURL).hostname}
5037
5037
  `);let B=process.env.AMP_API_KEY;if(B)TQ.write(`API key found in environment variable, storing...
5038
5038
  `),await Q.set("apiKey",B,A.ampURL),TQ.write(`API key successfully stored.