@sourcegraph/amp 0.0.1779668338-g19be90 → 0.0.1779686836-g4ef406

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 +16 -16
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -229,7 +229,7 @@ Expected format:
229
229
 
230
230
  `)}function U04(A){return A.content.every((Q)=>{return!(Q.type==="tool_result"&&!S3(Q.run.status))})}function FT(A){return A.role==="assistant"&&A.state.type==="complete"&&A.state.stopReason==="end_turn"}function B9(A,Q){return A.messages.findLast(($)=>$.role===Q)}function iB(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 e3(A){return A.messages.filter((Q)=>Q.role==="user"&&Q.content.some(($)=>$.type!=="tool_result")).length}function J04(A){return A.startsWith("functions.")?A.slice(10):A}function X04(A){if(A.type==="tool_use"&&l5(A)){let Q=A.normalizedName??A.name;if(!Q)return null;let $=A.input;return{name:J04(Q),input:$}}if(A.type==="server_tool_use"){if(!A.name)return null;return{name:J04(A.name),input:A.input}}return null}function G04(A){if(!("patchText"in A)||typeof A.patchText!=="string")return[];let Q;try{Q=DX(A.patchText)}catch(B){return u.debug("thread.diffStats.applyPatch.parseFailed",{error:B,patchTextLength:A.patchText.length}),[]}let $=[];for(let B of Q.hunks){if(B.type==="delete")continue;if(B.type==="add"){$.push({path:B.path,diffStat:EX(B.contents)});continue}let D=jv0(B.chunks.map((J)=>FX(J.oldLines.join(`
231
231
  `),J.newLines.join(`
232
- `))));$.push({path:B.movePath??B.path,diffStat:D})}return $}function p50(A){let Q=0,$=0,B=0;return A.messages.forEach((D)=>{if(D.role!=="assistant")return;D.content.forEach((J)=>{let F=X04(J);if(!F)return;let{name:E,input:Y}=F,Z=null;if(E==="edit_file"){if("old_str"in Y&&"new_str"in Y){let{old_str:U,new_str:X}=Y;Z=FX(U,X)}}else if(E==="apply_patch"){let U=G04(Y);Z=jv0(U.map((X)=>X.diffStat))}else if((E==="write_file"||E==="create_file")&&"content"in Y&&typeof Y.content==="string")Z=EX(Y.content);if(Z)Q+=Z.added,B+=Z.deleted,$+=Z.changed})}),{added:Q,changed:$,deleted:B}}function V04(A){let Q=new Map;return A.messages.forEach(($)=>{if($.role!=="assistant")return;$.content.forEach((B)=>{let D=X04(B);if(!D)return;let{name:J,input:F}=D,E,Y=null;if(J==="edit_file"){if("path"in F&&typeof F.path==="string"&&"old_str"in F&&"new_str"in F){E=F.path;let{old_str:Z,new_str:U}=F;Y=FX(Z,U)}}else if(J==="apply_patch"){for(let Z of G04(F)){let U=F04(Z.path,A.env?.initial?.trees);if(U){let X=Q.get(U)??{added:0,changed:0,deleted:0};X.added+=Z.diffStat.added,X.changed+=Z.diffStat.changed,X.deleted+=Z.diffStat.deleted,Q.set(U,X)}}return}else if((J==="write_file"||J==="create_file")&&"path"in F&&typeof F.path==="string"&&"content"in F&&typeof F.content==="string")E=F.path,Y=EX(F.content);if(E&&Y){let Z=F04(E,A.env?.initial?.trees);if(Z){let U=Q.get(Z)??{added:0,changed:0,deleted:0};U.added+=Y.added,U.changed+=Y.changed,U.deleted+=Y.deleted,Q.set(Z,U)}}})}),Q}function F04(A,Q){let $=A.startsWith("/"),B=/^[a-zA-Z]:[\\/]/.test(A);if(!$&&!B)return A;let D=A.replace(/\\/g,"/");if(Q&&Q.length>0)for(let E of Q){if(!E.uri)continue;let Y=E.uri.match(/^file:\/\/(.+)$/);if(!Y?.[1])continue;let Z=decodeURIComponent(Y[1]).replace(/\\/g,"/"),U=Z.startsWith("/")&&/^\/[a-zA-Z]:/.test(Z)?Z.slice(1):Z;if(D.startsWith(U)){let X=D.slice(U.length);return X.startsWith("/")?X.slice(1):X}}let J=D.match(/\/(?:Users|home)\/[^/]+\/[^/]+\/(.+)/);if(J?.[1])return J[1];let F=D.match(/^[a-zA-Z]:\/Users\/[^/]+\/[^/]+\/(.+)/);if(F?.[1])return F[1];return null}function ET(A,Q){let $=A.relationships?.filter((J)=>J.role==="child")??[],B=uv0(A),D=[...$,...B];return Q?D.filter((J)=>J.type===Q):D}function K04(A,Q){return ET(A,Q)[0]}function nB(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="user")return $}return}function Nd(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="user"&&$.agentMode)return $.agentMode}return}function uv0(A){let Q=[],$=new Set;if(!A.messages)return Q;return A.messages.forEach((B,D)=>{if(B.role!=="assistant")return;B.content.forEach((J)=>{if(J.type!=="tool_use")return;if(J.name!==QK)return;if(!l5(J))return;let F=J.input,E=typeof F.threadID==="string"?v8(F.threadID):null;if(E&&!$.has(E))$.add(E),Q.push({threadID:E,type:"mention",role:"parent",messageIndex:D,createdAt:Date.now()})})}),Q}var dQA,pQA;var a4=r(()=>{Cv0();P$();p0();h4();lI();$T();dQA=x.templateLiteral([x.string().regex(/^[0-9a-f]{8}$/),"-",x.string().regex(/^[0-9a-f]{4}$/),"-",x.string().regex(/^[0-9a-f]{4}$/),"-",x.string().regex(/^[0-9a-f]{4}$/),"-",x.string().regex(/^[0-9a-f]{12}$/)]),pQA=x.templateLiteral(["T-",dQA])});function J9(A){if(!A)return{};return{[Pv0]:A.id}}var D9="x-amp-feature",Pv0="x-amp-thread-id",TQ="x-amp-message-id",z04="X-Amp-Client-Application",W04="X-Amp-Client-Type",I04="X-Amp-Client-Version",H04="X-Amp-Installation-ID",q04="X-Amp-Device-Fingerprint";var aB=()=>{};function w04(A){N04=A}function hM(A){Cd=A}function M04(A){C04=A}function L04(A){wd=A.installationID,Md=A.deviceFingerprint}function O04(){if(!wd||!Md)return;return{installationID:wd,deviceFingerprint:Md}}function i5(){let A=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(A)return{type:"cli",name:"AmpSDK",version:A};let Q;if(!Cd)Q="CLI";else if(["Neovim","JetBrains","Zed"].includes(Cd))Q=Cd;else Q=`${Cd} CLI`;return{type:"cli",name:C04?`${Q} Execute Mode`:Q,version:N04}}function Y7(A){let Q={};if(Q[z04]=A.name,Q[W04]=A.type,wd)Q[H04]=wd;if(Md)Q[q04]=Md;if(A.version)Q[I04]=A.version;return Q}var N04=null,Cd=null,C04=!1,wd=null,Md=null;var vQ=r(()=>{aB()});function lQA(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 y$(A,Q,$){let B=$?`/threads/${Q}/${$}`:`/threads/${Q}`;return new URL(B,A)}async function k8(A,Q,$){let B=await $.getLatest(Q?.signal??void 0),D=await R04(A,Q,B);return fetch(D)}async function j04(A,Q,$){let B=await R04(Q,$,A);return fetch(B)}async function R04(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 D=await $.secrets.getToken("apiKey",B);lQA({proxy:$.settings.proxy});let J=new URL(A,B);return new Request(J,{...Q,duplex:"half",headers:{"Content-Type":"application/json",...Q?.headers,...Y7(i5()),...D?{Authorization:`Bearer ${D}`}:{}}})}async function u04(A,Q,$,B){let D=await e4.shareThreadWithOperator({threadID:A,message:$||void 0,ephemeralError:B||void 0},{config:Q});if(!D.ok)throw Error(`Failed to share thread: ${D.error.message}`)}async function c50(A,Q){let $=await k8("/api/telemetry",{method:"POST",redirect:"manual",body:A},Q);if(!$.ok){let B=await $.text(),D;try{D=JSON.parse(B).error||`HTTP ${$.status}`}catch{D=B||`HTTP ${$.status}`}throw Error(`Failed to submit telemetry: ${D}`)}}var u9=r(()=>{vQ();e2()});function nQA(A){if(new Blob([A]).size<=iQA)return{body:A};return{body:Me1.gzip(A),headers:{"Content-Encoding":"gzip"}}}function aQA(){return new Proxy({},{get:(A,Q)=>{return async(...$)=>{let B=$.at(1),D=$.at(0);if(!B?.config)throw Error("Internal API client requires configService in options. Call with { config: configService }");let{body:J,headers:F={}}=nQA(JSON.stringify({method:Q,params:D})),E=await k8("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:J,headers:F,signal:B?.signal},B.config);if(!E.ok)throw Error(`API request for ${Q} failed: ${E.status}`);return await E.json()}}})}var iQA=25600,e4;var e2=r(()=>{Le1();u9();e4=aQA()});function oQA(A){return A.config.pipe(y4(({settings:Q,secrets:$})=>F6(async()=>({url:Q.url,proxy:Q.proxy,apiKey:await $.getToken("apiKey",Q.url)}))),T4(cF),y4(()=>v_(600000).pipe(WA(void 0),S_(()=>F6(async(Q)=>{let $=await e4.getUserInfo({},{signal:Q,config:A});if($.ok)return $.result;if($.error&&$.error.code==="auth-required")return null;throw u.error("getUserInfo failed",{error:$.error}),Error(`getUserInfo error: ${$.error.code}`)})))),N1((Q)=>{return Q instanceof Error?{error:{message:String(Q)}}:Q===eU?"pending":Q?{user:Q,features:Q.features,workspace:Q?.team,mysteriousMessage:Q?.mysteriousMessage}:{error:{message:"User not found"}}}),T4((Q,$)=>cF(Q,$)),t6({shouldCountRefs:!0}))}function oF(A){let Q=P04.get(A);if(Q)return Q;let $=oQA(A);return P04.set(A,$),$}function e6(A){return Boolean(typeof A==="object"&&"user"in A&&A.user)}function gY(A){return typeof A==="object"&&"error"in A}var P04;var mY=r(()=>{u1();p0();e2();P04=new WeakMap});function C2(A){let Q=f6[A];return`${Q.provider}/${Q.name}`}function oB(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 oI(A){switch(A){case"anthropic":return f6.CLAUDE_SONNET_4_5;case"openai":return f6.GPT_5_4;case"xai":return f6.GROK_CODE_FAST_1;case"cerebras":return f6.Z_AI_GLM_4_7;case"fireworks":return f6.FIREWORKS_GLM_4P6;case"baseten":return f6.BASETEN_KIMI_K2P5;case"moonshotai":return f6.KIMI_K2_INSTRUCT;case"openrouter":return f6.SONOMA_SKY_ALPHA;case"groq":return f6.GPT_OSS_120B;case"vertexai":return f6.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${A}`)}}function x$(A){let{provider:Q,model:$}=oB(A);for(let B of Object.values(f6))if(B.provider===Q&&B.name===$)return B;return oI(Q)}function gM(A){for(let $ of Object.values(f6))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(f6))if(B.name===$)return B}return}function P9(A){let Q=A.indexOf("/");if(Q===-1)return A;return A.slice(Q+1)}function i7(A){let Q=x$(A);return Q.contextWindow-Q.maxOutputTokens}function l50(A){return x$(A).maxOutputTokens}var s4,f6,_v0;var b$=r(()=>{s4={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},f6={CLAUDE_SONNET_4:{provider:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_7:{provider:s4.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},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:s4.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:s4.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:s4.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:s4.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:s4.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:s4.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:s4.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:s4.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:s4.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:s4.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:s4.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:s4.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:s4.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:s4.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:s4.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:s4.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:s4.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:s4.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:s4.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:s4.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};_v0={FINDER:"finder"}});function i50(A){return typeof A==="string"&&tQA.includes(A)}function vv0(A){return A===mM}function kv0(A){return A===mM||A===k04}function YT(A){return A==="deep"||A===mM}function dM(A,Q){if(!kv0(A))return!0;return Boolean(Q&&m7(Q))}function Sv0(A){return A!==void 0&&e6(A)&&A.features.some((Q)=>Q.name===k$.ACCEPT_ABUSE_DATA_RETENTION&&Q.enabled)}function n50({providerModel:A,serverStatus:Q}){if(A===C2("GPT_5_5")&&!Sv0(Q))return C2("GPT_5_4");return A}function y04(A){if(typeof A!=="string")return!1;return Ld.includes(A)}function fv0(A,Q){let $=f5(Q);if(!$)return!1;if(rQA.has(A)){let B=$.finder??_v0.FINDER,D=sQA[B];if(A!==D)return!1}if($.includeTools){if($.deferredTools?.includes(A))return!0;return $.includeTools.includes(A)}return!0}function x04(A,Q){let $=f5(Q);if(!$)return!1;return $.deferredTools?.includes(A)??!1}function b04(A){if(A?.isInternalUser!==void 0)return A.isInternalUser;return Boolean(A?.userEmail&&m7(A.userEmail))}function rB(A,Q){let $=A?.["internal.visibleModes"]??[],B=A?.["experimental.modes"]??[],D=[...$,...B];return Object.values(pM).filter((J)=>{if(kv0(J.key)&&!b04(Q))return!1;if(J.key===a50)return!1;if(D.includes(`!${J.key}`))return!1;if(Q?.v2&&!(("visibleInV2"in J)&&J.visibleInV2))return!1;let E="visible"in J?J.visible:!1,Y=D.includes(J.key);return E||Y}).map((J)=>({mode:J.key,description:"description"in J?J.description:void 0})).sort((J,F)=>J.mode.localeCompare(F.mode))}function yv0(A,Q){let $=rB(A,Q),B=Ld.filter((D)=>{if(!f5(D))return!1;if(kv0(D)&&!b04(Q))return!1;return!0}).sort((D,J)=>D.localeCompare(J));return{visibleAgentModes:$,allowedAgentModes:B}}function f5(A){return Object.values(pM).find((Q)=>Q.key===A)}function JK(A){return f5(A)?.primaryModel??C2("CLAUDE_SONNET_4_5")}function xv0(A,Q){if(!A)return;return f5(A)?.subagents?.[Q]}function Od(A){let Q=f5(A);if(!Q)return!1;return x$(Q.primaryModel).capabilities?.vision??!1}function sB(A){if(!A)return;return f5(A)?.reasoningEffortControl}function o50(A,Q){let{levels:$}=A,B=Q?$.indexOf(Q):-1;if(B===-1)return $[0];return $[(B+1)%$.length]??$[0]}function n5(A,Q){return sB(A)?.levels.includes(Q)??!1}function ZX(A,Q={}){if(!A||!y04(A)||!sB(A))return;let $=Q["reasoning.effort"];if($!==void 0&&n5(A,$))return $;let B=f5(A)?.reasoningEffort;return B&&n5(A,B)?B:void 0}function bv0(A,Q){return Q.find(($)=>$.mode===A)?.description}function jd(A,Q){let B=(Q.findIndex((J)=>J.mode===A)+1)%Q.length;return Q[B]?.mode??"smart"}var rQA,sQA,tQA,T04,v04,mM="frontier",k04="nostromo",eQA,Tv0,_04,A$A,Q$A,S04,f04,$$A,B$A,pM,a50,Ld;var a5=r(()=>{b_();mY();b$();rQA=new Set(["finder"]),sQA={finder:"finder"},tQA=["none","minimal","low","medium","high","xhigh","max"];T04={r:0,g:55,b:0},v04={r:0,g:255,b:136};eQA=["finder","shell_command","apply_patch","web_search","read_web_page","read_mcp_resource","read_thread","find_thread","skill","oracle","handoff","librarian","Task","view_media","painter"],Tv0=["Read","finder","Bash","create_file","edit_file","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","Task","view_media","handoff","painter","read_mcp_resource"],_04=["code_review"],A$A=["code_review"],Q$A=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","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"],S04=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","finder","view_media","painter","handoff","send_message_to_aggman"],f04=["finder","apply_patch","shell_command","Task","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","view_media","handoff","painter"],$$A=["code_review"],B$A=Array.from(new Set([...Tv0,...f04,...S04])),pM={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:C2("CLAUDE_OPUS_4_7"),includeTools:Tv0,deferredTools:_04,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:C2("GPT_5_5"),includeTools:eQA,visible:!0,reasoningEffort:"none",subagents:{"task-subagent":{model:C2("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:C2("CLAUDE_OPUS_4_6"),includeTools:Q$A,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:C2("CLAUDE_OPUS_4_6"),includeTools:Tv0,deferredTools:_04,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.5",primaryModel:C2("GPT_5_5"),includeTools:S04,deferredTools:A$A,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}}},FRONTIER:{key:mM,displayName:"Frontier",description:"Frontier mode for Amp development and debugging",primaryModel:C2("GEMINI_3_5_FLASH"),includeTools:f04,deferredTools:$$A,visible:!0,visibleInV2:!0,reasoningEffort:"medium",subagents:{"task-subagent":{model:C2("GEMINI_3_5_FLASH"),reasoningEffort:"medium"}},uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}},NOSTROMO:{key:k04,displayName:"nostromo",description:"Internal-only deterministic test mode with scripted tool scenarios",primaryModel:C2("AMP_NOSTROMO"),includeTools:B$A,visible:!0,visibleInV2:!0,reasoningEffort:"low",uiHints:{labelAnimation:"jitter",primaryColor:{r:0,g:46,b:77},secondaryColor:{r:48,g:213,b:200}}}},a50=pM.AGG.key,Ld=Object.values(pM).map((A)=>A.key)});var y5=r(()=>{a5();b$()});function r50(A){let Q=D$A.flatMap(($)=>{if($==="reasoning.effort")return[];let B=A[$];return B===void 0?[]:[[$,B]]});return Object.fromEntries(Q)}function hv0(A){return J$A.includes(A)}function g04(A){let Q=A["internal.model"];if(Q&&typeof Q==="object"){let $=Q.oracle?.trim();if($&&$.length>0){let B=$.indexOf(":");return B===-1?$:$.slice(B+1).trim()}}return f6.GPT_5_4.name}function m04(A,Q){let $=A["internal.model"];if(!$)return null;let B;if(typeof $==="string")B=$.trim();else B=$[Q]?.trim();if(!B||B.length===0)return null;let D=B.indexOf(":");if(D===-1)return null;let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J||!F)return null;return`${J}/${F}`}var D$A,J$A,s50,h04;var rI=r(()=>{y5();D$A=["agent.skipTitleGenerationIfMessageContains","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.oracleReasoningEffort","openai.speed","painter.model","reasoning.effort","tools.disable","tools.enable"];J$A=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];s50=["mcpServers","mcpPermissions","url"],h04=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});function M$A(A){return Q20.safeParse(A)}function sI(A){return w$A.safeParse(A)}function FK(A){if(!A||!Array.isArray(A))return[];let Q=[];for(let[$,B]of A.entries()){let D=M$A(B);if(D.success)Q.push(D.data);else{let J=typeof B==="object"&&B!==null&&"tool"in B?String(B.tool):`entry at index ${$}`;u.warn(`Permission entry for tool "${J}" is invalid: ${D.error.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ")}`)}}return Q}var dv0,Q20,w$A;var EK=r(()=>{P$();p0();dv0=x.lazy(()=>x.union([x.string().describe('Pattern match where "*" matches any number of any characters'),x.array(dv0).min(1).describe("OR match of each entry"),x.boolean().describe("A literal boolean match"),x.number().describe("A literal number match"),x.null().describe("A literal null match"),x.undefined().describe("A literal undefined match"),x.record(x.string(),dv0).describe("Matching individual keys of an object")])),Q20=x.object({tool:x.string().min(1).describe("The name of the tool to which this entry applies"),matches:x.record(x.string(),dv0).optional().describe("Maps tool inputs to conditions"),action:x.enum(["allow","reject","ask","delegate"]).describe("How Amp should proceed in case of a match"),context:x.enum(["thread","subagent"]).optional().describe("Only apply this entry in this context"),to:x.string().min(1).optional().describe('Command to delegate to when action is "delegate"'),message:x.string().optional().describe('Message to return to the model when action is "reject". If set, the rejection is returned as an error so the model can continue.')}).superRefine((A,Q)=>{if(A.action==="delegate"&&!A.to)Q.addIssue({code:"custom",message:'delegate action requires "to" field',path:["to"]});if(A.action!=="delegate"&&A.to)Q.addIssue({code:"custom",message:'"to" field only allowed with delegate action',path:["to"]});if(A.message&&A.action!=="reject")Q.addIssue({code:"custom",message:'"message" field only allowed with reject action',path:["message"]})}),w$A=x.array(Q20).describe("Entries checked in sequence to configure tool permissions")});function A5(A,Q){let $=L$A(A,Q);return typeof $==="string"?$:$.toString()}function L$A(A,Q,$=!0){if(!Q)Q=O$A();let{workspaceFolders:B,isWindows:D,homeDir:J}=Q,F=typeof A==="string"?i0.parse(A):i0.from(A);if(B)for(let E of B){let Y=XA(E);if(B1.hasPrefix(F,Y)){let Z=Y.path.endsWith("/")?Y.path.slice(0,-1):Y.path,X=$&&B&&B.length>=2?_$(Y.path)+(D?"\\":"/"):"";return pv0(X+F.path.slice(Z.length+1),D,F.scheme)}}if(F?.scheme==="file"){if(J){let E=XA(J);if(B1.hasPrefix(F,E)){let Y=E.path.endsWith("/")?E.path.slice(0,-1):E.path,Z=F.path.slice(Y.length+1);return pv0("~"+(D?"\\":"/")+Z,D,F.scheme)}}return pv0(F.fsPath,D,F.scheme)}return F}function pv0(A,Q,$){return Q&&$==="file"?A.replaceAll("/","\\"):A}function B20(A){let Q=$20;return $20=A,Q}function O$A(){if($20)return $20;throw Error("must call setDisplayPathEnvInfo before calling displayPath() and related functions")}var $20=null;var h$=r(()=>{Q4();TI();VT0()});var t04;var cv0=r(()=>{fm();fm();t04=x});var g$;var kQ=r(()=>{cv0();cv0();g$=t04});function J20(A){if(!A)return!1;return A.range.startLine===A.range.endLine&&A.range.startCharacter===A.range.endCharacter}function YK(A){if(A<=0)return!1;try{return process.kill(A,0),!0}catch(Q){let $=Q?.code;if($==="ESRCH")return!1;if($==="EPERM"||$==="EACCES")return!0;return u.debug("PID check error",{pid:A,code:$}),!1}}var lM=r(()=>{p0()});import{execFile as j$A}from"node:child_process";import{promisify as R$A}from"node:util";function ud(){if(!lv0)lv0=u$A("sqlite3",["-version"]).then(()=>!0).catch(()=>!1);return lv0}var u$A,lv0;var iv0=r(()=>{u$A=R$A(j$A)});import{execFile as P$A,spawnSync as _d}from"node:child_process";import UT from"node:fs";import nv0 from"node:os";import tB from"node:path";import{promisify as _$A}from"node:util";async function h$A(A){try{if(!await ud())return[];let Q=await DBA(A);if(!Q)return[];let $=await E14(A);return(await F14(A,$)).map((D)=>({workspaceFolders:[D.workspaceFolder],port:0,ideName:A.ideName,authToken:"",pid:Q,connection:"query"}))}catch(Q){return u.debug(`Failed to list ${A.ideName} configs`,{error:Q instanceof Error?Q.message:String(Q)}),[]}}async function g$A(A,Q){if(!Q.pid||!YK(Q.pid))return null;let $=Q.workspaceFolders[0];if(!$)return null;let B=await E14(A),J=(await F14(A,B)).find((E)=>F20(E.workspaceFolder)===F20($));if(!J)return null;let F=await l$A(J.stateDBPath);if(!F)return{openFiles:[]};return F}function m$A(A,Q){let{filePath:$,line:B,column:D}=p$A(Q);if(!$)return!1;let J=B?`${$}:${B}${D?`:${D}`:""}`:$,F=EBA(A);if(!F)return A14(A,$,B,D);if(_d(F,["--goto",J],{stdio:"ignore"}).status===0)return!0;return A14(A,$,B,D)}function A14(A,Q,$,B){let D=Q.replaceAll("\\","/"),F=(D.startsWith("/")?D:`/${D}`).split("/").map((U)=>encodeURIComponent(U)).join("/"),E=$?`:${$}${B?`:${B}`:""}`:"",Y=`${A.urlScheme}://file${F}${E}`,Z=d$A(Y);if(Z.status===0)return!0;return u.debug(`Failed to open URI with ${A.ideName} URL scheme`,{schemeURI:Y,status:Z.status,stderr:Z.stderr?.toString().trim()}),!1}function d$A(A){if(process.platform==="darwin")return _d("open",[A],{stdio:"ignore"});if(process.platform==="win32")return _d("cmd.exe",["/c","start","",A],{stdio:"ignore"});return _d("xdg-open",[A],{stdio:"ignore"})}function p$A(A){try{let Q=i0.parse(A);if(Q.scheme!=="file")return{};let $=c$A(Q.fragment);return{filePath:Q.fsPath,line:$?.line,column:$?.column}}catch{return{}}}function c$A(A){let Q=A.match(v$A),$=Q?.groups?.line;if(!$)return null;return{line:Number.parseInt($,10),column:Q.groups?.column?Number.parseInt(Q.groups.column,10):void 0}}async function l$A(A){let Q=await $BA(A,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Q.length===0)return null;let $=i$A(Q.find((Y)=>Y.key==="memento/workbench.parts.editor")?.value);if(!$)return null;let B=$.leaves.flatMap((Y)=>Y.editors),D=$.leaves.find((Y)=>Y.id===$.activeGroup)??$.leaves[0],J=D?a$A(D):void 0,F=o$A(Q.find((Y)=>Y.key==="memento/workbench.editors.files.textFileEditor")?.value),E=J?await r$A(J,$.activeGroup,F):void 0;return{openFile:J,openFiles:B,selection:E}}function i$A(A){if(!A)return null;try{let Q=JSON.parse(A),$=Q["editorpart.state"]??Q.editorpart?.state,B=$?.activeGroup;if(typeof B!=="number")return null;let D=$?.serializedGrid,J=J14(D?.root??D);return{activeGroup:B,leaves:J}}catch(Q){return u.debug("Failed to parse VS Code editor state",{error:Q instanceof Error?Q.message:String(Q)}),null}}function J14(A){if(!A||typeof A!=="object")return[];let Q=A;if(Q.type==="leaf"){let $=Q.data;if(typeof $?.id!=="number")return[];let B=$.editors?.map((D)=>n$A(D.value)).filter((D)=>Boolean(D))??[];return[{id:$.id,editors:B,preview:typeof $.preview==="number"?$.preview:void 0,mru:Array.isArray($.mru)?$.mru.filter((D)=>Number.isInteger(D)):[]}]}if(Q.type==="branch")return(Array.isArray(Q.data??[])?Q.data??[]:[]).flatMap((B)=>J14(B));return[]}function n$A(A){if(!A)return;try{let Q=JSON.parse(A),$=Q.resourceJSON?.external;if($)return t1(i0.parse($));if(Q.resourceJSON?.scheme==="file"&&Q.resourceJSON.path)return t1(i0.file(Q.resourceJSON.path))}catch(Q){u.debug("Failed to parse VS Code editor URI",{error:Q instanceof Error?Q.message:String(Q)})}return}function a$A(A){let Q=A.mru[0]??A.preview??0;return A.editors[Q]??A.editors[0]}function o$A(A){if(!A)return new Map;try{let $=JSON.parse(A).textEditorViewState??[];return new Map($)}catch(Q){return u.debug("Failed to parse VS Code text editor state",{error:Q instanceof Error?Q.message:String(Q)}),new Map}}async function r$A(A,Q,$){let B=$.get(A)??$.get(decodeURIComponent(A))??$.get(encodeURI(A));if(!B)return;let J=(B[String(Q)]??Object.values(B)[0])?.cursorState?.[0];if(!J)return;let F=await s$A(A);if(F===void 0)return;let E=Q14(J.selectionStart.lineNumber,J.selectionStart.column),Y=Q14(J.position.lineNumber,J.position.column),Z=$14(E,Y)<=0?E:Y,U=$14(E,Y)<=0?Y:E,G=Z.line===U.line&&Z.character===U.character?t$A(F,Z.line):e$A(F,Z.line,Z.character,U.line,U.character);return{range:{startLine:Z.line,startCharacter:Z.character,endLine:U.line,endCharacter:U.character},content:G}}async function s$A(A){try{let Q=i0.parse(A);if(Q.scheme!=="file")return;return await UT.promises.readFile(Q.fsPath,"utf-8")}catch(Q){u.debug("Failed to read VS Code active file content",{fileURI:A,error:Q instanceof Error?Q.message:String(Q)});return}}function Q14(A,Q){return{line:Math.max(0,A-1),character:Math.max(0,Q-1)}}function $14(A,Q){if(A.line===Q.line)return A.character-Q.character;return A.line-Q.line}function t$A(A,Q){return A.split(`
232
+ `))));$.push({path:B.movePath??B.path,diffStat:D})}return $}function p50(A){let Q=0,$=0,B=0;return A.messages.forEach((D)=>{if(D.role!=="assistant")return;D.content.forEach((J)=>{let F=X04(J);if(!F)return;let{name:E,input:Y}=F,Z=null;if(E==="edit_file"){if("old_str"in Y&&"new_str"in Y){let{old_str:U,new_str:X}=Y;Z=FX(U,X)}}else if(E==="apply_patch"){let U=G04(Y);Z=jv0(U.map((X)=>X.diffStat))}else if((E==="write_file"||E==="create_file")&&"content"in Y&&typeof Y.content==="string")Z=EX(Y.content);if(Z)Q+=Z.added,B+=Z.deleted,$+=Z.changed})}),{added:Q,changed:$,deleted:B}}function V04(A){let Q=new Map;return A.messages.forEach(($)=>{if($.role!=="assistant")return;$.content.forEach((B)=>{let D=X04(B);if(!D)return;let{name:J,input:F}=D,E,Y=null;if(J==="edit_file"){if("path"in F&&typeof F.path==="string"&&"old_str"in F&&"new_str"in F){E=F.path;let{old_str:Z,new_str:U}=F;Y=FX(Z,U)}}else if(J==="apply_patch"){for(let Z of G04(F)){let U=F04(Z.path,A.env?.initial?.trees);if(U){let X=Q.get(U)??{added:0,changed:0,deleted:0};X.added+=Z.diffStat.added,X.changed+=Z.diffStat.changed,X.deleted+=Z.diffStat.deleted,Q.set(U,X)}}return}else if((J==="write_file"||J==="create_file")&&"path"in F&&typeof F.path==="string"&&"content"in F&&typeof F.content==="string")E=F.path,Y=EX(F.content);if(E&&Y){let Z=F04(E,A.env?.initial?.trees);if(Z){let U=Q.get(Z)??{added:0,changed:0,deleted:0};U.added+=Y.added,U.changed+=Y.changed,U.deleted+=Y.deleted,Q.set(Z,U)}}})}),Q}function F04(A,Q){let $=A.startsWith("/"),B=/^[a-zA-Z]:[\\/]/.test(A);if(!$&&!B)return A;let D=A.replace(/\\/g,"/");if(Q&&Q.length>0)for(let E of Q){if(!E.uri)continue;let Y=E.uri.match(/^file:\/\/(.+)$/);if(!Y?.[1])continue;let Z=decodeURIComponent(Y[1]).replace(/\\/g,"/"),U=Z.startsWith("/")&&/^\/[a-zA-Z]:/.test(Z)?Z.slice(1):Z;if(D.startsWith(U)){let X=D.slice(U.length);return X.startsWith("/")?X.slice(1):X}}let J=D.match(/\/(?:Users|home)\/[^/]+\/[^/]+\/(.+)/);if(J?.[1])return J[1];let F=D.match(/^[a-zA-Z]:\/Users\/[^/]+\/[^/]+\/(.+)/);if(F?.[1])return F[1];return null}function ET(A,Q){let $=A.relationships?.filter((J)=>J.role==="child")??[],B=uv0(A),D=[...$,...B];return Q?D.filter((J)=>J.type===Q):D}function K04(A,Q){return ET(A,Q)[0]}function nB(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="user")return $}return}function Nd(A){for(let Q=A.messages.length-1;Q>=0;Q--){let $=A.messages[Q];if($?.role==="user"&&$.agentMode)return $.agentMode}return}function uv0(A){let Q=[],$=new Set;if(!A.messages)return Q;return A.messages.forEach((B,D)=>{if(B.role!=="assistant")return;B.content.forEach((J)=>{if(J.type!=="tool_use")return;if(J.name!==QK)return;if(!l5(J))return;let F=J.input,E=typeof F.threadID==="string"?v8(F.threadID):null;if(E&&!$.has(E))$.add(E),Q.push({threadID:E,type:"mention",role:"parent",messageIndex:D,createdAt:Date.now()})})}),Q}var dQA,pQA;var a4=r(()=>{Cv0();P$();p0();h4();lI();$T();dQA=x.templateLiteral([x.string().regex(/^[0-9a-f]{8}$/),"-",x.string().regex(/^[0-9a-f]{4}$/),"-",x.string().regex(/^[0-9a-f]{4}$/),"-",x.string().regex(/^[0-9a-f]{4}$/),"-",x.string().regex(/^[0-9a-f]{12}$/)]),pQA=x.templateLiteral(["T-",dQA])});function J9(A){if(!A)return{};return{[Pv0]:A.id}}var D9="x-amp-feature",Pv0="x-amp-thread-id",TQ="x-amp-message-id",z04="X-Amp-Client-Application",W04="X-Amp-Client-Type",I04="X-Amp-Client-Version",H04="X-Amp-Installation-ID",q04="X-Amp-Device-Fingerprint";var aB=()=>{};function w04(A){N04=A}function hM(A){Cd=A}function M04(A){C04=A}function L04(A){wd=A.installationID,Md=A.deviceFingerprint}function O04(){if(!wd||!Md)return;return{installationID:wd,deviceFingerprint:Md}}function i5(){let A=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(A)return{type:"cli",name:"AmpSDK",version:A};let Q;if(!Cd)Q="CLI";else if(["Neovim","JetBrains","Zed"].includes(Cd))Q=Cd;else Q=`${Cd} CLI`;return{type:"cli",name:C04?`${Q} Execute Mode`:Q,version:N04}}function Y7(A){let Q={};if(Q[z04]=A.name,Q[W04]=A.type,wd)Q[H04]=wd;if(Md)Q[q04]=Md;if(A.version)Q[I04]=A.version;return Q}var N04=null,Cd=null,C04=!1,wd=null,Md=null;var vQ=r(()=>{aB()});function lQA(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 y$(A,Q,$){let B=$?`/threads/${Q}/${$}`:`/threads/${Q}`;return new URL(B,A)}async function k8(A,Q,$){let B=await $.getLatest(Q?.signal??void 0),D=await R04(A,Q,B);return fetch(D)}async function j04(A,Q,$){let B=await R04(Q,$,A);return fetch(B)}async function R04(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 D=await $.secrets.getToken("apiKey",B);lQA({proxy:$.settings.proxy});let J=new URL(A,B);return new Request(J,{...Q,duplex:"half",headers:{"Content-Type":"application/json",...Q?.headers,...Y7(i5()),...D?{Authorization:`Bearer ${D}`}:{}}})}async function u04(A,Q,$,B){let D=await e4.shareThreadWithOperator({threadID:A,message:$||void 0,ephemeralError:B||void 0},{config:Q});if(!D.ok)throw Error(`Failed to share thread: ${D.error.message}`)}async function c50(A,Q){let $=await k8("/api/telemetry",{method:"POST",redirect:"manual",body:A},Q);if(!$.ok){let B=await $.text(),D;try{D=JSON.parse(B).error||`HTTP ${$.status}`}catch{D=B||`HTTP ${$.status}`}throw Error(`Failed to submit telemetry: ${D}`)}}var u9=r(()=>{vQ();e2()});function nQA(A){if(new Blob([A]).size<=iQA)return{body:A};return{body:Me1.gzip(A),headers:{"Content-Encoding":"gzip"}}}function aQA(){return new Proxy({},{get:(A,Q)=>{return async(...$)=>{let B=$.at(1),D=$.at(0);if(!B?.config)throw Error("Internal API client requires configService in options. Call with { config: configService }");let{body:J,headers:F={}}=nQA(JSON.stringify({method:Q,params:D})),E=await k8("/api/internal?"+encodeURIComponent(Q),{method:"POST",body:J,headers:F,signal:B?.signal},B.config);if(!E.ok)throw Error(`API request for ${Q} failed: ${E.status}`);return await E.json()}}})}var iQA=25600,e4;var e2=r(()=>{Le1();u9();e4=aQA()});function oQA(A){return A.config.pipe(y4(({settings:Q,secrets:$})=>F6(async()=>({url:Q.url,proxy:Q.proxy,apiKey:await $.getToken("apiKey",Q.url)}))),T4(cF),y4(()=>v_(600000).pipe(WA(void 0),S_(()=>F6(async(Q)=>{let $=await e4.getUserInfo({},{signal:Q,config:A});if($.ok)return $.result;if($.error&&$.error.code==="auth-required")return null;throw u.error("getUserInfo failed",{error:$.error}),Error(`getUserInfo error: ${$.error.code}`)})))),N1((Q)=>{return Q instanceof Error?{error:{message:String(Q)}}:Q===eU?"pending":Q?{user:Q,features:Q.features,workspace:Q?.team,mysteriousMessage:Q?.mysteriousMessage}:{error:{message:"User not found"}}}),T4((Q,$)=>cF(Q,$)),t6({shouldCountRefs:!0}))}function oF(A){let Q=P04.get(A);if(Q)return Q;let $=oQA(A);return P04.set(A,$),$}function e6(A){return Boolean(typeof A==="object"&&"user"in A&&A.user)}function gY(A){return typeof A==="object"&&"error"in A}var P04;var mY=r(()=>{u1();p0();e2();P04=new WeakMap});function C2(A){let Q=f6[A];return`${Q.provider}/${Q.name}`}function oB(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 oI(A){switch(A){case"anthropic":return f6.CLAUDE_SONNET_4_5;case"openai":return f6.GPT_5_4;case"xai":return f6.GROK_CODE_FAST_1;case"cerebras":return f6.Z_AI_GLM_4_7;case"fireworks":return f6.FIREWORKS_GLM_4P6;case"baseten":return f6.BASETEN_KIMI_K2P5;case"moonshotai":return f6.KIMI_K2_INSTRUCT;case"openrouter":return f6.SONOMA_SKY_ALPHA;case"groq":return f6.GPT_OSS_120B;case"vertexai":return f6.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${A}`)}}function x$(A){let{provider:Q,model:$}=oB(A);for(let B of Object.values(f6))if(B.provider===Q&&B.name===$)return B;return oI(Q)}function gM(A){for(let $ of Object.values(f6))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(f6))if(B.name===$)return B}return}function P9(A){let Q=A.indexOf("/");if(Q===-1)return A;return A.slice(Q+1)}function i7(A){let Q=x$(A);return Q.contextWindow-Q.maxOutputTokens}function l50(A){return x$(A).maxOutputTokens}var s4,f6,_v0;var b$=r(()=>{s4={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},f6={CLAUDE_SONNET_4:{provider:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_7:{provider:s4.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},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.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:s4.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:s4.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:s4.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:s4.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:s4.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:s4.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:s4.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:s4.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:s4.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:s4.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:s4.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:s4.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:s4.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:s4.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:s4.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:s4.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:s4.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:s4.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:s4.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:s4.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:s4.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};_v0={FINDER:"finder"}});function i50(A){return typeof A==="string"&&tQA.includes(A)}function vv0(A){return A===mM}function kv0(A){return A===mM||A===k04}function YT(A){return A==="deep"||A===mM}function dM(A,Q){if(!kv0(A))return!0;return Boolean(Q&&m7(Q))}function Sv0(A){return A!==void 0&&e6(A)&&A.features.some((Q)=>Q.name===k$.ACCEPT_ABUSE_DATA_RETENTION&&Q.enabled)}function n50({providerModel:A,serverStatus:Q}){if(A===C2("GPT_5_5")&&!Sv0(Q))return C2("GPT_5_4");return A}function y04(A){if(typeof A!=="string")return!1;return Ld.includes(A)}function fv0(A,Q){let $=f5(Q);if(!$)return!1;if(rQA.has(A)){let B=$.finder??_v0.FINDER,D=sQA[B];if(A!==D)return!1}if($.includeTools){if($.deferredTools?.includes(A))return!0;return $.includeTools.includes(A)}return!0}function x04(A,Q){let $=f5(Q);if(!$)return!1;return $.deferredTools?.includes(A)??!1}function b04(A){if(A?.isInternalUser!==void 0)return A.isInternalUser;return Boolean(A?.userEmail&&m7(A.userEmail))}function rB(A,Q){let $=A?.["internal.visibleModes"]??[],B=A?.["experimental.modes"]??[],D=[...$,...B];return Object.values(pM).filter((J)=>{if(kv0(J.key)&&!b04(Q))return!1;if(J.key===a50)return!1;if(D.includes(`!${J.key}`))return!1;if(Q?.v2&&!(("visibleInV2"in J)&&J.visibleInV2))return!1;let E="visible"in J?J.visible:!1,Y=D.includes(J.key);return E||Y}).map((J)=>({mode:J.key,description:"description"in J?J.description:void 0})).sort((J,F)=>J.mode.localeCompare(F.mode))}function yv0(A,Q){let $=rB(A,Q),B=Ld.filter((D)=>{if(!f5(D))return!1;if(kv0(D)&&!b04(Q))return!1;return!0}).sort((D,J)=>D.localeCompare(J));return{visibleAgentModes:$,allowedAgentModes:B}}function f5(A){return Object.values(pM).find((Q)=>Q.key===A)}function JK(A){return f5(A)?.primaryModel??C2("CLAUDE_SONNET_4_5")}function xv0(A,Q){if(!A)return;return f5(A)?.subagents?.[Q]}function Od(A){let Q=f5(A);if(!Q)return!1;return x$(Q.primaryModel).capabilities?.vision??!1}function sB(A){if(!A)return;return f5(A)?.reasoningEffortControl}function o50(A,Q){let{levels:$}=A,B=Q?$.indexOf(Q):-1;if(B===-1)return $[0];return $[(B+1)%$.length]??$[0]}function n5(A,Q){return sB(A)?.levels.includes(Q)??!1}function ZX(A,Q={}){if(!A||!y04(A)||!sB(A))return;let $=Q["reasoning.effort"];if($!==void 0&&n5(A,$))return $;let B=f5(A)?.reasoningEffort;return B&&n5(A,B)?B:void 0}function bv0(A,Q){return Q.find(($)=>$.mode===A)?.description}function jd(A,Q){let B=(Q.findIndex((J)=>J.mode===A)+1)%Q.length;return Q[B]?.mode??"smart"}var rQA,sQA,tQA,T04,v04,mM="frontier",k04="nostromo",eQA,Tv0,_04,A$A,Q$A,S04,f04,$$A,B$A,pM,a50,Ld;var a5=r(()=>{b_();mY();b$();rQA=new Set(["finder"]),sQA={finder:"finder"},tQA=["none","minimal","low","medium","high","xhigh","max"];T04={r:0,g:55,b:0},v04={r:0,g:255,b:136};eQA=["finder","shell_command","apply_patch","web_search","read_web_page","read_mcp_resource","read_thread","find_thread","skill","oracle","handoff","librarian","Task","view_media","painter"],Tv0=["Read","finder","Bash","create_file","edit_file","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","Task","view_media","handoff","painter","read_mcp_resource"],_04=["code_review"],A$A=["code_review"],Q$A=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","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"],S04=["shell_command","apply_patch","web_search","read_web_page","chart","Task","skill","read_thread","find_thread","librarian","oracle","finder","view_media","painter","handoff","send_message_to_aggman"],f04=["finder","apply_patch","shell_command","Task","web_search","read_web_page","read_thread","find_thread","skill","oracle","librarian","view_media","handoff","painter"],$$A=["code_review"],B$A=Array.from(new Set([...Tv0,...f04,...S04])),pM={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:C2("CLAUDE_OPUS_4_7"),includeTools:Tv0,deferredTools:_04,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:C2("GPT_5_5"),includeTools:eQA,visible:!0,reasoningEffort:"none",subagents:{"task-subagent":{model:C2("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:C2("CLAUDE_OPUS_4_6"),includeTools:Q$A,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:C2("CLAUDE_OPUS_4_6"),includeTools:Tv0,deferredTools:_04,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.5",primaryModel:C2("GPT_5_5"),includeTools:S04,deferredTools:A$A,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}}},FRONTIER:{key:mM,displayName:"Frontier",description:"Frontier mode for Amp development and debugging",primaryModel:C2("GEMINI_3_5_FLASH"),includeTools:f04,deferredTools:$$A,visible:!0,visibleInV2:!0,reasoningEffort:"medium",subagents:{"task-subagent":{model:C2("GEMINI_3_5_FLASH"),reasoningEffort:"medium"}},uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}},NOSTROMO:{key:k04,displayName:"nostromo",description:"Internal-only deterministic test mode with scripted tool scenarios",primaryModel:C2("AMP_NOSTROMO"),includeTools:B$A,visible:!0,visibleInV2:!0,reasoningEffort:"low",uiHints:{labelAnimation:"jitter",primaryColor:{r:0,g:46,b:77},secondaryColor:{r:48,g:213,b:200}}}},a50=pM.AGG.key,Ld=Object.values(pM).map((A)=>A.key)});var y5=r(()=>{a5();b$()});function r50(A){let Q=D$A.flatMap(($)=>{if($==="reasoning.effort")return[];let B=A[$];return B===void 0?[]:[[$,B]]});return Object.fromEntries(Q)}function hv0(A){return J$A.includes(A)}function g04(A){let Q=A["internal.model"];if(Q&&typeof Q==="object"){let $=Q.oracle?.trim();if($&&$.length>0){let B=$.indexOf(":");return B===-1?$:$.slice(B+1).trim()}}return f6.GPT_5_5.name}function m04(A,Q){let $=A["internal.model"];if(!$)return null;let B;if(typeof $==="string")B=$.trim();else B=$[Q]?.trim();if(!B||B.length===0)return null;let D=B.indexOf(":");if(D===-1)return null;let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J||!F)return null;return`${J}/${F}`}var D$A,J$A,s50,h04;var rI=r(()=>{y5();D$A=["agent.skipTitleGenerationIfMessageContains","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.oracleReasoningEffort","openai.speed","painter.model","reasoning.effort","tools.disable","tools.enable"];J$A=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];s50=["mcpServers","mcpPermissions","url"],h04=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});function M$A(A){return Q20.safeParse(A)}function sI(A){return w$A.safeParse(A)}function FK(A){if(!A||!Array.isArray(A))return[];let Q=[];for(let[$,B]of A.entries()){let D=M$A(B);if(D.success)Q.push(D.data);else{let J=typeof B==="object"&&B!==null&&"tool"in B?String(B.tool):`entry at index ${$}`;u.warn(`Permission entry for tool "${J}" is invalid: ${D.error.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ")}`)}}return Q}var dv0,Q20,w$A;var EK=r(()=>{P$();p0();dv0=x.lazy(()=>x.union([x.string().describe('Pattern match where "*" matches any number of any characters'),x.array(dv0).min(1).describe("OR match of each entry"),x.boolean().describe("A literal boolean match"),x.number().describe("A literal number match"),x.null().describe("A literal null match"),x.undefined().describe("A literal undefined match"),x.record(x.string(),dv0).describe("Matching individual keys of an object")])),Q20=x.object({tool:x.string().min(1).describe("The name of the tool to which this entry applies"),matches:x.record(x.string(),dv0).optional().describe("Maps tool inputs to conditions"),action:x.enum(["allow","reject","ask","delegate"]).describe("How Amp should proceed in case of a match"),context:x.enum(["thread","subagent"]).optional().describe("Only apply this entry in this context"),to:x.string().min(1).optional().describe('Command to delegate to when action is "delegate"'),message:x.string().optional().describe('Message to return to the model when action is "reject". If set, the rejection is returned as an error so the model can continue.')}).superRefine((A,Q)=>{if(A.action==="delegate"&&!A.to)Q.addIssue({code:"custom",message:'delegate action requires "to" field',path:["to"]});if(A.action!=="delegate"&&A.to)Q.addIssue({code:"custom",message:'"to" field only allowed with delegate action',path:["to"]});if(A.message&&A.action!=="reject")Q.addIssue({code:"custom",message:'"message" field only allowed with reject action',path:["message"]})}),w$A=x.array(Q20).describe("Entries checked in sequence to configure tool permissions")});function A5(A,Q){let $=L$A(A,Q);return typeof $==="string"?$:$.toString()}function L$A(A,Q,$=!0){if(!Q)Q=O$A();let{workspaceFolders:B,isWindows:D,homeDir:J}=Q,F=typeof A==="string"?i0.parse(A):i0.from(A);if(B)for(let E of B){let Y=XA(E);if(B1.hasPrefix(F,Y)){let Z=Y.path.endsWith("/")?Y.path.slice(0,-1):Y.path,X=$&&B&&B.length>=2?_$(Y.path)+(D?"\\":"/"):"";return pv0(X+F.path.slice(Z.length+1),D,F.scheme)}}if(F?.scheme==="file"){if(J){let E=XA(J);if(B1.hasPrefix(F,E)){let Y=E.path.endsWith("/")?E.path.slice(0,-1):E.path,Z=F.path.slice(Y.length+1);return pv0("~"+(D?"\\":"/")+Z,D,F.scheme)}}return pv0(F.fsPath,D,F.scheme)}return F}function pv0(A,Q,$){return Q&&$==="file"?A.replaceAll("/","\\"):A}function B20(A){let Q=$20;return $20=A,Q}function O$A(){if($20)return $20;throw Error("must call setDisplayPathEnvInfo before calling displayPath() and related functions")}var $20=null;var h$=r(()=>{Q4();TI();VT0()});var t04;var cv0=r(()=>{fm();fm();t04=x});var g$;var kQ=r(()=>{cv0();cv0();g$=t04});function J20(A){if(!A)return!1;return A.range.startLine===A.range.endLine&&A.range.startCharacter===A.range.endCharacter}function YK(A){if(A<=0)return!1;try{return process.kill(A,0),!0}catch(Q){let $=Q?.code;if($==="ESRCH")return!1;if($==="EPERM"||$==="EACCES")return!0;return u.debug("PID check error",{pid:A,code:$}),!1}}var lM=r(()=>{p0()});import{execFile as j$A}from"node:child_process";import{promisify as R$A}from"node:util";function ud(){if(!lv0)lv0=u$A("sqlite3",["-version"]).then(()=>!0).catch(()=>!1);return lv0}var u$A,lv0;var iv0=r(()=>{u$A=R$A(j$A)});import{execFile as P$A,spawnSync as _d}from"node:child_process";import UT from"node:fs";import nv0 from"node:os";import tB from"node:path";import{promisify as _$A}from"node:util";async function h$A(A){try{if(!await ud())return[];let Q=await DBA(A);if(!Q)return[];let $=await E14(A);return(await F14(A,$)).map((D)=>({workspaceFolders:[D.workspaceFolder],port:0,ideName:A.ideName,authToken:"",pid:Q,connection:"query"}))}catch(Q){return u.debug(`Failed to list ${A.ideName} configs`,{error:Q instanceof Error?Q.message:String(Q)}),[]}}async function g$A(A,Q){if(!Q.pid||!YK(Q.pid))return null;let $=Q.workspaceFolders[0];if(!$)return null;let B=await E14(A),J=(await F14(A,B)).find((E)=>F20(E.workspaceFolder)===F20($));if(!J)return null;let F=await l$A(J.stateDBPath);if(!F)return{openFiles:[]};return F}function m$A(A,Q){let{filePath:$,line:B,column:D}=p$A(Q);if(!$)return!1;let J=B?`${$}:${B}${D?`:${D}`:""}`:$,F=EBA(A);if(!F)return A14(A,$,B,D);if(_d(F,["--goto",J],{stdio:"ignore"}).status===0)return!0;return A14(A,$,B,D)}function A14(A,Q,$,B){let D=Q.replaceAll("\\","/"),F=(D.startsWith("/")?D:`/${D}`).split("/").map((U)=>encodeURIComponent(U)).join("/"),E=$?`:${$}${B?`:${B}`:""}`:"",Y=`${A.urlScheme}://file${F}${E}`,Z=d$A(Y);if(Z.status===0)return!0;return u.debug(`Failed to open URI with ${A.ideName} URL scheme`,{schemeURI:Y,status:Z.status,stderr:Z.stderr?.toString().trim()}),!1}function d$A(A){if(process.platform==="darwin")return _d("open",[A],{stdio:"ignore"});if(process.platform==="win32")return _d("cmd.exe",["/c","start","",A],{stdio:"ignore"});return _d("xdg-open",[A],{stdio:"ignore"})}function p$A(A){try{let Q=i0.parse(A);if(Q.scheme!=="file")return{};let $=c$A(Q.fragment);return{filePath:Q.fsPath,line:$?.line,column:$?.column}}catch{return{}}}function c$A(A){let Q=A.match(v$A),$=Q?.groups?.line;if(!$)return null;return{line:Number.parseInt($,10),column:Q.groups?.column?Number.parseInt(Q.groups.column,10):void 0}}async function l$A(A){let Q=await $BA(A,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Q.length===0)return null;let $=i$A(Q.find((Y)=>Y.key==="memento/workbench.parts.editor")?.value);if(!$)return null;let B=$.leaves.flatMap((Y)=>Y.editors),D=$.leaves.find((Y)=>Y.id===$.activeGroup)??$.leaves[0],J=D?a$A(D):void 0,F=o$A(Q.find((Y)=>Y.key==="memento/workbench.editors.files.textFileEditor")?.value),E=J?await r$A(J,$.activeGroup,F):void 0;return{openFile:J,openFiles:B,selection:E}}function i$A(A){if(!A)return null;try{let Q=JSON.parse(A),$=Q["editorpart.state"]??Q.editorpart?.state,B=$?.activeGroup;if(typeof B!=="number")return null;let D=$?.serializedGrid,J=J14(D?.root??D);return{activeGroup:B,leaves:J}}catch(Q){return u.debug("Failed to parse VS Code editor state",{error:Q instanceof Error?Q.message:String(Q)}),null}}function J14(A){if(!A||typeof A!=="object")return[];let Q=A;if(Q.type==="leaf"){let $=Q.data;if(typeof $?.id!=="number")return[];let B=$.editors?.map((D)=>n$A(D.value)).filter((D)=>Boolean(D))??[];return[{id:$.id,editors:B,preview:typeof $.preview==="number"?$.preview:void 0,mru:Array.isArray($.mru)?$.mru.filter((D)=>Number.isInteger(D)):[]}]}if(Q.type==="branch")return(Array.isArray(Q.data??[])?Q.data??[]:[]).flatMap((B)=>J14(B));return[]}function n$A(A){if(!A)return;try{let Q=JSON.parse(A),$=Q.resourceJSON?.external;if($)return t1(i0.parse($));if(Q.resourceJSON?.scheme==="file"&&Q.resourceJSON.path)return t1(i0.file(Q.resourceJSON.path))}catch(Q){u.debug("Failed to parse VS Code editor URI",{error:Q instanceof Error?Q.message:String(Q)})}return}function a$A(A){let Q=A.mru[0]??A.preview??0;return A.editors[Q]??A.editors[0]}function o$A(A){if(!A)return new Map;try{let $=JSON.parse(A).textEditorViewState??[];return new Map($)}catch(Q){return u.debug("Failed to parse VS Code text editor state",{error:Q instanceof Error?Q.message:String(Q)}),new Map}}async function r$A(A,Q,$){let B=$.get(A)??$.get(decodeURIComponent(A))??$.get(encodeURI(A));if(!B)return;let J=(B[String(Q)]??Object.values(B)[0])?.cursorState?.[0];if(!J)return;let F=await s$A(A);if(F===void 0)return;let E=Q14(J.selectionStart.lineNumber,J.selectionStart.column),Y=Q14(J.position.lineNumber,J.position.column),Z=$14(E,Y)<=0?E:Y,U=$14(E,Y)<=0?Y:E,G=Z.line===U.line&&Z.character===U.character?t$A(F,Z.line):e$A(F,Z.line,Z.character,U.line,U.character);return{range:{startLine:Z.line,startCharacter:Z.character,endLine:U.line,endCharacter:U.character},content:G}}async function s$A(A){try{let Q=i0.parse(A);if(Q.scheme!=="file")return;return await UT.promises.readFile(Q.fsPath,"utf-8")}catch(Q){u.debug("Failed to read VS Code active file content",{fileURI:A,error:Q instanceof Error?Q.message:String(Q)});return}}function Q14(A,Q){return{line:Math.max(0,A-1),character:Math.max(0,Q-1)}}function $14(A,Q){if(A.line===Q.line)return A.character-Q.character;return A.line-Q.line}function t$A(A,Q){return A.split(`
233
233
  `)[Q]??""}function e$A(A,Q,$,B,D){let J=B14(A,Q,$),F=B14(A,B,D);if(F<=J)return"";return A.slice(J,F)}function B14(A,Q,$){let B=0,D=0;for(let J=0;J<A.length;J+=1){if(B===Q&&D===$)return J;if(A[J]===`
234
234
  `)B+=1,D=0;else D+=1}return A.length}async function F14(A,Q){if(Q?.size===0)return[];let $=tB.join(Y14(A),"workspaceStorage");if(!await Pd($))return[];let B=await UT.promises.readdir($,{withFileTypes:!0});return(await Promise.all(B.filter((F)=>F.isDirectory()).map(async(F)=>{let E=F.name,Y=tB.join($,E),Z=tB.join(Y,"state.vscdb"),U=tB.join(Y,"workspace.json");if(!await Pd(Z)||!await Pd(U))return null;let X=await QBA(U);if(!X||!await Pd(X))return null;if(Q&&!Q.has(F20(X)))return null;let G=await UT.promises.stat(Z);return{storageID:E,workspaceFolder:X,stateDBPath:Z,mtime:G.mtimeMs}}))).filter((F)=>F!==null).sort((F,E)=>E.mtime-F.mtime).slice(0,T$A)}async function E14(A){let Q=tB.join(Y14(A),"globalStorage","storage.json");if(!await Pd(Q))return null;try{let $=await UT.promises.readFile(Q,"utf-8"),D=JSON.parse($).windowsState,J=Array.isArray(D?.openedWindows)?D.openedWindows:[],F=J.length>0?J:[D?.lastActiveWindow],E=new Set;for(let Y of F){if(!Y)continue;let Z=ABA(Y);if(!Z)continue;E.add(F20(Z))}return E}catch($){return u.debug(`Failed to parse ${A.ideName} windowsState`,{storageFilePath:Q,error:$ instanceof Error?$.message:String($)}),null}}function ABA(A){if(A.folder)return D14(A.folder);let Q=A.workspaceIdentifier?.configURIPath;if(!Q)return null;let $=D14(Q);return $?tB.dirname($):null}function D14(A){try{return i0.parse(A).fsPath}catch{if(tB.isAbsolute(A))return A;return null}}async function QBA(A){try{let Q=await UT.promises.readFile(A,"utf-8"),$=JSON.parse(Q);if($.folder)return i0.parse($.folder).fsPath;if($.configuration)return tB.dirname(i0.parse($.configuration).fsPath)}catch(Q){u.debug("Failed to parse VS Code workspace metadata",{workspaceMetadataPath:A,error:Q instanceof Error?Q.message:String(Q)})}return null}async function Pd(A){try{return await UT.promises.access(A),!0}catch{return!1}}async function $BA(A,Q){let $=await av0("sqlite3",["-readonly","-json",BBA(A),Q],{timeout:x$A});if($.status!==0)return u.debug("sqlite3 query failed for VS Code database",{status:$.status,stderr:$.stderr?.trim()}),[];let B=$.stdout?.trim();if(!B)return[];try{return JSON.parse(B).filter((J)=>typeof J.key==="string"&&typeof J.value==="string")}catch(D){return u.debug("Failed to parse sqlite3 JSON output for VS Code database",{error:D instanceof Error?D.message:String(D)}),[]}}function BBA(A){let $=A.replaceAll("\\","/").split("/").map((D)=>encodeURIComponent(D)).join("/");return`file:${$.startsWith("/")?$:`/${$}`}?immutable=1`}async function DBA(A){return(await JBA()).find((B)=>FBA(A,B.command))?.pid??null}async function JBA(){if(process.platform==="win32"){let Q=await av0("tasklist",["/FO","CSV"]);if(Q.status!==0)return[];return Q.stdout.split(`
235
235
  `).slice(1).map(($)=>$.trim()).filter(Boolean).map(($)=>{let[B,D]=$.replaceAll('"',"").split(",");return{pid:Number.parseInt(D??"",10),command:B??""}}).filter(($)=>Number.isFinite($.pid)&&$.command)}let A=await av0("ps",["-ax","-o","pid=","-o","command="]);if(A.status!==0)return[];return A.stdout.split(`
@@ -256,7 +256,7 @@ Expected format:
256
256
  [... directory listing truncated, ${V} more ${U4(V,"entry","entries")} not shown ...]`}return{status:"done",progress:{},result:{absolutePath:J.fsPath,content:G,isDirectory:!0,directoryEntries:X}}}if(QL(J)){let Y=await uT(J,D);if(Y.status!=="success")return{status:"error",error:{message:Y.error,absolutePath:J.fsPath}};return{status:"done",progress:{},result:{absolutePath:J.fsPath,content:Y.image.data,isImage:!0,imageInfo:{mimeType:Y.image.mimeType,size:Y.image.size}}}}let E;if(B.read_range&&J.scheme==="file")E=(await QYA(J,B.read_range,D,$)).join(`
257
257
  `);else if(B.read_range){let Z=(await xA(J,{encoding:"utf8",signal:D})).split(`
258
258
  `);E=eEA(Z,B,Q,$)}else{let Y=await sk0(J,{maxBytes:A,signal:D,textProcessing:{addLineNumbers:!0,maxLines:Q,maxLineBytes:$,truncationStrategy:"ellipsis"}});if(Y.error)return{status:"error",error:{message:Y.error.message,absolutePath:J.fsPath}};if(Y.binary)return{status:"error",error:{message:`File appears to be binary and cannot be read as text (${(Y.fileSize/1024).toFixed(1)} KB). Binary files like executables, archives, or compiled assets are not supported by the ${k3} tool.`,absolutePath:J.fsPath}};if(Y.content===void 0){let Z=Math.round(Y.fileSize/1024),U=Math.round(A/1024);return{status:"error",error:{message:`Error: File content (${Z} KB) exceeds maximum allowed size (${U} KB). Use read_range parameters to read specific line ranges in the file, or use the ${_Q} tool to search for specific content.`,absolutePath:J.fsPath}}}E=Y.content}return{status:"done",progress:{},result:{absolutePath:J.fsPath,content:E}}}catch(F){return{status:"error",error:{message:F instanceof Error?F.message:String(F),absolutePath:J.fsPath}}}}}function eEA(A,Q,$,B){let D=A[A.length-1]===""?A.slice(0,-1):A,J={start:0,end:Math.min(D.length,$)},F=Q.read_range?{start:Math.max(0,Q.read_range[0]-1),end:Math.min(D.length,Q.read_range[1])}:J,E=D.slice(F.start,F.end).map((Y)=>Q5.pruneWideLine(Y,B)).map((Y,Z)=>`${Z+F.start+1}: ${Y}`);if(F.start>0)E.unshift(`[... omitted lines 1 to ${F.start} ...]`);if(F.end<D.length)E.push(`[... omitted lines ${F.end+1} to ${D.length} ...]`);return E.join(`
259
- `)}async function n20(A,Q,$){if(Q=Q.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(D,J)=>{return process.env[J]||D}),Q=Q.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(D,J)=>{return process.env[J]||D}),Q.startsWith("~")&&typeof process<"u"&&process.env.HOME)Q=tEA.join(process.env.HOME,Q.slice(1));if(d$(Q))return i0.file(Q);for(let D of A){$?.throwIfAborted();let J=B1.joinPath(D,Q),F=!1;try{await SA(J),F=!0}catch{}if($?.throwIfAborted(),F)return J}let B=A.at(0);if(B)return B1.joinPath(B,Q);return i0.file(Q)}function F9(A){if(!d$(A))throw Error(`Path must be absolute, not relative: ${A}`);return i0.file(A)}function Ap(A){let Q=_$(A),$=S30(Q).slice(1).toLowerCase();if(AYA.includes($))return!1;if(Q===".env.example"||Q===".env.sample")return!1;return/^\.env(\..*)?$/.test(Q)||/^env\..+$/.test(Q)||/\.(env|secret|credentials|envrc)$/i.test(Q)}async function QYA(A,Q,$,B){let D=Q?Math.max(1,Q[0]):1,J=Q?Math.max(D,Q[1]):D+1000-1,F=[],E=0,[{createInterface:Y},{createReadStream:Z}]=await Promise.all([import("node:readline"),import("node:fs")]),U=Y({input:Z(A.fsPath,{encoding:"utf8",highWaterMark:65536}),crlfDelay:1/0}),X=eF($,()=>U.close()),G=20000,V=!1;try{for await(let z of U){if(E++,E<D)continue;if(E>J){if(!V)V=!0;if(E>=G)break;continue}F.push(Q5.pruneWideLine(z,B))}}finally{X(),U.close()}if(D>1)F.unshift(`[... omitted lines 1 to ${D-1} ...]`);if(V){let z=E>=G?`${G}+`:String(E);F.push(`[... omitted lines ${J+1} to ${z} ...]`)}let K=D;return F.map((z)=>z.startsWith("[... omitted lines")?z:`${K++}: ${z}`)}var JH=65536,c64=32768,i20=500,FS0=4096,JS0=1000,AYA;var yQ=r(()=>{Q4();TI();AE();Y5();jA();sd();DH();h4();PT();AYA=["py","js","ts","tsx","jsx","go","rs","cpp","c","cc","cxx","cs","java","scala","rb","php","swift","kt","dart","pl","r","m","mm","h","hpp","lua","zig"]});function n64(A){return`Subagent stopped after reaching the maximum of ${A} turns.`}function a20(A,Q,$){if(A.startsWith("mcp__"))return Q.allowMcp??!1;if(A.startsWith("tb__")){if(!(Q.allowToolbox??!1))return!1;let B="subagentType"in Q?Q.subagentType:void 0;if(B&&$){if(!$.subagentTypes)return!1;return $.subagentTypes.includes("all")||$.subagentTypes.includes(B)}return!0}return Q.includeTools.includes(A)}var YS0,i64,$YA,ZS0,BYA,DYA,JYA=24,FYA=36,EYA,E9;var KX=r(()=>{b$();YS0=["read_github","search_github","commit_search","diff","list_directory_github","list_repositories","glob_github"],i64=["read_bitbucket_enterprise","search_bitbucket_enterprise","commit_search_bitbucket_enterprise","diff_bitbucket_enterprise","list_directory_bitbucket_enterprise","list_repositories_bitbucket_enterprise","glob_bitbucket_enterprise"];$YA=["Grep","glob","Read"],ZS0=["Read","Grep","glob","web_search","read_web_page","read_thread","find_thread"],BYA=["Read","Bash","edit_file","create_file","read_web_page","web_search","finder","skill","task_list","view_media"],DYA=["Read","Grep","glob","web_search","read_web_page","Bash"],EYA=["Read","Grep","glob","Bash"],E9={finder:{key:"finder",displayName:"Finder",model:C2("CLAUDE_HAIKU_4_5"),includeTools:$YA,allowMcp:!1,allowToolbox:!1},oracle:{key:"oracle",displayName:"Oracle",model:C2("GPT_5_4"),includeTools:ZS0,allowMcp:!1,allowToolbox:!1},librarian:{key:"librarian",displayName:"Librarian",model:C2("CLAUDE_SONNET_4_6"),includeTools:YS0,allowMcp:!1,allowToolbox:!1},"task-subagent":{key:"task-subagent",displayName:"Task Subagent",model:void 0,includeTools:BYA,allowMcp:!0,allowToolbox:!0},"code-review":{key:"code-review",displayName:"Code Review",model:C2("GEMINI_3_1_PRO_PREVIEW"),maxTurns:JYA,includeTools:DYA,allowMcp:!1,allowToolbox:!1},"codereview-check":{key:"codereview-check",displayName:"Codereview Check",model:C2("CLAUDE_HAIKU_4_5"),maxTurns:FYA,includeTools:EYA,allowMcp:!1,allowToolbox:!1}}});function o64(A){return{tool:A,action:"allow"}}function YYA(A){if(!A||!("cmd"in A))return A;let{cmd:Q,...$}=A;return{...$,command:Q}}function ZYA(A){return A.flatMap((Q)=>{if(Q.tool!==IA)return[];return[{...Q,tool:u8,matches:YYA(Q.matches)}]})}var a64,_T;var o20=r(()=>{h4();a64=[{tool:"Bash",action:"ask",matches:{cmd:"*git*push*"}},{tool:"Bash",action:"allow",matches:{cmd:"/rg\\s+[-;(]+/"}},{tool:"mcp__*",action:"allow"},{tool:j50,action:"allow"},{tool:"tb__*",action:"allow"},{tool:"Bash",matches:{cmd:"/^(.*\\s+)?(bazel|ibazel)\\s+.*\\/\\/[^\\s]*.*$/"},action:"allow"},{tool:"Bash",matches:{cmd:["ls","ls *","dir","dir *","cat *","head *","tail *","less *","more *","grep *","egrep *","fgrep *","tree","tree *","file *","wc *","pwd","stat *","du *","df *","ps *","top","htop","echo *","printenv *","id","which *","whereis *","date","cal *","uptime","free *","ping *","dig *","nslookup *","host *","netstat *","ss *","lsof *","ifconfig *","ip *","man *","info *","mkdir *","touch *","uname *","whoami","go version","go env *","go help *","cargo version","cargo --version","cargo help *","rustc --version","rustc --help","rustc --explain *","javac --version","javac -version","javac -help","javac --help","dotnet --info","dotnet --version","dotnet --help","dotnet help *","gcc --version","gcc -v","gcc --help","gcc -dumpversion","g++ --version","g++ -v","g++ --help","g++ -dumpversion","clang --version","clang --help","clang++ --version","clang++ --help","python -V","python --version","python -h","python --help","python3 -V","python3 --version","python3 -h","python3 --help","ruby -v","ruby --version","ruby -h","ruby --help","node -v","node --version","node -h","node --help","npm --help","npm --version","npm -v","npm help *","yarn --help","yarn --version","yarn -v","yarn help *","pnpm --help","pnpm --version","pnpm -v","pnpm help *","pytest -h","pytest --help","pytest --version","jest --help","jest --version","mocha --help","mocha --version","make --version","make --help","docker --version","docker --help","docker version","docker help *","git --version","git --help","git help *","git version"]},action:"allow"},{tool:"Bash",matches:{cmd:["go test *","go run *","go build *","go vet *","go fmt *","go list *","cargo test *","cargo run *","cargo build *","cargo check *","cargo fmt *","cargo tree *","make -n *","make --dry-run *","mvn test *","mvn verify *","mvn dependency:tree *","gradle tasks *","gradle dependencies *","gradle properties *","dotnet test *","dotnet list *","python -c *","ruby -e *","node -e *","npm list *","npm ls *","npm outdated *","npm test*","npm run*","npm view *","npm info *","yarn list*","yarn ls *","yarn info *","yarn test*","yarn run *","yarn why *","pnpm list*","pnpm ls *","pnpm outdated *","pnpm test*","pnpm run *","pytest --collect-only *","jest --listTests *","jest --showConfig *","mocha --list *","git status*","git show *","git diff*","git grep *","git branch *","git tag *","git remote -v *","git rev-parse --is-inside-work-tree *","git rev-parse --show-toplevel *","git config --list *","git log *"]},action:"allow"},{tool:"Bash",matches:{cmd:["./gradlew *","./mvnw *","./build.sh *","./configure *","cmake *","./node_modules/.bin/tsc *","./node_modules/.bin/eslint *","./node_modules/.bin/prettier *","prettier *","./node_modules/.bin/tailwindcss *","./node_modules/.bin/tsx *","./node_modules/.bin/vite *","bun *","tsx *","vite *"]},action:"allow"},{tool:"Bash",matches:{cmd:[".venv/bin/activate *",".venv/Scripts/activate *","source .venv/bin/activate *","source venv/bin/activate *","pip list *","pip show *","pip check *","pip freeze *","uv *","poetry show *","poetry check *","pipenv check *"]},action:"allow"},{tool:"Bash",matches:{cmd:["asdf list *","asdf current *","asdf which *","mise list *","mise current *","mise which *","mise use *","rbenv version *","rbenv versions *","rbenv which *","nvm list *","nvm current *","nvm which *"]},action:"allow"},{tool:"Bash",matches:{cmd:["./test*","./run_tests.sh *","./run_*_tests.sh *","vitest *","bundle exec rspec *","bundle exec rubocop *","rspec *","rubocop *","swiftlint *","clippy *","ruff *","black *","isort *","mypy *","flake8 *","bandit *","safety *","biome check *","biome format *"]},action:"allow"},{tool:"Bash",matches:{cmd:["rails server *","rails s *","bin/rails server *","bin/rails s *","flask run *","django-admin runserver *","python manage.py runserver *","uvicorn *","streamlit run *"]},action:"allow"},{tool:"Bash",matches:{cmd:["bin/rails db:status","bin/rails db:version","rails db:rollback *","rails db:status *","rails db:version *","alembic current *","alembic history *","bundle exec rails db:status","bundle exec rails db:version"]},action:"allow"},{tool:"Bash",matches:{cmd:["docker ps *","docker images *","docker logs *","docker inspect *","docker info *","docker stats *","docker system df *","docker system info *","podman ps *","podman images *","podman logs *","podman inspect *","podman info *"]},action:"allow"},{tool:"Bash",matches:{cmd:["aws --version *","aws configure list *","aws sts get-caller-identity *","aws s3 ls *","gcloud config list *","gcloud auth list *","gcloud projects list *","az account list *","az account show *","kubectl get *","kubectl describe *","kubectl logs *","kubectl version *","helm list *","helm status *","helm version *"]},action:"allow"},{tool:"Bash",matches:{cmd:["swift build *","swift test *","zig build *","zig build test*","kotlinc *","scalac *","javac *","javap *","clang *","jar *","sbt *","gradle *","bazel build *","bazel test *","bazel run *","mix *","lua *","ruby *","php *"]},action:"allow"},{tool:"Bash",matches:{cmd:["mkdir -p *","chmod +x *","dos2unix *","unix2dos *","ln -s *"]},action:"allow"},{tool:"Bash",matches:{cmd:["for *","while *","do *","done *","if *","then *","else *","elif *","fi *","case *","esac *","in *","function *","select *","until *","{ *","} *","[[ *","]] *"]},action:"ask"},{tool:"Bash",matches:{cmd:"/^find(?!.*(-delete|-exec|-execdir)).*$/"},action:"allow"},{tool:"Bash",matches:{cmd:"/^(echo|ls|pwd|date|whoami|id|uname)\\s.*[&|;].*\\s*(echo|ls|pwd|date|whoami|id|uname)($|\\s.*)/"},action:"allow"},{tool:"Bash",matches:{cmd:"/^(cat|grep|head|tail|less|more|find)\\s.*\\|\\s*(grep|head|tail|less|more|wc|sort|uniq)($|\\s.*)/"},action:"allow"},{tool:"Bash",matches:{cmd:"/^rm\\s+.*(-[rf].*-[rf]|-[rf]{2,}|--recursive.*--force|--force.*--recursive).*$/"},action:"ask"},{tool:"Bash",matches:{cmd:"/^find.*(-delete|-exec|-execdir).*$/"},action:"ask"},{tool:"Bash",matches:{cmd:"/^(ls|cat|grep|head|tail|file|stat)\\s+[^/]*$/"},action:"allow"},{tool:"Bash",matches:{cmd:"/(^|\\s)(\\/(?!dev\\/(null|zero|stdout|stderr|stdin))[^\\s]*|\\.\\.\\/)(?![^\\s]*\\.(log|txt|md|json|yml|yaml)$)/"},action:"ask"},{tool:"Bash",action:"ask"},o64("Glob")],_T=[...a64,...ZYA(a64),...ne1.map(o64)]});class r64{input;position=0;line=1;column=1;tokens=[];constructor(A){this.input=A}current(){return this.position<this.input.length?this.input[this.position]:""}peek(){return this.position+1<this.input.length?this.input[this.position+1]:""}advance(){let A=this.current();if(this.position++,A===`
259
+ `)}async function n20(A,Q,$){if(Q=Q.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(D,J)=>{return process.env[J]||D}),Q=Q.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(D,J)=>{return process.env[J]||D}),Q.startsWith("~")&&typeof process<"u"&&process.env.HOME)Q=tEA.join(process.env.HOME,Q.slice(1));if(d$(Q))return i0.file(Q);for(let D of A){$?.throwIfAborted();let J=B1.joinPath(D,Q),F=!1;try{await SA(J),F=!0}catch{}if($?.throwIfAborted(),F)return J}let B=A.at(0);if(B)return B1.joinPath(B,Q);return i0.file(Q)}function F9(A){if(!d$(A))throw Error(`Path must be absolute, not relative: ${A}`);return i0.file(A)}function Ap(A){let Q=_$(A),$=S30(Q).slice(1).toLowerCase();if(AYA.includes($))return!1;if(Q===".env.example"||Q===".env.sample")return!1;return/^\.env(\..*)?$/.test(Q)||/^env\..+$/.test(Q)||/\.(env|secret|credentials|envrc)$/i.test(Q)}async function QYA(A,Q,$,B){let D=Q?Math.max(1,Q[0]):1,J=Q?Math.max(D,Q[1]):D+1000-1,F=[],E=0,[{createInterface:Y},{createReadStream:Z}]=await Promise.all([import("node:readline"),import("node:fs")]),U=Y({input:Z(A.fsPath,{encoding:"utf8",highWaterMark:65536}),crlfDelay:1/0}),X=eF($,()=>U.close()),G=20000,V=!1;try{for await(let z of U){if(E++,E<D)continue;if(E>J){if(!V)V=!0;if(E>=G)break;continue}F.push(Q5.pruneWideLine(z,B))}}finally{X(),U.close()}if(D>1)F.unshift(`[... omitted lines 1 to ${D-1} ...]`);if(V){let z=E>=G?`${G}+`:String(E);F.push(`[... omitted lines ${J+1} to ${z} ...]`)}let K=D;return F.map((z)=>z.startsWith("[... omitted lines")?z:`${K++}: ${z}`)}var JH=65536,c64=32768,i20=500,FS0=4096,JS0=1000,AYA;var yQ=r(()=>{Q4();TI();AE();Y5();jA();sd();DH();h4();PT();AYA=["py","js","ts","tsx","jsx","go","rs","cpp","c","cc","cxx","cs","java","scala","rb","php","swift","kt","dart","pl","r","m","mm","h","hpp","lua","zig"]});function n64(A){return`Subagent stopped after reaching the maximum of ${A} turns.`}function a20(A,Q,$){if(A.startsWith("mcp__"))return Q.allowMcp??!1;if(A.startsWith("tb__")){if(!(Q.allowToolbox??!1))return!1;let B="subagentType"in Q?Q.subagentType:void 0;if(B&&$){if(!$.subagentTypes)return!1;return $.subagentTypes.includes("all")||$.subagentTypes.includes(B)}return!0}return Q.includeTools.includes(A)}var YS0,i64,$YA,ZS0,BYA,DYA,JYA=24,FYA=36,EYA,E9;var KX=r(()=>{b$();YS0=["read_github","search_github","commit_search","diff","list_directory_github","list_repositories","glob_github"],i64=["read_bitbucket_enterprise","search_bitbucket_enterprise","commit_search_bitbucket_enterprise","diff_bitbucket_enterprise","list_directory_bitbucket_enterprise","list_repositories_bitbucket_enterprise","glob_bitbucket_enterprise"];$YA=["Grep","glob","Read"],ZS0=["Read","Grep","glob","web_search","read_web_page","read_thread","find_thread"],BYA=["Read","Bash","edit_file","create_file","read_web_page","web_search","finder","skill","task_list","view_media"],DYA=["Read","Grep","glob","web_search","read_web_page","Bash"],EYA=["Read","Grep","glob","Bash"],E9={finder:{key:"finder",displayName:"Finder",model:C2("CLAUDE_HAIKU_4_5"),includeTools:$YA,allowMcp:!1,allowToolbox:!1},oracle:{key:"oracle",displayName:"Oracle",model:C2("GPT_5_5"),includeTools:ZS0,allowMcp:!1,allowToolbox:!1},librarian:{key:"librarian",displayName:"Librarian",model:C2("CLAUDE_SONNET_4_6"),includeTools:YS0,allowMcp:!1,allowToolbox:!1},"task-subagent":{key:"task-subagent",displayName:"Task Subagent",model:void 0,includeTools:BYA,allowMcp:!0,allowToolbox:!0},"code-review":{key:"code-review",displayName:"Code Review",model:C2("GEMINI_3_1_PRO_PREVIEW"),maxTurns:JYA,includeTools:DYA,allowMcp:!1,allowToolbox:!1},"codereview-check":{key:"codereview-check",displayName:"Codereview Check",model:C2("CLAUDE_HAIKU_4_5"),maxTurns:FYA,includeTools:EYA,allowMcp:!1,allowToolbox:!1}}});function o64(A){return{tool:A,action:"allow"}}function YYA(A){if(!A||!("cmd"in A))return A;let{cmd:Q,...$}=A;return{...$,command:Q}}function ZYA(A){return A.flatMap((Q)=>{if(Q.tool!==IA)return[];return[{...Q,tool:u8,matches:YYA(Q.matches)}]})}var a64,_T;var o20=r(()=>{h4();a64=[{tool:"Bash",action:"ask",matches:{cmd:"*git*push*"}},{tool:"Bash",action:"allow",matches:{cmd:"/rg\\s+[-;(]+/"}},{tool:"mcp__*",action:"allow"},{tool:j50,action:"allow"},{tool:"tb__*",action:"allow"},{tool:"Bash",matches:{cmd:"/^(.*\\s+)?(bazel|ibazel)\\s+.*\\/\\/[^\\s]*.*$/"},action:"allow"},{tool:"Bash",matches:{cmd:["ls","ls *","dir","dir *","cat *","head *","tail *","less *","more *","grep *","egrep *","fgrep *","tree","tree *","file *","wc *","pwd","stat *","du *","df *","ps *","top","htop","echo *","printenv *","id","which *","whereis *","date","cal *","uptime","free *","ping *","dig *","nslookup *","host *","netstat *","ss *","lsof *","ifconfig *","ip *","man *","info *","mkdir *","touch *","uname *","whoami","go version","go env *","go help *","cargo version","cargo --version","cargo help *","rustc --version","rustc --help","rustc --explain *","javac --version","javac -version","javac -help","javac --help","dotnet --info","dotnet --version","dotnet --help","dotnet help *","gcc --version","gcc -v","gcc --help","gcc -dumpversion","g++ --version","g++ -v","g++ --help","g++ -dumpversion","clang --version","clang --help","clang++ --version","clang++ --help","python -V","python --version","python -h","python --help","python3 -V","python3 --version","python3 -h","python3 --help","ruby -v","ruby --version","ruby -h","ruby --help","node -v","node --version","node -h","node --help","npm --help","npm --version","npm -v","npm help *","yarn --help","yarn --version","yarn -v","yarn help *","pnpm --help","pnpm --version","pnpm -v","pnpm help *","pytest -h","pytest --help","pytest --version","jest --help","jest --version","mocha --help","mocha --version","make --version","make --help","docker --version","docker --help","docker version","docker help *","git --version","git --help","git help *","git version"]},action:"allow"},{tool:"Bash",matches:{cmd:["go test *","go run *","go build *","go vet *","go fmt *","go list *","cargo test *","cargo run *","cargo build *","cargo check *","cargo fmt *","cargo tree *","make -n *","make --dry-run *","mvn test *","mvn verify *","mvn dependency:tree *","gradle tasks *","gradle dependencies *","gradle properties *","dotnet test *","dotnet list *","python -c *","ruby -e *","node -e *","npm list *","npm ls *","npm outdated *","npm test*","npm run*","npm view *","npm info *","yarn list*","yarn ls *","yarn info *","yarn test*","yarn run *","yarn why *","pnpm list*","pnpm ls *","pnpm outdated *","pnpm test*","pnpm run *","pytest --collect-only *","jest --listTests *","jest --showConfig *","mocha --list *","git status*","git show *","git diff*","git grep *","git branch *","git tag *","git remote -v *","git rev-parse --is-inside-work-tree *","git rev-parse --show-toplevel *","git config --list *","git log *"]},action:"allow"},{tool:"Bash",matches:{cmd:["./gradlew *","./mvnw *","./build.sh *","./configure *","cmake *","./node_modules/.bin/tsc *","./node_modules/.bin/eslint *","./node_modules/.bin/prettier *","prettier *","./node_modules/.bin/tailwindcss *","./node_modules/.bin/tsx *","./node_modules/.bin/vite *","bun *","tsx *","vite *"]},action:"allow"},{tool:"Bash",matches:{cmd:[".venv/bin/activate *",".venv/Scripts/activate *","source .venv/bin/activate *","source venv/bin/activate *","pip list *","pip show *","pip check *","pip freeze *","uv *","poetry show *","poetry check *","pipenv check *"]},action:"allow"},{tool:"Bash",matches:{cmd:["asdf list *","asdf current *","asdf which *","mise list *","mise current *","mise which *","mise use *","rbenv version *","rbenv versions *","rbenv which *","nvm list *","nvm current *","nvm which *"]},action:"allow"},{tool:"Bash",matches:{cmd:["./test*","./run_tests.sh *","./run_*_tests.sh *","vitest *","bundle exec rspec *","bundle exec rubocop *","rspec *","rubocop *","swiftlint *","clippy *","ruff *","black *","isort *","mypy *","flake8 *","bandit *","safety *","biome check *","biome format *"]},action:"allow"},{tool:"Bash",matches:{cmd:["rails server *","rails s *","bin/rails server *","bin/rails s *","flask run *","django-admin runserver *","python manage.py runserver *","uvicorn *","streamlit run *"]},action:"allow"},{tool:"Bash",matches:{cmd:["bin/rails db:status","bin/rails db:version","rails db:rollback *","rails db:status *","rails db:version *","alembic current *","alembic history *","bundle exec rails db:status","bundle exec rails db:version"]},action:"allow"},{tool:"Bash",matches:{cmd:["docker ps *","docker images *","docker logs *","docker inspect *","docker info *","docker stats *","docker system df *","docker system info *","podman ps *","podman images *","podman logs *","podman inspect *","podman info *"]},action:"allow"},{tool:"Bash",matches:{cmd:["aws --version *","aws configure list *","aws sts get-caller-identity *","aws s3 ls *","gcloud config list *","gcloud auth list *","gcloud projects list *","az account list *","az account show *","kubectl get *","kubectl describe *","kubectl logs *","kubectl version *","helm list *","helm status *","helm version *"]},action:"allow"},{tool:"Bash",matches:{cmd:["swift build *","swift test *","zig build *","zig build test*","kotlinc *","scalac *","javac *","javap *","clang *","jar *","sbt *","gradle *","bazel build *","bazel test *","bazel run *","mix *","lua *","ruby *","php *"]},action:"allow"},{tool:"Bash",matches:{cmd:["mkdir -p *","chmod +x *","dos2unix *","unix2dos *","ln -s *"]},action:"allow"},{tool:"Bash",matches:{cmd:["for *","while *","do *","done *","if *","then *","else *","elif *","fi *","case *","esac *","in *","function *","select *","until *","{ *","} *","[[ *","]] *"]},action:"ask"},{tool:"Bash",matches:{cmd:"/^find(?!.*(-delete|-exec|-execdir)).*$/"},action:"allow"},{tool:"Bash",matches:{cmd:"/^(echo|ls|pwd|date|whoami|id|uname)\\s.*[&|;].*\\s*(echo|ls|pwd|date|whoami|id|uname)($|\\s.*)/"},action:"allow"},{tool:"Bash",matches:{cmd:"/^(cat|grep|head|tail|less|more|find)\\s.*\\|\\s*(grep|head|tail|less|more|wc|sort|uniq)($|\\s.*)/"},action:"allow"},{tool:"Bash",matches:{cmd:"/^rm\\s+.*(-[rf].*-[rf]|-[rf]{2,}|--recursive.*--force|--force.*--recursive).*$/"},action:"ask"},{tool:"Bash",matches:{cmd:"/^find.*(-delete|-exec|-execdir).*$/"},action:"ask"},{tool:"Bash",matches:{cmd:"/^(ls|cat|grep|head|tail|file|stat)\\s+[^/]*$/"},action:"allow"},{tool:"Bash",matches:{cmd:"/(^|\\s)(\\/(?!dev\\/(null|zero|stdout|stderr|stdin))[^\\s]*|\\.\\.\\/)(?![^\\s]*\\.(log|txt|md|json|yml|yaml)$)/"},action:"ask"},{tool:"Bash",action:"ask"},o64("Glob")],_T=[...a64,...ZYA(a64),...ne1.map(o64)]});class r64{input;position=0;line=1;column=1;tokens=[];constructor(A){this.input=A}current(){return this.position<this.input.length?this.input[this.position]:""}peek(){return this.position+1<this.input.length?this.input[this.position+1]:""}advance(){let A=this.current();if(this.position++,A===`
260
260
  `)this.line++,this.column=1;else this.column++;return A}skipWhitespace(){while(this.current()&&/\s/.test(this.current())&&this.current()!==`
261
261
  `)this.advance()}readString(){let A="",Q=this.current();this.advance();while(this.current()&&this.current()!==Q)if(this.current()==="\\"&&this.peek()===Q)this.advance(),A+=this.advance();else A+=this.advance();if(!this.current())throw Error("Unterminated string");return this.advance(),A}readIdentifier(){let A="";if(this.current()==="-"&&/\d/.test(this.peek()))A+=this.advance();while(this.current()&&/[a-zA-Z0-9_*.-]/.test(this.current()))A+=this.advance();if((this.current()==="e"||this.current()==="E")&&/[-+]?\d/.test(this.peek())){if(A+=this.advance(),this.current()==="+"||this.current()==="-")A+=this.advance();while(this.current()&&/\d/.test(this.current()))A+=this.advance()}return A}readFlag(){let A="";this.advance(),this.advance();while(this.current()&&/[a-zA-Z0-9_*:.-]/.test(this.current()))A+=this.advance();return A}readComment(){let A="";this.advance();while(this.current()&&this.current()!==`
262
262
  `)A+=this.advance();return A.trim()}tokenize(){this.tokens=[];while(this.position<this.input.length){let A={position:this.position,line:this.line,column:this.column};if(this.skipWhitespace(),!this.current())break;if(this.current()==="'"||this.current()==='"'){try{let Q=this.readString();this.tokens.push({type:"STRING",value:Q,...A})}catch(Q){throw Error(`Parse error at line ${this.line}, column ${this.column}: ${Q}`)}continue}if(this.current()===`
@@ -1840,7 +1840,7 @@ engineer who can't ask follow-ups once started.
1840
1840
 
1841
1841
  ### Oracle
1842
1842
 
1843
- - Senior engineering advisor with GPT-5.4 reasoning model for reviews, architecture, deep debugging, and
1843
+ - Senior engineering advisor with GPT-5.5 reasoning model for reviews, architecture, deep debugging, and
1844
1844
  planning.
1845
1845
  - Use for: Code reviews, architecture decisions, performance analysis, complex debugging, planning Task Tool runs
1846
1846
  - Don't use for: Simple file searches, bulk code execution
@@ -2079,7 +2079,7 @@ engineer who can't ask follow-ups once started.
2079
2079
 
2080
2080
  ### Oracle
2081
2081
 
2082
- - Senior engineering advisor with GPT-5.4 reasoning model for reviews, architecture, deep debugging, and
2082
+ - Senior engineering advisor with GPT-5.5 reasoning model for reviews, architecture, deep debugging, and
2083
2083
  planning.
2084
2084
  - Use for: Code reviews, architecture decisions, performance analysis, complex debugging, planning Task Tool runs
2085
2085
  - Don't use for: Simple file searches, bulk code execution
@@ -4293,7 +4293,7 @@ Guidelines:
4293
4293
  - Consider alternatives and trade-offs, but limit them per the principles above.
4294
4294
  - Be thorough but concise—focus on the highest-leverage insights.
4295
4295
 
4296
- IMPORTANT: Only your last message is returned to the main agent and displayed to the user. Your last message should be comprehensive yet focused, with a clear, simple recommendation that helps the user act immediately.`}var GJ2=za0(null,null);function Fj4(A,Q){switch(A.status){case"in-progress":return{status:"in-progress",progress:A.turns.map(($)=>({message:$.message,reasoning:$.reasoning,isThinking:$.isThinking,tool_uses:[...$.activeTools.values()]}))};case"done":return{status:"done",result:A.message,progress:A.turns.map(($)=>({message:$.message,reasoning:$.reasoning,isThinking:!1,tool_uses:[...$.activeTools.values()]})),"~debug":{...A["~debug"],reasoningEffort:Q}};case"error":return{status:"error",error:{message:A.message}};case"cancelled":return{status:"cancelled"}}}var L23=[{description:"Review the authentication system architecture and suggest improvements",args:{task:"Review the authentication architecture and suggest improvements",files:["src/auth/index.ts","src/auth/jwt.ts"]}},{description:"Plan the implementation of real-time collaboration features",args:{task:"Plan the implementation of real-time collaboration feature"}},{description:"Analyze the performance bottlenecks in the data processing pipeline",args:{task:"Analyze performance bottlenecks",context:"Users report slow response times when processing large datasets"}},{description:"Review this API design and suggest better patterns",args:{task:"Review API design",context:"This is a REST API for user management",files:["src/api/users.ts"]}},{description:"Debug failing tests after refactor",args:{task:"Help debug why tests are failing",context:'Tests fail with "undefined is not a function" after refactoring the auth module',files:["src/auth/auth.test.ts"]}}],O23=({args:A},Q)=>{let $=Dj4(Q.config.settings);return F6(async()=>{let B=await k1(Q.configService.workspaceRoot),D=B?c3(B):null,J=Q.dir?c3(Q.dir):D,F=za0(J,D??J);return{fileMentions:await nQ0(A.files??[],{searchPaths:B?[B]:[]}),systemPrompt:F}}).pipe(y4(({fileMentions:B,systemPrompt:D})=>{if(!A.task)throw Error('Missing required parameter "task"');let J=Jj4({task:A.task,context:A.context,parentThreadID:Q.thread.id},B?ZD(B):void 0),F=g04(Q.config.settings);return u.debug("Oracle starting consultation:",{model:F,reasoningEffort:$,task:A.task.substring(0,100)+(A.task.length>100?"...":""),hasContext:!!A.context,files:B?.files.map((Y)=>({uri:Y.uri,isImage:Y.isImage,imageInfo:Y.imageInfo}))}),new FQ().run(XF0,{systemPrompt:D,model:F,spec:E9.oracle},{conversation:GF0(J,{imageBlocks:B?.imageBlocks,reasoningEffort:$}),toolService:Q.toolService,env:Q})}),N1((B)=>Fj4(B,$)))},Ej4={spec:{name:t2,description:`Consult the oracle - an AI advisor powered by OpenAI's GPT-5.4 reasoning model that can plan, review, and provide expert guidance.
4296
+ IMPORTANT: Only your last message is returned to the main agent and displayed to the user. Your last message should be comprehensive yet focused, with a clear, simple recommendation that helps the user act immediately.`}var GJ2=za0(null,null);function Fj4(A,Q){switch(A.status){case"in-progress":return{status:"in-progress",progress:A.turns.map(($)=>({message:$.message,reasoning:$.reasoning,isThinking:$.isThinking,tool_uses:[...$.activeTools.values()]}))};case"done":return{status:"done",result:A.message,progress:A.turns.map(($)=>({message:$.message,reasoning:$.reasoning,isThinking:!1,tool_uses:[...$.activeTools.values()]})),"~debug":{...A["~debug"],reasoningEffort:Q}};case"error":return{status:"error",error:{message:A.message}};case"cancelled":return{status:"cancelled"}}}var L23=[{description:"Review the authentication system architecture and suggest improvements",args:{task:"Review the authentication architecture and suggest improvements",files:["src/auth/index.ts","src/auth/jwt.ts"]}},{description:"Plan the implementation of real-time collaboration features",args:{task:"Plan the implementation of real-time collaboration feature"}},{description:"Analyze the performance bottlenecks in the data processing pipeline",args:{task:"Analyze performance bottlenecks",context:"Users report slow response times when processing large datasets"}},{description:"Review this API design and suggest better patterns",args:{task:"Review API design",context:"This is a REST API for user management",files:["src/api/users.ts"]}},{description:"Debug failing tests after refactor",args:{task:"Help debug why tests are failing",context:'Tests fail with "undefined is not a function" after refactoring the auth module',files:["src/auth/auth.test.ts"]}}],O23=({args:A},Q)=>{let $=Dj4(Q.config.settings);return F6(async()=>{let B=await k1(Q.configService.workspaceRoot),D=B?c3(B):null,J=Q.dir?c3(Q.dir):D,F=za0(J,D??J);return{fileMentions:await nQ0(A.files??[],{searchPaths:B?[B]:[]}),systemPrompt:F}}).pipe(y4(({fileMentions:B,systemPrompt:D})=>{if(!A.task)throw Error('Missing required parameter "task"');let J=Jj4({task:A.task,context:A.context,parentThreadID:Q.thread.id},B?ZD(B):void 0),F=g04(Q.config.settings);return u.debug("Oracle starting consultation:",{model:F,reasoningEffort:$,task:A.task.substring(0,100)+(A.task.length>100?"...":""),hasContext:!!A.context,files:B?.files.map((Y)=>({uri:Y.uri,isImage:Y.isImage,imageInfo:Y.imageInfo}))}),new FQ().run(XF0,{systemPrompt:D,model:F,spec:E9.oracle},{conversation:GF0(J,{imageBlocks:B?.imageBlocks,reasoningEffort:$}),toolService:Q.toolService,env:Q})}),N1((B)=>Fj4(B,$)))},Ej4={spec:{name:t2,description:`Consult the oracle - an AI advisor powered by OpenAI's GPT-5.5 reasoning model that can plan, review, and provide expert guidance.
4297
4297
 
4298
4298
  The oracle has access to the following tools:
4299
4299
  - ${ZS0.join(`
@@ -4791,13 +4791,13 @@ ${z}`))}},error:(K)=>{if(!V)V=!0,Z(Error(`Failed to spawn brew: ${K.message}`))}
4791
4791
  ${z}`;if(F==="pnpm"&&z.includes("Unable to find the global bin directory"))W+=`
4792
4792
 
4793
4793
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4794
- npm install -g ${J}`;Z(Error(W))}},error:(K)=>{if(!G)G=!0,Z(Error(`Failed to spawn ${F}: ${K.message}`))},complete:()=>{if(!G)G=!0,Y()}})})}p0();p0();Fz();var kq3="@ampcode/cli";async function UY0(A,Q,$=kq3){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,J=new AbortController,F=setTimeout(()=>J.abort(),5000);try{let E=await fetch(D,{signal:J.signal});if(!E.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await E.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=Po(A,Z),X=U<0,G,V;if(Y.time){let K=Y.time[A],z=Y.time[Z],W=Date.now();if(K)G=Math.floor((W-new Date(K).getTime())/3600000);if(z)V=Math.floor((W-new Date(z).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:U,hasUpdate:X,currentVersionAge:G,latestVersionAge:V}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:G,latestVersionAge:V,source:"npm"}}catch(E){return u.debug("Error checking npm version",{error:E}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var Sq3="https://static.ampcode.com/cli/cli-version.txt";async function XY0(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${Sq3}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=(await B.text()).trim();if(!D||!/^\d+\.\d+\.\d+/.test(D))return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=Po(A,D),F=J<0;return u.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:J,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return u.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}var fq3=604800000;function Iy4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let $=Date.now()-Q;if($>fq3)return{ageMs:$};return null}function Po(A,Q){let $=(F)=>{let[E,Y]=F.split("-");return{parts:E?.split(".").map(Number)||[],label:Y}},B=$(A),D=$(Q),J=Math.max(B.parts.length,D.parts.length);for(let F=0;F<J;F++){let E=B.parts[F]||0,Y=D.parts[F]||0;if(E<Y)return-1;if(E>Y)return 1}if(B.label===D.label)return 0;if(!B.label&&D.label)return 1;if(B.label&&!D.label)return-1;if(B.label&&D.label)return B.label<D.label?-1:1;return 0}function _o(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,J=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?RE(B):void 0;return{sha:J,timestamp:B,age:F}}catch{return null}}u1();p0();import{readFile as yq3,realpath as xq3}from"node:fs/promises";import{dirname as Hy4,join as bq3}from"node:path";async function qy4(A){switch(A){case"binary":case"brew":return hq3(Ro());case"npm":case"pnpm":case"yarn":case"bun":return gq3()}}async function hq3(A){let Q=await KN(A,["--version"],5000);if(Q.reason!=="success")return u.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function gq3(){try{let A=process.argv[1];if(!A)return null;let Q=await xq3(A),$=Hy4(Hy4(Q));return await mq3(bq3($,"package.json"))}catch(A){return u.debug("failed to read installed version from package.json",{error:A}),null}}async function mq3(A){let Q=await yq3(A,"utf8"),$=JSON.parse(Q);if(!$.name||!St0($.name))return u.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}p0();import{spawn as dq3}from"node:child_process";function mt0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return u.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var GY0=null,To=null;function Ny4(A){return new Promise((Q)=>{let $=dq3("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(D)=>{B+=D.toString()}),$.on("close",(D,J)=>{if(D!==0||J==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function VY0(){if(GY0)return GY0;if(To)return To;To=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return mt0(A);let Q=await Ny4("@sourcegraph:registry");if(Q)return mt0(Q);let $=await Ny4("registry");if($)return mt0($);return"https://registry.npmjs.org"})();try{return GY0=await To,GY0}finally{To=null}}var pq3=3600000,cq3=5000;function KY0(A,Q,$={}){let B=new d4,D=B.pipe(t6({shouldCountRefs:!1})),J=$.startDelayMs??0,F=$.checkIntervalMs??pq3,E=!1,Y=()=>{E=!0};return setImmediate(async()=>{let Z=u.getChild("update");if(J>0){if(await sX(J),E)return}let U=D.subscribe({next:(G)=>{Z.debug("emit new state",G)}}),X=A;try{while(!E){let G=await lq3(X,Q,Z,B);if(G.stop)return;if(G.updatedTo)X=G.updatedTo;if(G.emittedVisibleState){if(await sX(cq3),E)return;B.next("hidden")}if(F<=0)return;let V=1000,K=F;while(K>0&&!E){let z=Math.min(V,K);await sX(z),K-=z}}}finally{U.unsubscribe(),B.complete()}}),{state:D,dispose:Y}}async function lq3(A,Q,$,B){let D={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),D.stop=!0,D;let J=await Q.get("updates.mode");if(J==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await jG(),E=F==="binary"||F==="brew",Y=E?void 0:await zN();$.debug("checking",{currentVersion:A,mode:J,packageManager:F,isBinaryDistribution:E,npmPackageName:Y});let Z;if(E)Z=await XY0(A);else{let G=await VY0();Z=await UY0(A,G,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),D;let U=(G)=>{B.next(G),D.emittedVisibleState=!0};if(F){let G=await qy4(F);if(G&&Po(G,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:G,latestVersion:Z.latestVersion}),D.updatedTo=G,Po(A,G)<0){let V=await Tz(G),K={from:A,to:G,externallyUpdated:!0,...V};if(V.status==="same")$.info("on-disk already updated by another instance",K),U("updated");else $.warn("on-disk already updated by another instance, with PATH warning",K),U("updated-with-warning")}return D}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let G=Z.currentVersionAge-Z.latestVersionAge,V=0.5;if(Math.abs(G)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:G}),!0}return!1};if(!J)J=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:J});if(F==="brew"){if(!X())U("update-available-brew");return D}if(F==="binary"&&process.execPath!==Ro()){if($.debug("non-standard binary path, showing warning"),!X())U("update-available-unrecognized-path");return D}if(J==="warn"){if(!X())U("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())U("update-available");return D}try{await uo(Z.latestVersion,F),D.updatedTo=Z.latestVersion;let G=await Tz(Z.latestVersion),V={from:Z.currentVersion,to:Z.latestVersion,...G};if(G.status==="same")$.info("success",V),U("updated");else $.warn("success with warning",V),U("updated-with-warning")}catch(G){U("update-error")}return D}catch(J){return $.debug("check failed",{error:J}),D}}Fz();import{stderr as pE}from"node:process";function Cy4(A){let Q=new oq().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 vt0(B.force||!1,B.verbose||!1,"0.0.1779668338-g19be90"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new oq("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 aq3(B.targetVersion)});A.addCommand($)}function iq3(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4794
+ npm install -g ${J}`;Z(Error(W))}},error:(K)=>{if(!G)G=!0,Z(Error(`Failed to spawn ${F}: ${K.message}`))},complete:()=>{if(!G)G=!0,Y()}})})}p0();p0();Fz();var kq3="@ampcode/cli";async function UY0(A,Q,$=kq3){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,J=new AbortController,F=setTimeout(()=>J.abort(),5000);try{let E=await fetch(D,{signal:J.signal});if(!E.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await E.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=Po(A,Z),X=U<0,G,V;if(Y.time){let K=Y.time[A],z=Y.time[Z],W=Date.now();if(K)G=Math.floor((W-new Date(K).getTime())/3600000);if(z)V=Math.floor((W-new Date(z).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:U,hasUpdate:X,currentVersionAge:G,latestVersionAge:V}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:G,latestVersionAge:V,source:"npm"}}catch(E){return u.debug("Error checking npm version",{error:E}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var Sq3="https://static.ampcode.com/cli/cli-version.txt";async function XY0(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${Sq3}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=(await B.text()).trim();if(!D||!/^\d+\.\d+\.\d+/.test(D))return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=Po(A,D),F=J<0;return u.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:J,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return u.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}var fq3=604800000;function Iy4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let $=Date.now()-Q;if($>fq3)return{ageMs:$};return null}function Po(A,Q){let $=(F)=>{let[E,Y]=F.split("-");return{parts:E?.split(".").map(Number)||[],label:Y}},B=$(A),D=$(Q),J=Math.max(B.parts.length,D.parts.length);for(let F=0;F<J;F++){let E=B.parts[F]||0,Y=D.parts[F]||0;if(E<Y)return-1;if(E>Y)return 1}if(B.label===D.label)return 0;if(!B.label&&D.label)return 1;if(B.label&&!D.label)return-1;if(B.label&&D.label)return B.label<D.label?-1:1;return 0}function _o(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,J=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?RE(B):void 0;return{sha:J,timestamp:B,age:F}}catch{return null}}u1();p0();import{readFile as yq3,realpath as xq3}from"node:fs/promises";import{dirname as Hy4,join as bq3}from"node:path";async function qy4(A){switch(A){case"binary":case"brew":return hq3(Ro());case"npm":case"pnpm":case"yarn":case"bun":return gq3()}}async function hq3(A){let Q=await KN(A,["--version"],5000);if(Q.reason!=="success")return u.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function gq3(){try{let A=process.argv[1];if(!A)return null;let Q=await xq3(A),$=Hy4(Hy4(Q));return await mq3(bq3($,"package.json"))}catch(A){return u.debug("failed to read installed version from package.json",{error:A}),null}}async function mq3(A){let Q=await yq3(A,"utf8"),$=JSON.parse(Q);if(!$.name||!St0($.name))return u.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}p0();import{spawn as dq3}from"node:child_process";function mt0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return u.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var GY0=null,To=null;function Ny4(A){return new Promise((Q)=>{let $=dq3("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(D)=>{B+=D.toString()}),$.on("close",(D,J)=>{if(D!==0||J==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function VY0(){if(GY0)return GY0;if(To)return To;To=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return mt0(A);let Q=await Ny4("@sourcegraph:registry");if(Q)return mt0(Q);let $=await Ny4("registry");if($)return mt0($);return"https://registry.npmjs.org"})();try{return GY0=await To,GY0}finally{To=null}}var pq3=3600000,cq3=5000;function KY0(A,Q,$={}){let B=new d4,D=B.pipe(t6({shouldCountRefs:!1})),J=$.startDelayMs??0,F=$.checkIntervalMs??pq3,E=!1,Y=()=>{E=!0};return setImmediate(async()=>{let Z=u.getChild("update");if(J>0){if(await sX(J),E)return}let U=D.subscribe({next:(G)=>{Z.debug("emit new state",G)}}),X=A;try{while(!E){let G=await lq3(X,Q,Z,B);if(G.stop)return;if(G.updatedTo)X=G.updatedTo;if(G.emittedVisibleState){if(await sX(cq3),E)return;B.next("hidden")}if(F<=0)return;let V=1000,K=F;while(K>0&&!E){let z=Math.min(V,K);await sX(z),K-=z}}}finally{U.unsubscribe(),B.complete()}}),{state:D,dispose:Y}}async function lq3(A,Q,$,B){let D={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),D.stop=!0,D;let J=await Q.get("updates.mode");if(J==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await jG(),E=F==="binary"||F==="brew",Y=E?void 0:await zN();$.debug("checking",{currentVersion:A,mode:J,packageManager:F,isBinaryDistribution:E,npmPackageName:Y});let Z;if(E)Z=await XY0(A);else{let G=await VY0();Z=await UY0(A,G,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),D;let U=(G)=>{B.next(G),D.emittedVisibleState=!0};if(F){let G=await qy4(F);if(G&&Po(G,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:G,latestVersion:Z.latestVersion}),D.updatedTo=G,Po(A,G)<0){let V=await Tz(G),K={from:A,to:G,externallyUpdated:!0,...V};if(V.status==="same")$.info("on-disk already updated by another instance",K),U("updated");else $.warn("on-disk already updated by another instance, with PATH warning",K),U("updated-with-warning")}return D}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let G=Z.currentVersionAge-Z.latestVersionAge,V=0.5;if(Math.abs(G)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:G}),!0}return!1};if(!J)J=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:J});if(F==="brew"){if(!X())U("update-available-brew");return D}if(F==="binary"&&process.execPath!==Ro()){if($.debug("non-standard binary path, showing warning"),!X())U("update-available-unrecognized-path");return D}if(J==="warn"){if(!X())U("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())U("update-available");return D}try{await uo(Z.latestVersion,F),D.updatedTo=Z.latestVersion;let G=await Tz(Z.latestVersion),V={from:Z.currentVersion,to:Z.latestVersion,...G};if(G.status==="same")$.info("success",V),U("updated");else $.warn("success with warning",V),U("updated-with-warning")}catch(G){U("update-error")}return D}catch(J){return $.debug("check failed",{error:J}),D}}Fz();import{stderr as pE}from"node:process";function Cy4(A){let Q=new oq().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 vt0(B.force||!1,B.verbose||!1,"0.0.1779686836-g4ef406"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new oq("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 aq3(B.targetVersion)});A.addCommand($)}function iq3(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4795
4795
  `),B=!1,$=0}function J(F){if(!Q)return;let E=F.padEnd($," ");A.write(`\r${E}`),B=!0,$=E.length}return{flushProgressLine:D,renderProgress:J}}function nq3(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)pE.write(t0.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.
4796
4796
  `))}async function aq3(A){let $=process.platform==="win32"&&Lj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:D}=iq3(pE);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")pE.write(t0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4797
4797
 
4798
4798
  `));try{if(!A){pE.write(t0.blue(`Checking for updates...
4799
- `));let E=!1,Y;if(Lj()){let Z=await XY0("0.0.1779668338-g19be90");E=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await VY0(),U=await zN(),X=await UY0("0.0.1779668338-g19be90",Z,U);nq3(X),E=X.hasUpdate,Y=X.latestVersion}if(!E){let Z=_o("0.0.1779668338-g19be90"),U=Z?.age?`released ${Z.age} ago`:`built ${RE(new Date("2026-05-25T00:23:23.173Z"))} ago`;pE.write(t0.green(`✓ Amp is already up to date on version ${"0.0.1779668338-g19be90"} (${U})
4800
- `));let X=await Tz("0.0.1779668338-g19be90",$);if(X.warning)pE.write(`
4799
+ `));let E=!1,Y;if(Lj()){let Z=await XY0("0.0.1779686836-g4ef406");E=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await VY0(),U=await zN(),X=await UY0("0.0.1779686836-g4ef406",Z,U);nq3(X),E=X.hasUpdate,Y=X.latestVersion}if(!E){let Z=_o("0.0.1779686836-g4ef406"),U=Z?.age?`released ${Z.age} ago`:`built ${RE(new Date("2026-05-25T05:31:37.501Z"))} ago`;pE.write(t0.green(`✓ Amp is already up to date on version ${"0.0.1779686836-g4ef406"} (${U})
4800
+ `));let X=await Tz("0.0.1779686836-g4ef406",$);if(X.warning)pE.write(`
4801
4801
  `+t0.yellow(X.warning)+`
4802
4802
  `);process.exit(0)}if(!Y)pE.write(t0.yellow("[WARN] could not find latest version")),process.exit(0);A=Y}pE.write(t0.blue(`Updating to version ${A}...
4803
4803
  `)),await uo(A,void 0,(E)=>{B(),pE.write(t0.dim(`Running: ${E}
@@ -5097,7 +5097,7 @@ ${B}`}function ao(A){let Q=A.lastIndexOf("/");return Q===-1?A:A.slice(Q+1)}funct
5097
5097
  ${Q.join(`
5098
5098
  `)}`:void 0}}function tL3(A){let Q=[],$=new Set,B=A.split(`
5099
5099
  `);for(let D=0;D<B.length;D++){let F=B[D].match(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/);if(!F)continue;let E=F[1],Y=B[D+1]?.match(/^\*\*\* Move to: (.+)$/);if(Y)E=Y[1];if($.has(E))continue;$.add(E),Q.push(E)}return Q}function g2(A){if(A.status!=="error"||!A.error)return;if(typeof A.error==="object"&&"message"in A.error){let Q=A.error.message;if(typeof Q==="string"&&Q.trim())return Q}return String(A.error)}function eL3(A,Q){if(A==="find_thread"){let $=typeof Q.query==="string"?Q.query.trim():void 0;return{kind:"search",title:$?`Searched threads: ${$}`:"Searched threads",icon:"search"}}if(A==="read_thread"){let $=typeof Q.threadID==="string"?Q.threadID.trim():void 0,B=typeof Q.goal==="string"?Q.goal.trim():void 0;return{kind:"thread",title:B?`Read thread: ${B}`:$?`Read thread ${$}`:"Read thread",icon:"threads"}}if(A==="slack_read"){let $=typeof Q.type==="string"?Q.type:void 0,B=typeof Q.query==="string"?Q.query.trim():void 0,D=B?`: ${B}`:"";if($==="users")return{kind:"search",title:`Slack searched users${D}`,icon:"slack"};if($==="channels")return{kind:"search",title:`Slack searched channels${D}`,icon:"slack"};if($==="messages")return{kind:"read",title:`Slack read messages${D}`,icon:"slack"};if($==="thread")return{kind:"read",title:"Slack read thread",icon:"slack"};return{kind:"read",title:B?`Slack read: ${B}`:"Slack read",icon:"slack"}}if(A==="docs_list"){let $=lE(Q);return{kind:"list",title:$?`Listed docs: ${$}`:"Listed docs",icon:"docs"}}if(A==="docs_read"){let $=lE(Q);return{kind:"read",title:$?`Read docs: ${$}`:"Read docs",icon:"docs"}}if(A==="github_repo_ci_status"){let $=lE(Q);return{kind:"read",title:$?`Read CI status: ${$}`:"Read CI status",icon:"github"}}if(A==="web_search"){let $=lE(Q);return{kind:"search",title:$?`Searched web: ${$}`:"Searched web",icon:"web"}}if(A==="read_web_page"){let $=lE(Q);return{kind:"web-page",title:$?`Read web page: ${$}`:"Read web page",icon:"web"}}if(A==="search_github"||A==="commit_search"||A==="glob_github"){let $=lE(Q);return{kind:"search",title:$?`Searched GitHub: ${$}`:"Searched GitHub",icon:"github"}}if(A==="list_directory_github"||A==="list_repositories"){let $=lE(Q);return{kind:"list",title:$?`Listed GitHub content: ${$}`:"Listed GitHub content",icon:"github"}}if(A==="read_github"||A==="diff"){let $=lE(Q);return{kind:"read",title:$?`Read GitHub content: ${$}`:"Read GitHub content",icon:"github"}}return}function rY0(A,Q){if(A==="Read"){let D=AO3(Q);if(D)return D}if(A==="view_media")return QO3(Q);if(A==="read_thread"){let D=typeof Q.goal==="string"?Q.goal.trim():void 0;if(D)return`Read thread: ${D}`;let J=typeof Q.threadID==="string"?Q.threadID.trim():void 0;return J?`Read thread ${J}`:"Read thread"}if(A==="find_thread"){let D=typeof Q.query==="string"?Q.query.trim():void 0;return D?`Searched threads: ${D}`:"Searched threads"}if(A==="skill")return`Read skill ${Q.name}`;if(A==="file_tree")return $O3(Q);if(A==="web_search"){let D=eb4(Q);return D?`Web Search ${D}`:"Web Search"}if(A==="read_web_page"){let D=tb4(Q);return D?`Read ${D}`:"Read"}if(A.toLowerCase()==="Grep".toLowerCase())return DO3(Q);let $=lE(Q);if(!$)return A;let B=$.includes("/")?_$($):$;return`${A} ${B}`}function AO3(A){let Q=typeof A.path==="string"?A.path.trim():void 0,$=BO3(A.read_range);if(!Q)return $?`Read ${$}`:void 0;let B=_$(Q);return $?`Read ${B} ${$}`:`Read ${B}`}function QO3(A){let Q=typeof A.path==="string"?A.path.trim():void 0;if(!Q)return"View media";return`View ${_$(Q)}`}function $O3(A){let Q=typeof A.path==="string"?A.path.trim():void 0;if(!Q)return"List";let $=Q==="/"?Q:Q.replace(/\/+$/,"");return`List ${$.includes("/")?_$($)||$:$}`}function BO3(A){if(!Array.isArray(A)||A.length!==2)return;let[Q,$]=A;if(typeof Q!=="number"||typeof $!=="number"||!Number.isInteger(Q)||!Number.isInteger($))return;if(Q<1||$===-1||$<Q)return;if(Q===$)return`L${Q}`;return`L${Q}-${$}`}function DO3(A){let Q=A.path?.trim(),$=A.pattern?.trim();if(Q&&$)return`Grep ${Q} "${$}"`;if($)return`Grep "${$}"`;if(Q)return`Grep ${Q}`;return"Grep"}function lE(A){for(let Q of["path","filePattern","pattern","query","url","objective","description","prompt"])if(typeof A[Q]==="string"&&A[Q].trim())return A[Q].trim();return}function tb4(A){if(typeof A.url!=="string")return;return A.url.trim()||void 0}function eb4(A){let Q=typeof A.query==="string"?A.query:void 0,$=typeof A.objective==="string"?A.objective:void 0;return(Q??$)?.trim()||void 0}function JO3(A){let Q=A.replace(/\/+$/,""),$=Q.lastIndexOf("/");return($===-1?Q:Q.slice($+1)).replace(/\.md$/i,"")||A}function FO3(A,Q){let $=YB(Q.result)?Q.result:void 0,B=YB($?.check)?$.check:void 0;return typeof B?.name==="string"?B.name:JO3(A)}function EO3(A){if(A.status!=="done")return;let Q=YB(A.result)?A.result:void 0;return Array.isArray(Q?.issues)?Q.issues.length:void 0}function YO3(A){let Q=Object.entries(A).filter(([,$])=>$!==void 0&&$!==null&&$!=="");if(Q.length===0)return;return Q.map(([$,B])=>{let D=typeof B==="string"?B:JSON.stringify(B);return`${$}: ${D}`}).join(`
5100
- `)}function ye0(A,Q){let $=[...A],B=new Set($.map((D)=>`${D.kind}:${D.title}`));for(let D of $h4(Q)){let J=`${D.kind}:${D.title}`;if(B.has(J))continue;B.add(J),$.push(Ah4(D,Q.status))}return $}function Ah4(A,Q){return{...A,status:Q}}function Qh4(A){return A.activityKind!=="subagent"||A.status===void 0||bM(A.status)}function $h4(A){return ZO3(A).map((Q)=>({kind:"read",title:`Read ${i$(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function ZO3(A){if(A.status!=="done"||!YB(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap(($)=>{if(!YB($)||typeof $.uri!=="string"||typeof $.lineCount!=="number"||!Number.isFinite($.lineCount))return[];return[{uri:$.uri,lineCount:$.lineCount,...typeof $.content==="string"?{content:$.content}:{}}]})}function UO3(A,Q,$){if(A==="oracle"){let B=typeof Q.task==="string"?Q.task.trim():void 0;return Re0({label:{active:"Oracle exploring",complete:"Oracle has spoken"},detail:B,run:$})}if(A==="librarian"){let B=typeof Q.query==="string"?Q.query.trim():void 0;return Re0({label:{active:"Librarian researching",complete:"Librarian researched"},detail:B,run:$})}if(A==="Task"){let B=typeof Q.description==="string"?Q.description.trim():void 0,D=typeof Q.prompt==="string"?Q.prompt.trim():void 0;return Re0({label:{active:"Subagent working",complete:"Subagent finished"},detail:B??D,run:$})}if(A==="code_review"){let B=GO3($,Q),D=ye0(B.actions,$),J={label:{active:"Reviewing code",complete:"Reviewed code"},activityKind:"subagent",actions:D,summary:B.summary,hasInProgress:bM($.status),status:$.status},F=typeof Q.diff_description==="string"?Q.diff_description.trim():void 0;if(F!==void 0)J.detail=F;let E=g2($);if(E!==void 0)J.error=E;return J}return}function Re0(A){let Q=ye0([],A.run),$={label:A.label,activityKind:"subagent",actions:Q,summary:Te0(Q),hasInProgress:bM(A.run.status),status:A.run.status};if(A.detail!==void 0)$.detail=A.detail;let B=g2(A.run);if(B!==void 0)$.error=B;return $}function XO3(A){let Q="result"in A&&YB(A.result)?A.result:void 0,$=nb4("progress"in A?A.progress:void 0),B=YB($)?$:void 0;return{main:(YB(Q?.main)?Q.main:void 0)??(YB(B?.main)?B.main:void 0),checks:(YB(Q?.checks)?Q.checks:void 0)??(YB(B?.checks)?B.checks:void 0)}}function GO3(A,Q){let $=[],B=new Set,D=(U)=>{let X=`${U.kind}:${U.title}`;if(B.has(X))return;B.add(X),$.push(U)},{main:J,checks:F}=XO3(A);if(A.status==="queued")D({kind:"review",title:"Code review queued"});if(A.status==="error"){let U=g2(A)??"Unknown error";D({kind:"review",title:`Code review failed: ${U}`})}let E=0,Y=0;for(let[U,X]of Object.entries(F??{})){if(!YB(X))continue;Y+=1;let G=FO3(U,X);if(X.status==="done"){E+=1;let V=EO3(X);if(V===void 0)D({kind:"review",title:`Check ${G}: complete`});else if(V===0)D({kind:"review",title:`Check ${G}: ok`});else D({kind:"review",title:`Check ${G}: ${V} ${U4(V,"issue")} found`});continue}if(X.status==="error"){E+=1;let V=typeof X.error==="string"&&X.error.trim()?X.error.trim():"Unknown error";D({kind:"review",title:`Check ${G}: error (${V})`});continue}if(X.status==="in-progress"){let V=typeof X.message==="string"&&X.message.trim()?X.message.trim():"Running check...";D({kind:"review",title:`Check ${G}: ${V}`})}}if(J?.status==="done"&&Y>0&&E<Y)D({kind:"review",title:"Main review complete, running checks..."});if(A.status==="done")D({kind:"review",title:"Code review complete"});if($.length===0)D({kind:"review",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let Z=Q.thinking==="low"?"quick code review":"code review";return{actions:$,summary:Y>0?`${E}/${Y} checks · ${Z}`:Z}}function Te0(A,Q=""){let $=0,B=0,D=new Map;for(let F of A){if(F.icon==="docs"&&(F.title.startsWith("Read ")||F.title.startsWith("Load "))){$++;continue}if(F.title.startsWith("Read skill ")){B++;continue}D.set(F.kind,(D.get(F.kind)??0)+1)}let J=[];for(let[F,E,Y]of[["read","file",void 0],["view","media file","media files"],["web-page","web page","web pages"],["thread","thread",void 0],["skill","skill",void 0],["guidance","guidance file","guidance files"],["search","search","searches"],["web","web search","web searches"],["review","review","reviews"],["list","list",void 0]]){let Z=F==="guidance"?$:F==="skill"?B:D.get(F);if(!Z)continue;J.push(`${Z} ${U4(Z,E,Y)}`)}if(J.length>0)return J.join(", ");return Q}function VO3(A){if(A.kind==="search"&&KO3(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return iJ0(A)}function KO3(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function YB(A){return typeof A==="object"&&A!==null}u1();var zO3="T-00000000-0000-0000-0000-000000000000";class eY0{messagesState=new ME0(zO3);transcriptEntries=[];transcriptListeners=new Set;transcriptReader={read:()=>this.transcriptEntries,subscribe:(A)=>{return this.transcriptListeners.add(A),()=>this.transcriptListeners.delete(A)}};_agentMode;_reasoningEffort=void 0;observerState;activeErrorPayload=null;activeErrorSeq=null;connectionErrorSubject=new a1(null);activeErrorSubject=new a1(null);agentMessageIdSubject=new a1(null);cancelledSubject=new d4;queuedMessageRemovalSubject=new d4;transcriptRebuildBatchDepth=0;pendingTranscriptRebuildPreviousLength=null;log=u;constructor(A,Q=null){this._agentMode=A,this._reasoningEffort=ZX(A,Q??{}),this.observerState=new wE0({initialAgentLoopState:"idle",initialThreadSettings:Q,dedupeQueuedMessageAdds:!1,compactionRecordsState:"idle"})}logObserverServerMessage(A,Q){if(!CE0(Q))return;this.log.info(A,NE0(Q,{direction:"receive"}))}get agentMode(){return this._agentMode}set agentMode(A){if(this._agentMode===A)return;if(this._agentMode=A,this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}get reasoningEffort(){return this._reasoningEffort}reader(){return this.transcriptReader}protocolMessages(){return this.messagesState.messages()}agentState(){return this.observerState.agentLoopState}agentMessageId(){return this.agentMessageIdSubject}connectionInfo(){return this.observerState.connectionInfo}threadID(){return this.observerState.threadId}pluginMessages(){return this.observerState.pluginMessages}pluginUIRequests(){return this.observerState.pluginUIRequests}connectionError(){return this.connectionErrorSubject}setConnectionError(A){if(this.connectionErrorSubject.getValue()===A)return;this.connectionErrorSubject.next(A)}pendingSend(){return this.observerState.pendingSend}status(){return this.observerState.status}stageBytes(){return this.observerState.stageBytes}activeError(){return this.activeErrorSubject}cancelled(){return this.cancelledSubject}getActiveErrorSeq(){return this.activeErrorSeq}title(){return this.observerState.threadTitle}queuedMessages(){return this.observerState.queuedMessages}queuedMessageRemovalEvents(){return this.queuedMessageRemovalSubject}threadSettings(){return this.observerState.threadSettings}compactionState(){return this.observerState.compactionState}beginTranscriptRebuildBatch(){this.transcriptRebuildBatchDepth+=1}endTranscriptRebuildBatch(){if(this.transcriptRebuildBatchDepth===0)return;if(this.transcriptRebuildBatchDepth-=1,this.transcriptRebuildBatchDepth>0)return;let A=this.pendingTranscriptRebuildPreviousLength;if(this.pendingTranscriptRebuildPreviousLength=null,A!==null)this.rebuildTranscriptEntries(A)}dismissActiveError(){if(this.activeErrorPayload===null)return;this.activeErrorPayload=null,this.activeErrorSeq=null,this.activeErrorSubject.next(null)}onMessageAdded(A){this.logObserverServerMessage("[observer] onMessageAdded",A),this.observerState.onMessageAdded(A),this.applyThreadMessageEvent(A)}onMessageRemoved(A){this.log.info("[observer] onMessageRemoved",{data:{messageId:A}}),this.observerState.onMessageRemoved(A);let Q=this.transcriptEntries.length;if(this.messagesState.remove(A).changed)this.requestTranscriptRebuild(Q)}onMessageUpdated(A){this.logObserverServerMessage("[observer] onMessageUpdated",A),this.observerState.onMessageUpdated(A),this.applyThreadMessageEvent(A)}onDelta(A){this.observerState.onDelta(A),this.applyThreadMessageEvent(A)}onTruncate(A){this.logObserverServerMessage("[observer] onTruncate",A),this.observerState.onTruncate(A),this.applyThreadMessageEvent(A)}onAgentState(A){this.logObserverServerMessage("[observer] onAgentState",A);let Q=rQ(this.observerState.agentLoopState.getValue()),$=this._agentMode;if(A.agentMode!==void 0)this._agentMode=A.agentMode;this._reasoningEffort=A.reasoningEffort,this.agentMessageIdSubject.next(A.messageId??null),this.observerState.onAgentState(A);let B=rQ(this.observerState.agentLoopState.getValue());if(($!==this._agentMode||Q!==B)&&this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}onThreadSettings(A){this.logObserverServerMessage("[observer] onThreadSettings",A),this.observerState.onThreadSettings(A)}onThreadId(A){this.log.info("[observer] onThreadId",{data:{threadId:A}}),this.log=u.with({threadId:A}),this.messagesState.setThreadID(A),this.observerState.onThreadId(A),this.observerState.threadId.complete()}onConnectionChanged(A){if(this.log.info("[observer] onConnectionChanged",{data:A}),this.observerState.onConnectionChanged(A),I9(A))this.setConnectionError(null)}onQueuedMessages(A){this.logObserverServerMessage("[observer] onQueuedMessages",A);let Q=A.type==="queued_message_removed"?this.observerState.queuedMessages.getValue().find(($)=>$.queuedMessage.messageId===A.queuedMessageId):void 0;if(this.observerState.onQueuedMessages(A),A.type==="queued_message_removed"&&Q!==void 0)this.queuedMessageRemovalSubject.next({message:Q,serverMessage:A})}onUserActionMessageDeliveryStatusChanged(A,Q,$){this.log.info("[observer] onUserActionMessageDeliveryStatusChanged",{data:{messageId:A,status:Q,sentAt:$}}),this.observerState.onUserActionMessageDeliveryStatusChanged(A,Q,$)}onUserMessageSendPending(A,Q){this.log.info("[observer] onUserMessageSendPending",{data:{messageId:A,sentAt:Q}}),this.observerState.onUserMessageSendPending(A,Q)}onUserMessageSendAck(A){this.log.info("[observer] onUserMessageSendAck",{data:{messageId:A}}),this.observerState.onUserMessageSendAck(A)}onErrorNotice(A){if(this.logObserverServerMessage("[observer] onErrorNotice",A),this.activeErrorPayload!==null)return;this.observerState.onErrorNotice(A)}onActiveError(A){if(this.logObserverServerMessage("[observer] onActiveError",A),this.observerState.onActiveError(A),A.type==="error_set")this.activeErrorPayload=A.error,this.activeErrorSeq=A.seq;else this.activeErrorPayload=null,this.activeErrorSeq=null;this.activeErrorSubject.next(this.activeErrorPayload)}onCancelled(A){this.logObserverServerMessage("[observer] onCancelled",A),this.observerState.onCancelled(A),this.cancelledSubject.next(A)}onToolProgress(A){this.logObserverServerMessage("[observer] onToolProgress",A),this.observerState.onToolProgress(A),this.applyThreadMessageEvent(A)}onExecutorStatus(A){this.logObserverServerMessage("[observer] onExecutorStatus",A),this.observerState.onExecutorStatus(A)}onExecutorError(A){this.logObserverServerMessage("[observer] onExecutorError",A),this.observerState.onExecutorError(A)}onObservers(A){this.logObserverServerMessage("[observer] onObservers",A),this.observerState.onObservers(A)}onArtifactEvent(A){this.observerState.onArtifactEvent(A)}onEnvironmentUpdate(A){this.observerState.onEnvironmentUpdate(A)}onPluginMessage(A){this.observerState.onPluginMessage(A)}onRetryEvent(A){this.log.info("[observer] onRetryEvent",{data:A}),this.observerState.onRetryEvent(A)}onThreadTitle(A){this.log.info("[observer] onThreadTitle",{data:A}),this.observerState.onThreadTitle(A)}onCompactionEvent(A){this.log.info("[observer] onCompactionEvent",{data:A});let Q=A.type==="compaction_started"?"compacting":"idle";if(A.type==="compaction_started"&&this.observerState.compactionState.getValue()===Q)return;let $=this.transcriptEntries.length;if(this.observerState.onCompactionEvent(A),A.type==="compaction_complete"&&A.cutMessageId!==void 0||A.type==="compaction_records")this.requestTranscriptRebuild($)}applyThreadMessageEvent(A){let Q=this.transcriptEntries.length;if(!this.messagesState.apply(A).changed)return;this.requestTranscriptRebuild(Q)}requestTranscriptRebuild(A){if(this.transcriptRebuildBatchDepth===0){this.rebuildTranscriptEntries(A);return}this.pendingTranscriptRebuildPreviousLength=Math.min(this.pendingTranscriptRebuildPreviousLength??A,A)}rebuildTranscriptEntries(A){let Q=Sb4(this.messagesState.messages(),{threadID:this.messagesState.getThreadID(),...kb4(this._agentMode),isWorking:rQ(this.observerState.agentLoopState.getValue()),compactionCutMessageIDs:this.observerState.compactionRecords.getValue().map(($)=>$.cutMessageId)});this.transcriptEntries.length=0,this.transcriptEntries.push(...Q),this.notifyTranscriptReaders(WO3(A,Q.length))}notifyTranscriptReaders(A){for(let Q of this.transcriptListeners)Q(A)}}function WO3(A,Q){return Array.from({length:Math.max(A,Q)},($,B)=>B)}var IO3=45000;class xe0{rivetEndpoint;apiKey;configService;runtimeDependencies;loadThreadHistory;importThreadIntoActor;observingClients=[];_lastActiveObservingClient=null;connectionErrorSubject=new d4;constructor(A,Q,$,B,D,J){this.rivetEndpoint=A;this.apiKey=Q;this.configService=$;this.runtimeDependencies=B;this.loadThreadHistory=D;this.importThreadIntoActor=J}get lastActiveObservingClient(){return this._lastActiveObservingClient}get activeThreadIDs(){let A=new Set;for(let Q of this.observingClients){let $=Q.threadID??Q.client.getThreadId();if($)A.add($)}return[...A]}get connectionErrors$(){return this.connectionErrorSubject}async connectToThread(A,Q={}){let $=Q.observerOnly??!1,B=$?"observer":"executor",D=this.observingClients.find((Z)=>(Z.threadID===A||Z.client.getThreadId()===A)&&($?Z.observerOnly:!0));if(D)return this._lastActiveObservingClient=D,this.persistLastThreadID(A),D;let J=this.createClient({threadID:A,requiredRole:B}),F=await J.loadThreadHistory(A);if(!F)throw J.dispose(),new W9("Thread not found");if(F.needsImport){if(!this.importThreadIntoActor)throw J.dispose(),new W9("Thread requires import before connecting");try{await this.importThreadIntoActor(A)}catch(Z){throw J.dispose(),oo(Z)}}let E=new eY0(F.agentMode);E.beginTranscriptRebuildBatch();try{J.setObserverCallbacks(E)}finally{E.endTranscriptRebuildBatch()}let Y={client:J,observer:E,threadID:A,logger:u.with({threadId:A}),observerOnly:$,connectionSubscription:Qf(J,{onError:({threadID:Z,error:U})=>this.emitConnectionError(E,U,Z)})};return this.connectAndResume(J,F.version,{observerOnly:$,onExecutorAlreadyConnected:Q.onExecutorAlreadyConnected,onDowngradedToObserver:()=>{Y.observerOnly=!0},onRetryableConnectError:(Z)=>this.emitConnectionError(E,Z,A,{showInObserver:!1})}).catch((Z)=>{this.emitConnectionError(E,Z,A)}),this.persistLastThreadID(A),this.observingClients.push(Y),this._lastActiveObservingClient=Y,Y}createNewThread(A,Q,$){let B=this.createClient({agentMode:A,initialThreadMeta:$,requiredRole:"executor"}),D=new eY0(A,Q??null);B.setObserverCallbacks(D);let J={client:B,observer:D,threadID:null,logger:u,observerOnly:!1,connectionSubscription:Qf(B,{requireRole:"executor",onError:({threadID:F,error:E})=>this.emitConnectionError(D,E,F)})};if(Q)B.sendClientUpdateThreadSettings(Q);else bf(this.configService).then((F)=>{B.sendClientUpdateThreadSettings(F)}).catch((F)=>{u.warn("Failed to seed thread settings",{threadID:B.getThreadId(),error:F instanceof Error?F.message:String(F)})});return this.observingClients.push(J),this.connectAndResume(B,0,{onRetryableConnectError:(F)=>this.emitConnectionError(D,F,void 0,{showInObserver:!1})}).then((F)=>{let E=F.getThreadId();if(J.threadID=E,E)J.logger=u.with({threadId:E}),this.persistLastThreadID(E)}).catch((F)=>{this.emitConnectionError(D,F)}),this._lastActiveObservingClient=J,J}dispose(){for(let{client:A,connectionSubscription:Q}of this.observingClients.values())Q.unsubscribe(),A.dispose();this.observingClients.length=0,this._lastActiveObservingClient=null,this.connectionErrorSubject.complete()}createClient(A={}){let{threadID:Q,agentMode:$,initialThreadMeta:B,requiredRole:D}=A,J=If(async(F)=>{try{let E={agentMode:$,executorType:"local-client"};if(!F&&B)E.threadMeta=B;return await c9(F,this.configService,this.apiKey,E)}catch(E){throw oo(E)}},Q);return new zG({transport:Hf({rivetEndpoint:this.rivetEndpoint,credentialsProvider:J,initialThreadID:Q,pingIntervalMs:5000,requiredRole:D}),threadHistoryLoader:this.loadThreadHistory})}async connectAndResume(A,Q,$={}){let B=$.observerOnly??!1,D=null;try{await HO3(A,$);let J=A.getThreadId();if(!J)throw A.disconnect(),new W9("Thread client connected without a thread ID");if(B)return await qO3(A),A.resumeFromVersion(Q),A;D=this.createExecutor(A,J),D.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),D.handleConnectionChange(A.getConnectionInfo());try{await D.ensureReady({timeoutMs:IO3,timeoutMessage:"Couldn’t connect to Amp servers — run amp: reconnect to retry"})}catch(F){if(!fa(F))throw F;if(D.dispose(),D=null,(await $.onExecutorAlreadyConnected?.({existingExecutorPid:F.payload.existingExecutorPid??null})??"observe")==="disconnect")return A.disconnect(),A;A.downgradeExecutorRequirementToObserver(),$.onDowngradedToObserver?.()}return A.resumeFromVersion(Q),A}catch(J){throw A.disconnect(),oo(J)}}createExecutor(A,Q){return new Cj({transport:A,toolService:this.runtimeDependencies.toolService,configService:this.configService,clientID:this.runtimeDependencies.clientID,threadId:Q,invokeTool:($)=>this.runtimeDependencies.invokeTool(Q,$),requestPluginToolCall:this.runtimeDependencies.requestPluginToolCall,requestPluginToolResult:this.runtimeDependencies.requestPluginToolResult,pluginService:this.runtimeDependencies.pluginService,pluginPlatform:this.runtimeDependencies.pluginPlatform,readFileSystemDirectory:this.runtimeDependencies.readFileSystemDirectory,skillService:this.runtimeDependencies.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:process.cwd()})}emitConnectionError(A,Q,$,B={}){let D=oo(Q);if(B.showInObserver!==!1)A.setConnectionError(D.message);this.connectionErrorSubject.next({threadID:$??void 0,error:D})}persistLastThreadID(A){this.runtimeDependencies.persistLastThreadID(A).catch((Q)=>{u.warn("Failed to persist last active thread ID",{threadID:A,error:Q instanceof Error?Q.message:String(Q)})})}}async function HO3(A,Q){try{await A.connect()}catch(B){let D=oo(B),J=A.getConnectionInfo().state;if(J!=="reconnecting"&&J!=="connecting")throw D;if(J==="reconnecting")Q.onRetryableConnectError?.(D);await Bh4(A);return}let $=A.getConnectionInfo();if($.state==="connected")return;if($.state==="reconnecting"||$.state==="connecting"){await Bh4(A);return}throw new W9("Connection canceled")}async function Bh4(A){if((await k1(A.connectionChanges().pipe(l3(($)=>$.state==="connected"||$.state==="disconnected"),j8(1)))).state==="disconnected")throw new W9("Couldn’t connect to Amp servers — run amp: reconnect to retry")}async function qO3(A){if(I9(A.getConnectionInfo()))return;if((await k1(A.connectionChanges().pipe(l3(($)=>I9($)||$.state==="disconnected"),j8(1)))).state==="disconnected")throw new W9("Couldn’t connect to Amp servers — run amp: reconnect to retry")}function oo(A){if(A instanceof W9)return A;if(A instanceof Error){let Q=A.message||"Unknown connection error";return new W9(Q,A)}if(typeof A==="string"&&A.length>0)return new W9(A,A);return new W9("Unknown connection error",A)}async function Dh4(A){let Q=await A.configService.getLatest(A.signal),$=await Q.secrets.getToken("apiKey",Q.settings.url);if(!$)throw Error("API key required. Please run `amp login` first.");let B=await c9(A.threadID,A.configService,$,{signal:A.signal}),D=aJ(A.ampURL),F=await LG({endpoint:D,poolName:B.poolName}).threadActor.get([A.threadID]).fetch("/skills",{method:"GET",headers:{Authorization:`Bearer ${$}`},signal:A.signal,skipReadyWait:!0});if(!F.ok){let Y=await F.text();throw Error(`Skills request failed (${F.status}): ${Y}`)}let E=await F.json();if(!E.ok)throw Error(E.error);return{skills:E.skills,errors:E.errors}}pF();p0();jA();jA();Q4();var iE={agentMode:"smart",launchCount:0,neoInvadersHighScore:0,shortcutsHintUsed:!1,neoWelcomeDismissed:!1};function Fh4(A,Q){if(Q==="execute")return A.lastExecuteThreadId??A.lastThreadId;return A.lastThreadId}function mf(A,Q,$){if($==="execute")return{...A,lastExecuteThreadId:Q};return{...A,lastThreadId:Q}}function Eh4(A){return{...A,neoWelcomeDismissed:!0}}function Yh4(A=P_){return B1.joinPath(i0.file(A),"session.json")}var Jh4=Promise.resolve();async function bz(A={}){try{let Q=await NO3(A.dataDir),$={...iE,agentMode:Q?.agentMode??iE.agentMode,launchCount:Q?.launchCount??iE.launchCount,neoInvadersHighScore:Q?.neoInvadersHighScore??iE.neoInvadersHighScore,neoWelcomeDismissed:Q?.neoWelcomeDismissed??iE.neoWelcomeDismissed,shortcutsHintUsed:Q?.shortcutsHintUsed??iE.shortcutsHintUsed,lastThreadId:Q?.lastThreadId,lastExecuteThreadId:Q?.lastExecuteThreadId},B={...Q?.lastReasoningEffortByMode};if(Object.keys(B).length>0)$.lastReasoningEffortByMode=B;let D={...Q?.lastSpeedByMode};if(Object.keys(D).length>0)$.lastSpeedByMode=D;return $}catch{return{...iE}}}async function NO3(A){try{let Q=await xA(Yh4(A),"utf8");return JSON.parse(Q)}catch(Q){if(N5(Q))return;throw Q}}async function CO3(A,Q){try{let $=Yh4(Q.dataDir),B=$.with({path:`${$.path}.amptmp`});await SQ(B1.joinPath($,".."),{recursive:!0}),await n7(B,JSON.stringify(A,null,2)),await y20(B,$)}catch($){u.warn("Failed to save session state.",{error:$ instanceof Error?$.message:String($)})}}async function GQ(A,Q={}){let $={...iE},B=Jh4.catch(()=>{return}).then(async()=>{let D=await bz(Q);$={...iE,...A(D)},await CO3($,Q)});return Jh4=B.then(()=>{return},()=>{return}),await B,$}class be0{constructor(){}isEnabled(A){return!0}consumesKey(A){return!0}toString(){return`${this.constructor.name}()`}}class T1 extends be0{onInvoke;constructor(A){super();this.onInvoke=A}invoke(A){return this.onInvoke(A)}}function wO3(A){return"state"in A}function Zh4(A,Q){let $=A.element.parent;while($){if(wO3($)&&$.state instanceof AZ0){if(Q($.state))return}$=$.parent}}class QZ0{invokeAction(A,Q){let $=this.findAction(A,Q);if($&&$.enabled)return $.action.invoke(A);return null}findAction(A,Q){let $=null;return Zh4(Q,(B)=>{let D=B.getActionForIntent(A);if(!D)return!1;return $={action:D,enabled:D.isEnabled(A)},!0}),$}}class x4 extends u0{actions;child;dispatcher;constructor({actions:A,child:Q,dispatcher:$,key:B}){super({key:B});this.actions=A,this.child=Q,this.dispatcher=$}createState(){return new AZ0}static invoke(A,Q){return x4.of(A).invokeAction(Q,A)}static maybeInvoke(A,Q){try{return x4.invoke(A,Q)}catch{return null}}static find(A,Q){let $=x4.maybeFind(A,Q);if(!$){let B=Q?.constructor.name||"unknown";throw Error(`No action found for intent type: ${B}`)}return $}static maybeFind(A,Q){if(!Q)return null;let $=null;return Zh4(A,(B)=>{let D=B.getActionForIntent(Q);if(!D)return!1;return $=D,!0}),$}static of(A){let Q=A.findAncestorStateOfType(AZ0);if(!Q)throw Error("No Actions widget found in context");return Q.dispatcher}static handler(A,Q){let $=x4.of(A).findAction(Q,A);if($&&$.enabled)return()=>$.action.invoke(Q);return null}}class AZ0 extends R0{dispatcher=new QZ0;getActionForIntent(A){let Q=A.constructor;return this.widget.actions.get(Q)}build(A){return this.widget.child}}class V4{constructor(){}toString(){return`${this.constructor.name}()`}}class ON extends V4{constructor(){super()}}class ro extends V4{constructor(){super()}}class so extends V4{constructor(){super()}}class to extends V4{constructor(){super()}}class eo extends V4{constructor(){super()}}class jN extends V4{constructor(){super()}}class $Z0 extends V4{constructor(){super()}}class Ar extends V4{constructor(){super()}}class Qr extends V4{constructor(){super()}}class $r extends V4{constructor(){super()}}class df extends V4{constructor(){super()}}class pf extends V4{direction;constructor(A){super();this.direction=A}toString(){return`NavigateToPromptHistoryIntent(direction: ${this.direction})`}}class Sj extends V4{constructor(){super()}}class RN extends V4{constructor(){super()}}function MO3(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let $=A.key.toLowerCase();if(["control","meta","alt","shift"].includes($))return"";if($===" ")$="space";return Q.push($),Q.join("+")}function Uh4(A){let Q=A.toLowerCase().split("+"),$=Q.pop()||"";return{modifiers:new Set(Q),key:$}}function Xh4(A,Q){let $=Uh4(A),B=Uh4(Q);if($.key!==B.key)return!1;for(let D of B.modifiers)if(!$.modifiers.has(D))return!1;if(B.modifiers.size===0&&$.modifiers.size>0)return!1;return!0}class cf{sequence;timeout;matchedKeys=[];timeoutId=null;constructor(A,Q={}){this.sequence=A,this.timeout=Q.timeout??2000}getProgress(){return{matched:[...this.matchedKeys],remaining:this.sequence.slice(this.matchedKeys.length)}}isInProgress(){return this.matchedKeys.length>0}reset(){if(this.matchedKeys=[],this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null}handleKeyEvent(A){let Q=MO3(A);if(!Q)return"none";let $=this.matchedKeys.length,B=this.sequence[$];if(B&&Xh4(Q,B)){if(this.matchedKeys.push(B),this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null;if(this.matchedKeys.length===this.sequence.length)return this.reset(),"matched";return this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}else if(this.matchedKeys.length>0){this.reset();let D=this.sequence[0];if(D&&Xh4(Q,D))return this.matchedKeys.push(D),this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}return"none"}dispose(){this.reset()}toString(){return this.sequence.map((A)=>{return A.replace("ctrl+","C-").replace("meta+","M-").replace("alt+","A-")}).join(" ")}}class lf{sequences;activeSequence=null;constructor(A=new Map){this.sequences=A}handleKeyEvent(A){if(this.activeSequence){let Q=this.activeSequence.handleKeyEvent(A);if(Q==="matched"){let $=this.sequences.get(this.activeSequence);return this.activeSequence=null,{intent:$,consumed:!0,progress:null}}else if(Q==="progress")return{intent:null,consumed:!0,progress:this.activeSequence.getProgress()};else this.activeSequence=null}for(let[Q,$]of this.sequences){let B=Q.handleKeyEvent(A);if(B==="matched")return{intent:$,consumed:!0,progress:null};else if(B==="progress")return this.activeSequence=Q,{intent:null,consumed:!0,progress:Q.getProgress()}}return{intent:null,consumed:!1,progress:null}}isInProgress(){return this.activeSequence!==null}getProgress(){return this.activeSequence?.getProgress()??null}reset(){this.activeSequence=null;for(let A of this.sequences.keys())A.reset()}dispose(){for(let A of this.sequences.keys())A.dispose()}}class r6{static _nextDebugId=0;_debugId;_parent=null;_children=[];_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;_manager=null;constructor(A={}){if(this._debugId=`focus-${r6._nextDebugId++}`,this._debugLabel=A.debugLabel??null,this._canRequestFocus=A.canRequestFocus??!0,this._skipTraversal=A.skipTraversal??!1,A.onKey)this._keyHandlers.push(A.onKey);this._onPasteCallback=A.onPaste??null}get debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let A=this._manager?.primaryFocus;return this._hasPrimaryFocus||(A?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(A){if(this._canRequestFocus!==A){if(this._canRequestFocus=A,!A&&this._hasPrimaryFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(A){this._skipTraversal=A}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(A){this._onPasteCallback=A}get enclosingScope(){let A=this._parent;while(A!==null){if(he0(A))return A;A=A._parent}return null}get ancestors(){let A=[],Q=this._parent;while(Q!==null)A.push(Q),Q=Q._parent;return A}requestFocus(){if(!this._canRequestFocus)return!1;return this._doRequestFocus({findFirstFocus:!0}),this._manager!==null}unfocus(A="scope"){if(!this.hasFocus&&this._manager?._markedForFocus!==this)return;let Q=this.enclosingScope;if(Q===null)return;switch(A){case"scope":{let $=Q;$._clearFocusedChildren();let B=$.enclosingScope;while(!$.canRequestFocus&&B!==null)B._removeFromHistory($),$=B,$._clearFocusedChildren(),B=$.enclosingScope;$._doRequestFocus({findFirstFocus:!1});break}case"previouslyFocusedChild":{let $=Q;$._removeFromHistory(this);let B=$.enclosingScope;while($.focusedChild===null&&!$.canRequestFocus&&B!==null)B._removeFromHistory($),$=B,B=$.enclosingScope;$._doRequestFocus({findFirstFocus:!0});break}}}_doRequestFocus({findFirstFocus:A}){if(!this._canRequestFocus)return;if(this._hasPrimaryFocus&&this._manager?._markedForFocus===null)return;this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this)}_setAsFocusedChildForScope(){let A=this;for(let Q of this.ancestors)if(he0(Q))Q._pushFocusedChild(A),A=Q}_isDecendantOf(A){if(A===null)return!1;if(this._parent===A)return!0;return this._parent?._isDecendantOf(A)??!1}_isAncestorTo(A){return A?._isDecendantOf(this)??!1}_reparent(A){if(A._parent===this)return;let Q=A.enclosingScope,$=Q!==null&&Q===this.enclosingScope;if(A._parent?._removeChild(A,!$),this._children.push(A),A._parent=this,A._updateManager(this._manager),A._requestFocusWhenReparented)A._doRequestFocus({findFirstFocus:!0}),A._requestFocusWhenReparented=!1}_removeChild(A,Q=!0){let $=this._children.indexOf(A);if($!==-1)this._children.splice($,1);if(Q){let B=A.enclosingScope;if(B!==null)B._removeFromHistory(A),A._collectDescendants().forEach((D)=>B._removeFromHistory(D))}A._parent=null}_collectDescendants(){let A=[],Q=[...this._children];while(Q.length>0){let $=Q.pop();A.push($);for(let B of $._children)Q.push(B)}return A}_updateManager(A){this._manager=A;for(let Q of this._children)Q._updateManager(A)}_requestFocusWhenReparented=!1;_setFocus(A){if(this._hasPrimaryFocus===A)return;let Q=this.hasFocus;this._hasPrimaryFocus=A;let $=this.hasFocus;if(this._notifyListeners(),Q!==$)this._notifyAncestorListeners()}addListener(A){this._listeners.add(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A(this)}_notifyAncestorListeners(){let A=this._parent;while(A)A._notifyListeners(),A=A._parent}_handleKeyEvent(A){return this.handleKeyEvent(A)}_handlePasteEvent(A){if(this._onPasteCallback)return this._onPasteCallback(A);return"ignored"}toStringShort(){let A=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasPrimaryFocus?" FOCUSED":"",$=this._canRequestFocus?"":" (can't focus)";return`Focus${he0(this)?"Scope":""}Node${A}${Q}${$}`}toStringDeep(A="",Q=!0){let $=A+this.toStringShort();if(Q&&this._children.length>0){let B=A+" ";for(let D of this._children)$+=`
5100
+ `)}function ye0(A,Q){let $=[...A],B=new Set($.map((D)=>`${D.kind}:${D.title}`));for(let D of $h4(Q)){let J=`${D.kind}:${D.title}`;if(B.has(J))continue;B.add(J),$.push(Ah4(D,Q.status))}return $}function Ah4(A,Q){return{...A,status:Q}}function Qh4(A){return A.activityKind!=="subagent"||A.status===void 0||bM(A.status)}function $h4(A){return ZO3(A).map((Q)=>({kind:"read",title:`Read ${i$(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function ZO3(A){if(A.status!=="done"||!YB(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap(($)=>{if(!YB($)||typeof $.uri!=="string"||typeof $.lineCount!=="number"||!Number.isFinite($.lineCount))return[];return[{uri:$.uri,lineCount:$.lineCount,...typeof $.content==="string"?{content:$.content}:{}}]})}function UO3(A,Q,$){if(A==="oracle"){let B=typeof Q.task==="string"?Q.task.trim():void 0;return Re0({label:{active:"Oracle exploring",complete:"Oracle has spoken"},detail:B,run:$})}if(A==="librarian"){let B=typeof Q.query==="string"?Q.query.trim():void 0;return Re0({label:{active:"Librarian researching",complete:"Librarian researched"},detail:B,run:$})}if(A==="Task"){let B=typeof Q.description==="string"?Q.description.trim():void 0,D=typeof Q.prompt==="string"?Q.prompt.trim():void 0;return Re0({label:{active:"Subagent working",complete:"Subagent finished"},detail:B??D,run:$})}if(A==="code_review"){let B=GO3($,Q),D=ye0(B.actions,$),J={label:{active:"Reviewing code",complete:"Reviewed code"},activityKind:"subagent",actions:D,summary:B.summary,hasInProgress:bM($.status),status:$.status},F=typeof Q.diff_description==="string"?Q.diff_description.trim():void 0;if(F!==void 0)J.detail=F;let E=g2($);if(E!==void 0)J.error=E;return J}return}function Re0(A){let Q=ye0([],A.run),$={label:A.label,activityKind:"subagent",actions:Q,summary:Te0(Q),hasInProgress:bM(A.run.status),status:A.run.status};if(A.detail!==void 0)$.detail=A.detail;let B=g2(A.run);if(B!==void 0)$.error=B;return $}function XO3(A){let Q="result"in A&&YB(A.result)?A.result:void 0,$=nb4("progress"in A?A.progress:void 0),B=YB($)?$:void 0;return{main:(YB(Q?.main)?Q.main:void 0)??(YB(B?.main)?B.main:void 0),checks:(YB(Q?.checks)?Q.checks:void 0)??(YB(B?.checks)?B.checks:void 0)}}function GO3(A,Q){let $=[],B=new Set,D=(U)=>{let X=`${U.kind}:${U.title}`;if(B.has(X))return;B.add(X),$.push(U)},{main:J,checks:F}=XO3(A);if(A.status==="queued")D({kind:"review",title:"Code review queued"});if(A.status==="error"){let U=g2(A)??"Unknown error";D({kind:"review",title:`Code review failed: ${U}`})}let E=0,Y=0;for(let[U,X]of Object.entries(F??{})){if(!YB(X))continue;Y+=1;let G=FO3(U,X);if(X.status==="done"){E+=1;let V=EO3(X);if(V===void 0)D({kind:"review",title:`Check ${G}: complete`});else if(V===0)D({kind:"review",title:`Check ${G}: ok`});else D({kind:"review",title:`Check ${G}: ${V} ${U4(V,"issue")} found`});continue}if(X.status==="error"){E+=1;let V=typeof X.error==="string"&&X.error.trim()?X.error.trim():"Unknown error";D({kind:"review",title:`Check ${G}: error (${V})`});continue}if(X.status==="in-progress"){let V=typeof X.message==="string"&&X.message.trim()?X.message.trim():"Running check...";D({kind:"review",title:`Check ${G}: ${V}`})}}if(J?.status==="done"&&Y>0&&E<Y)D({kind:"review",title:"Main review complete, running checks..."});if(A.status==="done")D({kind:"review",title:"Code review complete"});if($.length===0)D({kind:"review",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let Z=Q.thinking==="low"?"quick code review":"code review";return{actions:$,summary:Y>0?`${E}/${Y} checks · ${Z}`:Z}}function Te0(A,Q=""){let $=0,B=0,D=new Map;for(let F of A){if(F.icon==="docs"&&(F.title.startsWith("Read ")||F.title.startsWith("Load "))){$++;continue}if(F.title.startsWith("Read skill ")){B++;continue}D.set(F.kind,(D.get(F.kind)??0)+1)}let J=[];for(let[F,E,Y]of[["read","file",void 0],["view","media file","media files"],["web-page","web page","web pages"],["thread","thread",void 0],["skill","skill",void 0],["guidance","guidance file","guidance files"],["search","search","searches"],["web","web search","web searches"],["review","review","reviews"],["list","list",void 0]]){let Z=F==="guidance"?$:F==="skill"?B:D.get(F);if(!Z)continue;J.push(`${Z} ${U4(Z,E,Y)}`)}if(J.length>0)return J.join(", ");return Q}function VO3(A){if(A.kind==="search"&&KO3(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return iJ0(A)}function KO3(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function YB(A){return typeof A==="object"&&A!==null}u1();var zO3="T-00000000-0000-0000-0000-000000000000";class eY0{messagesState=new ME0(zO3);transcriptEntries=[];transcriptListeners=new Set;transcriptReader={read:()=>this.transcriptEntries,subscribe:(A)=>{return this.transcriptListeners.add(A),()=>this.transcriptListeners.delete(A)}};_agentMode;_reasoningEffort=void 0;observerState;activeErrorPayload=null;activeErrorSeq=null;connectionErrorSubject=new a1(null);activeErrorSubject=new a1(null);agentMessageIdSubject=new a1(null);cancelledSubject=new d4;queuedMessageRemovalSubject=new d4;transcriptRebuildBatchDepth=0;pendingTranscriptRebuildPreviousLength=null;log=u;constructor(A,Q=null){this._agentMode=A,this._reasoningEffort=ZX(A,Q??{}),this.observerState=new wE0({initialAgentLoopState:"idle",initialThreadSettings:Q,dedupeQueuedMessageAdds:!1,compactionRecordsState:"idle"})}logObserverServerMessage(A,Q){if(!CE0(Q))return;this.log.info(A,NE0(Q,{direction:"receive"}))}get agentMode(){return this._agentMode}set agentMode(A){if(this._agentMode===A)return;if(this._agentMode=A,this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}get reasoningEffort(){return this._reasoningEffort}reader(){return this.transcriptReader}protocolMessages(){return this.messagesState.messages()}agentState(){return this.observerState.agentLoopState}agentMessageId(){return this.agentMessageIdSubject}connectionInfo(){return this.observerState.connectionInfo}threadID(){return this.observerState.threadId}pluginMessages(){return this.observerState.pluginMessages}pluginUIRequests(){return this.observerState.pluginUIRequests}connectionError(){return this.connectionErrorSubject}setConnectionError(A){if(this.connectionErrorSubject.getValue()===A)return;this.connectionErrorSubject.next(A)}pendingSend(){return this.observerState.pendingSend}status(){return this.observerState.status}stageBytes(){return this.observerState.stageBytes}activeError(){return this.activeErrorSubject}cancelled(){return this.cancelledSubject}getActiveErrorSeq(){return this.activeErrorSeq}title(){return this.observerState.threadTitle}queuedMessages(){return this.observerState.queuedMessages}queuedMessageRemovalEvents(){return this.queuedMessageRemovalSubject}threadSettings(){return this.observerState.threadSettings}compactionState(){return this.observerState.compactionState}beginTranscriptRebuildBatch(){this.transcriptRebuildBatchDepth+=1}endTranscriptRebuildBatch(){if(this.transcriptRebuildBatchDepth===0)return;if(this.transcriptRebuildBatchDepth-=1,this.transcriptRebuildBatchDepth>0)return;let A=this.pendingTranscriptRebuildPreviousLength;if(this.pendingTranscriptRebuildPreviousLength=null,A!==null)this.rebuildTranscriptEntries(A)}dismissActiveError(){if(this.activeErrorPayload===null)return;this.activeErrorPayload=null,this.activeErrorSeq=null,this.activeErrorSubject.next(null)}onMessageAdded(A){this.logObserverServerMessage("[observer] onMessageAdded",A),this.observerState.onMessageAdded(A),this.applyThreadMessageEvent(A)}onMessageRemoved(A){this.log.info("[observer] onMessageRemoved",{data:{messageId:A}}),this.observerState.onMessageRemoved(A);let Q=this.transcriptEntries.length;if(this.messagesState.remove(A).changed)this.requestTranscriptRebuild(Q)}onMessageUpdated(A){this.logObserverServerMessage("[observer] onMessageUpdated",A),this.observerState.onMessageUpdated(A),this.applyThreadMessageEvent(A)}onDelta(A){this.observerState.onDelta(A),this.applyThreadMessageEvent(A)}onTruncate(A){this.logObserverServerMessage("[observer] onTruncate",A),this.observerState.onTruncate(A),this.applyThreadMessageEvent(A)}onAgentState(A){this.logObserverServerMessage("[observer] onAgentState",A);let Q=rQ(this.observerState.agentLoopState.getValue()),$=this._agentMode;if(A.agentMode!==void 0)this._agentMode=A.agentMode;this._reasoningEffort=A.reasoningEffort,this.agentMessageIdSubject.next(A.messageId??null),this.observerState.onAgentState(A);let B=rQ(this.observerState.agentLoopState.getValue());if(($!==this._agentMode||Q!==B)&&this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}onThreadSettings(A){this.logObserverServerMessage("[observer] onThreadSettings",A),this.observerState.onThreadSettings(A)}onThreadId(A){this.log.info("[observer] onThreadId",{data:{threadId:A}}),this.log=u.with({threadId:A}),this.messagesState.setThreadID(A),this.observerState.onThreadId(A),this.observerState.threadId.complete()}onConnectionChanged(A){if(this.log.info("[observer] onConnectionChanged",{data:A}),this.observerState.onConnectionChanged(A),I9(A))this.setConnectionError(null)}onQueuedMessages(A){this.logObserverServerMessage("[observer] onQueuedMessages",A);let Q=A.type==="queued_message_removed"?this.observerState.queuedMessages.getValue().find(($)=>$.queuedMessage.messageId===A.queuedMessageId):void 0;if(this.observerState.onQueuedMessages(A),A.type==="queued_message_removed"&&Q!==void 0)this.queuedMessageRemovalSubject.next({message:Q,serverMessage:A})}onUserActionMessageDeliveryStatusChanged(A,Q,$){this.log.info("[observer] onUserActionMessageDeliveryStatusChanged",{data:{messageId:A,status:Q,sentAt:$}}),this.observerState.onUserActionMessageDeliveryStatusChanged(A,Q,$)}onUserMessageSendPending(A,Q){this.log.info("[observer] onUserMessageSendPending",{data:{messageId:A,sentAt:Q}}),this.observerState.onUserMessageSendPending(A,Q)}onUserMessageSendAck(A){this.log.info("[observer] onUserMessageSendAck",{data:{messageId:A}}),this.observerState.onUserMessageSendAck(A)}onErrorNotice(A){if(this.logObserverServerMessage("[observer] onErrorNotice",A),this.activeErrorPayload!==null)return;this.observerState.onErrorNotice(A)}onActiveError(A){if(this.logObserverServerMessage("[observer] onActiveError",A),this.observerState.onActiveError(A),A.type==="error_set")this.activeErrorPayload=A.error,this.activeErrorSeq=A.seq;else this.activeErrorPayload=null,this.activeErrorSeq=null;this.activeErrorSubject.next(this.activeErrorPayload)}onCancelled(A){this.logObserverServerMessage("[observer] onCancelled",A),this.observerState.onCancelled(A),this.cancelledSubject.next(A)}onToolProgress(A){this.logObserverServerMessage("[observer] onToolProgress",A),this.observerState.onToolProgress(A),this.applyThreadMessageEvent(A)}onExecutorStatus(A){this.logObserverServerMessage("[observer] onExecutorStatus",A),this.observerState.onExecutorStatus(A)}onExecutorError(A){this.logObserverServerMessage("[observer] onExecutorError",A),this.observerState.onExecutorError(A)}onObservers(A){this.logObserverServerMessage("[observer] onObservers",A),this.observerState.onObservers(A)}onArtifactEvent(A){this.observerState.onArtifactEvent(A)}onEnvironmentUpdate(A){this.observerState.onEnvironmentUpdate(A)}onPluginMessage(A){this.observerState.onPluginMessage(A)}onRetryEvent(A){this.log.info("[observer] onRetryEvent",{data:A}),this.observerState.onRetryEvent(A)}onThreadTitle(A){this.log.info("[observer] onThreadTitle",{data:A}),this.observerState.onThreadTitle(A)}onCompactionEvent(A){this.log.info("[observer] onCompactionEvent",{data:A});let Q=A.type==="compaction_started"?"compacting":"idle";if(A.type==="compaction_started"&&this.observerState.compactionState.getValue()===Q)return;let $=this.transcriptEntries.length;if(this.observerState.onCompactionEvent(A),A.type==="compaction_complete"&&A.cutMessageId!==void 0||A.type==="compaction_records")this.requestTranscriptRebuild($)}applyThreadMessageEvent(A){let Q=this.transcriptEntries.length;if(!this.messagesState.apply(A).changed)return;this.requestTranscriptRebuild(Q)}requestTranscriptRebuild(A){if(this.transcriptRebuildBatchDepth===0){this.rebuildTranscriptEntries(A);return}this.pendingTranscriptRebuildPreviousLength=Math.min(this.pendingTranscriptRebuildPreviousLength??A,A)}rebuildTranscriptEntries(A){let Q=Sb4(this.messagesState.messages(),{threadID:this.messagesState.getThreadID(),...kb4(this._agentMode),isWorking:rQ(this.observerState.agentLoopState.getValue()),compactionCutMessageIDs:this.observerState.compactionRecords.getValue().map(($)=>$.cutMessageId)});this.transcriptEntries.length=0,this.transcriptEntries.push(...Q),this.notifyTranscriptReaders(WO3(A,Q.length))}notifyTranscriptReaders(A){for(let Q of this.transcriptListeners)Q(A)}}function WO3(A,Q){return Array.from({length:Math.max(A,Q)},($,B)=>B)}var IO3=45000;class xe0{rivetEndpoint;apiKey;configService;runtimeDependencies;loadThreadHistory;importThreadIntoActor;observingClients=[];_lastActiveObservingClient=null;connectionErrorSubject=new d4;constructor(A,Q,$,B,D,J){this.rivetEndpoint=A;this.apiKey=Q;this.configService=$;this.runtimeDependencies=B;this.loadThreadHistory=D;this.importThreadIntoActor=J}get lastActiveObservingClient(){return this._lastActiveObservingClient}get activeThreadIDs(){let A=new Set;for(let Q of this.observingClients){let $=Q.threadID??Q.client.getThreadId();if($)A.add($)}return[...A]}get connectionErrors$(){return this.connectionErrorSubject}async connectToThread(A,Q={}){let $=Q.observerOnly??!1,B=$?"observer":"executor",D=this.observingClients.find((Z)=>(Z.threadID===A||Z.client.getThreadId()===A)&&($?Z.observerOnly:!0));if(D)return this._lastActiveObservingClient=D,this.persistLastThreadID(A),D;let J=this.createClient({threadID:A,requiredRole:B}),F=await J.loadThreadHistory(A);if(!F)throw J.dispose(),new W9("Thread not found");if(F.needsImport){if(!this.importThreadIntoActor)throw J.dispose(),new W9("Thread requires import before connecting");try{await this.importThreadIntoActor(A)}catch(Z){throw J.dispose(),oo(Z)}}let E=new eY0(F.agentMode);E.beginTranscriptRebuildBatch();try{J.setObserverCallbacks(E)}finally{E.endTranscriptRebuildBatch()}let Y={client:J,observer:E,threadID:A,logger:u.with({threadId:A}),observerOnly:$,connectionSubscription:Qf(J,{onError:({threadID:Z,error:U})=>this.emitConnectionError(E,U,Z)})};return this.connectAndResume(J,F.version,{observerOnly:$,onExecutorAlreadyConnected:Q.onExecutorAlreadyConnected,onDowngradedToObserver:()=>{Y.observerOnly=!0},onRetryableConnectError:(Z)=>this.emitConnectionError(E,Z,A,{showInObserver:!1})}).catch((Z)=>{this.emitConnectionError(E,Z,A)}),this.persistLastThreadID(A),this.observingClients.push(Y),this._lastActiveObservingClient=Y,Y}createNewThread(A,Q,$){let B=this.createClient({agentMode:A,initialThreadMeta:$,requiredRole:"executor"}),D=new eY0(A,Q??null);B.setObserverCallbacks(D);let J={client:B,observer:D,threadID:null,logger:u,observerOnly:!1,connectionSubscription:Qf(B,{requireRole:"executor",onError:({threadID:F,error:E})=>this.emitConnectionError(D,E,F)})};if(Q)B.sendClientUpdateThreadSettings(Q);else bf(this.configService).then((F)=>{B.sendClientUpdateThreadSettings(F)}).catch((F)=>{u.warn("Failed to seed thread settings",{threadID:B.getThreadId(),error:F instanceof Error?F.message:String(F)})});return this.observingClients.push(J),this.connectAndResume(B,0,{onRetryableConnectError:(F)=>this.emitConnectionError(D,F,void 0,{showInObserver:!1})}).then((F)=>{let E=F.getThreadId();if(J.threadID=E,E)J.logger=u.with({threadId:E}),this.persistLastThreadID(E)}).catch((F)=>{this.emitConnectionError(D,F)}),this._lastActiveObservingClient=J,J}dispose(){for(let{client:A,connectionSubscription:Q}of this.observingClients.values())Q.unsubscribe(),A.dispose();this.observingClients.length=0,this._lastActiveObservingClient=null,this.connectionErrorSubject.complete()}createClient(A={}){let{threadID:Q,agentMode:$,initialThreadMeta:B,requiredRole:D}=A,J=If(async(F)=>{try{let E={agentMode:$,executorType:"local-client"};if(!F&&B)E.threadMeta=B;return await c9(F,this.configService,this.apiKey,E)}catch(E){throw oo(E)}},Q);return new zG({transport:Hf({rivetEndpoint:this.rivetEndpoint,credentialsProvider:J,initialThreadID:Q,pingIntervalMs:5000,requiredRole:D}),threadHistoryLoader:this.loadThreadHistory})}async connectAndResume(A,Q,$={}){let B=$.observerOnly??!1,D=null;try{await HO3(A,$);let J=A.getThreadId();if(!J)throw A.disconnect(),new W9("Thread client connected without a thread ID");if(B)return await qO3(A),A.resumeFromVersion(Q),A;D=this.createExecutor(A,J),D.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),D.handleConnectionChange(A.getConnectionInfo());try{await D.ensureReady({timeoutMs:IO3,timeoutMessage:"Couldn’t connect to Amp servers — run amp: reconnect to retry"})}catch(F){if(!fa(F))throw F;if(D.dispose(),D=null,(await $.onExecutorAlreadyConnected?.({existingExecutorPid:F.payload.existingExecutorPid??null})??"observe")==="disconnect")return A.disconnect(),A;A.downgradeExecutorRequirementToObserver(),$.onDowngradedToObserver?.()}return A.resumeFromVersion(Q),A}catch(J){throw A.disconnect(),oo(J)}}createExecutor(A,Q){return new Cj({transport:A,toolService:this.runtimeDependencies.toolService,configService:this.configService,clientID:this.runtimeDependencies.clientID,threadId:Q,invokeTool:($)=>this.runtimeDependencies.invokeTool(Q,$),requestPluginToolCall:this.runtimeDependencies.requestPluginToolCall,requestPluginToolResult:this.runtimeDependencies.requestPluginToolResult,pluginService:this.runtimeDependencies.pluginService,pluginPlatform:this.runtimeDependencies.pluginPlatform,readFileSystemDirectory:this.runtimeDependencies.readFileSystemDirectory,skillService:this.runtimeDependencies.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:process.cwd()})}emitConnectionError(A,Q,$,B={}){let D=oo(Q);if(B.showInObserver!==!1)A.setConnectionError(D.message);this.connectionErrorSubject.next({threadID:$??void 0,error:D})}persistLastThreadID(A){this.runtimeDependencies.persistLastThreadID(A).catch((Q)=>{u.warn("Failed to persist last active thread ID",{threadID:A,error:Q instanceof Error?Q.message:String(Q)})})}}async function HO3(A,Q){try{await A.connect()}catch(B){let D=oo(B),J=A.getConnectionInfo().state;if(J!=="reconnecting"&&J!=="connecting")throw D;if(J==="reconnecting")Q.onRetryableConnectError?.(D);await Bh4(A);return}let $=A.getConnectionInfo();if($.state==="connected")return;if($.state==="reconnecting"||$.state==="connecting"){await Bh4(A);return}throw new W9("Connection canceled")}async function Bh4(A){if((await k1(A.connectionChanges().pipe(l3(($)=>$.state==="connected"||$.state==="disconnected"),j8(1)))).state==="disconnected")throw new W9("Couldn’t connect to Amp servers — run amp: reconnect to retry")}async function qO3(A){if(I9(A.getConnectionInfo()))return;if((await k1(A.connectionChanges().pipe(l3(($)=>I9($)||$.state==="disconnected"),j8(1)))).state==="disconnected")throw new W9("Couldn’t connect to Amp servers — run amp: reconnect to retry")}function oo(A){if(A instanceof W9)return A;if(A instanceof Error){let Q=A.message||"Unknown connection error";return new W9(Q,A)}if(typeof A==="string"&&A.length>0)return new W9(A,A);return new W9("Unknown connection error",A)}async function Dh4(A){let Q=await A.configService.getLatest(A.signal),$=await Q.secrets.getToken("apiKey",Q.settings.url);if(!$)throw Error("API key required. Please run `amp login` first.");let B=await c9(A.threadID,A.configService,$,{signal:A.signal}),D=aJ(A.ampURL),F=await LG({endpoint:D,poolName:B.poolName}).threadActor.get([A.threadID]).fetch("/skills",{method:"GET",headers:{Authorization:`Bearer ${$}`},signal:A.signal,skipReadyWait:!0});if(!F.ok){let Y=await F.text();throw Error(`Skills request failed (${F.status}): ${Y}`)}let E=await F.json();if(!E.ok)throw Error(E.error);return{skills:E.skills,errors:E.errors}}pF();p0();jA();jA();Q4();var iE={agentMode:"deep",launchCount:0,neoInvadersHighScore:0,shortcutsHintUsed:!1,neoWelcomeDismissed:!1};function Fh4(A,Q){if(Q==="execute")return A.lastExecuteThreadId??A.lastThreadId;return A.lastThreadId}function mf(A,Q,$){if($==="execute")return{...A,lastExecuteThreadId:Q};return{...A,lastThreadId:Q}}function Eh4(A){return{...A,neoWelcomeDismissed:!0}}function Yh4(A=P_){return B1.joinPath(i0.file(A),"session.json")}var Jh4=Promise.resolve();async function bz(A={}){try{let Q=await NO3(A.dataDir),$={...iE,agentMode:Q?.agentMode??iE.agentMode,launchCount:Q?.launchCount??iE.launchCount,neoInvadersHighScore:Q?.neoInvadersHighScore??iE.neoInvadersHighScore,neoWelcomeDismissed:Q?.neoWelcomeDismissed??iE.neoWelcomeDismissed,shortcutsHintUsed:Q?.shortcutsHintUsed??iE.shortcutsHintUsed,lastThreadId:Q?.lastThreadId,lastExecuteThreadId:Q?.lastExecuteThreadId},B={...Q?.lastReasoningEffortByMode};if(Object.keys(B).length>0)$.lastReasoningEffortByMode=B;let D={...Q?.lastSpeedByMode};if(Object.keys(D).length>0)$.lastSpeedByMode=D;return $}catch{return{...iE}}}async function NO3(A){try{let Q=await xA(Yh4(A),"utf8");return JSON.parse(Q)}catch(Q){if(N5(Q))return;throw Q}}async function CO3(A,Q){try{let $=Yh4(Q.dataDir),B=$.with({path:`${$.path}.amptmp`});await SQ(B1.joinPath($,".."),{recursive:!0}),await n7(B,JSON.stringify(A,null,2)),await y20(B,$)}catch($){u.warn("Failed to save session state.",{error:$ instanceof Error?$.message:String($)})}}async function GQ(A,Q={}){let $={...iE},B=Jh4.catch(()=>{return}).then(async()=>{let D=await bz(Q);$={...iE,...A(D)},await CO3($,Q)});return Jh4=B.then(()=>{return},()=>{return}),await B,$}class be0{constructor(){}isEnabled(A){return!0}consumesKey(A){return!0}toString(){return`${this.constructor.name}()`}}class T1 extends be0{onInvoke;constructor(A){super();this.onInvoke=A}invoke(A){return this.onInvoke(A)}}function wO3(A){return"state"in A}function Zh4(A,Q){let $=A.element.parent;while($){if(wO3($)&&$.state instanceof AZ0){if(Q($.state))return}$=$.parent}}class QZ0{invokeAction(A,Q){let $=this.findAction(A,Q);if($&&$.enabled)return $.action.invoke(A);return null}findAction(A,Q){let $=null;return Zh4(Q,(B)=>{let D=B.getActionForIntent(A);if(!D)return!1;return $={action:D,enabled:D.isEnabled(A)},!0}),$}}class x4 extends u0{actions;child;dispatcher;constructor({actions:A,child:Q,dispatcher:$,key:B}){super({key:B});this.actions=A,this.child=Q,this.dispatcher=$}createState(){return new AZ0}static invoke(A,Q){return x4.of(A).invokeAction(Q,A)}static maybeInvoke(A,Q){try{return x4.invoke(A,Q)}catch{return null}}static find(A,Q){let $=x4.maybeFind(A,Q);if(!$){let B=Q?.constructor.name||"unknown";throw Error(`No action found for intent type: ${B}`)}return $}static maybeFind(A,Q){if(!Q)return null;let $=null;return Zh4(A,(B)=>{let D=B.getActionForIntent(Q);if(!D)return!1;return $=D,!0}),$}static of(A){let Q=A.findAncestorStateOfType(AZ0);if(!Q)throw Error("No Actions widget found in context");return Q.dispatcher}static handler(A,Q){let $=x4.of(A).findAction(Q,A);if($&&$.enabled)return()=>$.action.invoke(Q);return null}}class AZ0 extends R0{dispatcher=new QZ0;getActionForIntent(A){let Q=A.constructor;return this.widget.actions.get(Q)}build(A){return this.widget.child}}class V4{constructor(){}toString(){return`${this.constructor.name}()`}}class ON extends V4{constructor(){super()}}class ro extends V4{constructor(){super()}}class so extends V4{constructor(){super()}}class to extends V4{constructor(){super()}}class eo extends V4{constructor(){super()}}class jN extends V4{constructor(){super()}}class $Z0 extends V4{constructor(){super()}}class Ar extends V4{constructor(){super()}}class Qr extends V4{constructor(){super()}}class $r extends V4{constructor(){super()}}class df extends V4{constructor(){super()}}class pf extends V4{direction;constructor(A){super();this.direction=A}toString(){return`NavigateToPromptHistoryIntent(direction: ${this.direction})`}}class Sj extends V4{constructor(){super()}}class RN extends V4{constructor(){super()}}function MO3(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let $=A.key.toLowerCase();if(["control","meta","alt","shift"].includes($))return"";if($===" ")$="space";return Q.push($),Q.join("+")}function Uh4(A){let Q=A.toLowerCase().split("+"),$=Q.pop()||"";return{modifiers:new Set(Q),key:$}}function Xh4(A,Q){let $=Uh4(A),B=Uh4(Q);if($.key!==B.key)return!1;for(let D of B.modifiers)if(!$.modifiers.has(D))return!1;if(B.modifiers.size===0&&$.modifiers.size>0)return!1;return!0}class cf{sequence;timeout;matchedKeys=[];timeoutId=null;constructor(A,Q={}){this.sequence=A,this.timeout=Q.timeout??2000}getProgress(){return{matched:[...this.matchedKeys],remaining:this.sequence.slice(this.matchedKeys.length)}}isInProgress(){return this.matchedKeys.length>0}reset(){if(this.matchedKeys=[],this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null}handleKeyEvent(A){let Q=MO3(A);if(!Q)return"none";let $=this.matchedKeys.length,B=this.sequence[$];if(B&&Xh4(Q,B)){if(this.matchedKeys.push(B),this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null;if(this.matchedKeys.length===this.sequence.length)return this.reset(),"matched";return this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}else if(this.matchedKeys.length>0){this.reset();let D=this.sequence[0];if(D&&Xh4(Q,D))return this.matchedKeys.push(D),this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}return"none"}dispose(){this.reset()}toString(){return this.sequence.map((A)=>{return A.replace("ctrl+","C-").replace("meta+","M-").replace("alt+","A-")}).join(" ")}}class lf{sequences;activeSequence=null;constructor(A=new Map){this.sequences=A}handleKeyEvent(A){if(this.activeSequence){let Q=this.activeSequence.handleKeyEvent(A);if(Q==="matched"){let $=this.sequences.get(this.activeSequence);return this.activeSequence=null,{intent:$,consumed:!0,progress:null}}else if(Q==="progress")return{intent:null,consumed:!0,progress:this.activeSequence.getProgress()};else this.activeSequence=null}for(let[Q,$]of this.sequences){let B=Q.handleKeyEvent(A);if(B==="matched")return{intent:$,consumed:!0,progress:null};else if(B==="progress")return this.activeSequence=Q,{intent:null,consumed:!0,progress:Q.getProgress()}}return{intent:null,consumed:!1,progress:null}}isInProgress(){return this.activeSequence!==null}getProgress(){return this.activeSequence?.getProgress()??null}reset(){this.activeSequence=null;for(let A of this.sequences.keys())A.reset()}dispose(){for(let A of this.sequences.keys())A.dispose()}}class r6{static _nextDebugId=0;_debugId;_parent=null;_children=[];_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;_manager=null;constructor(A={}){if(this._debugId=`focus-${r6._nextDebugId++}`,this._debugLabel=A.debugLabel??null,this._canRequestFocus=A.canRequestFocus??!0,this._skipTraversal=A.skipTraversal??!1,A.onKey)this._keyHandlers.push(A.onKey);this._onPasteCallback=A.onPaste??null}get debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let A=this._manager?.primaryFocus;return this._hasPrimaryFocus||(A?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(A){if(this._canRequestFocus!==A){if(this._canRequestFocus=A,!A&&this._hasPrimaryFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(A){this._skipTraversal=A}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(A){this._onPasteCallback=A}get enclosingScope(){let A=this._parent;while(A!==null){if(he0(A))return A;A=A._parent}return null}get ancestors(){let A=[],Q=this._parent;while(Q!==null)A.push(Q),Q=Q._parent;return A}requestFocus(){if(!this._canRequestFocus)return!1;return this._doRequestFocus({findFirstFocus:!0}),this._manager!==null}unfocus(A="scope"){if(!this.hasFocus&&this._manager?._markedForFocus!==this)return;let Q=this.enclosingScope;if(Q===null)return;switch(A){case"scope":{let $=Q;$._clearFocusedChildren();let B=$.enclosingScope;while(!$.canRequestFocus&&B!==null)B._removeFromHistory($),$=B,$._clearFocusedChildren(),B=$.enclosingScope;$._doRequestFocus({findFirstFocus:!1});break}case"previouslyFocusedChild":{let $=Q;$._removeFromHistory(this);let B=$.enclosingScope;while($.focusedChild===null&&!$.canRequestFocus&&B!==null)B._removeFromHistory($),$=B,B=$.enclosingScope;$._doRequestFocus({findFirstFocus:!0});break}}}_doRequestFocus({findFirstFocus:A}){if(!this._canRequestFocus)return;if(this._hasPrimaryFocus&&this._manager?._markedForFocus===null)return;this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this)}_setAsFocusedChildForScope(){let A=this;for(let Q of this.ancestors)if(he0(Q))Q._pushFocusedChild(A),A=Q}_isDecendantOf(A){if(A===null)return!1;if(this._parent===A)return!0;return this._parent?._isDecendantOf(A)??!1}_isAncestorTo(A){return A?._isDecendantOf(this)??!1}_reparent(A){if(A._parent===this)return;let Q=A.enclosingScope,$=Q!==null&&Q===this.enclosingScope;if(A._parent?._removeChild(A,!$),this._children.push(A),A._parent=this,A._updateManager(this._manager),A._requestFocusWhenReparented)A._doRequestFocus({findFirstFocus:!0}),A._requestFocusWhenReparented=!1}_removeChild(A,Q=!0){let $=this._children.indexOf(A);if($!==-1)this._children.splice($,1);if(Q){let B=A.enclosingScope;if(B!==null)B._removeFromHistory(A),A._collectDescendants().forEach((D)=>B._removeFromHistory(D))}A._parent=null}_collectDescendants(){let A=[],Q=[...this._children];while(Q.length>0){let $=Q.pop();A.push($);for(let B of $._children)Q.push(B)}return A}_updateManager(A){this._manager=A;for(let Q of this._children)Q._updateManager(A)}_requestFocusWhenReparented=!1;_setFocus(A){if(this._hasPrimaryFocus===A)return;let Q=this.hasFocus;this._hasPrimaryFocus=A;let $=this.hasFocus;if(this._notifyListeners(),Q!==$)this._notifyAncestorListeners()}addListener(A){this._listeners.add(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A(this)}_notifyAncestorListeners(){let A=this._parent;while(A)A._notifyListeners(),A=A._parent}_handleKeyEvent(A){return this.handleKeyEvent(A)}_handlePasteEvent(A){if(this._onPasteCallback)return this._onPasteCallback(A);return"ignored"}toStringShort(){let A=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasPrimaryFocus?" FOCUSED":"",$=this._canRequestFocus?"":" (can't focus)";return`Focus${he0(this)?"Scope":""}Node${A}${Q}${$}`}toStringDeep(A="",Q=!0){let $=A+this.toStringShort();if(Q&&this._children.length>0){let B=A+" ";for(let D of this._children)$+=`
5101
5101
  `+D.toStringDeep(B,!0)}return $}addKeyHandler(A){this._keyHandlers.push(A)}removeKeyHandler(A){let Q=this._keyHandlers.indexOf(A);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(A){for(let Q of this._keyHandlers)if(Q(A)==="handled")return"handled";return"ignored"}dispose(){this._parent?._removeChild(this,!0),this._children.length=0,this._keyHandlers=[]}}function he0(A){return A._isFocusScopeNode===!0}class uN extends r6{_isFocusScopeNode=!0;_focusedChildren=[];constructor(A={}){super({canRequestFocus:A.canRequestFocus??!0,skipTraversal:A.skipTraversal??!0,...A})}get focusedChild(){return this._focusedChildren.length===0?null:this._focusedChildren[this._focusedChildren.length-1]}autofocus(A){if(A.parent===null)this._reparent(A);let Q=this._manager;if(Q===null){A._requestFocusWhenReparented=!0;return}Q._enqueueAutofocus(this,A)}_doRequestFocus({findFirstFocus:A}){while(this._focusedChildren.length>0&&(!this._focusedChildren[this._focusedChildren.length-1].canRequestFocus||this._focusedChildren[this._focusedChildren.length-1].enclosingScope===null))this._focusedChildren.pop();let Q=this.focusedChild;if(!A||Q===null){if(this.canRequestFocus)this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this);return}Q._doRequestFocus({findFirstFocus:!0})}_pushFocusedChild(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1);this._focusedChildren.push(A)}_removeFromHistory(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1)}_clearFocusedChildren(){this._focusedChildren.length=0}get focusedChildren(){return this._focusedChildren}}class m2{static _instance=null;static _keystrokes=[];static _MAX_KEYSTROKES=100;_rootScope;_primaryFocus=null;_markedForFocus=null;_pendingAutofocuses=[];_haveScheduledUpdate=!1;constructor(){this._rootScope=new uN({debugLabel:"Root Focus Scope",canRequestFocus:!1}),this._rootScope._updateManager(this)}static getRecentKeystrokes(){return[...m2._keystrokes]}static _recordKeystroke(A,Q,$){if(m2._keystrokes.push({timestamp:Date.now(),key:A,focusPath:Q,handled:$}),m2._keystrokes.length>m2._MAX_KEYSTROKES)m2._keystrokes.shift()}static get instance(){if(!m2._instance)m2._instance=new m2;return m2._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(A){if(!A.canRequestFocus)return!1;return A._doRequestFocus({findFirstFocus:!0}),!0}_markNextFocus(A){if(this._primaryFocus===A){this._markedForFocus=null;return}this._commitFocus(A)}_commitFocus(A){if(this._primaryFocus===A)return;let Q=this._primaryFocus;this._primaryFocus=A,Q?._setFocus(!1),A?._setFocus(!0)}_enqueueAutofocus(A,Q){this._pendingAutofocuses.push({scope:A,node:Q}),this._scheduleUpdate()}_scheduleUpdate(){if(this._haveScheduledUpdate)return;this._haveScheduledUpdate=!0,queueMicrotask(()=>{this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()})}_applyFocusChangesIfNeeded(){let A=this._pendingAutofocuses;this._pendingAutofocuses=[];for(let Q of A)this._applyAutofocusIfValid(Q)}_applyAutofocusIfValid(A){let{scope:Q,node:$}=A;if((Q.parent!==null||Q===this._rootScope)&&Q._manager===this&&Q.focusedChild===null&&$.ancestors.includes(Q))$._doRequestFocus({findFirstFocus:!0})}flushAutofocus(){this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()}handleKeyEvent(A){if(!this._primaryFocus)return!1;let Q=void 0,$=this._primaryFocus;while($){let D=$._handleKeyEvent(A)==="handled";if(Q)Q.push({id:$.debugId,debugLabel:$.debugLabel,handled:D});if(D){if(Q)m2._recordKeystroke(this.formatKeyEvent(A),Q,!0);return!0}$=$.parent}if(Q)m2._recordKeystroke(this.formatKeyEvent(A),Q,!1);return!1}formatKeyEvent(A){let Q=[];if(A.ctrlKey)Q.push("Ctrl");if(A.altKey)Q.push("Alt");if(A.shiftKey)Q.push("Shift");if(A.metaKey)Q.push("Meta");if(A.key)Q.push(A.key);return Q.join("+")}handlePasteEvent(A){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(A)==="handled")return!0;Q=Q.parent}return!1}registerNode(A,Q=null){q4(A!==Q,"Focus node cannot be its own parent"),(Q??this._rootScope)._reparent(A)}unregisterNode(A){if(A.hasPrimaryFocus||this._markedForFocus===A)A.unfocus("previouslyFocusedChild");if(this._pendingAutofocuses=this._pendingAutofocuses.filter(($)=>$.node!==A&&$.scope!==A),A.parent?._removeChild(A,!0),this._primaryFocus===A)this._commitFocus(null);A._updateManager(null)}_focusNodeToDebugInfo(A){let Q=A instanceof uN,$=Q?A:null;return{id:A.debugId,debugLabel:A.debugLabel,hasPrimaryFocus:A.hasPrimaryFocus,hasFocus:A.hasFocus,canRequestFocus:A.canRequestFocus,skipTraversal:A.skipTraversal,isPrimaryFocus:this._primaryFocus===A,isScope:Q,focusedChildIds:$?$.focusedChildren.map((B)=>B.debugId):[],children:A.children.map((B)=>this._focusNodeToDebugInfo(B))}}debugDumpFocusTree(){return{timestamp:Date.now(),rootScope:this._focusNodeToDebugInfo(this._rootScope),primaryFocusId:this._primaryFocus?.debugId??null,focusStack:this._rootScope.focusedChildren.map((A)=>({id:A.debugId,debugLabel:A.debugLabel}))}}dispose(){this._primaryFocus=null,this._markedForFocus=null,this._pendingAutofocuses=[],this._haveScheduledUpdate=!1,this._rootScope.dispose(),m2._instance=null}}class v4 extends u0{focusNode;child;autofocus;canRequestFocus;skipTraversal;onKey;onPaste;onFocusChange;debugLabel;constructor({key:A,focusNode:Q,child:$,autofocus:B=!1,canRequestFocus:D=!0,skipTraversal:J=!1,onKey:F,onPaste:E,onFocusChange:Y,debugLabel:Z}){super({key:A});this.focusNode=Q,this.child=$,this.autofocus=B,this.canRequestFocus=D,this.skipTraversal=J,this.onKey=F||null,this.onPaste=E||null,this.onFocusChange=Y||null,this.debugLabel=Z||null}createState(){return new nf}}class nf extends R0{_internalFocusNode=null;_isDisposed=!1;_focusChangeHandler=null;_didAutofocus=!1;get effectiveFocusNode(){return this.widget.focusNode??this._internalFocusNode}createFocusNode(A){return new r6(A)}initState(){if(super.initState(),!this.widget.focusNode){let $={canRequestFocus:this.widget.canRequestFocus,skipTraversal:this.widget.skipTraversal};if(this.widget.onKey)$.onKey=this.widget.onKey;if(this.widget.onPaste)$.onPaste=this.widget.onPaste;if(this.widget.debugLabel)$.debugLabel=this.widget.debugLabel;this._internalFocusNode=this.createFocusNode($)}if(this.widget.onKey&&this.widget.focusNode)this.effectiveFocusNode.addKeyHandler(this.widget.onKey);if(this.widget.onPaste)this.effectiveFocusNode.onPaste=this.widget.onPaste;if(this.widget.onFocusChange)this._focusChangeHandler=($)=>{if(!this._isDisposed&&this.widget.onFocusChange)this.widget.onFocusChange($.hasFocus)},this.effectiveFocusNode.addListener(this._focusChangeHandler);let Q=this.context.findAncestorStateOfType(nf)?.effectiveFocusNode||null;if(m2.instance.registerNode(this.effectiveFocusNode,Q),this.widget.autofocus&&!this._didAutofocus)this._didAutofocus=!0,this.findEnclosingScope().autofocus(this.effectiveFocusNode)}findEnclosingScope(){return this.effectiveFocusNode.enclosingScope??m2.instance.rootScope}dispose(){if(this._didAutofocus=!1,this.widget.onKey)this.effectiveFocusNode.removeKeyHandler(this.widget.onKey);if(m2.instance.unregisterNode(this.effectiveFocusNode),this._isDisposed=!0,this._focusChangeHandler)this.effectiveFocusNode.removeListener(this._focusChangeHandler),this._focusChangeHandler=null;if(this._internalFocusNode)this._internalFocusNode.dispose(),this._internalFocusNode=null;super.dispose()}build(A){return this.widget.child}}function Gh4(A){let Q=A.key;if(Q.length===1&&Q>="a"&&Q<="z")return Q;if(A.code!==void 0)return A.code;return Q}class G1{key;shift;ctrl;alt;meta;constructor(A,Q={}){this.key=A;this.shift=Q.shift??!1,this.ctrl=Q.ctrl??!1,this.alt=Q.alt??!1,this.meta=Q.meta??!1}accepts(A){return Gh4(A)===this.key&&A.shiftKey===this.shift&&A.ctrlKey===this.ctrl&&A.altKey===this.alt&&A.metaKey===this.meta}static key(A){return new G1(A)}static ctrl(A){return new G1(A,{ctrl:!0})}static shift(A){return new G1(A,{shift:!0})}static alt(A){return new G1(A,{alt:!0})}static meta(A){return new G1(A,{meta:!0})}modifiers(){let A=[];if(this.meta)A.push("Meta");if(this.ctrl)A.push("Ctrl");if(this.alt)A.push("Alt");if(this.shift)A.push("Shift");return A}toString(){let A=this.modifiers();return A.length>0?`${A.join("+")}+${this.key}`:this.key}}class ge0{shortcuts=new Map;constructor(A=new Map){this.shortcuts=new Map(A)}handleKeyEvent(A){for(let[Q,$]of this.shortcuts)if(Q.accepts(A))return $;return null}addShortcut(A,Q){this.shortcuts.set(A,Q)}removeShortcut(A){return this.shortcuts.delete(A)}getAllShortcuts(){return new Map(this.shortcuts)}copyWith(A){let Q=new Map([...this.shortcuts,...A]);return new ge0(Q)}}class vA extends u0{shortcuts;child;manager;debugLabel;focusNode;constructor({shortcuts:A,child:Q,manager:$,debugLabel:B,focusNode:D,key:J}){super({key:J});this.shortcuts=A,this.child=Q,this.manager=$,this.debugLabel=B,this.focusNode=D}createState(){return new Vh4}}class Vh4 extends R0{manager=null;initState(){if(super.initState(),this.createManager(),this.widget.focusNode)this.widget.focusNode.addKeyHandler(this.handleKeyEvent)}didUpdateWidget(A){if(super.didUpdateWidget(A),A.shortcuts!==this.widget.shortcuts||A.manager!==this.widget.manager)this.createManager()}createManager(){if(this.widget.manager)this.manager=this.widget.manager;else this.manager=new ge0(this.widget.shortcuts)}dispose(){if(this.widget.focusNode)this.widget.focusNode.removeKeyHandler(this.handleKeyEvent);super.dispose()}handleKeyEvent=(A)=>{if(!this.manager)return"ignored";let Q=this.manager.handleKeyEvent(A);if(Q){if(this.invokeIntent(Q)==="handled")return"handled"}return"ignored"};invokeIntent(A){let $=new QZ0().findAction(A,this.context);if($&&$.enabled){if($.action.invoke(A)==="ignored")return null;return"handled"}return null}build(A){if(this.widget.focusNode)return this.widget.child;else return new v4({onKey:this.handleKeyEvent,autofocus:!1,canRequestFocus:!0,skipTraversal:!1,debugLabel:this.widget.debugLabel,child:this.widget.child})}}p0();p0();import{execFile as jO3}from"node:child_process";function me0(){let A=LO3();if(A)return A;let Q=OO3();if(Q)return{...Q,pixelWidth:0,pixelHeight:0};return null}function LO3(){try{let A=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Q=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),B=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Q)({ws_row:Q.types.ushort,ws_col:Q.types.ushort,ws_xpixel:Q.types.ushort,ws_ypixel:Q.types.ushort}),D=A.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),J=process.platform==="darwin"?1074295912:21523,F=new B;if(D.ioctl(process.stdout.fd,J,F.ref())===0)return{rows:F.ws_row,columns:F.ws_col,pixelWidth:F.ws_xpixel,pixelHeight:F.ws_ypixel};return null}catch(A){return null}}function OO3(){try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows)return{columns:process.stdout.columns,rows:process.stdout.rows};let A=process.stdin;if(process.stdin.isTTY&&A.columns&&A.rows)return{columns:A.columns,rows:A.rows};let Q=process.stdout;if(typeof Q.getWindowSize==="function"){let $=Q.getWindowSize();if($[0]>0&&$[1]>0)return{columns:$[0],rows:$[1]}}return null}catch(A){return null}}function Br(A){return{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,kittyGraphics:!1,background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:N9()?"none":"standard",scrollStep:()=>3,...A}}var zh4=[{sequence:"\x1B[?1049h\x1B[H\x1B]66;w=1; \x1B\\\x1B[6n\x1B[?1049l",description:"Query Kitty explicit width support"},{sequence:"\x1B]10;?\x07",description:"Query terminal foreground color (OSC 10)"},{sequence:"\x1B]11;?\x07",description:"Query terminal background color (OSC 11)"},{sequence:"\x1B]12;?\x07",description:"Query terminal cursor color (OSC 12)"},{sequence:"\x1B]4;0;?\x07",description:"Query terminal color 0 (OSC 4)"},{sequence:"\x1B]4;1;?\x07",description:"Query terminal color 1 (OSC 4)"},{sequence:"\x1B]4;2;?\x07",description:"Query terminal color 2 (OSC 4)"},{sequence:"\x1B]4;3;?\x07",description:"Query terminal color 3 (OSC 4)"},{sequence:"\x1B]4;4;?\x07",description:"Query terminal color 4 (OSC 4)"},{sequence:"\x1B]4;5;?\x07",description:"Query terminal color 5 (OSC 4)"},{sequence:"\x1B]4;6;?\x07",description:"Query terminal color 6 (OSC 4)"},{sequence:"\x1B]4;7;?\x07",description:"Query terminal color 7 (OSC 4)"},{sequence:"\x1B[?2026$p",description:"Query synchronized output support"},{sequence:"\x1B[?2027$p",description:"Query emoji width mode support"},{sequence:"\x1B[?1016$p",description:"Query pixel mouse mode support"},{sequence:"\x1B[?2031$p",description:"Query color palette change notifications support (mode 2031)"},{sequence:"\x1B[?u",description:"Query Kitty keyboard protocol support"},{sequence:"\x1B[>0q",description:"Query terminal version (XTVERSION)"},{sequence:"\x1BP+q4d73\x1B\\",description:"Query OSC 52 clipboard support (XTGETTCAP Ms)"},{sequence:HN("\x1B_Gi=1,a=q\x1B\\"),description:"Query Kitty graphics protocol support",shouldSend:()=>{return!N9()&&process.env.TERM_PROGRAM!=="Apple_Terminal"&&!Pf()}},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}];function Kh4(A,Q){return new Promise(($)=>{jO3(A,Q,{encoding:"utf8",timeout:1000},(B,D)=>{$(B?null:D.trim())})})}class de0{options;capabilities;tmuxKittyGraphicsPromise=null;constructor(A={}){this.options=A;this.capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,kittyGraphics:!1,background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:N9()?"none":"standard",scrollStep:()=>this.getScrollStep()},this.tmuxKittyGraphicsPromise=this.detectKittyGraphicsFromEnv().then((Q)=>{this.capabilities.kittyGraphics=this.capabilities.kittyGraphics||Q})}complete=!1;colorUpdateTimer=null;onColorPaletteChange;inbandPixelData=null;kittyWidthQuerySent=!1;rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]};processDecrqss(A,Q){if(A==="?2026")this.capabilities.syncOutput=Q==="1"||Q==="2";if(A==="?2027")this.capabilities.emojiWidth=Q==="1"||Q==="2";if(A==="?1016")this.capabilities.pixelMouse=Q==="1"||Q==="2";if(A==="?2031")this.capabilities.colorPaletteNotifications=Q==="1"||Q==="2";if(A==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(A,Q){if(this.checkPixelDimensions(),this.detectJetBrains()||this.detectTmux())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(A){this.capabilities.xtversion=A;let Q=["ghostty","kitty","wezterm","foot","alacritty","iterm2","tmux"],$=A.toLowerCase();if(Q.some((B)=>$.includes(B)))this.capabilities.osc52=!0;return!1}processXtgettcap(A,Q){if(A.toLowerCase()==="4d73")this.capabilities.osc52=Q.length>0;return!1}processKittyGraphics(){if(this.isITerm2())return this.capabilities.kittyGraphics=!1,!1;return this.capabilities.kittyGraphics=!0,!1}processCursorPositionReport(A,Q){if(this.kittyWidthQuerySent){if(A===1&&Q===2)this.capabilities.kittyExplicitWidth=!0,u.info("Kitty explicit width support detected");this.kittyWidthQuerySent=!1}return!1}markKittyWidthQuerySent(){this.kittyWidthQuerySent=!0}processOsc10(A){let Q=A.match(/^10;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let $=Q[1],B=Q[2],D=Q[3],J=(Z)=>{let U=Number.parseInt(Z,16),X=Z.length*4;return U/(2**X-1)*255},F=Math.round(J($)),E=Math.round(J(B)),Y=Math.round(J(D));return this.rgbColors.foreground={r:F,g:E,b:Y},!1}processOsc11(A){let Q=A.match(/^11;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let $=Q[1],B=Q[2],D=Q[3],J=(U)=>{let X=Number.parseInt(U,16),G=U.length*4;return X/(2**G-1)*255},F=Math.round(J($)),E=Math.round(J(B)),Y=Math.round(J(D));this.rgbColors.background={r:F,g:E,b:Y};let Z=0.299*F+0.587*E+0.114*Y;return this.capabilities.background=Z<128?"dark":"light",!1}processOsc12(A){let Q=A.match(/^12;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let $=Q[1],B=Q[2],D=Q[3],J=(Z)=>{let U=Number.parseInt(Z,16),X=Z.length*4;return U/(2**X-1)*255},F=Math.round(J($)),E=Math.round(J(B)),Y=Math.round(J(D));return this.rgbColors.cursor={r:F,g:E,b:Y},!1}processOsc4(A){let Q=A.match(/^4;(\d+);rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3]||!Q[4])return!1;let $=Number.parseInt(Q[1],10),B=Q[2],D=Q[3],J=Q[4],F=(U)=>{let X=Number.parseInt(U,16),G=U.length*4;return X/(2**G-1)*255},E=Math.round(F(B)),Y=Math.round(F(D)),Z=Math.round(F(J));if($>=0&&$<=7)this.rgbColors.indices[$]={r:E,g:Y,b:Z};return!1}setColorPaletteChangeCallback(A){this.onColorPaletteChange=A}handleColorPaletteChangeNotification(){if(u.info("Color palette changed, re-querying colors..."),this.rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]},this.colorUpdateTimer)clearTimeout(this.colorUpdateTimer);this.colorUpdateTimer=setTimeout(()=>{let A=this.getRgbColors();if(this.onColorPaletteChange&&A)u.info("Color re-query complete, notifying callback"),this.onColorPaletteChange();this.colorUpdateTimer=null},200)}getColorQuerySequences(){return["\x1B]10;?\x07","\x1B]11;?\x07","\x1B]12;?\x07","\x1B]4;0;?\x07","\x1B]4;1;?\x07","\x1B]4;2;?\x07","\x1B]4;3;?\x07","\x1B]4;4;?\x07","\x1B]4;5;?\x07","\x1B]4;6;?\x07","\x1B]4;7;?\x07"]}updateInbandPixelData(A,Q,$,B){if($&&B&&$>0&&B>0)this.inbandPixelData={pixelWidth:$,pixelHeight:B,columns:A,rows:Q},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let A=me0();this.capabilities.pixelDimensions=!!(A&&A.pixelWidth>0&&A.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}async prepareCapabilities(){await this.tmuxKittyGraphicsPromise}getRgbColors(){if(!this.rgbColors.foreground||!this.rgbColors.background||!this.rgbColors.cursor)return u.info("Missing fg, bg, or cursor color",{fg:!!this.rgbColors.foreground,bg:!!this.rgbColors.background,cursor:!!this.rgbColors.cursor}),null;for(let A=0;A<8;A++)if(!this.rgbColors.indices[A])return u.info(`Missing palette color ${A}`),null;return u.info("All RGB colors available",{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indicesCount:this.rgbColors.indices.filter((A)=>A!==null).length}),{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indices:this.rgbColors.indices}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let A=me0();if(A&&A.pixelWidth>0&&A.pixelHeight>0)return{pixelWidth:A.pixelWidth,pixelHeight:A.pixelHeight,columns:A.columns,rows:A.rows};return null}getPendingQueries(){return this.complete?[]:["\x1B[c"]}async detectKittyGraphicsFromEnv(){let A=["kitty","ghostty","wezterm"];if(yZ()){let[Q,$]=await Promise.all([Kh4("tmux",["show-environment","-g","TERM"]),Kh4("tmux",["show-environment","-g","TERM_PROGRAM"])]),B=(Q??"").replace(/^TERM=/,"").toLowerCase(),D=($??"").replace(/^TERM_PROGRAM=/,"").toLowerCase();for(let J of A)if(B.includes(J)||D.includes(J))return u.debug("Detected Kitty graphics support from tmux environment",{term:B,termProgram:D}),!0}return!1}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.options.animationDisabled)return"disabled";if(process.env.NO_ANIMATION==="1"||process.env.NO_ANIMATIONS==="1")return"disabled";if(this.detectEmacs()||this.detectSSH())return"disabled";if(this.detectAppleTerminalUnderTmux())return"disabled";if(this.detectJetBrains())return"slow";return"fast"}detectEmacs(){return!!process.env.INSIDE_EMACS}detectJetBrains(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}detectSSH(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}detectTmux(){return!!process.env.TMUX}detectAppleTerminalUnderTmux(){return!!process.env.TMUX&&process.env.__CFBundleIdentifier==="com.apple.Terminal"}isITerm2(){if(this.capabilities.xtversion?.toLowerCase().includes("iterm2"))return!0;return process.env.TERM_PROGRAM==="iTerm.app"}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if(N9())return 1;return 3}}p0();import{execFile as fj}from"node:child_process";import{existsSync as RO3}from"node:fs";import{platform as BZ0}from"node:os";import{promisify as uO3}from"node:util";var Dr=uO3(fj);function Wh4(){if(BZ0()!=="linux")return!1;return Boolean(process.env.WSL_DISTRO_NAME)||RO3("/proc/sys/fs/binfmt_misc/WSLInterop")}var PO3=(A)=>`\x1B]52;c;${A}\x1B\\`,_O3="\x1B]52;c;?\x1B\\",TO3="\x1B]52;p;?\x1B\\",vO3="No clipboard tool found. Install xclip (X11) or wl-clipboard (Wayland), e.g. `sudo apt install xclip`.",kO3="Failed to write to clipboard via xclip/wl-copy.",SO3="Failed to write to clipboard via pbcopy.",Ih4="Failed to write to clipboard via clip.exe and PowerShell.",fO3="Clipboard is not supported in this terminal. Enable OSC 52 in your terminal settings or install a platform clipboard tool.";class Hh4{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;tmuxSetClipboard="unknown";setCapabilities(A){if(this.capabilities=A,yZ())this.detectTmuxSetClipboard()}detectTmuxSetClipboard(){fj("tmux",["show-options","-s","-v","set-clipboard"],{timeout:1000},(A,Q)=>{if(!A){let $=Q.trim();if($==="on"||$==="external"||$==="off")this.tmuxSetClipboard=$}})}isTmuxOsc52Allowed(){return this.tmuxSetClipboard==="on"||this.tmuxSetClipboard==="unknown"}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(A){try{return await Dr("which",[A]),!0}catch{return!1}}async writeToPbcopy(A){try{let Q=fj("pbcopy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise(($,B)=>{Q.on("close",(D)=>{if(D===0)$();else B(Error(`pbcopy exited with code ${D}`))})}),!0}catch{return!1}}async writeToWlCopy(A){try{let Q=fj("wl-copy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise(($,B)=>{Q.on("close",(D)=>{if(D===0)$();else B(Error(`wl-copy exited with code ${D}`))})}),!0}catch{return!1}}async writeToXclip(A){try{let Q=fj("xclip",["-selection","clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise(($,B)=>{Q.on("close",(D)=>{if(D===0)$();else B(Error(`xclip exited with code ${D}`))})}),!0}catch{return!1}}async writeToClipExe(A){try{let Q=fj("clip.exe");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise(($,B)=>{Q.on("close",(D)=>{if(D===0)$();else B(Error(`clip.exe exited with code ${D}`))})}),!0}catch{return!1}}async writeToPowerShell(A){try{let Q=fj("powershell.exe",["-NoProfile","-Command","$Input | Set-Clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise(($,B)=>{Q.on("close",(D)=>{if(D===0)$();else B(Error(`powershell.exe exited with code ${D}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(A){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise!==void 0)return this.pendingReadPromise;this.pendingReadPromise=new Promise(($)=>{this.readResolve=$,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,$(null)},2000),process.stdout.write(A)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(_O3)}handleOSC52Response(A){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(A,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:A}=await Dr("pbpaste");return A}catch{return null}}async readFromWlPaste(A){try{let Q=["--no-newline"];if(A==="primary")Q.push("--primary");let{stdout:$}=await Dr("wl-paste",Q);return $}catch{return null}}async readFromXclip(A){try{let{stdout:Q}=await Dr("xclip",["-selection",A,"-o"]);return Q}catch{return null}}async readFromPowerShell(){try{let{stdout:A}=await Dr("powershell.exe",["-NoProfile","-Command","Get-Clipboard"]);return A}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(TO3)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}let A=BZ0();if(A==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else if(A==="win32"){let Q=await this.readFromPowerShell();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}if(Wh4()){let Q=await this.readFromPowerShell();if(Q!==null)return Q}}return null}async readPrimarySelection(){let A=BZ0();if(A==="darwin"||A==="win32")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(A){let Q=yZ(),$=!1;if(this.isOsc52Supported()&&(!Q||this.isTmuxOsc52Allowed())){let J=Buffer.from(A).toString("base64"),F=PO3(J);if(process.stdout.write(F),$=!0,!Q)return{ok:!0}}let B=BZ0(),D=fO3;if(B==="darwin"){if(await this.writeToPbcopy(A))return{ok:!0};D=SO3}else if(B==="win32"){if(await this.writeToPowerShell(A))return{ok:!0};if(await this.writeToClipExe(A))return{ok:!0};D=Ih4}else{let J=await this.commandExists("wl-copy");if(J&&await this.writeToWlCopy(A))return{ok:!0};let F=await this.commandExists("xclip");if(F&&await this.writeToXclip(A))return{ok:!0};if(Wh4()){if(await this.writeToPowerShell(A))return{ok:!0};D=Ih4}else D=J||F?kO3:vO3}if($)return{ok:!0};return{ok:!1,userFacingErrorMessage:D}}}var LD=new Hh4;function yO3(A){return A.replace(/\r\n|\r/g,`
5102
5102
  `)}function xO3(A){return A.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function qh4(A){let Q=A;return Q=yO3(Q),Q=xO3(Q),Q}var bO3=50,hO3=200,gO3=200,mO3=50;class Ch4{eventBuffer=[];bufferTimer=null;filterDirection=null;lastEventTime=0;onEmitEvent=()=>{};constructor(A){this.onEmitEvent=A}handleWheelEvent(A){if(A.button!=="wheel_up"&&A.button!=="wheel_down")return!0;let Q=Date.now();if(this.filterDirection!==null)if(Q-this.lastEventTime>hO3)this.filterDirection=null;else return this.lastEventTime=Q,A.button===this.filterDirection;if(this.lastEventTime=Q,this.eventBuffer.push(A),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},bO3);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Q)=>Q.button==="wheel_down")){this.filterDirection="wheel_down";for(let Q of this.eventBuffer)if(Q.button==="wheel_down")this.onEmitEvent(Q)}else{this.filterDirection="wheel_up";for(let Q of this.eventBuffer)this.onEmitEvent(Q)}this.eventBuffer=[]}}class pe0{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;finishingCapabilityDetection=!1;windowsKittyProbeTimeout=null;windowsKittyProbePending=!1;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundExitCleanup=this.exitCleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;lastRenderDiffStats={repaintedCellCount:0,totalCellCount:1920,repaintedPercent:0,bytesWritten:0};options={};constructor(){this.screen=new rJ(80,24),this.renderer=new ho,this.tty=jY0(),this.jetBrainsWheelFilter=new Ch4((A)=>{for(let Q of this.mouseHandlers)Q(A)})}setOptions(A){this.options={...this.options,...A}}init(){if(this.initialized)throw Error("TUI is already initialized");try{if(this.parser=new Rj,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.parser.onDeviceAttributes((A)=>{if(this.queryParser&&this.initialized){if(this.queryParser.processDeviceAttributes(A.primary,A.secondary))this.finishInitialization()}}),this.parser.onDecrqss((A)=>{if(this.queryParser&&this.initialized)this.queryParser.processDecrqss(A.request,A.response),this.handleWindowsKittyProbeResponse(A.request,A.response)}),this.parser.onDcs((A)=>{if(this.queryParser&&this.initialized){if(A.final==="|"&&A.private===">")this.queryParser.processXtversion(A.data);if(A.final==="r"&&A.intermediates==="+"&&A.params.length>0&&A.params[0]?.value===1)this.parseXtgettcapResponse(A.data)}}),this.parser.onApc((A)=>{if(this.queryParser&&this.initialized){if(A.data.startsWith("G"))this.queryParser.processKittyGraphics()}}),this.parser.onCursorPositionReport((A)=>{if(this.queryParser&&this.initialized)this.queryParser.processCursorPositionReport(A.row,A.col)}),this.parser.onColorPaletteChange((A)=>{if(this.queryParser&&this.initialized){u.info("Color palette change detected, re-querying colors");let Q=this.queryParser.getColorQuerySequences();for(let $ of Q)process.stdout.write($);this.queryParser.handleColorPaletteChangeNotification()}}),this.parser.onMouse((A)=>{if(N9()&&!this.jetBrainsWheelFilter.handleWheelEvent(A))return;for(let Q of this.mouseHandlers)Q(A)}),this.parser.onFocus((A)=>{for(let Q of this.focusHandlers)Q(A)}),this.parser.onResize((A)=>{this.handleInbandResize(A)}),this.tty.on("data",(A)=>{this.parser?.parse(A)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),process.stdout.isTTY)process.stdout.on("resize",this.boundHandleResize);this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.enableMouse(),this.enableBracketedPaste(),this.createCapabilityPromise(),this.startCapabilityDetection()}catch(A){throw this.deinit().catch(()=>{}),A}}async deinit(){if(this.initialized){let A="",Q="",$=(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys(),B=async(D)=>{if(!D)return;await new Promise((J)=>{process.stdout.write(D,()=>{J()})})};if(A+=this.renderer.endSync(),this.inAltScreen)A+=this.renderer.clearScreen()+$+this.renderer.exitAltScreen(),$="",this.inAltScreen=!1;if(Q+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+$+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)Q+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))Q+=this.renderer.setProgressBarOff();if(await B(A),process.platform==="win32"&&A)await new Promise((D)=>{setTimeout(D,mO3)});await B(Q)}if(this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null;if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;if(this.windowsKittyProbeTimeout)clearTimeout(this.windowsKittyProbeTimeout),this.windowsKittyProbeTimeout=null;this.windowsKittyProbePending=!1,this.keyHandlers.length=0,this.mouseHandlers.length=0,this.resizeHandlers.length=0,this.focusHandlers.length=0,this.pasteHandlers.length=0,this.capabilityHandlers.length=0,process.removeListener("SIGWINCH",this.boundHandleResize),process.stdout.removeListener("resize",this.boundHandleResize),process.removeListener("SIGINT",this.boundCleanup),process.removeListener("SIGTERM",this.boundCleanup),process.removeListener("exit",this.boundExitCleanup),process.removeListener("SIGCONT",this.boundHandleResume),this.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1}getEarlyInputText(){return this.tty.getEarlyInputText()}onKey(A){this.keyHandlers.push(A)}offKey(A){let Q=this.keyHandlers.indexOf(A);if(Q!==-1)this.keyHandlers.splice(Q,1)}onMouse(A){this.mouseHandlers.push(A)}offMouse(A){let Q=this.mouseHandlers.indexOf(A);if(Q!==-1)this.mouseHandlers.splice(Q,1)}onResize(A){this.resizeHandlers.push(A)}offResize(A){let Q=this.resizeHandlers.indexOf(A);if(Q!==-1)this.resizeHandlers.splice(Q,1)}onFocus(A){this.focusHandlers.push(A)}offFocus(A){let Q=this.focusHandlers.indexOf(A);if(Q!==-1)this.focusHandlers.splice(Q,1)}onPaste(A){this.pasteHandlers.push(A)}offPaste(A){let Q=this.pasteHandlers.indexOf(A);if(Q!==-1)this.pasteHandlers.splice(Q,1)}onCapabilities(A){this.capabilityHandlers.push(A)}offCapabilities(A){let Q=this.capabilityHandlers.indexOf(A);if(Q!==-1)this.capabilityHandlers.splice(Q,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}getQueryParser(){return this.queryParser}async waitForCapabilities(A=1000){if(!this.initialized)throw Error("TUI is not initialized");if(this.capabilities)return this.capabilities;if(!this.capabilityPromise)throw Error("Capability detection not started");return this.capabilityPromise}getSize(){return{...this.terminalSize}}getScreen(){return this.screen}getLastRenderDiffStats(){return this.lastRenderDiffStats}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let A=this.screen.getDiff(),Q=this.screen.getSize(),$=Q.width*Q.height,B=A.length,D=$>0?B/$*100:0;this.lastRenderDiffStats={repaintedCellCount:B,totalCellCount:$,repaintedPercent:D,bytesWritten:0};let J=this.screen.getCursor();if(A.length>0||J!==null){let E=new bo;E.append(this.renderer.startSync()),E.append(this.renderer.hideCursor()),E.append(this.renderer.reset()),E.append(this.renderer.moveTo(0,0));let Y=this.renderer.render(A);if(E.append(Y),J)if(E.append(this.renderer.moveTo(J.x,J.y)),this.screen.isCursorVisible())E.append(this.renderer.setCursorShape(this.screen.getCursorShape())),E.append(this.renderer.showCursor());else E.append(this.renderer.hideCursor());else E.append(this.renderer.hideCursor());E.append(this.renderer.endSync());let Z=E.toString();this.lastRenderDiffStats={...this.lastRenderDiffStats,bytesWritten:Buffer.byteLength(Z,"utf8")},process.stdout.write(Z),this.screen.present()}}clearScreen(){let A=this.renderer.clearScreen()+this.renderer.hideCursor();process.stdout.write(A),this.renderer.resetState()}showCursor(){process.stdout.write(this.renderer.showCursor())}hideCursor(){process.stdout.write(this.renderer.hideCursor())}setCursor(A,Q){this.screen.setCursor(A,Q)}clearCursor(){this.screen.clearCursor()}setCursorShape(A){this.screen.setCursorShape(A)}setMouseCursor(A){let Q=`\x1B]22;${A}\x07`;process.stdout.write(Q)}resetMouseCursor(){this.setMouseCursor(YA.DEFAULT)}enableBracketedPaste(){process.stdout.write(this.renderer.enableBracketedPaste())}disableBracketedPaste(){process.stdout.write(this.renderer.disableBracketedPaste())}enableKittyKeyboard(A){process.stdout.write(this.renderer.enableKittyKeyboard(A))}disableKittyKeyboard(){process.stdout.write(this.renderer.disableKittyKeyboard())}enableModifyOtherKeys(){process.stdout.write(this.renderer.enableModifyOtherKeys())}disableModifyOtherKeys(){process.stdout.write(this.renderer.disableModifyOtherKeys())}async writeClipboard(A){let{ok:Q}=await LD.writeText(A);return Q}get clipboard(){return LD}enterAltScreen(){if(!this.initialized)throw Error("TUI not initialized");if(!this.inAltScreen)process.stdout.write(this.renderer.enterAltScreen()),this.inAltScreen=!0,this.screen.markForRefresh()}exitAltScreen(){if(this.inAltScreen)process.stdout.write(this.renderer.exitAltScreen()),this.inAltScreen=!1}isInAltScreen(){return this.inAltScreen}enableMouse(){if(this.initialized){let A=process.platform!=="win32"&&(this.queryParser?.shouldUsePixelMouse()??!1),Q=this.renderer.enableMouse(A);process.stdout.write(Q)}}disableMouse(){if(this.initialized)process.stdout.write(this.renderer.disableMouse())}enableEmojiWidth(){if(this.initialized){let A=this.renderer.enableEmojiWidth();process.stdout.write(A)}}disableEmojiWidth(){if(this.initialized)process.stdout.write(this.renderer.disableEmojiWidth())}enableInBandResize(){if(this.initialized){let A=this.renderer.enableInBandResize();process.stdout.write(A)}}disableInBandResize(){if(this.initialized)process.stdout.write(this.renderer.disableInBandResize())}enableColorPaletteNotifications(){if(this.initialized)u.info("Enabling mode 2031 (color palette change notifications)"),process.stdout.write("\x1B[?2031h")}disableColorPaletteNotifications(){if(this.initialized)process.stdout.write("\x1B[?2031l")}setMouseShape(A){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(A))}suspend(){if(!this.initialized||this.suspended)return;let A="";if(A+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)A+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))A+=this.renderer.setProgressBarOff();if(this.inAltScreen)A+=this.renderer.exitAltScreen(),this.inAltScreen=!1;if(process.stdout.write(A),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.hideCursor(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableModifyOtherKeys(),this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend();try{process.kill(0,"SIGTSTP"),u.debug(`Successfully suspended process ${process.pid}`)}catch(A){u.debug(`Failed to suspend process ${process.pid}: ${A}`)}}handleResume(){if(!this.initialized||!this.suspended)return;this.resume(),setImmediate(()=>{if(this.initialized&&!this.suspended)this.render()})}updateTerminalSize(){if(!this.tty.stdin||!Nh4(this.tty.stdin)){this.terminalSize={width:80,height:24};return}let A=dO3(process.stdout);if(A)this.terminalSize=A}handleKeyEvent(A){for(let Q of this.keyHandlers)Q(A)}handlePasteEvent(A){this.dispatchSyntheticPaste(A.text)}dispatchSyntheticPaste(A){let Q={type:"paste",text:qh4(A)};for(let $ of this.pasteHandlers)$(Q)}handleOscEvent(A){if(A.data.startsWith("10;")&&this.queryParser){this.queryParser.processOsc10(A.data);return}if(A.data.startsWith("11;")&&this.queryParser){this.queryParser.processOsc11(A.data);return}if(A.data.startsWith("12;")&&this.queryParser){this.queryParser.processOsc12(A.data);return}if(A.data.startsWith("4;")&&this.queryParser){this.queryParser.processOsc4(A.data);return}if(A.data.startsWith("52;c;")){let Q=A.data.slice(5);if(Q&&Q!=="?")LD.handleOSC52Response(Q)}}createCapabilityPromise(){this.capabilityPromise=new Promise((A)=>{this.capabilityResolve=A})}startCapabilityDetection(){if(!this.tty.stdin||!Nh4(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new de0(this.options.queryOptions),process.env.TERM_PROGRAM==="Apple_Terminal"){let A=Br({canRgb:!1});this.capabilities=A;let Q={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let $ of this.capabilityHandlers)$(Q);if(this.capabilityResolve)this.capabilityResolve(A),this.capabilityResolve=null;return}if(process.platform==="win32"){this.startWindowsKittyProbe();return}this.sendCapabilityQueries(),this.startCapabilityTimeout()}finishInitialization(){this.finishInitializationAsync()}async finishInitializationAsync(){if(!this.initialized||!this.queryParser||this.capabilities||this.finishingCapabilityDetection)return;if(this.finishingCapabilityDetection=!0,await this.queryParser.prepareCapabilities(),!this.initialized||!this.queryParser||this.capabilities)return;if(this.capabilities=this.queryParser.getCapabilities(),this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;let A={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities),HY0(this.capabilities.background);for(let Q of this.capabilityHandlers)Q(A);if(this.capabilityResolve)u.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Q=this.queryParser.getPixelDimensions();if(Q){let $=Q.pixelWidth/Q.columns,B=Q.pixelHeight/Q.rows;this.parser?.setSgrToMouseConverter((D)=>vo(D,!0,$,B))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();if(this.enableModifyOtherKeys(),this.enableInBandResize(),this.capabilities.colorPaletteNotifications)this.enableColorPaletteNotifications();LD.setCapabilities(this.capabilities)}sendCapabilityQueries(A="all"){if(!this.queryParser)return;for(let Q of zh4){let $=Q.description==="Query Kitty explicit width support";if(A==="onlyKittyExplicitWidth"&&!$)continue;if(A==="skipKittyExplicitWidth"&&$)continue;if(Q.shouldSend&&!Q.shouldSend())continue;if(process.stdout.write(Q.sequence),$)this.queryParser.markKittyWidthQuerySent()}}startCapabilityTimeout(){if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout);this.capabilityTimeout=setTimeout(()=>{if(!this.capabilities&&this.capabilityResolve&&this.queryParser)this.finishInitialization()},2000)}startWindowsKittyProbe(){this.windowsKittyProbePending=!0,process.stdout.write(this.renderer.queryKittyKeyboard()),this.sendCapabilityQueries("onlyKittyExplicitWidth"),this.windowsKittyProbeTimeout=setTimeout(()=>{this.finishWindowsKittyProbe(!1)},gO3)}handleWindowsKittyProbeResponse(A,Q){if(process.platform!=="win32"||!this.windowsKittyProbePending||A!=="u")return;this.finishWindowsKittyProbe(!0)}finishWindowsKittyProbe(A){if(!this.windowsKittyProbePending)return;if(this.windowsKittyProbePending=!1,this.windowsKittyProbeTimeout)clearTimeout(this.windowsKittyProbeTimeout),this.windowsKittyProbeTimeout=null;if(!A)this.tty.enableWindowsVirtualTerminalInput();this.sendCapabilityQueries("skipKittyExplicitWidth"),this.startCapabilityTimeout()}parseXtgettcapResponse(A){if(!this.queryParser)return;let Q=A.indexOf("=");if(Q!==-1){let $=A.slice(0,Q),B=A.slice(Q+1);if(this.queryParser.processXtgettcap($,B))this.finishInitialization()}}handleResize(){if(this.pendingResize=!0,this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer);this.resizeDebounceTimer=setTimeout(()=>{this.processResize()},10)}handleInbandResize(A){if(this.terminalSize={width:A.width,height:A.height},this.queryParser&&A.pixelWidth&&A.pixelHeight){let Q=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(A.width,A.height,A.pixelWidth,A.pixelHeight);let $=this.queryParser.shouldUsePixelMouse();if(process.platform!=="win32"&&!Q&&$)this.disableMouse(),this.enableMouse();if($){let B=A.pixelWidth/A.width,D=A.pixelHeight/A.height;this.parser?.setSgrToMouseConverter((J)=>vo(J,!0,B,D))}}this.screen.resize(A.width,A.height),setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(A)}catch($){u.error("Error in resize handler:",$)}})}processResize(){if(!this.pendingResize||!this.initialized)return;let A={...this.terminalSize};if(this.updateTerminalSize(),A.width===this.terminalSize.width&&A.height===this.terminalSize.height){this.pendingResize=!1;return}this.finishResize(),this.pendingResize=!1}finishResize(){this.screen.resize(this.terminalSize.width,this.terminalSize.height);let A={type:"resize",width:this.terminalSize.width,height:this.terminalSize.height};setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(A)}catch($){u.error("Error in resize handler:",$)}})}setupCleanupHandlers(){process.setMaxListeners(0),process.on("SIGINT",this.boundCleanup),process.on("SIGTERM",this.boundCleanup),process.on("exit",this.boundExitCleanup),process.on("SIGCONT",this.boundHandleResume)}exitCleanup(){if(!this.initialized)return;let A=this.renderer.endSync(),Q=(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys();if(this.inAltScreen)A+=this.renderer.clearScreen()+Q+this.renderer.exitAltScreen(),Q="",this.inAltScreen=!1;if(A+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+Q+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)A+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))A+=this.renderer.setProgressBarOff();try{process.stdout.write(A)}catch{}this.tty.dispose(),this.initialized=!1}cleanup(){this.deinit().catch(()=>{})}}function Nh4(A){return"isTTY"in A&&A.isTTY===!0&&typeof A.setRawMode==="function"}function dO3(A){try{if(A._refreshSize?.(),A.isTTY&&A.columns&&A.rows)return{width:A.columns,height:A.rows};let Q=A.getWindowSize?.();if(Q&&Q[0]>0&&Q[1]>0)return{width:Q[0],height:Q[1]}}catch{}return null}p0();p0();var Jr;((D)=>{D.BUILD="build";D.LAYOUT="layout";D.PAINT="paint";D.RENDER="render"})(Jr||={});var pO3=60,vG=1000/pO3;function cO3(){if(typeof process>"u")return!1;return process.env.BUN_TEST==="1"||process.env.VITEST==="true"||process.env.NODE_TEST_CONTEXT==="1"}class i6{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_executingPostFrameCallbacks=!1;_pendingFrameImmediate=null;_pendingFrameTimer=null;_lastFrameTimestamp=0;_useFramePacing=!cO3();_stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}};_lastCompletedStats=this.deepCopyStats(this._stats);static get instance(){return i6._instance??=new i6}requestFrame(){if(this._frameScheduled)return;if(this._frameInProgress){this._frameScheduled=!0;return}if(!this._useFramePacing){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let A=performance.now(),Q=this._lastFrameTimestamp,$=A-Q;if(Q===0||$>=vG){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let B=Math.max(0,vG-$);this._frameScheduled=!0,this.scheduleFrameExecution(B)}scheduleFrameExecution(A){if(A<=0){this._pendingFrameImmediate=setImmediate(()=>this.runScheduledFrame());return}this._pendingFrameTimer=setTimeout(()=>this.runScheduledFrame(),A)}runScheduledFrame(){if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;if(this._frameInProgress)return;this.executeFrame()}addFrameCallback(A,Q,$,B=0,D){this._frameCallbacks.set(A,{callback:Q,phase:$,priority:B,name:D||A})}removeFrameCallback(A){this._frameCallbacks.delete(A)}addPostFrameCallback(A,Q){if(this._postFrameCallbacks.push({callback:A,name:Q}),!this._frameScheduled&&(!this._frameInProgress||this._executingPostFrameCallbacks))this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let A=performance.now();this._frameScheduled=!1,this._frameInProgress=!0;try{for(let Q of["build","layout","paint","render"])this.executePhase(Q);this.executePostFrameCallbacks()}catch(Q){u.error("Frame execution error:",Q instanceof Error?Q.message:String(Q))}finally{if(this.recordFrameStats(performance.now()-A),this._lastFrameTimestamp=A,this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1,this._frameScheduled){let $=performance.now()-this._lastFrameTimestamp,B=$>=vG?0:Math.max(0,vG-$);this.scheduleFrameExecution(B)}}}executePhase(A){let Q=performance.now();try{let $=Array.from(this._frameCallbacks.values()).filter((B)=>B.phase===A).sort((B,D)=>B.priority-D.priority);for(let B of $)try{B.callback()}catch(D){u.error(`Frame callback error in ${A} phase (${B.name})`,{errorMessage:D instanceof Error?D.message:String(D),errorType:D?.constructor?.name,stackTrace:D instanceof Error?D.stack:void 0}),q4(!1,`FATAL: ${A} error in ${B.name}: ${D}`)}}finally{let $=performance.now()-Q;this.recordPhaseStats(A,$)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let A=this._postFrameCallbacks.splice(0);this._executingPostFrameCallbacks=!0;try{for(let{callback:Q,name:$}of A)try{Q()}catch(B){u.error(`Post-frame callback error (${$||"anonymous"}):`,B instanceof Error?B.message:String(B))}}finally{this._executingPostFrameCallbacks=!1}}recordFrameStats(A){this._stats.lastFrameTime=A}recordPhaseStats(A,Q){this._stats.phaseStats[A].lastTime=Q}get isFrameScheduled(){return this._frameScheduled||this._frameInProgress}get isFrameInProgress(){return this._frameInProgress}get frameStats(){return this.deepCopyStats(this._lastCompletedStats)}deepCopyStats(A){return{...A,phaseStats:{["build"]:{...A.phaseStats.build},["layout"]:{...A.phaseStats.layout},["paint"]:{...A.phaseStats.paint},["render"]:{...A.phaseStats.render}}}}resetStats(){this._stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}}}get pendingPostFrameCallbacks(){return this._postFrameCallbacks.length}cancelPendingWork(){let A=this._pendingFrameImmediate!==null;if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;let Q=this._pendingFrameTimer!==null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;let $=this._postFrameCallbacks.length;this._postFrameCallbacks.length=0;let B=this._frameScheduled,D=this._frameInProgress;return this._frameScheduled=!1,{hadPendingImmediate:A,hadPendingTimer:Q,clearedPostFrameCallbacks:$,frameWasScheduled:B,frameInProgress:D}}dispose(){if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this._lastFrameTimestamp=0,this.resetStats()}}class ce0{_dirtyElements=new Set;_stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0};_buildTimes=[];_elementsPerFrame=[];constructor(){}scheduleBuildFor(A){if(this._dirtyElements.has(A))return;this._dirtyElements.add(A),i6.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let A=performance.now(),Q=0;try{while(this._dirtyElements.size>0){let $=Array.from(this._dirtyElements);this._dirtyElements.clear(),$.sort((B,D)=>B.depth-D.depth);for(let B of $)if(B.dirty)try{B.performRebuild(),B._dirty=!1,Q++}catch(D){u.error("Element rebuild error:",{error:D instanceof Error?D.message:String(D),stack:D instanceof Error?D.stack:void 0,elementType:B.widget.constructor.name,elementDebugLabel:B.widget.debugLabel}),B._dirty=!1}}}finally{this.recordBuildStats(performance.now()-A,Q)}}recordBuildStats(A,Q){if(this._stats.totalRebuilds+=Q,this._stats.elementsRebuiltThisFrame=Q,this._stats.lastBuildTime=A,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Q),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,A),this._buildTimes.push(A),this._elementsPerFrame.push(Q),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce(($,B)=>$+B,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce(($,B)=>$+B,0)/this._elementsPerFrame.length}get dirtyElements(){return Array.from(this._dirtyElements)}get hasDirtyElements(){return this._dirtyElements.size>0}get buildStats(){return{...this._stats}}resetBuildStats(){this._stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0},this._buildTimes.length=0,this._elementsPerFrame.length=0}dispose(){this._dirtyElements.clear()}}var le0=5,lO3=1000;function nE(A,Q){if(A.length===0)return 0;let $=[...A].sort((J,F)=>J-F),B=Math.max(0,Math.min(Q,1)),D=Math.ceil($.length*B)-1;return $[Math.max(0,D)]||0}class wh4{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];repaintPercents=[];bytesWritten=[];lastKeyEventTime=0;lastMouseEventTime=0;lastRepaintPercent=0;lastBytesWritten=0;MAX_SAMPLES=1024;recordFrame(A){if(this.frameTimes.push(A),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(A,Q){let $=this.phaseTimes[A];if($.push(Q),$.length>this.MAX_SAMPLES)$.shift()}recordKeyEvent(A){if(this.lastKeyEventTime=A,this.keyEventTimes.push(A),this.keyEventTimes.length>this.MAX_SAMPLES)this.keyEventTimes.shift()}recordMouseEvent(A){if(this.lastMouseEventTime=A,this.mouseEventTimes.push(A),this.mouseEventTimes.length>this.MAX_SAMPLES)this.mouseEventTimes.shift()}recordRepaintPercent(A){if(this.lastRepaintPercent=A,this.repaintPercents.push(A),this.repaintPercents.length>this.MAX_SAMPLES)this.repaintPercents.shift()}recordBytesWritten(A){if(this.lastBytesWritten=A,this.bytesWritten.push(A),this.bytesWritten.length>this.MAX_SAMPLES)this.bytesWritten.shift()}getFrameP99(){return nE(this.frameTimes,0.99)}getFrameP95(){return nE(this.frameTimes,0.95)}getPhaseP99(A){return nE(this.phaseTimes[A],0.99)}getPhaseP95(A){return nE(this.phaseTimes[A],0.95)}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return nE(this.keyEventTimes,0.99)}getKeyEventP95(){return nE(this.keyEventTimes,0.95)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return nE(this.mouseEventTimes,0.99)}getMouseEventP95(){return nE(this.mouseEventTimes,0.95)}getLastRepaintPercent(){return this.lastRepaintPercent}getRepaintPercentP99(){return nE(this.repaintPercents,0.99)}getRepaintPercentP95(){return nE(this.repaintPercents,0.95)}getLastBytesWritten(){return this.lastBytesWritten}getBytesWrittenP99(){return nE(this.bytesWritten,0.99)}getBytesWrittenP95(){return nE(this.bytesWritten,0.95)}reset(){this.frameTimes=[];for(let A of Object.values(Jr))this.phaseTimes[A]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.repaintPercents=[],this.bytesWritten=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0,this.lastRepaintPercent=0,this.lastBytesWritten=0}}class ie0{enabled=!1;tracker=new wh4;overlayWidth=56;overlayHeight=26;resetButtonLabel="[ Reset ]";memorySamples=[];lastMemorySampleTimestamp=0;memoryStartedAt=Date.now();setEnabled(A){if(A&&!this.enabled)this.resetMemorySamples(Date.now());this.enabled=A}reset(){this.tracker.reset(),this.resetMemorySamples(Date.now())}isEnabled(){return this.enabled}recordKeyEvent(A){this.tracker.recordKeyEvent(A)}recordMouseEvent(A){this.tracker.recordMouseEvent(A)}recordStats(A,Q){this.tracker.recordFrame(A.lastFrameTime);for(let $ of Object.values(Jr))this.tracker.recordPhase($,A.phaseStats[$].lastTime);if(Q)this.tracker.recordRepaintPercent(Q.repaintedPercent),this.tracker.recordBytesWritten(Q.bytesWritten)}handleMouseEvent(A,Q){if(!this.enabled||A.action!=="press"&&A.action!=="release")return!1;if(A.action==="press"&&A.button!=="left")return!1;let $=this.getOverlayGeometry(Q.width,Q.height);if(!$)return!1;let{x:B,y:D}=$,J=B+this.overlayWidth-this.resetButtonLabel.length-2,F=D+this.overlayHeight-2,E=Math.floor(A.x),Y=Math.floor(A.y);if(!(E>=J&&E<J+this.resetButtonLabel.length&&Y===F))return!1;return this.reset(),!0}draw(A,Q){if(!this.enabled)return;this.recordMemorySample(Date.now());let{width:$,height:B}=A.getSize(),D=this.getOverlayGeometry($,B);if(!D)return;let{x:J,y:F}=D,E=Z8.default().colorScheme,Y=E.border,Z=E.foreground,U=E.warning,X=E.success,G=" Gotta Go Fast ",V=Math.floor((this.overlayWidth-G.length)/2);A.setCell(J,F,K6("╭",{fg:Z}));for(let b0=1;b0<this.overlayWidth-1;b0++)if(b0>=V&&b0<V+G.length)A.setCell(J+b0,F,K6(G[b0-V]||"─",{fg:U}));else A.setCell(J+b0,F,K6("─",{fg:Z}));A.setCell(J+this.overlayWidth-1,F,K6("╮",{fg:Z}));for(let b0=1;b0<this.overlayHeight-1;b0++){A.setCell(J,F+b0,K6("│",{fg:Z})),A.setCell(J+this.overlayWidth-1,F+b0,K6("│",{fg:Z}));for(let E1=1;E1<this.overlayWidth-1;E1++)A.setCell(J+E1,F+b0,K6(" ",{fg:Z}))}A.setCell(J,F+this.overlayHeight-1,K6("╰",{fg:Z}));for(let b0=1;b0<this.overlayWidth-1;b0++)A.setCell(J+b0,F+this.overlayHeight-1,K6("─",{fg:Z}));A.setCell(J+this.overlayWidth-1,F+this.overlayHeight-1,K6("╯",{fg:Z}));let K=J+1,z=F+1;this.drawText(A,K,z++," Last P95 P99",Y);let W=this.tracker.getLastKeyEventTime(),I=this.tracker.getKeyEventP95(),H=this.tracker.getKeyEventP99(),q=W.toFixed(2).padStart(5," "),N=I.toFixed(2).padStart(5," "),C=H.toFixed(2).padStart(5," "),O=this.getTimingColor(W),L=this.getTimingColor(I),j=this.getTimingColor(H);this.drawLastP95P99Row(A,K,z++,{label:"Key",labelColor:Y,last:{text:q,color:O},p95:{text:N,color:L},p99:{text:C,color:j}});let k=this.tracker.getLastMouseEventTime(),_=this.tracker.getMouseEventP95(),S=this.tracker.getMouseEventP99(),h=k.toFixed(2).padStart(5," "),b=_.toFixed(2).padStart(5," "),v=S.toFixed(2).padStart(5," "),y=this.getTimingColor(k),c=this.getTimingColor(_),p=this.getTimingColor(S);this.drawLastP95P99Row(A,K,z++,{label:"Mouse",labelColor:Y,last:{text:h,color:y},p95:{text:b,color:c},p99:{text:v,color:p}}),z++;for(let b0 of["build","layout","paint","render"]){let E1=Q.phaseStats[b0].lastTime,S1=this.tracker.getPhaseP95(b0),K4=this.tracker.getPhaseP99(b0),r1=E1.toFixed(2).padStart(5," "),H4=S1.toFixed(2).padStart(5," "),C4=K4.toFixed(2).padStart(5," "),M1=this.getTimingColor(E1),B4=this.getTimingColor(S1),c4=this.getTimingColor(K4),T0=b0.charAt(0).toUpperCase()+b0.slice(1);this.drawLastP95P99Row(A,K,z++,{label:T0,labelColor:Y,last:{text:r1,color:M1},p95:{text:H4,color:B4},p99:{text:C4,color:c4}})}z++;let g=Q.lastFrameTime,i=this.tracker.getFrameP95(),o=this.tracker.getFrameP99(),A0=g.toFixed(2).padStart(5," "),W0=i.toFixed(2).padStart(5," "),Y0=o.toFixed(2).padStart(5," "),I0=this.getTimingColor(g),$0=this.getTimingColor(i),j0=this.getTimingColor(o);this.drawLastP95P99Row(A,K,z++,{label:"Frame",labelColor:Z,last:{text:A0,color:I0},p95:{text:W0,color:$0},p99:{text:Y0,color:j0}});let Q0=this.tracker.getLastRepaintPercent(),M0=this.tracker.getRepaintPercentP95(),n=this.tracker.getRepaintPercentP99(),a=`${Q0.toFixed(1)}%`.padStart(5," "),t=`${M0.toFixed(1)}%`.padStart(5," "),e=`${n.toFixed(1)}%`.padStart(5," "),F0=this.getPercentColor(Q0),J0=this.getPercentColor(M0),C0=this.getPercentColor(n);this.drawLastP95P99Row(A,K,z++,{label:"Repaint",labelColor:Z,last:{text:a,color:F0},p95:{text:t,color:J0},p99:{text:e,color:C0}});let w0=this.formatBytes(this.tracker.getLastBytesWritten()).padStart(5," "),_0=this.formatBytes(this.tracker.getBytesWrittenP95()).padStart(5," "),U0=this.formatBytes(this.tracker.getBytesWrittenP99()).padStart(5," ");this.drawLastP95P99Row(A,K,z++,{label:"Bytes",labelColor:Z,last:{text:w0,color:Z},p95:{text:_0,color:Z},p99:{text:U0,color:Z}}),z++,this.drawMemorySection(A,K,z,Z,Y,X);let P0=J+this.overlayWidth-this.resetButtonLabel.length-2,d0=F+this.overlayHeight-2;this.drawText(A,P0,d0,this.resetButtonLabel,U)}getOverlayGeometry(A,Q){let $=A-this.overlayWidth-2,B=1;if($<0||1+this.overlayHeight>=Q)return null;return{x:$,y:1}}drawLastP95P99Row(A,Q,$,B){let D=` ${B.label.padStart(7," ")} `,J=Q;this.drawText(A,J,$,D,B.labelColor),J+=D.length,this.drawText(A,J,$,B.last.text,B.last.color),J+=B.last.text.length,this.drawText(A,J,$," ",B.labelColor),J+=3,this.drawText(A,J,$,B.p95.text,B.p95.color),J+=B.p95.text.length,this.drawText(A,J,$," ",B.labelColor),J+=3,this.drawText(A,J,$,B.p99.text,B.p99.color)}drawMemorySection(A,Q,$,B,D,J){let F=this.memorySamples.at(-1);if(!F)return;let E=Math.min(...this.memorySamples.map((G)=>G.bytes)),Y=Math.max(...this.memorySamples.map((G)=>G.bytes)),U=new Date(this.memoryStartedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),X=this.formatDuration(Date.now()-this.memoryStartedAt);this.drawLabelValueRow(A,Q,$,"Memory",this.formatMemory(F.bytes),{labelColor:D,valueColor:B}),this.drawLabelValueRow(A,Q,$+1,"Range",`${this.formatMemory(E)}–${this.formatMemory(Y)}`,{labelColor:D,valueColor:B}),this.drawLabelValueRow(A,Q,$+2,"Since",`${U} ${X} ago`,{labelColor:D,valueColor:B}),this.drawMemoryGraph(A,Q,$+3,J)}drawLabelValueRow(A,Q,$,B,D,J){let F=` ${B.padStart(7," ")} `;this.drawText(A,Q,$,F,J.labelColor),this.drawText(A,Q+F.length,$,D,J.valueColor)}drawMemoryGraph(A,Q,$,B){let D=this.overlayWidth-2,J=this.memorySamples.slice(-D);if(J.length===0)return;let F=Math.min(...J.map((U)=>U.bytes)),E=Math.max(...J.map((U)=>U.bytes)),Y=Math.max(1,E-F),Z=Math.max(0,D-J.length);J.forEach((U,X)=>{let G=(U.bytes-F)/Y,V=le0-1-Math.round(G*(le0-1));for(let K=V;K<le0;K++)this.drawText(A,Q+Z+X,$+K,"█",B)})}recordMemorySample(A){if(A-this.lastMemorySampleTimestamp<lO3)return;this.lastMemorySampleTimestamp=A,this.memorySamples.push({bytes:process.memoryUsage().rss});let Q=this.overlayWidth-2;if(this.memorySamples.length>Q)this.memorySamples=this.memorySamples.slice(-Q)}resetMemorySamples(A){this.memoryStartedAt=A,this.lastMemorySampleTimestamp=0,this.memorySamples=[]}getTimingColor(A){let Q=Z8.default().colorScheme,$=vG,B=vG*0.7;if(A>=$)return Q.destructive;if(A>=B)return Q.warning;return Q.foreground}getPercentColor(A){let Q=Z8.default().colorScheme;if(A>=50)return Q.destructive;if(A>=20)return Q.warning;return Q.foreground}drawText(A,Q,$,B,D){for(let J=0;J<B.length;J++)A.setCell(Q+J,$,K6(B[J]||" ",{fg:D}))}formatBytes(A){if(A>=1e4)return`${Math.round(A/1000)}k`;if(A>=1000)return`${(A/1000).toFixed(1)}k`;return`${Math.round(A)}`}formatMemory(A){let Q=A/1024/1024;if(Q>=1000)return`${(Q/1024).toFixed(1)}GB`;return`${Math.round(Q)}MB`}formatDuration(A){let Q=Math.max(1,Math.floor(A/1000)),$=[{label:"week",seconds:604800},{label:"day",seconds:86400},{label:"hour",seconds:3600},{label:"minute",seconds:60},{label:"second",seconds:1}],B=$.find((F)=>Q>=F.seconds)||$.at(-1);if(!B)return"0 seconds";let D=Math.floor(Q/B.seconds),J=D===1?"":"s";return`${D} ${B.label}${J}`}}class af{size;capabilities;constructor(A,Q){this.size=A;this.capabilities=Q}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}class b1 extends GA{data;constructor({key:A,data:Q,child:$}){super(A!==void 0?{key:A,child:$}:{child:$});this.data=Q}updateShouldNotify(A){return this.data!==A.data||this.data.size.width!==A.data.size.width||this.data.size.height!==A.data.size.height||this.data.capabilities!==A.data.capabilities}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(b1);if(!Q)throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.");return Q.data}static sizeOf(A){return b1.of(A).size}static capabilitiesOf(A){return b1.of(A).capabilities}}class ne0{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(A){if(!i6.instance.isFrameInProgress)i6.instance.requestFrame()}requestPaint(A){if(this._nodesNeedingPaint.has(A))return;if(this._nodesNeedingPaint.add(A),!i6.instance.isFrameInProgress)i6.instance.requestFrame()}setRootRenderObject(A){this._rootRenderObject=A}updateRootConstraints(A){let Q=new w1(0,A.width,0,A.height),$=!this._rootConstraints||this._rootConstraints.maxWidth!==Q.maxWidth||this._rootConstraints.maxHeight!==Q.maxHeight;if(this._rootConstraints=Q,$&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){let A=!1;if(this._rootRenderObject&&this._rootConstraints&&"needsLayout"in this._rootRenderObject&&this._rootRenderObject.needsLayout){if("layout"in this._rootRenderObject&&typeof this._rootRenderObject.layout==="function")this._rootRenderObject.layout(this._rootConstraints),A=!0}return A}flushPaint(){if(this._nodesNeedingPaint.size===0)return;try{for(let A of this._nodesNeedingPaint)if(A.needsPaint)A._needsPaint=!1}finally{this._nodesNeedingPaint.clear()}}get nodesNeedingLayout(){return[]}get nodesNeedingPaint(){return Array.from(this._nodesNeedingPaint)}get hasNodesNeedingLayout(){return Boolean(this._rootRenderObject&&this._rootRenderObject.needsLayout)}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(A){this._nodesNeedingPaint.delete(A)}}class z4{static _instance;frameScheduler=i6.instance;buildOwner;pipelineOwner;focusManager=m2.instance;mouseManager=o3.instance;frameStatsOverlay=new ie0;tui=new pe0;rootElement;isRunning=!1;rootElementMountedCallback;forcePaintOnNextFrame=!1;shouldPaintCurrentFrame=!1;didPaintCurrentFrame=!1;frameStatsOverlayRefreshInterval=null;eventCallbacks={key:[],mouse:[],paste:[]};keyInterceptors=[];rgbColorChangeCallbacks=[];cachedRgbColors=null;static get instance(){return z4._instance??=new z4}pendingResizeEvent=null;constructor(){this.buildOwner=new ce0,this.pipelineOwner=new ne0,this.frameScheduler.addFrameCallback("frame-start",()=>this.beginFrame(),"build",-2000,"WidgetsBinding.beginFrame"),this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>{this.buildOwner.buildScopes(),this.updateRootRenderObject()},"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{if(this.updateRootConstraints(),this.pipelineOwner.flushLayout())this.shouldPaintCurrentFrame=!0},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),Vx4({scheduleBuildFor:(A)=>this.buildOwner.scheduleBuildFor(A)},{requestLayout:(A)=>this.pipelineOwner.requestLayout(A),requestPaint:(A)=>this.pipelineOwner.requestPaint(A),removeFromQueues:(A)=>this.pipelineOwner.removeFromQueues(A)}),this.setupErrorHandler()}setupErrorHandler(){process.on("uncaughtException",(A)=>{u.error("Framework uncaught exception",A)})}getRgbColors(){return this.cachedRgbColors}onRgbColorsChanged(A){return this.rgbColorChangeCallbacks.push(A),()=>{let Q=this.rgbColorChangeCallbacks.indexOf(A);if(Q!==-1)this.rgbColorChangeCallbacks.splice(Q,1)}}notifyRgbColorsChanged(){for(let A of this.rgbColorChangeCallbacks)A()}updateRgbColors(A){this.cachedRgbColors=A;let Q=this.tui.getScreen();Q.setDefaultColors({type:"rgb",value:A.bg},{type:"rgb",value:A.fg}),Q.setIndexRgbMapping(A.indices),HY0(vz(),A.bg),this.notifyRgbColorsChanged(),this.requestForcedPaintFrame()}async runApp(A){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Q}=await Promise.resolve().then(() => (Fr(),Mh4));Q(this.tui);let{initIdleTracking:$}=await Promise.resolve().then(() => (FZ0(),Oh4));$(this.tui),await this.tui.waitForCapabilities(1000);let B=this.tui.getQueryParser(),D=B?.getRgbColors();if(u.info("Initial RGB colors from terminal",{available:!!D}),D)this.updateRgbColors(D);if(B)B.setColorPaletteChangeCallback(()=>{let E=B.getRgbColors();if(E)this.updateRgbColors(E)});let J=this.createMediaQueryWrapper(A);if(this.rootElement=J.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let F=this.rootElement.renderObject;if(!F&&this.rootElement.children.length>0)F=this.rootElement.children[0]?.renderObject;if(F)this.pipelineOwner.setRootRenderObject(F),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),u.debug("Setting up event handlers..."),this.setupEventHandlers(),u.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),u.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),u.debug("waitForExit completed")}finally{u.debug("Cleaning up..."),await this.cleanup()}}stop(){if(this.isRunning=!1,this.exitResolve)this.exitResolve(),this.exitResolve=null}updateRootConstraints(){let A=this.tui.getSize();this.pipelineOwner.updateRootConstraints(A)}updateRootRenderObject(){if(!this.rootElement)return;let A=this.rootElement.renderObject;if(!A&&this.rootElement.children.length>0)A=this.rootElement.children[0]?.renderObject;if(A)this.pipelineOwner.setRootRenderObject(A),this.mouseManager.setRootRenderObject(A)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let A=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Q={width:A.width,height:A.height},$=this.tui.getCapabilities()||Br(),B=new af(Q,$),D=this.rootElement;if(D.widget instanceof b1){let F=new b1({data:B,child:D.widget.child});D.update(F)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Q),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}beginFrame(){this.didPaintCurrentFrame=!1,this.shouldPaintCurrentFrame=this.forcePaintOnNextFrame||this.buildOwner.hasDirtyElements||this.pipelineOwner.hasNodesNeedingLayout||this.pipelineOwner.hasNodesNeedingPaint||this.tui.getScreen().requiresFullRefresh,this.forcePaintOnNextFrame=!1}requestForcedPaintFrame(){this.forcePaintOnNextFrame=!0,this.frameScheduler.requestFrame()}paint(){if(!this.shouldPaintCurrentFrame)return;if(this.pipelineOwner.flushPaint(),!this.rootElement)return;let A=this.rootElement.renderObject;if(!A&&this.rootElement.children.length>0)A=this.rootElement.children[0]?.renderObject;if(!A)return;try{let Q=this.tui.getScreen();Q.clear(),Q.clearCursor(),this.renderRenderObject(A,Q,0,0);let $=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats($,this.tui.getLastRenderDiffStats()),this.frameStatsOverlay.draw(Q,$),this.didPaintCurrentFrame=!0}catch(Q){u.error("Paint error:",Q)}}render(){if(!this.didPaintCurrentFrame)return;try{this.tui.render()}catch(A){u.error("Render error:",A)}}renderRenderObject(A,Q,$,B){if("paint"in A&&typeof A.paint==="function")A.paint(Q,$,B)}createMediaQueryWrapper(A){let Q=this.tui.getCapabilities()||Br(),$=this.tui.getSize(),B=new af($,Q);return new b1({data:B,child:A})}setupEventHandlers(){this.tui.onResize((A)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=A,this.frameScheduler.requestFrame()}),this.tui.onKey((A)=>{let Q=performance.now();for(let D of this.eventCallbacks.key)D(A);for(let D of this.keyInterceptors)if(D(A)){let J=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(J);return}if(this.focusManager.handleKeyEvent(A)){let D=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(D);return}this.handleGlobalKeyEvent(A);let B=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(B)}),this.tui.onMouse((A)=>{let Q=performance.now();for(let B of this.eventCallbacks.mouse)B(A);if(this.frameStatsOverlay.handleMouseEvent(A,this.tui.getSize())){this.requestForcedPaintFrame();let B=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent(B);return}this.mouseManager.handleMouseEvent(A);let $=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent($)}),this.tui.onPaste((A)=>{for(let Q of this.eventCallbacks.paste)Q(A);this.focusManager.handlePasteEvent(A)}),this.tui.onFocus(()=>{this.requestForcedPaintFrame()}),this.tui.onCapabilities((A)=>{if(this.rootElement){let Q=this.tui.getSize(),$=new af(Q,A.capabilities),B=this.rootElement;if(B.widget instanceof b1){let D=new b1({data:$,child:B.widget.child});B.update(D)}this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame()}})}handleGlobalKeyEvent(A){if(A.ctrlKey&&A.key==="z"&&!A.shiftKey&&!A.altKey&&!A.metaKey){this.tui.handleSuspend();return}}toggleFrameStatsOverlay(){let A=!this.frameStatsOverlay.isEnabled();if(this.frameStatsOverlay.setEnabled(A),A)this.frameStatsOverlayRefreshInterval=setInterval(()=>{this.requestForcedPaintFrame()},1000);else if(this.frameStatsOverlayRefreshInterval)clearInterval(this.frameStatsOverlayRefreshInterval),this.frameStatsOverlayRefreshInterval=null;this.requestForcedPaintFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise!==null)return this.exitPromise;return this.exitPromise=new Promise((A)=>{if(this.exitResolve=A,!this.isRunning)A()}),this.exitPromise}async cleanup(){if(this.isRunning=!1,this.frameStatsOverlayRefreshInterval)clearInterval(this.frameStatsOverlayRefreshInterval),this.frameStatsOverlayRefreshInterval=null;if(this.rootElement)this.rootElement.unmount(),this.rootElement=void 0;this.buildOwner.dispose(),this.pipelineOwner.dispose(),this.focusManager.dispose(),this.mouseManager.dispose(),this.frameScheduler.cancelPendingWork(),this.frameScheduler.removeFrameCallback("frame-start"),this.frameScheduler.removeFrameCallback("resize"),this.frameScheduler.removeFrameCallback("build"),this.frameScheduler.removeFrameCallback("layout"),this.frameScheduler.removeFrameCallback("paint"),this.frameScheduler.removeFrameCallback("render"),await this.tui.deinit()}get tuiInstance(){return this.tui}get rootElementInstance(){return this.rootElement}setRootElementMountedCallback(A){this.rootElementMountedCallback=A}on(A,Q){let $=this.eventCallbacks[A];return $.push(Q),()=>{let B=$.indexOf(Q);if(B!==-1)$.splice(B,1)}}dispatchSyntheticPaste(A){this.tui.dispatchSyntheticPaste(A)}addKeyInterceptor(A,Q){if(Q?.position==="front")this.keyInterceptors.unshift(A);else this.keyInterceptors.push(A);return()=>{let $=this.keyInterceptors.indexOf(A);if($!==-1)this.keyInterceptors.splice($,1)}}}async function Yr(A,Q){let $=z4.instance;if(Q?.onRootElementMounted)$.setRootElementMountedCallback(Q.onRootElementMounted);await $.runApp(A)}class H1 extends Q${createElement(){return new ae0(this)}}class ae0 extends sJ{_child;_context;constructor(A){super(A)}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new tJ(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(A){if(this.widget===A)return;if(super.update(A),this._context)this._context.widget=A;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let A=this.widget.build(this._context);if(this._child){if(this._child.widget===A)return;if(this._child.widget.canUpdate(A))this._child.update(A);else{let Q=this._child,$=this.findNearestRenderObjectAncestor();if($&&Q.renderObject)$.dropChild(Q.renderObject);else if(!$&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=A.createElement(),this.addChild(this._child),this._child.mount(),$&&this._child.renderObject)$.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!$&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}}else this._child=A.createElement(),this.addChild(this._child),this._child.mount()}findNearestRenderObjectAncestor(){let A=this.parent;while(A){if(A.renderObject){if(this._child?.renderObject&&A.renderObject===this._child.renderObject){A=A.parent;continue}return A.renderObject}A=A.parent}return}}class QF extends GA{forceDim;constructor({key:A,forceDim:Q,child:$}){super({key:A,child:$});this.forceDim=Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(QF)}static shouldForceDim(A){return QF.maybeOf(A)?.forceDim??!1}updateShouldNotify(A){return this.forceDim!==A.forceDim}}class kG extends GA{controller;constructor({key:A,controller:Q,child:$}){super({key:A,child:$});this.controller=Q}static of(A){return A.dependOnInheritedWidgetOfExactType(kG)?.controller??null}static require(A){let Q=kG.of(A);if(!Q)throw Error(`InheritedSelectionArea.require() called with a context that does not contain an InheritedSelectionArea.
5103
5103
  No InheritedSelectionArea ancestor could be found starting from the given context. This can happen if the context comes from a widget above the SelectionArea.
@@ -5225,7 +5225,7 @@ ${B}`).join(`
5225
5225
  `).length,D=new d({text:new w(A,new T({color:$}))});if(B<=dU0)return D;return new X0({width:1/0,height:dU0,child:new i8({autofocus:!1,controller:Q,child:D})})}function Yf3(){return new Map([[G1.key("PageUp"),new pU0],[G1.key("PageDown"),new T41],[G1.ctrl("u"),new pU0],[G1.shift("Home"),new v41],[G1.shift("End"),new k41]])}function Zf3(A,Q,$){return Math.max(Q,Math.min(A,$))}var S41=8,zi4=1,Wi4=S41-1;class f41 extends V4{}class y41 extends V4{}class cU0 extends V4{}class lU0 extends V4{}class x41 extends V4{}class b41 extends V4{}class h41 extends u0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Ii4}}class Ii4 extends R0{messageScroll=new v6;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=Uf3(Q,this.messageScroll),B=Xf3(Q.options.message),D=B?new x4({actions:this.buildScrollActions(),child:new vA({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:Vf3(),child:$})}):$,J=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)J.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return J.push({keys:["Esc"],label:"cancel"}),new C6({header:Q.options.title,minWidth:64,maxWidth:80,footer:J,autofocus:!1,onDismiss:Q.onCancel,child:D})}buildScrollActions(){let A=(Q)=>{let $=Kf3(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[f41,new T1(()=>A(-zi4))],[y41,new T1(()=>A(zi4))],[cU0,new T1(()=>A(-Wi4))],[lU0,new T1(()=>A(Wi4))],[x41,new T1(()=>this.messageScroll.jumpTo(0))],[b41,new T1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function Uf3(A,Q){let $=A.options.options.map((D)=>({value:D,label:D})),B=Math.max(0,$.findIndex((D)=>D.value===A.options.initialValue));return new G8({options:$,selectedIndex:B,body:Gf3(A.options.message,Q),onSelect:(D)=>{if(D===null){A.onCancel();return}A.onSelect(D)},padding:V0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function Xf3(A){if(A===void 0)return!1;return A.split(`
5226
5226
  `).length>S41}function Gf3(A,Q){if(A===void 0)return;let $=A.split(`
5227
5227
  `).length,B=Math.min($,S41);return new X0({width:1/0,height:B,child:new i8({autofocus:!1,controller:Q,child:new d({text:new w(A)})})})}function Vf3(){return new Map([[G1.key("PageUp"),new cU0],[G1.key("PageDown"),new lU0],[G1.ctrl("u"),new cU0],[G1.ctrl("d"),new lU0],[G1.ctrl("y"),new f41],[G1.ctrl("e"),new y41],[G1.shift("Home"),new x41],[G1.shift("End"),new b41]])}function Kf3(A,Q,$){return Math.max(Q,Math.min(A,$))}var zf3=3,Wf3=new y6("NeoPluginDialogOverlay");function Hi4(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}}class g41{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(!VE0($.method))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 k4({key:Wf3,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new Ns({key:new fz(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 _41({key:new fz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new h41({key:new fz(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.neoContext.pluginPlatform;if(!A)return;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.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,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 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(Hi4(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(Hi4(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 D=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,D))}catch(D){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,D instanceof Error?D.message:String(D)))}}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 $=AT4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=QT4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=$T4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=BT4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.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(Bc($.errorMessage))continue;let B=`${$.uri.toString()}
5228
- ${$.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,D]of this.statusItems){if(Q.has(D.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.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){u.error("Neo plugin command failed",{error:D,command:A}),this.options.toastController.show(D instanceof Error?D.message:String(D),"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=eF(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=eF(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=eF(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),D={pluginURI:A,id:Q};if($!==void 0)D.value=$;this.statusItems.set(B,D)})};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))})};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,zf3)}scheduleResolvingDialogAdvance(A,Q){i6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"NeoPluginIntegration.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)}}var If3=48;class m41{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 Is({width:If3,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()}}p0();import{spawnSync as Hf3}from"node:child_process";import U$ from"node:process";var qi4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function Cs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else z4.instance.stop()}function Ni4(A){return{noun:"amp",verb:"Relaunch (Quit, then Reopen & Resume Thread)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update","resume","reopen"],shortcut:U$.env.NODE_ENV==="development"&&U$.platform==="darwin"?G1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),Cs(A)}}}function qf3(A,Q){let{command:$,args:B}=Cf3(A),D=U$.env.AMP_USE_EXECVE_RELAUNCH==="1";if(u.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:D?"execve":"spawnSync"}),D)return Nf3($,B,Q);let J=Hf3($,B,{cwd:Q,env:U$.env,stdio:"inherit"});if(J.error)return u.error("Failed to relaunch Amp",{error:J.error}),1;return J.status??1}function Nf3(A,Q,$){try{U$.chdir($),jf3(A,Q)}catch(B){return u.error("Failed to relaunch Amp",{error:B}),1}}class d41{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{u.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 qf3(this.requestedThreadIDs,A)}}function Cf3(A){let Q=A.length>0?["threads","continue",...A]:[],$=wf3(U$.argv),B=Lf3();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=U$.argv[1],J=D&&Mf3(D)?[D]:[];return{command:U$.execPath,args:[...J,...$,...Q]}}function wf3(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[J,F]=D.split("=",2);if(!J)continue;let E=J.slice(2),Y=E.startsWith("no-")?E.slice(3):E;if(qi4.booleans.has(Y)){Q.push(D);continue}if(!qi4.options.has(E))continue;if(F!==void 0){Q.push(D);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(D,Z),B+=1}return Q}function Mf3(A){return A!==U$.execPath&&!A.startsWith("/$bunfs/")}function Lf3(){if(U$.env.NODE_ENV!=="development")return null;let A=U$.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=Of3(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function Of3(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)}function jf3(A,Q){if(!U$.execve)throw Error("process.execve is unavailable in this runtime");if(A.includes("/"))return U$.execve(A,[A,...Q],U$.env);return U$.execve("/usr/bin/env",["env",A,...Q],U$.env)}var Rf3=18000000;class p41{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??Rf3)-(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(()=>Cs(this.options))}}_l();e2();import{readFile as uf3}from"node:fs/promises";import c41 from"node:os";function Pf3(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Ci4(A,Q){try{return{path:Q,contents:qg0(await uf3(A,"utf8"))}}catch{return null}}async function iU0(A,Q){let $=[],B=Pf3(),D=await e4.getThread({thread:Q},{config:A.configService}),J=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(UD(J),null,2)});let F=await Ci4(eS(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let E=await Ci4(A.settingsFilePath,`${B}/settings/global.json`);if(E)$.push(E);let Y=await jG()??"unknown",Z=await e4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779668338-g19be90",clientOS:`${c41.platform()} ${c41.release()} ${c41.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class l41{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)}}}}class nU0 extends h3{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new i41(this.offstage)}updateRenderObject(A){if(A instanceof i41)A.offstage=this.offstage}}class i41 extends c1{_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;q4(!!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 ws{_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 n41 extends u0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new wi4}}class wi4 extends R0{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 _j,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new _j,$=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 nU0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,J=D?new k4({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new nU0({key:B.key,offstage:!D,child:J}))}return new i4({fit:"expand",children:Q})}}import Mi4 from"node:process";class o41 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((B)=>B.status.type!=="hidden"),$=_f3(Q);return new C6({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:V0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new pA({items:Q,showBorder:!1,getLabel:(B)=>{let D=a41(B);return B.keywords&&B.keywords.length>0?`${D} ${B.keywords.join(" ").toLowerCase()}`:D},sortItems:(B,D,J)=>{if(J===""){let U=B.item.status.type==="disabled"?1:0,X=D.item.status.type==="disabled"?1:0;if(U!==X)return U-X;let G=B.item.sortBoost??0,V=D.item.sortBoost??0;if(G!==V)return V-G;let K=B.item.noun?.toLowerCase()??"",z=D.item.noun?.toLowerCase()??"";if(K!==z)return K<z?-1:1;return 0}let F=oj(B.item.verb.toLowerCase(),J),E=oj(D.item.verb.toLowerCase(),J);if(F!==E)return E-F;let Y=oj(a41(B.item),J),Z=oj(a41(D.item),J);if(Y!==Z)return Z-Y;return D.score-B.score},isItemDisabled:(B)=>B.status.type==="disabled",buildDisabledReasonWidget:(B,D)=>{if(B.status.type!=="disabled")return;let{colors:J}=O0.of(D);return new d({text:new w(B.status.reason,new T({color:J.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(B,D,J,F)=>new Li4({command:B,isSelected:D,isDisabled:J,categoryWidth:$,buildContext:F}),onAccept:(B)=>{this.props.onAccept(B)},onDismiss:this.props.onDismiss})})}}class Li4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,buildContext:J}=this.props,F=O0.of(J),{colors:E,app:Y}=F,Z=$?Y.selectionBackground:void 0,U=$?Y.selectionForeground:E.foreground,X=$?U:E.mutedForeground,G=new d({text:new w(Q.noun?.toLowerCase()??"",new T({color:X,dim:B||!$})),textAlign:"right"}),V=[new w(Q.verb.toLowerCase(),new T({color:U,bold:!0,dim:B}))];if(B)V.push(new w(" (unavailable)",new T({color:U,dim:!0})));let K=d.spans(V),z=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)z.push({child:Tf3(Q.shortcut,F,B)});return new Oi4({columns:z,padding:V0.horizontal(1),backgroundColor:Z})}}function a41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function _f3(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,J4($.noun)):Q},0)}function Tf3(A,Q,$){let{colors:B,app:D}=Q,J=new T({color:B.mutedForeground,dim:$}),F=[];for(let E of A.modifiers()){if(F.length>0)F.push(new w(" ",J));F.push(new w(vf3(E),new T({color:D.keybind,bold:!0,dim:$})))}if(F.length>0)F.push(new w(" ",J));return F.push(new w(kf3(A),new T({color:D.keybind,bold:!0,dim:$}))),d.spans(F)}function vf3(A){return A==="Meta"&&Mi4.platform==="darwin"?"Cmd":A}function kf3(A){return A.meta&&Mi4.platform==="darwin"?A.key.toUpperCase():A.key}class Oi4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,J=[];for(let E=0;E<Q.length;E++){let Y=Q[E];if(E>0&&$>0)J.push(new X0({width:$}));if(Y.fixedWidth!==void 0)J.push(new X0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)J.push(new R1({child:Y.child}));else J.push(Y.child)}let F=new r0({crossAxisAlignment:"start",children:J});if(!B&&!D)return F;return new x0({decoration:D?{color:D}:void 0,padding:B,child:F})}}class r41{#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 ws,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class w9 extends GA{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=w9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(w9)?.commandRegistry??null}}class s41 extends u0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new ji4}}class ji4 extends R0{modalStack=new ws;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=w9.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=w9.of(A).commands,$=new o41({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 n41({root:$,controller:this.modalStack})}}var t41=[{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"]}]}],e41=[{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 aU0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=b1.of(A).size.width,B=50,D=$<50,J=[];for(let F of this.items){let[E,Y]=this.renderRow(F),Z;if(D)Z=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[E,new f0({padding:V0.only({left:4}),child:Y})]});else Z=new r0({crossAxisAlignment:"start",children:[new R1({flex:1,child:E}),new X0({width:1}),new R1({flex:1,child:Y})]});J.push(new f0({padding:V0.horizontal(6),child:Z}))}return new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:J})}}class A61 extends u0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:$}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=$??!0}createState(){return new Ri4}}class Ri4 extends R0{scrollController;initState(){this.scrollController=new v6,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=b1.of(A),F=new T({color:$.primary,bold:!0}),E=new T({color:$.secondary,bold:!0}),Y=new T({color:D.keybind}),Z=new T({color:D.command}),U=new T({color:$.foreground}),X=new T({color:$.foreground}),G=J.size.width,V=J.size.height,K=G-4,z=V-4,W=Math.max(40,Math.min(80,K)),I=new Set(["permissions-disable"]),q=[...this.widget.commands.filter((L)=>{let j=L.noun?.toLowerCase();return j!=="dev"&&j!=="debug"&&!L.id.startsWith("debug-")&&!I.has(L.id)})].sort((L,j)=>{let k=(L.noun??"").toLowerCase(),_=(j.noun??"").toLowerCase(),S=k.localeCompare(_);if(S!==0)return S;let h=L.verb.toLowerCase(),b=j.verb.toLowerCase(),v=h.localeCompare(b);if(v!==0)return v;return L.id.localeCompare(j.id)}),N=new k6({autofocus:!0,controller:this.scrollController,child:new x0({constraints:new w1(W,W,0,Number.POSITIVE_INFINITY),child:new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new $4({child:new d({text:new w(`Amp CLI - Help & Keyboard Shortcuts
5228
+ ${$.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,D]of this.statusItems){if(Q.has(D.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.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){u.error("Neo plugin command failed",{error:D,command:A}),this.options.toastController.show(D instanceof Error?D.message:String(D),"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=eF(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=eF(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=eF(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),D={pluginURI:A,id:Q};if($!==void 0)D.value=$;this.statusItems.set(B,D)})};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))})};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,zf3)}scheduleResolvingDialogAdvance(A,Q){i6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"NeoPluginIntegration.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)}}var If3=48;class m41{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 Is({width:If3,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()}}p0();import{spawnSync as Hf3}from"node:child_process";import U$ from"node:process";var qi4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function Cs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else z4.instance.stop()}function Ni4(A){return{noun:"amp",verb:"Relaunch (Quit, then Reopen & Resume Thread)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update","resume","reopen"],shortcut:U$.env.NODE_ENV==="development"&&U$.platform==="darwin"?G1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),Cs(A)}}}function qf3(A,Q){let{command:$,args:B}=Cf3(A),D=U$.env.AMP_USE_EXECVE_RELAUNCH==="1";if(u.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:D?"execve":"spawnSync"}),D)return Nf3($,B,Q);let J=Hf3($,B,{cwd:Q,env:U$.env,stdio:"inherit"});if(J.error)return u.error("Failed to relaunch Amp",{error:J.error}),1;return J.status??1}function Nf3(A,Q,$){try{U$.chdir($),jf3(A,Q)}catch(B){return u.error("Failed to relaunch Amp",{error:B}),1}}class d41{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{u.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 qf3(this.requestedThreadIDs,A)}}function Cf3(A){let Q=A.length>0?["threads","continue",...A]:[],$=wf3(U$.argv),B=Lf3();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=U$.argv[1],J=D&&Mf3(D)?[D]:[];return{command:U$.execPath,args:[...J,...$,...Q]}}function wf3(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[J,F]=D.split("=",2);if(!J)continue;let E=J.slice(2),Y=E.startsWith("no-")?E.slice(3):E;if(qi4.booleans.has(Y)){Q.push(D);continue}if(!qi4.options.has(E))continue;if(F!==void 0){Q.push(D);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(D,Z),B+=1}return Q}function Mf3(A){return A!==U$.execPath&&!A.startsWith("/$bunfs/")}function Lf3(){if(U$.env.NODE_ENV!=="development")return null;let A=U$.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=Of3(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function Of3(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)}function jf3(A,Q){if(!U$.execve)throw Error("process.execve is unavailable in this runtime");if(A.includes("/"))return U$.execve(A,[A,...Q],U$.env);return U$.execve("/usr/bin/env",["env",A,...Q],U$.env)}var Rf3=18000000;class p41{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??Rf3)-(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(()=>Cs(this.options))}}_l();e2();import{readFile as uf3}from"node:fs/promises";import c41 from"node:os";function Pf3(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Ci4(A,Q){try{return{path:Q,contents:qg0(await uf3(A,"utf8"))}}catch{return null}}async function iU0(A,Q){let $=[],B=Pf3(),D=await e4.getThread({thread:Q},{config:A.configService}),J=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(UD(J),null,2)});let F=await Ci4(eS(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let E=await Ci4(A.settingsFilePath,`${B}/settings/global.json`);if(E)$.push(E);let Y=await jG()??"unknown",Z=await e4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779686836-g4ef406",clientOS:`${c41.platform()} ${c41.release()} ${c41.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class l41{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)}}}}class nU0 extends h3{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new i41(this.offstage)}updateRenderObject(A){if(A instanceof i41)A.offstage=this.offstage}}class i41 extends c1{_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;q4(!!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 ws{_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 n41 extends u0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new wi4}}class wi4 extends R0{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 _j,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new _j,$=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 nU0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,J=D?new k4({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new nU0({key:B.key,offstage:!D,child:J}))}return new i4({fit:"expand",children:Q})}}import Mi4 from"node:process";class o41 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((B)=>B.status.type!=="hidden"),$=_f3(Q);return new C6({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:V0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new pA({items:Q,showBorder:!1,getLabel:(B)=>{let D=a41(B);return B.keywords&&B.keywords.length>0?`${D} ${B.keywords.join(" ").toLowerCase()}`:D},sortItems:(B,D,J)=>{if(J===""){let U=B.item.status.type==="disabled"?1:0,X=D.item.status.type==="disabled"?1:0;if(U!==X)return U-X;let G=B.item.sortBoost??0,V=D.item.sortBoost??0;if(G!==V)return V-G;let K=B.item.noun?.toLowerCase()??"",z=D.item.noun?.toLowerCase()??"";if(K!==z)return K<z?-1:1;return 0}let F=oj(B.item.verb.toLowerCase(),J),E=oj(D.item.verb.toLowerCase(),J);if(F!==E)return E-F;let Y=oj(a41(B.item),J),Z=oj(a41(D.item),J);if(Y!==Z)return Z-Y;return D.score-B.score},isItemDisabled:(B)=>B.status.type==="disabled",buildDisabledReasonWidget:(B,D)=>{if(B.status.type!=="disabled")return;let{colors:J}=O0.of(D);return new d({text:new w(B.status.reason,new T({color:J.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(B,D,J,F)=>new Li4({command:B,isSelected:D,isDisabled:J,categoryWidth:$,buildContext:F}),onAccept:(B)=>{this.props.onAccept(B)},onDismiss:this.props.onDismiss})})}}class Li4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,buildContext:J}=this.props,F=O0.of(J),{colors:E,app:Y}=F,Z=$?Y.selectionBackground:void 0,U=$?Y.selectionForeground:E.foreground,X=$?U:E.mutedForeground,G=new d({text:new w(Q.noun?.toLowerCase()??"",new T({color:X,dim:B||!$})),textAlign:"right"}),V=[new w(Q.verb.toLowerCase(),new T({color:U,bold:!0,dim:B}))];if(B)V.push(new w(" (unavailable)",new T({color:U,dim:!0})));let K=d.spans(V),z=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)z.push({child:Tf3(Q.shortcut,F,B)});return new Oi4({columns:z,padding:V0.horizontal(1),backgroundColor:Z})}}function a41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function _f3(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,J4($.noun)):Q},0)}function Tf3(A,Q,$){let{colors:B,app:D}=Q,J=new T({color:B.mutedForeground,dim:$}),F=[];for(let E of A.modifiers()){if(F.length>0)F.push(new w(" ",J));F.push(new w(vf3(E),new T({color:D.keybind,bold:!0,dim:$})))}if(F.length>0)F.push(new w(" ",J));return F.push(new w(kf3(A),new T({color:D.keybind,bold:!0,dim:$}))),d.spans(F)}function vf3(A){return A==="Meta"&&Mi4.platform==="darwin"?"Cmd":A}function kf3(A){return A.meta&&Mi4.platform==="darwin"?A.key.toUpperCase():A.key}class Oi4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,J=[];for(let E=0;E<Q.length;E++){let Y=Q[E];if(E>0&&$>0)J.push(new X0({width:$}));if(Y.fixedWidth!==void 0)J.push(new X0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)J.push(new R1({child:Y.child}));else J.push(Y.child)}let F=new r0({crossAxisAlignment:"start",children:J});if(!B&&!D)return F;return new x0({decoration:D?{color:D}:void 0,padding:B,child:F})}}class r41{#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 ws,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class w9 extends GA{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=w9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(w9)?.commandRegistry??null}}class s41 extends u0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new ji4}}class ji4 extends R0{modalStack=new ws;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=w9.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=w9.of(A).commands,$=new o41({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 n41({root:$,controller:this.modalStack})}}var t41=[{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"]}]}],e41=[{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 aU0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=b1.of(A).size.width,B=50,D=$<50,J=[];for(let F of this.items){let[E,Y]=this.renderRow(F),Z;if(D)Z=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[E,new f0({padding:V0.only({left:4}),child:Y})]});else Z=new r0({crossAxisAlignment:"start",children:[new R1({flex:1,child:E}),new X0({width:1}),new R1({flex:1,child:Y})]});J.push(new f0({padding:V0.horizontal(6),child:Z}))}return new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:J})}}class A61 extends u0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:$}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=$??!0}createState(){return new Ri4}}class Ri4 extends R0{scrollController;initState(){this.scrollController=new v6,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=b1.of(A),F=new T({color:$.primary,bold:!0}),E=new T({color:$.secondary,bold:!0}),Y=new T({color:D.keybind}),Z=new T({color:D.command}),U=new T({color:$.foreground}),X=new T({color:$.foreground}),G=J.size.width,V=J.size.height,K=G-4,z=V-4,W=Math.max(40,Math.min(80,K)),I=new Set(["permissions-disable"]),q=[...this.widget.commands.filter((L)=>{let j=L.noun?.toLowerCase();return j!=="dev"&&j!=="debug"&&!L.id.startsWith("debug-")&&!I.has(L.id)})].sort((L,j)=>{let k=(L.noun??"").toLowerCase(),_=(j.noun??"").toLowerCase(),S=k.localeCompare(_);if(S!==0)return S;let h=L.verb.toLowerCase(),b=j.verb.toLowerCase(),v=h.localeCompare(b);if(v!==0)return v;return L.id.localeCompare(j.id)}),N=new k6({autofocus:!0,controller:this.scrollController,child:new x0({constraints:new w1(W,W,0,Number.POSITIVE_INFINITY),child:new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new $4({child:new d({text:new w(`Amp CLI - Help & Keyboard Shortcuts
5229
5229
  `,F)})}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new w(`Editor Shortcuts
5230
5230
  `,E)})}),new aU0({items:t41.filter((L)=>L.submitOnEnterOnly===void 0||L.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(L)=>{let j=[];for(let _ of L.methods){let S=this.buildCleanKeyCombination(_);j.push(S)}let k=j.join(", ");return[new d({text:new w(k,Y)}),new d({text:new w(L.description,U)})]}}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new w(`Scrolling & Navigation
5231
5231
  `,E)})}),new aU0({items:e41,renderRow:(L)=>{let j=[];for(let _ of L.methods){let S=this.buildCleanKeyCombination(_);j.push(S)}let k=j.join(", ");return[new d({text:new w(k,Y)}),new d({text:new w(L.description,U)})]}}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new w(`Command Palette Commands
@@ -5316,7 +5316,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)h=this.widget.centerContent
5316
5316
  `))}return F}function ad3(A,Q,$){let{colors:B,app:D}=$,J=od3(Q.status,$);if(A.push(new w(` ${J.icon} `,new T({color:J.color}))),A.push(new w(Q.name,new T({color:Q.status==="pending"?B.warning:D.command}))),Q.status==="pending")A.push(new w(" discovering...",new T({color:B.foreground,dim:!0})));else if(Q.description)A.push(new w(` ${Fs4(Q.description,50)}`,new T({color:B.foreground,dim:!0})));if(Q.error)A.push(new w(` ${Fs4(Q.error,40)}`,new T({color:D.toolError})));A.push(new w(`
5317
5317
  `))}function od3(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 Fs4(A,Q){let $=A.replace(/\s+/g," ").trim();if(J4($)<=Q)return $;let B="...",D=J4(B);if(Q<=D)return UQ(B,Q);return`${UQ($,Q-D,!0,"")}${B}`}var X31="https://ampcode.com/news/neo",G31=[{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:X31,href:X31},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function rd3(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:X31,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function sd3(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var dy=50,HR=40,Z31=1000,td3=420,ed3=760,Ap3=-250,Qp3=1100,pX0=33,Us4=0.999,$p3=2.1,Bp3=720,Dp3=420,Hs4="Meet the new",qs4="Amp",Ns4="CLI",V31=G4(Hs4).length,Jp3=G4(qs4).length,Fp3=G4(Ns4).length,cX0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},Xs4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},Gs4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},Vs4=[cX0,Xs4,Gs4,cX0,Xs4,Gs4,cX0],Ep3=cX0;class K31 extends u0{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??sd3(),this.introStages=this.variant==="npm-migration"?rd3(this.binaryInstallCommand):G31,this.dismissible=this.variant!=="npm-migration"}createState(){return new Cs4}}class Cs4 extends R0{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=Z31;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 n9(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=JF(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=Us4,this.firstStageHintVisible=this.animationProgress>=Us4,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:Z31,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=JF(A/ed3);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},pX0)}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=JF($/td3);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},pX0)}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 D=performance.now()-this.startedAt,J=JF(D/this.animationDurationMs),F=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*py(J);if(this.setState(()=>{this.animationProgress=F}),J>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},pX0)}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,Z31+Ap3),Q=A+Qp3;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?JF((A-this.firstStageTitleRevealStartedAt)/Bp3):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?JF((A-this.firstStageHintRevealStartedAt)/Dp3):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},pX0)}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=Ks4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:zs4(Ks4(this.previousIntroStage),A,py(this.stageTransitionProgress));return this.dismissProgress>0?zs4(Q,Ep3,py(this.dismissProgress)):Q}build(A){let Q=L1.of(A).colorScheme,$=O0.of(A),B=this.currentOrbPalette(),D=B$(1,"frontier",B),J=b1.of(A).size,E=this.widget.animationProgress??this.animationProgress,Y=Math.max(J.width/dy,J.height/HR)*$p3,Z=Y+(1-Y)*E,U=py(this.dismissProgress),X=Math.max(dy,Math.round(dy*Z)),G=Math.max(HR,Math.round(HR*Z)),V=Math.round((J.width-X)/2),K=Math.round((J.height-G)/2),z=Math.max(0,Math.floor((J.width-dy)/2)),W=-Math.floor(HR/2),I=Math.round(V+(z-V)*E),H=Math.round(K+(W-K)*E),q=I+X/2,N=H+G/2,C=Yp3({dismissProgress:this.dismissProgress,easedDismissProgress:U,introOrbScale:Z,normalOrbCenterX:q,normalOrbCenterY:N,size:J}),O=Math.max(dy,Math.round(dy*C.orbScale)),L=Math.max(HR,Math.round(HR*C.orbScale)),j=C.orbCenterX,k=C.orbCenterY,_=Math.round(j-O/2),S=Math.round(k-L/2),h=Math.max(3,Math.min(J.height-5,Math.floor(HR/2)+2)),b=Math.max(h+3,J.height-3),v=C.textDissolveProgress,y=this.isFinalIntroStage()?C.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,p=c&&this.firstStageHintVisible,g=p&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),i=this.introStage===0?this.firstStageTitleRevealProgress:1,o=this.introStage===0?this.firstStageHintRevealProgress:1,A0=Math.max(24,Math.min(74,J.width-4)),W0=Math.min(12,Math.max(8,J.height-h-6)),Y0=Math.max(0,Math.floor((J.width-A0)/2)),I0=Math.max(0,Math.min(J.height-W0,Math.floor(J.height*0.55-W0/2))),j0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new NN({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new NN({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new k4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(Q0)=>{if(Q0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&Q0.key==="c"&&Q0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&Q0.key==="q")return this.widget.onQuit?.(),"handled";if((Q0.key===" "||Q0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(Q0.key==="Escape"||Q0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(Q0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(Q0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new i4({fit:"expand",children:[new ws4({color:Q.background,dissolveProgress:y}),new i4({fit:"expand",children:[new O1({onClick:()=>{},child:X0.expand()}),new o4({left:_,top:S,width:O,height:L,child:j0}),...c?[new o4({left:Y0,top:I0,width:A0,height:W0,child:Up3({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:A0,height:W0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:D,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:i,dissolveProgress:v,context:A})})]:[],...p?[...g?[new o4({left:Y0,top:Math.max(0,b-1),width:A0,height:1,child:new d({text:Wp3({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new o4({left:Y0,top:b,width:A0,height:1,child:Hp3({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:o,dissolveProgress:v,context:A})})]:[]]})]})})}}class ws4 extends j5{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Ms4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Ms4 extends c1{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;q4(!!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),D=Math.floor($+this.offset.y),J=Math.floor(this.size.width),F=Math.floor(this.size.height),E={bg:this.color},Y=JF(this.dissolveProgress);if(Y<=0){A.fill(B,D,J,F," ",E);return}if(Y>=1)return;for(let Z=0;Z<F;Z++)for(let U=0;U<J;U++)if(!Zp3(U,Z,J,F,Y))A.fill(B+U,D+Z,1,1," ",E)}}function JF(A){return Math.min(1,Math.max(0,A))}function py(A){return 1-(1-A)**3}function Ks4(A){return Vs4[A]??Vs4[0]}function zs4(A,Q,$){return{primary:vj(A.primary,Q.primary,$),secondary:vj(A.secondary,Q.secondary,$)}}function Yp3({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:D,size:J}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(J.width*0.54-B)*Q,orbCenterY:D-J.height*0.44*Q,textDissolveProgress:JF(A/0.52),backdropDissolveProgress:py(JF((A-0.12)/0.88))}}function Zp3(A,Q,$,B,D){let J=B<=1?0:Q/(B-1),F=Ls4(A+Q*Math.max(1,$));return(1-J)*0.72+F*0.28<D}function Up3({introStages:A,stage:Q,previousStage:$,progress:B,direction:D,width:J,height:F,foreground:E,mutedForeground:Y,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K}){if($===null||B>=1)return U31({introStages:A,stage:Q,foreground:E,mutedForeground:Y,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K});let z=py(B),W=D*Math.round((1-z)*J),I=-D*Math.round(z*J);return new gz(new i4({fit:"expand",children:[new o4({left:I,top:0,width:J,height:F,child:U31({introStages:A,stage:$,foreground:E,mutedForeground:Y,accent:Z,link:U,keybind:X,titleRevealProgress:$===0?1:G,dissolveProgress:V,context:K})}),new o4({left:W,top:0,width:J,height:F,child:U31({introStages:A,stage:Q,foreground:E,mutedForeground:Y,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K})})]}))}function U31({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:D,link:J,keybind:F,titleRevealProgress:E,dissolveProgress:Y,context:Z}){let U=A[Q]??A[0]??G31[0],X=new T({color:D,bold:!0}),G=new T({color:$}),V=A===G31&&Q===0,K=[...U.title===null?[]:[new d({text:V?lX0(Vp3({progress:E,foreground:D,pulseColor:D}),Y):new w(KB(U.title,Y),X),textAlign:"center"})],...U.body.length>0?[Xp3()]:[],...U.body.map((z)=>Gp3(z,G,B,J,F,Y,Z))];return new $4({child:new f0({padding:V0.horizontal(1),child:new S0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:K})})})}function Xp3(){return X0.height(1)}function Gp3(A,Q,$,B,D,J,F){if(typeof A==="string")return new d({text:new w(KB(A,J),Q),textAlign:"center"});if("codeBlock"in A)return new U5({onCopy:(E,Y)=>{if(Y)w3.success(F,"Copied to clipboard",2000)},child:new S0({mainAxisSize:"min",children:A.codeBlock.map((E)=>new d({text:new w(KB(E,J),new T({color:D})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let E=new d({text:new w("",void 0,[new w(KB(A.text,J),new T({color:$,dim:!0})),new w(KB(A.keybind,J,G4(A.text).length),new T({color:D}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $4({child:new U5({child:E})});return E}if("highlightText"in A){let E=P6.createSpan(A.href,A.linkText,new T({color:B,underline:!0})),Y=aZ.of(F),Z=new w("",void 0,[new w(A.text,Q),new w(A.highlightText,new T({color:D})),new w(A.textAfterHighlight,Q),new w(E.text,E.style,E.children,E.hyperlink,()=>{n6(F,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new w(A.textAfter,Q)]);return new d({text:lX0(Z,J),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new S0({mainAxisSize:"min",children:[new d({text:new w(KB(A.text,J),Q),textAlign:"center"}),new $4({child:new r0({mainAxisSize:"min",children:[P6.createWidget(F,A.href,KB(A.linkText,J),new T({color:B,underline:!0})),new d({text:new w(KB(A.textAfter,J),Q)})]})})]});let E=P6.createSpan(A.href,A.linkText,new T({color:B,underline:!0})),Y=aZ.of(F),Z=new w("",void 0,[new w(A.text,Q),new w(E.text,E.style,E.children,E.hyperlink,()=>{n6(F,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new w(A.textAfter,Q)]);return new d({text:lX0(Z,J),textAlign:"center"})}if(J>0)return new d({text:new w(KB(A.text,J),new T({color:B,underline:!0})),textAlign:"center"});return new $4({child:P6.createWidget(F,A.href,A.text,new T({color:B,underline:!0}))})}function Vp3({progress:A,foreground:Q,pulseColor:$}){let B=new T({color:Q,bold:!0}),D=new T({color:zp3({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new w("",void 0,[new w(Kp3(A).padEnd(V31," "),B),new w(" ",B),new w(Ws4(qs4,Jp3,A,0.72),B),new w(" ",B),new w(Ws4(Ns4,Fp3,A,0.88),D)])}function Kp3(A){let Q=G4(Hs4),$=Math.min(V31,Math.ceil(JF(A/0.62)*V31));return Q.slice(0,$).join("")}function Ws4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function zp3({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=JF((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function Wp3({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new w(KB(`${A}/${Q}`,B),new T({color:$,dim:!0}))}function Ip3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J}){let F=new T({color:B}),E=new T({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit, or use ",U=Q?"":"amp --take-me-back",X=Q?"":" to use the old version",G=`${Z}${U}${X}`;if(!Q)return new w("",void 0,[new w(Y,F),new w(Z,E),new w(U,F),new w(X,E)]);let V=Is4(Y,D),K=Is4(G,JF((D*(G4(Y).length+G4(G).length)-G4(Y).length)/G4(G).length));return new w("",void 0,[new w(KB(V,J),F),new w(KB(K.slice(0,Z.length),J),E),new w(KB(K.slice(Z.length,Z.length+U.length),J),F),new w(KB(K.slice(Z.length+U.length),J),E)])}function Hp3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J,context:F}){if(Q)return new d({text:Ip3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J}),textAlign:"center"});let E=new T({color:B}),Y=new T({color:$,dim:!0});return new U5({onCopy:(Z,U)=>{if(U)w3.success(F,"Copied to clipboard",2000)},child:new d({text:new w("",void 0,[new w("q",E),new w(" to quit, or use ",Y),new w("amp --take-me-back",E),new w(" to use the old version",Y)]),textAlign:"center",selectable:!0})})}function Is4(A,Q){let $=G4(A),B=Math.min($.length,Math.ceil(JF(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function lX0(A,Q,$=0){if(Q<=0)return A;let B=$+G4(A.text??"").length,D=A.children?.map((J)=>{let F=lX0(J,Q,B);return B+=G4(J.toPlainText()).length,F});return new w(A.text?KB(A.text,Q,$):A.text,A.style,D,A.hyperlink,A.onClick)}function KB(A,Q,$=0){if(Q<=0)return A;return G4(A).map((D,J)=>{if(D.trim()==="")return D;return Ls4($+J)<Q?" ":D}).join("")}function Ls4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}p0();e2();function $C(A,Q){let{colors:$,dim:B}=Q,D=[];if(A.totalCostUSD===null)return D;let J=A.costBreakdown,F=J?.freeUSD??0,E=J?.paidUSD??0;if(F===0&&E===0)return D;let Z={decimalPlaces:"more-if-tiny",intent:"cost"};if(E===0)D.push(new w(iG(F,Z),new T({color:$.foreground,dim:B}))),D.push(new w(" (free)",new T({color:$.foreground,dim:B})));else if(F>0)D.push(new w(iG(F,Z),new T({color:$.foreground,dim:B}))),D.push(new w(" (free)",new T({color:$.foreground,dim:B}))),D.push(new w(" + ",new T({color:$.foreground,dim:B}))),D.push(new w(iG(E,Z),new T({color:$.foreground,dim:B,bold:!B})));else D.push(new w(iG(E,Z),new T({color:$.foreground,dim:B,bold:!B})));return D}class z31 extends V4{}class W31 extends V4{}function qp3(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function Np3(A,Q){let $=O0.of(Q),{colors:B}=$,D=$C(A,{colors:{foreground:B.foreground}}),J=[];if(D.length>0)J.push(new w("Total: ",new T({color:B.mutedForeground}))),J.push(...D);else if(A.totalCostUSD===null)J.push(new w("Usage information is currently unavailable."));else J.push(new w("No usage recorded for this thread yet."));if(A.costBreakdownURL)J.push(new w(`
5318
5318
 
5319
- `)),J.push(new w("Details: ",new T({color:B.mutedForeground}))),J.push(new w(A.costBreakdownURL,new T({color:$.app.link})));return new d({text:new w("",void 0,J)})}function Cp3(A,Q,$){let B=Np3(A,Q);if(!A.costBreakdownURL)return new C6({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:$,child:B});let D=A.costBreakdownURL,J=new T1(()=>{return x4.maybeInvoke(Q,new K8(D,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),F=new T1(()=>{return n6(Q,D),"handled"});return new C6({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:$,child:new x4({actions:new Map([[z31,J],[W31,F]]),child:new vA({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[G1.key("o"),new W31],[G1.key("y"),new z31]]),child:new v4({autofocus:!0,debugLabel:"ThreadCostBody",child:B})})})})}function Os4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,$,B)=>{let D=A.getActiveThreadID();if(!D)return;try{let J=await e4.threadDisplayCostInfo({threadID:D},{config:A.configService});if(!J.ok){A.toastController.show(qp3(D,J.error),"error",5000),B();return}Q.push(Cp3(J.result,$,B))}catch(J){u.error("Failed to load Neo thread cost",{error:J,threadID:D}),A.toastController.show(`Failed to show thread cost: ${J instanceof Error?J.message:String(J)}`,"error",5000),B()}}}}p0();u9();Q4();class ez extends V4{direction;constructor(A){super();this.direction=A}}class iX0 extends V4{}class ns extends V4{}class nX0 extends V4{index;constructor(A){super();this.index=A}}function I31(A){return A.length+2}class H31 extends u0{props;constructor(A){super();this.props=A}createState(){return new js4}}class js4 extends R0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let D=$+B;if(D<Q.length&&this.isSelectable(D))return D;let J=$-B;if(J>=0&&this.isSelectable(J))return J}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof ez)return this.moveSelection(A.direction),"handled";if(A instanceof iX0)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof ns)return this.widget.props.onDismiss(),"handled";if(A instanceof nX0)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[G1.key("ArrowDown"),new ez(1)],[G1.key("j"),new ez(1)],[G1.ctrl("n"),new ez(1)],[G1.key("ArrowUp"),new ez(-1)],[G1.key("k"),new ez(-1)],[G1.ctrl("p"),new ez(-1)],[G1.key("Enter"),new iX0],[G1.key("Escape"),new ns],[G1.ctrl("."),new ns]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new nX0($))}),A}buildActions(){return new Map([[ez,new T1(this.invoke)],[iX0,new T1(this.invoke)],[ns,new T1(this.invoke)],[nX0,new T1(this.invoke)]])}build(A){let Q=O0.of(A),$=wp3(this.widget.props.entries,b1.of(A).supportsEmojiWidth);return new x0({width:this.widget.props.width,height:I31(this.widget.props.entries),decoration:new R4(Q.colors.background,d1.all(new p1(Q.colors.border,1,"solid"))),child:new x4({actions:this.buildActions(),child:new vA({debugLabel:"NeoContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new v4({autofocus:!0,debugLabel:"NeoContextPicker",child:new S0({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,D)=>this.buildEntry(B,D,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new x0({height:1,decoration:{border:new d1(new p1(B.colors.border,1,"solid"))}});let D=Q===this.selectedIndex,J=A.enabled??!0,F=new T({color:D?B.app.selectionForeground:B.colors.foreground,dim:!J}),E=new T({color:D?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!J});return new O1({onClick:()=>this.acceptIndex(Q),child:new x0({padding:V0.symmetric(1,0),decoration:D?new R4(B.app.selectionBackground):void 0,child:new r0({crossAxisAlignment:"start",children:[new R1({child:new d({text:new w(A.label,F),maxLines:1,overflow:"ellipsis"})}),new X0({width:1}),new X0({width:$,child:new d({text:new w(Rs4(A),E),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function wp3(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,J4(Rs4(B),Q)):$},0)}function Rs4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var Mp3=36,Lp3=24,Op3=72;class us4 extends u0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new Ps4}}class Ps4 extends R0{build(A){return this.widget.onContext(A),this.widget.child}}function _s4(A){return A.replace(/ ago$/,"")}function aX0(A){return A.reduce((Q,$)=>Math.max(Q,J4(_s4($.description.timeAgo))),0)}function Ts4(A){return Math.max(Lp3,Math.min(A,Op3))}class q31 extends V4{}class N31 extends V4{}class C31{options;visibility;width=Mp3;constructor(A){this.options=A;this.visibility=new zr(A.state)}isVisible(){return this.visibility.isEnabled()}buildBody(A){return new r0({crossAxisAlignment:"stretch",children:[this.buildSlot(),new R1({child:A})]})}buildSlot(){if(!this.options.isAvailable()||this.visibility.isDisabled())return new X0({width:0});return new X0({width:this.width,child:new k4({debugLabel:"ThreadListSidebar",child:new vs4({activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:t1(i0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize})})})}commands(){if(!this.options.isAvailable())return[];return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",keywords:["sidebar","recent","history","threads"],shortcut:G1.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggle()}}]}shortcutEntries(){return this.options.isAvailable()?[[G1.alt("s"),new kU0]]:[]}actionEntries(){if(!this.options.isAvailable())return[];return[[kU0,new T1(()=>this.toggle())]]}toggle=()=>{if(!this.options.isAvailable())return"ignored";if(this.visibility.isDisabled()&&this.options.isBlocked())return"ignored";return this.visibility.toggle(),"handled"};close=()=>{this.visibility.disable()};resize=(A)=>{let Q=Ts4(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class vs4 extends u0{props;constructor(A){super();this.props=A}createState(){return new ks4}}class ks4 extends R0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;timeColWidth=0;contextMenu=null;pendingThreadMutations=new Map;resizeSession=null;isResizeHandleHovered=!1;pickerController=new kr;threadItemContexts=new Map;shortcuts=new Map([[G1.alt("w"),new q31],[G1.ctrl("."),new N31]]);actions=new Map([[q31,new T1(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[N31,new T1(()=>this.openContextMenu())]]);get isBusy(){return this.isLoading||this.isSwitchingThread}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null}initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=ZA1(A);if(!this.mounted)return;this.setState(()=>{this.pickerController.selectedItem=Q.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.timeColWidth=aX0(Q),this.isLoading=!1,this.hasError=!1})}catch(A){if(u.error("Failed to load threads for Neo sidebar",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A),this.widget.props.onDismiss()}catch(Q){u.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:G1.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:G1.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new G1("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.pickerController.selectedItem;if(!A||this.isBusy||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=I31(Q),B=this.getContextMenuWidth(),D=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:D.left,top:D.top,width:B,height:$}}),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),D=1,J=this.threadItemContexts.get(A)?.findRenderObject(),F=this.context.findRenderObject();if(!(J instanceof c1)||!(F instanceof c1))return{left:B,top:1};let E=J.localToGlobal({x:0,y:0}),Y=F.localToGlobal({x:0,y:0}),Z=E.y-Y.y,U=Z+J.size.height,X=b1.sizeOf(this.context).height,G=Math.max(1,Math.min(F.size.height,X-Y.y)),z=G-U>=Q||Z<G/2?U:Z-Q,W=Math.max(0,G-Q);return{left:B,top:Math.max(0,Math.min(z,W))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveContextMenuThread(Q);return}if(A==="copy-id"){x4.maybeInvoke(this.context,new K8(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}x4.maybeInvoke(this.context,new K8(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q),this.timeColWidth=aX0(this.getOptimisticThreads())}),i6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.threads=this.threads.filter(($)=>$.id!==A),this.timeColWidth=aX0(this.getOptimisticThreads())}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A),this.timeColWidth=aX0(this.getOptimisticThreads());let B=this.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.pickerController.selectedItem=$})}async archiveContextMenuThread(A){let Q=w3.maybeOf(this.context),{configService:$}=G5.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await xZ0({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A)}catch(B){if(u.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return y$(new URL(G5.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new o4({left:A.left,top:A.top,width:A.width,height:A.height,child:new k4({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new H31({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new o4({left:0,top:0,right:0,bottom:0,child:new O1({onClick:()=>this.closeContextMenu(),child:X0.expand()})})}buildThreadItem(A,Q,$,B){let D=O0.of(B),{app:J,colors:F}=D,E=!Q,Y=Q?J.selectionForeground:F.foreground,Z=Q?J.selectionForeground:F.mutedForeground,X=A.id===this.widget.props.activeThreadID?new d({text:new w("*",new T({color:Q?J.selectionForeground:F.success,dim:E}))}):void 0,G=_s4(A.description.timeAgo);return new us4(new x0({padding:V0.symmetric(1,0),child:new r0({children:[new X0({width:2,child:X}),new R1({child:new d({text:new w(A.title,new T({color:Y,dim:E})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new X0({width:$,child:r0.end([new d({text:new w(G,new T({color:Z,dim:E}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=Ts4(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new o4({top:0,right:0,bottom:0,width:1,child:new O1({cursor:YA.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new X0({width:1})})})}build(A){let Q=O0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$;this.threadItemContexts.clear();let D=this.isSwitchingThread?"Switching thread...":"Loading threads...",J=this.hasError?"Failed to load threads":"No threads match your filter",F=this.isResizeActive?2:1,E=new d1(void 0,new p1(Q.colors.border,F),void 0,void 0),Y=this.buildContextMenuOverlay(),Z=[new x0({decoration:new R4(Q.colors.background,E),child:new x4({actions:this.actions,child:new vA({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new pA({items:B,getLabel:(U)=>`${U.title} ${U.id}`,controller:this.pickerController,onAccept:(U)=>void this.handleSelectThread(U.id),onDismiss:this.widget.props.onDismiss,renderItem:(U,X,G,V)=>this.buildThreadItem(U,X,this.timeColWidth,V),enabled:!this.isBusy,isLoading:this.isBusy,hidePromptWhenLoading:!0,loadingText:D,emptyStateText:J,maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(Y)Z.push(this.buildContextMenuBackdrop()),Z.push(Y);return new x0({width:this.widget.props.width,child:new i4({fit:"expand",children:Z})})}}class w31 extends u0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;workspaceSettingsFilePath;neoContext;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.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,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.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.neoContext=A.neoContext}createState(){return new fs4}}class fs4 extends R0{editorController=new P2;commandPalette=new zr(this);commandRegistry=new r41;toastController=new X01;relaunchNotificationController=new m41;exitHintTimer=new Kr(this,1000);ideStatus=new X8(this,{});threadNavigationHistory=new l41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;endCreditsVisible=!1;neoInvadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new us;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return rh4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new C31({state:this,isAvailable:()=>this.widget.neoContext.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.neoContext.workspaceRoot,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>iU0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await xZ0({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await Dp4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await Jp4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(FB.getInstance().interceptConsole(),this.neoInvadersHighScore=this.widget.neoContext.neoInvadersHighScore??0,this.notices=new j41(this.widget.configService,($)=>this.setState($)),i6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(u.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(r50($.settings)))}),this.updateRelaunchIntegration=new p41({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.neoContext.sessionAgentMode);this.pluginIntegration=new g41({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new O41({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=z4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Xi4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],B=[Ni4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(D,J,F)=>{D.pushWithDismiss((E)=>UA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:E,onThreadSelected:F}))}},...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:(D,J,F)=>{A.navigateBack(),F()}},Os4({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:(D,J,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new k61({mcpServers:this.widget.neoContext.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((J)=>new Y31({toolboxes:this.widget.neoContext.toolboxes,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(D,J,F)=>{try{await n6(J,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{D$(this.widget.neoContext.settingsFilePath).catch((D)=>{u.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(D,J,F)=>{D.pushWithDismiss((E)=>new T61({onCancel:E,onSelect:(Y)=>{this.handleIdeSelection(Y),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new Q61({commands:w9.of(J).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showNeoWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",keywords:["team","contributors","movie","credits","easter egg"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new C6({header:"Amp Version",maxWidth:72,onDismiss:F,child:new d({text:new w(UZ0({version:"0.0.1779668338-g19be90",buildTimestamp:"2026-05-25T00:23:23.173Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:G1.ctrl("c"),status:{type:"enabled"},run:(D,J)=>{x4.maybeInvoke(J,new wy)}},...Q,...nl4(this.widget.neoContext.logFilePath)].map((D)=>this.commandRegistry.register(D));return()=>{for(let D of B)D()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,D=new E31({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,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.neoWelcomeVisible?null:B,onDismissNotice:(U)=>this.notices.dismiss(U)}),J=b1.of(A),F=J.capabilities.animationSupport!=="disabled",Y=[new x0({constraints:w1.tight(J.size.width,J.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())Y.push(new k4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new s41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Y.push(UA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Y.push(new k4({debugLabel:"NeoWelcomeDialogOverlay",child:new K31({onDismiss:this.dismissNeoWelcome,onQuit:()=>z4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let Z=this.executorAlreadyConnectedDialog;if(Z)Y.push(new k4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new P61({existingExecutorPid:Z.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(Y.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),Y.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Y.push(new B61({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:oX0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Y.push(new _61);if(this.endCreditsVisible)Y.push(new M61({onComplete:this.completeEndCredits,highScore:this.neoInvadersHighScore,onHighScoreChange:this.updateNeoInvadersHighScore}));return new G5({neoContext:this.widget.neoContext,child:new w9({commandRegistry:this.commandRegistry,child:new Ly({completionBuilder:this.widget.completionBuilder,child:new w3({controller:this.toastController,child:new x4({actions:this.buildActions(),child:new vA({debugLabel:"NeoAppShortcuts",shortcuts:this.buildShortcuts(),child:new v4({debugLabel:"AppShellFocus",child:new G01({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new $61({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new i4({children:Y})})})})})})})})})})}buildShortcuts(){let A=new Map([[G1.ctrl("c"),new uU0],[G1.ctrl("o"),new _U0],[G1.alt("i"),new vU0],[G1.alt("p"),new jN],[G1.ctrl("."),new fU0],[G1.ctrl("t"),new bU0],...this.threadListSidebar.shortcutEntries()]);if(oX0.env.NODE_ENV==="development"&&oX0.platform==="darwin")A.set(G1.meta("r"),new PU0);return A}buildActions(){let A=new T1(()=>{if(OD.hasAnyCopyableSelection())return OD.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new T1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new T1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new T1(()=>{return this.startNewDraftThread(),"handled"}),D=new T1(()=>{return z4.instance.stop(),"handled"}),J=new T1(()=>{return Cs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new T1((G)=>{if(!G.text)return"ignored";return z4.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{u.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),E=new T1(()=>{return z4.instance.toggleFrameStatsOverlay(),"handled"}),Y=new T1(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new T1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),U=Ti4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new T1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[uU0,A],[Gs,B],[wy,D],[PU0,J],[K8,F],[Ws,$],[_U0,Q],[vU0,Z],...this.threadListSidebar.actionEntries(),[fU0,Y],...U,[jN,E],[bU0,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}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 bf(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){u.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,$=A,B=EB(Q),D=oY0(this.widget.neoContext,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return aY0($,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ss4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(cF(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ss4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(cN);if(this.exitHintTimer.isActive())A.add(Iy);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),z4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};updateNeoInvadersHighScore=(A)=>{if(A<=this.neoInvadersHighScore)return;this.setState(()=>{this.neoInvadersHighScore=A}),GQ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{u.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!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")z4.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})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B)=>{await this.ensureDraftThreadSettingsInitialized();let D=this.activeThreadContext?.client.getThreadId(),J=A.find(g50);if(J)this.widget.history.add(J.text,oX0.cwd()),this.widget.history.reset();let F=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),E=$??F??null,Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,E??void 0);this.sendUserMessage(Y,A,Q,B),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(D),this.setActiveClient(Y)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:$};let B=EB(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:D};GQ((J)=>{let F={...J,agentMode:A};if($!==void 0)F={...F,lastReasoningEffortByMode:{...F.lastReasoningEffortByMode??{},[A]:$}};if(D!==void 0)F={...F,lastSpeedByMode:{...F.lastSpeedByMode??{},[A]:D}};return F}).catch((J)=>{u.warn("Failed to persist Neo session defaults for new message",{error:J instanceof Error?J.message:String(J)})})}sendUserMessage(A,Q,$,B){let D=fJ0(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{userState:D});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,userState:D})}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 $=this.activeThreadContext;if(!$)throw Error("appendToThread is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.append is only available for the active executor thread");for(let D of A)this.sendUserMessage($,[{type:"text",text:D.content}])};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.neoContext.observerOnly,onExecutorAlreadyConnected:(D)=>this.promptExecutorAlreadyConnected(D)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(u.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.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){u.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}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe(($)=>{this.widget.onActiveThreadChange?.($)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage($,(B)=>{A.sendPluginMessage(B)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...$]}}},(B)=>{A.sendPluginMessage(B)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){u.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.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(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.neoWelcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Ss4(A,Q,$){let B={...A};for(let D of jp3(Q,$)){if(!cF(A[D],Q[D]))continue;let J=$[D];if(J===void 0)delete B[D];else B[D]=J}return B}function jp3(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}a4();function ys4(A,Q,$,B){let D=DT(A),J="\x1B[0m",F="\x1B[34m",E="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${D}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let U=14,X=7,G=new rJ(U,X),V=new n9(42),K=new CN(U,X,U,X,U,X,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),V);K.layout(w1.tight(U,X)),K.paint(G,0,0);let z=G.getBuffer().getCells(),W=0;for(let j=0;j<X;j++)if(z[j].some((k)=>k.char!==" ")){W=j;break}let I=X-1;for(let j=X-1;j>=0;j--)if(z[j].some((k)=>k.char!==" ")){I=j;break}function H(j,k){if(!j)return"";if(j.type==="rgb"){let{r:_,g:S,b:h}=j.value;if($.getColorDepth()>=24)return`\x1B[${k?38:48};2;${_};${S};${h}m`;let b=uj(_,S,h);return`\x1B[${k?38:48};5;${b}m`}return""}let q=[];if(I>=W)for(let j=W;j<=I;j++){let k="";for(let _=0;_<U;_++){let S=z[j][_],h=S.char,b=H(S.style.fg,!0);k+=b+h+"\x1B[0m"}q.push(k)}let N=q.length,C=Math.max(N,Z.length),O=Math.floor((C-N)/2),L=Math.floor((C-Z.length)/2);for(let j=0;j<C;j++){let k=" ".repeat(U);if(j>=O&&j<O+N)k=q[j-O];let _=" ",S="";if(j>=L&&j<L+Z.length)S=Z[j-L];$.write(k+_+S+`
5319
+ `)),J.push(new w("Details: ",new T({color:B.mutedForeground}))),J.push(new w(A.costBreakdownURL,new T({color:$.app.link})));return new d({text:new w("",void 0,J)})}function Cp3(A,Q,$){let B=Np3(A,Q);if(!A.costBreakdownURL)return new C6({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:$,child:B});let D=A.costBreakdownURL,J=new T1(()=>{return x4.maybeInvoke(Q,new K8(D,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),F=new T1(()=>{return n6(Q,D),"handled"});return new C6({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:$,child:new x4({actions:new Map([[z31,J],[W31,F]]),child:new vA({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[G1.key("o"),new W31],[G1.key("y"),new z31]]),child:new v4({autofocus:!0,debugLabel:"ThreadCostBody",child:B})})})})}function Os4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,$,B)=>{let D=A.getActiveThreadID();if(!D)return;try{let J=await e4.threadDisplayCostInfo({threadID:D},{config:A.configService});if(!J.ok){A.toastController.show(qp3(D,J.error),"error",5000),B();return}Q.push(Cp3(J.result,$,B))}catch(J){u.error("Failed to load Neo thread cost",{error:J,threadID:D}),A.toastController.show(`Failed to show thread cost: ${J instanceof Error?J.message:String(J)}`,"error",5000),B()}}}}p0();u9();Q4();class ez extends V4{direction;constructor(A){super();this.direction=A}}class iX0 extends V4{}class ns extends V4{}class nX0 extends V4{index;constructor(A){super();this.index=A}}function I31(A){return A.length+2}class H31 extends u0{props;constructor(A){super();this.props=A}createState(){return new js4}}class js4 extends R0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let D=$+B;if(D<Q.length&&this.isSelectable(D))return D;let J=$-B;if(J>=0&&this.isSelectable(J))return J}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof ez)return this.moveSelection(A.direction),"handled";if(A instanceof iX0)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof ns)return this.widget.props.onDismiss(),"handled";if(A instanceof nX0)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[G1.key("ArrowDown"),new ez(1)],[G1.key("j"),new ez(1)],[G1.ctrl("n"),new ez(1)],[G1.key("ArrowUp"),new ez(-1)],[G1.key("k"),new ez(-1)],[G1.ctrl("p"),new ez(-1)],[G1.key("Enter"),new iX0],[G1.key("Escape"),new ns],[G1.ctrl("."),new ns]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new nX0($))}),A}buildActions(){return new Map([[ez,new T1(this.invoke)],[iX0,new T1(this.invoke)],[ns,new T1(this.invoke)],[nX0,new T1(this.invoke)]])}build(A){let Q=O0.of(A),$=wp3(this.widget.props.entries,b1.of(A).supportsEmojiWidth);return new x0({width:this.widget.props.width,height:I31(this.widget.props.entries),decoration:new R4(Q.colors.background,d1.all(new p1(Q.colors.border,1,"solid"))),child:new x4({actions:this.buildActions(),child:new vA({debugLabel:"NeoContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new v4({autofocus:!0,debugLabel:"NeoContextPicker",child:new S0({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,D)=>this.buildEntry(B,D,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new x0({height:1,decoration:{border:new d1(new p1(B.colors.border,1,"solid"))}});let D=Q===this.selectedIndex,J=A.enabled??!0,F=new T({color:D?B.app.selectionForeground:B.colors.foreground,dim:!J}),E=new T({color:D?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!J});return new O1({onClick:()=>this.acceptIndex(Q),child:new x0({padding:V0.symmetric(1,0),decoration:D?new R4(B.app.selectionBackground):void 0,child:new r0({crossAxisAlignment:"start",children:[new R1({child:new d({text:new w(A.label,F),maxLines:1,overflow:"ellipsis"})}),new X0({width:1}),new X0({width:$,child:new d({text:new w(Rs4(A),E),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function wp3(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,J4(Rs4(B),Q)):$},0)}function Rs4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var Mp3=36,Lp3=24,Op3=72;class us4 extends u0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new Ps4}}class Ps4 extends R0{build(A){return this.widget.onContext(A),this.widget.child}}function _s4(A){return A.replace(/ ago$/,"")}function aX0(A){return A.reduce((Q,$)=>Math.max(Q,J4(_s4($.description.timeAgo))),0)}function Ts4(A){return Math.max(Lp3,Math.min(A,Op3))}class q31 extends V4{}class N31 extends V4{}class C31{options;visibility;width=Mp3;constructor(A){this.options=A;this.visibility=new zr(A.state)}isVisible(){return this.visibility.isEnabled()}buildBody(A){return new r0({crossAxisAlignment:"stretch",children:[this.buildSlot(),new R1({child:A})]})}buildSlot(){if(!this.options.isAvailable()||this.visibility.isDisabled())return new X0({width:0});return new X0({width:this.width,child:new k4({debugLabel:"ThreadListSidebar",child:new vs4({activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:t1(i0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize})})})}commands(){if(!this.options.isAvailable())return[];return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",keywords:["sidebar","recent","history","threads"],shortcut:G1.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggle()}}]}shortcutEntries(){return this.options.isAvailable()?[[G1.alt("s"),new kU0]]:[]}actionEntries(){if(!this.options.isAvailable())return[];return[[kU0,new T1(()=>this.toggle())]]}toggle=()=>{if(!this.options.isAvailable())return"ignored";if(this.visibility.isDisabled()&&this.options.isBlocked())return"ignored";return this.visibility.toggle(),"handled"};close=()=>{this.visibility.disable()};resize=(A)=>{let Q=Ts4(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class vs4 extends u0{props;constructor(A){super();this.props=A}createState(){return new ks4}}class ks4 extends R0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;timeColWidth=0;contextMenu=null;pendingThreadMutations=new Map;resizeSession=null;isResizeHandleHovered=!1;pickerController=new kr;threadItemContexts=new Map;shortcuts=new Map([[G1.alt("w"),new q31],[G1.ctrl("."),new N31]]);actions=new Map([[q31,new T1(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[N31,new T1(()=>this.openContextMenu())]]);get isBusy(){return this.isLoading||this.isSwitchingThread}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null}initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=ZA1(A);if(!this.mounted)return;this.setState(()=>{this.pickerController.selectedItem=Q.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.timeColWidth=aX0(Q),this.isLoading=!1,this.hasError=!1})}catch(A){if(u.error("Failed to load threads for Neo sidebar",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A),this.widget.props.onDismiss()}catch(Q){u.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:G1.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:G1.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new G1("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.pickerController.selectedItem;if(!A||this.isBusy||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=I31(Q),B=this.getContextMenuWidth(),D=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:D.left,top:D.top,width:B,height:$}}),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),D=1,J=this.threadItemContexts.get(A)?.findRenderObject(),F=this.context.findRenderObject();if(!(J instanceof c1)||!(F instanceof c1))return{left:B,top:1};let E=J.localToGlobal({x:0,y:0}),Y=F.localToGlobal({x:0,y:0}),Z=E.y-Y.y,U=Z+J.size.height,X=b1.sizeOf(this.context).height,G=Math.max(1,Math.min(F.size.height,X-Y.y)),z=G-U>=Q||Z<G/2?U:Z-Q,W=Math.max(0,G-Q);return{left:B,top:Math.max(0,Math.min(z,W))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveContextMenuThread(Q);return}if(A==="copy-id"){x4.maybeInvoke(this.context,new K8(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}x4.maybeInvoke(this.context,new K8(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q),this.timeColWidth=aX0(this.getOptimisticThreads())}),i6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.threads=this.threads.filter(($)=>$.id!==A),this.timeColWidth=aX0(this.getOptimisticThreads())}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A),this.timeColWidth=aX0(this.getOptimisticThreads());let B=this.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.pickerController.selectedItem=$})}async archiveContextMenuThread(A){let Q=w3.maybeOf(this.context),{configService:$}=G5.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await xZ0({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A)}catch(B){if(u.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return y$(new URL(G5.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new o4({left:A.left,top:A.top,width:A.width,height:A.height,child:new k4({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new H31({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new o4({left:0,top:0,right:0,bottom:0,child:new O1({onClick:()=>this.closeContextMenu(),child:X0.expand()})})}buildThreadItem(A,Q,$,B){let D=O0.of(B),{app:J,colors:F}=D,E=!Q,Y=Q?J.selectionForeground:F.foreground,Z=Q?J.selectionForeground:F.mutedForeground,X=A.id===this.widget.props.activeThreadID?new d({text:new w("*",new T({color:Q?J.selectionForeground:F.success,dim:E}))}):void 0,G=_s4(A.description.timeAgo);return new us4(new x0({padding:V0.symmetric(1,0),child:new r0({children:[new X0({width:2,child:X}),new R1({child:new d({text:new w(A.title,new T({color:Y,dim:E})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new X0({width:$,child:r0.end([new d({text:new w(G,new T({color:Z,dim:E}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=Ts4(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new o4({top:0,right:0,bottom:0,width:1,child:new O1({cursor:YA.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new X0({width:1})})})}build(A){let Q=O0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$;this.threadItemContexts.clear();let D=this.isSwitchingThread?"Switching thread...":"Loading threads...",J=this.hasError?"Failed to load threads":"No threads match your filter",F=this.isResizeActive?2:1,E=new d1(void 0,new p1(Q.colors.border,F),void 0,void 0),Y=this.buildContextMenuOverlay(),Z=[new x0({decoration:new R4(Q.colors.background,E),child:new x4({actions:this.actions,child:new vA({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new pA({items:B,getLabel:(U)=>`${U.title} ${U.id}`,controller:this.pickerController,onAccept:(U)=>void this.handleSelectThread(U.id),onDismiss:this.widget.props.onDismiss,renderItem:(U,X,G,V)=>this.buildThreadItem(U,X,this.timeColWidth,V),enabled:!this.isBusy,isLoading:this.isBusy,hidePromptWhenLoading:!0,loadingText:D,emptyStateText:J,maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(Y)Z.push(this.buildContextMenuBackdrop()),Z.push(Y);return new x0({width:this.widget.props.width,child:new i4({fit:"expand",children:Z})})}}class w31 extends u0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;workspaceSettingsFilePath;neoContext;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.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,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.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.neoContext=A.neoContext}createState(){return new fs4}}class fs4 extends R0{editorController=new P2;commandPalette=new zr(this);commandRegistry=new r41;toastController=new X01;relaunchNotificationController=new m41;exitHintTimer=new Kr(this,1000);ideStatus=new X8(this,{});threadNavigationHistory=new l41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;endCreditsVisible=!1;neoInvadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new us;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return rh4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new C31({state:this,isAvailable:()=>this.widget.neoContext.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.neoContext.workspaceRoot,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>iU0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await xZ0({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await Dp4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await Jp4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(FB.getInstance().interceptConsole(),this.neoInvadersHighScore=this.widget.neoContext.neoInvadersHighScore??0,this.notices=new j41(this.widget.configService,($)=>this.setState($)),i6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(u.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(r50($.settings)))}),this.updateRelaunchIntegration=new p41({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.neoContext.sessionAgentMode);this.pluginIntegration=new g41({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new O41({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=z4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Xi4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],B=[Ni4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(D,J,F)=>{D.pushWithDismiss((E)=>UA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:E,onThreadSelected:F}))}},...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:(D,J,F)=>{A.navigateBack(),F()}},Os4({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:(D,J,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new k61({mcpServers:this.widget.neoContext.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((J)=>new Y31({toolboxes:this.widget.neoContext.toolboxes,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(D,J,F)=>{try{await n6(J,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{D$(this.widget.neoContext.settingsFilePath).catch((D)=>{u.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(D,J,F)=>{D.pushWithDismiss((E)=>new T61({onCancel:E,onSelect:(Y)=>{this.handleIdeSelection(Y),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new Q61({commands:w9.of(J).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showNeoWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",keywords:["team","contributors","movie","credits","easter egg"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new C6({header:"Amp Version",maxWidth:72,onDismiss:F,child:new d({text:new w(UZ0({version:"0.0.1779686836-g4ef406",buildTimestamp:"2026-05-25T05:31:37.501Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:G1.ctrl("c"),status:{type:"enabled"},run:(D,J)=>{x4.maybeInvoke(J,new wy)}},...Q,...nl4(this.widget.neoContext.logFilePath)].map((D)=>this.commandRegistry.register(D));return()=>{for(let D of B)D()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,D=new E31({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,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.neoWelcomeVisible?null:B,onDismissNotice:(U)=>this.notices.dismiss(U)}),J=b1.of(A),F=J.capabilities.animationSupport!=="disabled",Y=[new x0({constraints:w1.tight(J.size.width,J.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())Y.push(new k4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new s41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Y.push(UA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Y.push(new k4({debugLabel:"NeoWelcomeDialogOverlay",child:new K31({onDismiss:this.dismissNeoWelcome,onQuit:()=>z4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let Z=this.executorAlreadyConnectedDialog;if(Z)Y.push(new k4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new P61({existingExecutorPid:Z.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(Y.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),Y.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Y.push(new B61({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:oX0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Y.push(new _61);if(this.endCreditsVisible)Y.push(new M61({onComplete:this.completeEndCredits,highScore:this.neoInvadersHighScore,onHighScoreChange:this.updateNeoInvadersHighScore}));return new G5({neoContext:this.widget.neoContext,child:new w9({commandRegistry:this.commandRegistry,child:new Ly({completionBuilder:this.widget.completionBuilder,child:new w3({controller:this.toastController,child:new x4({actions:this.buildActions(),child:new vA({debugLabel:"NeoAppShortcuts",shortcuts:this.buildShortcuts(),child:new v4({debugLabel:"AppShellFocus",child:new G01({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new $61({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new i4({children:Y})})})})})})})})})})}buildShortcuts(){let A=new Map([[G1.ctrl("c"),new uU0],[G1.ctrl("o"),new _U0],[G1.alt("i"),new vU0],[G1.alt("p"),new jN],[G1.ctrl("."),new fU0],[G1.ctrl("t"),new bU0],...this.threadListSidebar.shortcutEntries()]);if(oX0.env.NODE_ENV==="development"&&oX0.platform==="darwin")A.set(G1.meta("r"),new PU0);return A}buildActions(){let A=new T1(()=>{if(OD.hasAnyCopyableSelection())return OD.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new T1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new T1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new T1(()=>{return this.startNewDraftThread(),"handled"}),D=new T1(()=>{return z4.instance.stop(),"handled"}),J=new T1(()=>{return Cs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new T1((G)=>{if(!G.text)return"ignored";return z4.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{u.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),E=new T1(()=>{return z4.instance.toggleFrameStatsOverlay(),"handled"}),Y=new T1(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new T1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),U=Ti4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new T1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[uU0,A],[Gs,B],[wy,D],[PU0,J],[K8,F],[Ws,$],[_U0,Q],[vU0,Z],...this.threadListSidebar.actionEntries(),[fU0,Y],...U,[jN,E],[bU0,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}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 bf(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){u.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,$=A,B=EB(Q),D=oY0(this.widget.neoContext,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return aY0($,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ss4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(cF(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ss4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(cN);if(this.exitHintTimer.isActive())A.add(Iy);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),z4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};updateNeoInvadersHighScore=(A)=>{if(A<=this.neoInvadersHighScore)return;this.setState(()=>{this.neoInvadersHighScore=A}),GQ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{u.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!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")z4.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})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B)=>{await this.ensureDraftThreadSettingsInitialized();let D=this.activeThreadContext?.client.getThreadId(),J=A.find(g50);if(J)this.widget.history.add(J.text,oX0.cwd()),this.widget.history.reset();let F=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),E=$??F??null,Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,E??void 0);this.sendUserMessage(Y,A,Q,B),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(D),this.setActiveClient(Y)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:$};let B=EB(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:D};GQ((J)=>{let F={...J,agentMode:A};if($!==void 0)F={...F,lastReasoningEffortByMode:{...F.lastReasoningEffortByMode??{},[A]:$}};if(D!==void 0)F={...F,lastSpeedByMode:{...F.lastSpeedByMode??{},[A]:D}};return F}).catch((J)=>{u.warn("Failed to persist Neo session defaults for new message",{error:J instanceof Error?J.message:String(J)})})}sendUserMessage(A,Q,$,B){let D=fJ0(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{userState:D});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,userState:D})}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 $=this.activeThreadContext;if(!$)throw Error("appendToThread is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.append is only available for the active executor thread");for(let D of A)this.sendUserMessage($,[{type:"text",text:D.content}])};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.neoContext.observerOnly,onExecutorAlreadyConnected:(D)=>this.promptExecutorAlreadyConnected(D)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(u.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.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){u.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}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe(($)=>{this.widget.onActiveThreadChange?.($)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage($,(B)=>{A.sendPluginMessage(B)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...$]}}},(B)=>{A.sendPluginMessage(B)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){u.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.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(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.neoWelcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Ss4(A,Q,$){let B={...A};for(let D of jp3(Q,$)){if(!cF(A[D],Q[D]))continue;let J=$[D];if(J===void 0)delete B[D];else B[D]=J}return B}function jp3(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}a4();function ys4(A,Q,$,B){let D=DT(A),J="\x1B[0m",F="\x1B[34m",E="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${D}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let U=14,X=7,G=new rJ(U,X),V=new n9(42),K=new CN(U,X,U,X,U,X,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),V);K.layout(w1.tight(U,X)),K.paint(G,0,0);let z=G.getBuffer().getCells(),W=0;for(let j=0;j<X;j++)if(z[j].some((k)=>k.char!==" ")){W=j;break}let I=X-1;for(let j=X-1;j>=0;j--)if(z[j].some((k)=>k.char!==" ")){I=j;break}function H(j,k){if(!j)return"";if(j.type==="rgb"){let{r:_,g:S,b:h}=j.value;if($.getColorDepth()>=24)return`\x1B[${k?38:48};2;${_};${S};${h}m`;let b=uj(_,S,h);return`\x1B[${k?38:48};5;${b}m`}return""}let q=[];if(I>=W)for(let j=W;j<=I;j++){let k="";for(let _=0;_<U;_++){let S=z[j][_],h=S.char,b=H(S.style.fg,!0);k+=b+h+"\x1B[0m"}q.push(k)}let N=q.length,C=Math.max(N,Z.length),O=Math.floor((C-N)/2),L=Math.floor((C-Z.length)/2);for(let j=0;j<C;j++){let k=" ".repeat(U);if(j>=O&&j<O+N)k=q[j-O];let _=" ",S="";if(j>=L&&j<L+Z.length)S=Z[j-L];$.write(k+_+S+`
5320
5320
  `)}if(B)$.write(`
5321
5321
  \x1B[90m${B}\x1B[0m
5322
5322
  `)}p0();p0();import{exec as qR}from"node:child_process";function rX0(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")qR("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")qR("powershell [console]::beep(800,200)");else if(process.platform==="linux")qR("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")qR("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")qR("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")qR("powershell [console]::beep(1000,300)");else if(process.platform==="linux")qR("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){u.error(`Failed to play notification sound (${A}):`,Q)}}Fr();FZ0();var Rp3=2000,up3="Agent is ready",Pp3="Waiting for approval";function xs4(A){let Q=!0,$=!0,B=A.configService.config.subscribe((I)=>{Q=I.settings["notifications.enabled"]??!0,$=I.settings["notifications.system.enabled"]!==!1}),D=0,J=()=>{let I=V?.prepareTerminalTitleForNotification();if(I!==void 0)process.stdout.write(LY0(I))},F=(I)=>{if(!Q)return;let H=Date.now();if(H-D<Rp3)return;if(D=H,hz())return;if(BY0())J(),setTimeout(DY0,go);else rX0(I)},E=()=>{F("idle"),K(up3)},Y=()=>{F("requires-user-input"),K(Pp3)},Z=(I)=>I?.attempt===void 0||I.attempt===0,U=null,X=null,G=null,V,K=(I)=>{if(!Q||!$)return;if(hz()&&!Er()&&!Pf())return;J(),setTimeout(()=>{process.stdout.write(mo(I))},go)},z=()=>{U?.unsubscribe(),X?.unsubscribe(),U=null,X=null,G=null,V=void 0};return{attach:(I,H,q)=>{if(z(),V=q,H)X=H.subscribe({next:(N)=>{if(N===null)return;if(!Z(N))return;E()},error:(N)=>{u.debug("Neo notification active error stream errored",{error:N})}});U=I.subscribe({next:(N)=>{try{let C=G!==null&&rQ(G),O=G==="awaiting_approval",L=C||O;if(N==="awaiting_approval"&&!O)Y();else if(N==="idle"&&L)E()}catch(C){u.debug("Neo notification handling failed",{error:C})}finally{G=N}},error:(N)=>{u.debug("Neo notification agent state stream errored",{error:N})}})},detach:z,unsubscribe(){z(),B.unsubscribe()}}}function _p3({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:$,neoWelcomeVariant:B,neoWelcomeDismissed:D}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let J=!A&&!D;return{show:J,markDismissedOnDismiss:J}}async function Tp3(A){await GQ((Q)=>mf(Q,A,"interactive"))}async function bs4(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:J=!1,observerOnly:F=!1,initialAgentMode:E,initialReasoningEffort:Y,onFirstFrame:Z,showNeoWelcome:U=!1,hideNeoWelcome:X=!1,neoWelcomeVariant:G="intro"}=Q,V=G==="npm-migration";if($.length>1)u.info("Resuming multiple initial threads",{threadIDs:$});let K=async(_)=>{let S=await A.getThreadFromServer(_);if(!S)return null;return iE0(S)},z=async(_)=>{let S=await A.getThreadFromServer(_);if(!S)throw Error(`Thread ${_} not found`);let h=await c9(_,A.configService,A.apiKey,{usesThreadActors:!0}),b=LG({endpoint:A.rivetEndpoint,poolName:h.poolName}),v={wsToken:h.wsToken,transport:"amp-rpc"},c=await b.threadActor.getOrCreate([_],{params:v,createWithInput:{threadId:h.threadId,threadVersion:h.threadVersion,ownerUserId:h.ownerUserId,...h.agentMode?{agentMode:h.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:zS4(S)}),skipReadyWait:!0});if(!c.ok&&c.status!==409)throw Error(`Thread import failed (${c.status}): ${await c.text()}`);try{await lS4(_,A.configService,A.apiKey,{executorType:"local-client"})}catch(p){u.warn("failed to mark thread as imported on server",{threadID:_,error:p instanceof Error?p.message:String(p)})}},W=new xe0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:AN.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(_)=>A.pluginService.event.toolCall(_),requestPluginToolResult:(_)=>A.pluginService.event.toolResult(_),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,invokeTool:async(_,S)=>{let h=typeof S.args==="object"&&S.args!==null?S.args:{},b=await GN({toolName:S.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:S.toolCallId,threadId:_});return A.toolService.invokeTool(S.toolName,{args:h},b)},persistLastThreadID:Tp3,readFileSystemDirectory:A.readFileSystemDirectory},K,z),I=await bz(),H=_p3({initialUserInput:B,showNeoWelcome:U,hideNeoWelcome:X,neoWelcomeVariant:G,neoWelcomeDismissed:I.neoWelcomeDismissed}),q={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(_)=>{let S=await A.getThreadFromServer(_);return S?vX(S):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Ta,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:V?!1:F,neoInvadersHighScore:I.neoInvadersHighScore,sessionAgentMode:E??I.agentMode,explicitReasoningEffort:Y,lastReasoningEffortByMode:I.lastReasoningEffortByMode,lastSpeedByMode:I.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},N=(_,S)=>{return Dh4({ampURL:A.ampURL,configService:A.configService,threadID:_,signal:S})},C=new J01,O=xs4({configService:A.configService}),L=await A.configService.getLatest();z4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:L.settings["terminal.animation"]===!1}});let j=new Set,k=new d41;try{await Yr(new w31({clientPool:W,listSkillsForThread:N,completionBuilder:A.completionBuilder,history:new Ho,ideManager:C,configService:A.configService,updateService:A.updateService,initialThreadIDs:V?[]:$,notificationService:O,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:V?void 0:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:V?!1:J,workspaceSettingsFilePath:A.workspaceSettingsFilePath,neoContext:q,showNeoWelcome:H.show,neoWelcomeVariant:G,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:k.request,onNeoWelcomeDismissed:H.markDismissedOnDismiss?()=>{GQ(Eh4).catch((S)=>{u.warn("Failed to mark Neo welcome as dismissed",{error:S})})}:void 0,onThreadArchived:(S)=>{j.add(S)},onFirstFrame:Z}));let _=W.lastActiveObservingClient;if(_&&k.shouldShowExitSummary){let{client:S,observer:h}=_,b=S.getThreadId();if(b){let v={id:b,title:h.title().getValue(),agentMode:h.agentMode,archived:j.has(b)},y=`${A.ampURL.replace(/\/$/,"")}/threads/${b}`;ys4(v,y,process.stdout)}}}finally{process.stdout.write(IN("")),O.unsubscribe(),W.dispose(),await A.dispose?.()}process.exit(k.relaunchIfRequested(A.workspaceRoot)??0)}Y5();function cy(A){let Q=[],$={meta:{visibility:"private",sharedGroupIDs:[]}};if(A.workspace?.disablePrivateThreads)$.disabledReason="Disabled by workspace policy";if(Q.push($),A.workspace?.groups&&A.workspace.groups.length>0){let F={meta:{visibility:"private",shareWithAllCreatorGroups:!0}};if(A.creatorIsViewer===!1)F.disabledReason="Can only be set by thread creator";Q.push(F)}if(A.workspace)Q.push({meta:{visibility:"thread_workspace_shared"}});let B=A.workspace?.disablePublicSharing?"Disabled by workspace policy":void 0,D={meta:{visibility:"public_unlisted"}},J={meta:{visibility:"public_discoverable"}};if(B)D.disabledReason=B,J.disabledReason=B;return Q.push(D,J),Q}function hs4(A){if(A.visibility==="thread_group_shared")return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0;if(A.visibility!=="private")return!0;if("shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups)return!0;return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0}function NR(A,Q={}){switch(A.visibility){case"thread_workspace_shared":return{text:"Workspace",description:"Visible to all members of the workspace"};case"public_discoverable":return{text:"Public",description:"Visible on public profile & publicly searchable"};case"public_unlisted":return{text:"Unlisted",description:"Visible to anyone on the Internet who has the link"};case"thread_group_shared":case"private":{let $=A.visibility==="private"&&"shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups,B=$?Q.workspace?.groups.map((J)=>J.id)??[]:("sharedGroupIDs"in A)?A.sharedGroupIDs:[],D=B.reduce((J,F)=>{let E=Q.workspace?.groups.find((Y)=>Y.id===F)?.name;if(E)J.push(`'${E}'`);return J},[]);if(D.length>0)return{text:"Group",description:`Shared with ${U4(D.length,"group")} ${D.join(", ")} and workspace admins`};if($)return{text:"Group",description:"Shared with creator groups and workspace admins"};if(B.length>0)return{text:"Group",description:`Shared with ${U4(B.length,"group")} and workspace admins`};return{text:"Private",description:Q.workspace?"Only visible to you and workspace admins":"Only you can see this thread"}}}}function sX0(A){if(A.visibility==="private")return"shareWithAllCreatorGroups"in A?"group":"private";if(A.visibility==="thread_workspace_shared")return"workspace";if(A.visibility==="public_unlisted")return"unlisted";return"public"}function ly(A,Q=null){let $=A!==null&&typeof A==="object"&&"visibility"in A?A.visibility:void 0;if(!$||typeof $!=="string")return;let D=cy({workspace:Q?.team??void 0}).filter((J)=>!J.disabledReason).map((J)=>sX0(J.meta));if(D.includes($))return vp3($);if($==="group"&&!D.includes("group")){if(Q?.team?.groups!==void 0)return Error(`Group visibility is not available. You are not a member of any group in this workspace.
@@ -7078,7 +7078,7 @@ ${D}`,Q);this.line=$,this.column=B,this.codeblock=D}}/*!
7078
7078
  `),J=[];for(let F=0;F<D.length;F++){let Z=D[F].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of Z)if(U.startsWith("\x00")&&U.endsWith("\x01"))J.push(new w(U.slice(1,-1),new T({color:B.app.keybind,bold:!0})));else J.push(new w(U,new T({color:$.colorScheme.foreground})));if(F<D.length-1)J.push(new w(`
7079
7079
  `))}return new x0({decoration:{color:$.colorScheme.background,border:d1.all(new p1(B.app.keybind,1,"rounded"))},child:new f0({padding:V0.symmetric(0,1),child:new d({text:new w(void 0,void 0,J)})})})}}class v51 extends j5{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:$=null,showAxes:B=!0,colors:D=VV0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=$,this.showAxes=B,this.colors=D}createRenderObject(){return new _51({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function q16(A,Q,$,B,D,J,F){if(J<=0)return null;switch(A){case"horizontal-bar":{let E=$;return E>=0&&E<J?E:null}case"bar":case"stacked-bar":{let E=F?l2:0,Y=B-E;if(Y<=0)return null;let Z=Q-E;if(Z<0||Z>=Y)return null;let U=Math.max(1,Math.floor(Y/J)),X=Math.floor(Z/U);return X>=0&&X<J?X:null}case"line":case"sparkline":case"stacked-area":{let E=F?l2:0,Y=B-E;if(Y<=0)return null;let Z=Math.max(0,Math.min(Y-1,Q-E));if(J===1)return 0;let U=Y/(J-1),X=Math.round(Z/U);return Math.max(0,Math.min(J-1,X))}default:return null}}function Br3(A,Q,$,B,D,J,F,E){if(D<=0||Q<0||Q>=D)return null;let Y=2;switch(A){case"horizontal-bar":return{x:Math.floor($/2),y:Q};case"bar":case"stacked-bar":{let Z=J?l2:0,U=$-Z,X=B-(J?Y:0);if(U<=0||X<=0)return null;let G=Math.max(1,Math.floor(U/D)),V=Z+Q*G+Math.floor(G/2),K=E>0?F/E:0,z=Math.round((1-K)*(X-1));return{x:V,y:z}}case"line":case"sparkline":case"stacked-area":{let Z=J?l2:0,U=$-Z,X=B-(J?Y:0);if(U<=0||X<=0)return null;let G=D>1?Z+Math.round(Q/(D-1)*(U-1)):Z+Math.floor(U/2),V=E>0?F/E:0,K=Math.round((1-V)*(X-1));return{x:G,y:K}}default:return null}}function Dr3(A){let Q=0;for(let $ of A)for(let B of $.points)if(B.value>Q)Q=B.value;return Q||1}function Jr3(A,Q,$,B,D){if($.length<=1){let E=B(A.value),Y=A.meta?` (${A.meta})`:"";return A.label.length+2+E.length+Y.length}let J=A.label.length,F=0;for(let E of $){let Y=E.points[Q];if(!Y)continue;F+=Y.value;let Z=2+E.name.length+2+B(Y.value).length;J=Math.max(J,Z)}if(D){let E=9+B(F).length;J=Math.max(J,E)}return J}function Fr3(A,Q,$,B,D,J,F){let E;try{let K=L1.of(A),z=O0.of(A);E={foreground:K.colorScheme.foreground,background:K.colorScheme.background,border:z.app.keybind}}catch{E={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let Y=new T({color:E.foreground,bold:!0}),Z=new T({color:E.foreground}),U=new T({color:E.foreground,dim:!0}),X=[],G=new T({color:E.foreground,underline:!0}),V=(K,z)=>new w(z,G,void 0,kz(K),()=>{n6(A,K)});if(B.length<=1){if(X.push(new w(`${Q.label}: `,Y)),Q.link)X.push(V(Q.link,J(Q.value)));else X.push(new w(J(Q.value),Z));if(Q.meta)X.push(new w(` (${Q.meta})`,U))}else{let K=F==="stacked-bar"||F==="stacked-area";X.push(new w(`${Q.label}
7080
7080
  `,Y));let z=0;for(let W=0;W<B.length;W++){let I=B[W],H=I.points[$];if(!H)continue;z+=H.value;let q=I.color??D[W%D.length]??E.foreground;if(X.push(new w("● ",new T({color:q}))),X.push(new w(`${I.name}: `,U)),H.link)X.push(V(H.link,J(H.value)));else X.push(new w(J(H.value),Z));if(W<B.length-1||K)X.push(new w(`
7081
- `))}if(K)X.push(new w(" ",U)),X.push(new w("Total: ",U)),X.push(new w(J(z),Z))}return new x0({decoration:{color:E.background,border:d1.all(new p1(E.border,1,"rounded"))},child:new d({text:new w(void 0,void 0,X)})})}p0();function N16(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Y5();a5();y5();h$();u9();e2();fQ();nH();a4();sv();M_();u1();p0();u9();class k51{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,$])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779668338-g19be90"},parameters:{metadata:{count:$}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await c50(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class zC extends u0{props;constructor(A){super();this.props=A}createState(){return new C16}}class C16 extends R0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=($)=>{this.setState(()=>{this._state=$(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class w16 extends R0{controller=new P2;focusNode=new r6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=this.widget.props.isRequiredArg??!0,J=this.controller.text.trim().length>0,F=!D||J,E=d1.all(new p1($.foreground,1,"solid")),Y=new ZB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(V)=>{let K=V.trim();if(D&&K.length===0)return;this.widget.props.onSubmit(K)},autofocus:!0,style:{textColor:$.foreground,border:null},maxLines:1}),Z=new r0({children:[new x0({decoration:{color:$.background},child:new d({text:new w(">",new T({color:$.foreground}))})}),new R1({child:Y})]}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:this.widget.props.title?new w(this.widget.props.title,new T({color:B.command,bold:!0})):new w("",void 0,[new w("Command: ",new T({color:$.foreground})),new w(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=[];if(F)X.push(new w("Enter",new T({color:B.keybind}))),X.push(new w(" to submit, ",new T({color:$.foreground,dim:!0})));X.push(new w("Esc",new T({color:B.keybind}))),X.push(new w(" to cancel",new T({color:$.foreground,dim:!0})));let G=new x0({padding:V0.symmetric(1,0),child:new d({text:new w("",void 0,X)})});return new x0({decoration:{border:E,color:$.background},padding:V0.all(1),child:new S0({children:[U,new X0({height:1}),Z,new Z3,G]})})}}class Gt extends u0{props;constructor(A){super();this.props=A}createState(){return new w16}}fQ();class M16 extends R0{controller=new P2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new r6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=_9)return!1;let Q=await pG(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,J=b1.of(A).size.height,F=Math.max(Math.floor(J*0.5),10),E=new sz({controller:this.controller,triggers:[new $Y],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim(),this.imageAttachments)},theme:$,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:z4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),Y=new v4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:E}),Z=new x0({constraints:new w1({maxHeight:F}),padding:V0.symmetric(1,0),child:Y}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:new w("",void 0,[new w("Command: ",new T({color:$.foreground})),new w(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=new x0({padding:V0.symmetric(1,0),child:new d({text:this.isConfirmingClearInput?new w("",void 0,[new w("Esc",new T({color:B.keybind})),new w(" again to clear input",new T({color:$.foreground,dim:!0}))]):new w("",void 0,[new w("Press ",new T({color:$.foreground,dim:!0})),new w("Enter",new T({color:B.keybind})),new w(" to submit, ",new T({color:$.foreground,dim:!0})),new w("Esc",new T({color:B.keybind})),new w(" to clear",new T({color:$.foreground,dim:!0}))])})}),G=[U,new X0({height:1}),new R1({child:Z}),new X0({height:1}),X];return new x0({decoration:{border:d1.all(new p1($.foreground,1,"solid")),color:$.background},padding:V0.all(1),child:new S0({children:G})})}}class S51 extends u0{props;constructor(A){super();this.props=A}createState(){return new M16}}function L16(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),D=Math.floor($/3600000),J=Math.floor($/86400000);if(B<1)return"just now";if(B<60)return`${B}m ago`;if(D<24)return`${D}h ago`;if(J<7)return`${J}d ago`;return A.toLocaleDateString()}class f51 extends H1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((D,J)=>J.pubDate.getTime()-D.pubDate.getTime()),$=Math.max(0,...Q.map((D)=>L16(D.pubDate).length));return new pA({items:Q,getLabel:(D)=>D.title,onAccept:(D)=>this.props.onSelect?.(D),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(D,J,F,E)=>{let Y=O0.of(E),{colors:Z}=Y,U=Y.app,X=J?U.selectionBackground:void 0,G=J?U.selectionForeground:Z.foreground,V=Z.mutedForeground,K=(z,W)=>new X0({width:W,child:r0.end([new d({text:new w(z,new T({color:V}))})])});return new x0({decoration:X?{color:X}:void 0,padding:V0.symmetric(2,0),child:new r0({children:[new R1({child:new d({text:new w(D.title,new T({color:G})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),K(L16(D.pubDate),$)]})})}})}}class W${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!W$._instance)W$._instance=new W$;return W$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class O16 extends R0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){u.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){u.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let $=this.widget.props.currentLabels||[],B=this.labels.some((J)=>J.name===Q),D=$.includes(Q);return!B&&!D}build(A){let Q=O0.of(A),{app:$,colors:B}=Q,D=this.currentQuery.trim().toLowerCase(),J=D.length>0?this.getValidationError(D):null,F=this.getAvailableLabels(),Y=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...F];return new pA({title:"Add Label",items:Y,getLabel:(Z)=>{if("__isCreateMarker"in Z)return this.currentQuery.trim().toLowerCase();return Z.name},onAccept:(Z)=>{if("__isCreateMarker"in Z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:J||"Type to create a new label",renderItem:(Z,U,X,G)=>{let V=U?$.selectionBackground:void 0,K=U?$.selectionForeground:B.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new w("",void 0,[new w("Create new label: ",new T({color:K})),new w(W,new T({color:K,bold:!0}))])})})}return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new w(Z.name,new T({color:K}))})})},filterItem:(Z,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in Z&&Z.__isCreateMarker)return this.shouldShowCreateMarker(U);let G=U.trim().toLowerCase();return G.length===0||Z.name.includes(G)},sortItems:(Z,U,X)=>{let G="__isCreateMarker"in Z.item&&Z.item.__isCreateMarker,V="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(G&&!V)return-1;if(!G&&V)return 1;return U.score-Z.score}})}}class y51 extends u0{props;constructor(A){super();this.props=A}createState(){return new O16}}class eZ extends u0{props;constructor(A){super();this.props=A}createState(){return new j16}}class j16 extends R0{_spinner=new qA;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=d1.all(new p1($.foreground,1,"solid")),J=this._spinner.toBraille(),F=new d({textAlign:"center",text:new w("",void 0,[new w(J,new T({color:B.processing})),new w(" ",void 0),new w(this.widget.props.message,new T({color:$.foreground}))])}),Y=[new R1({child:new S0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[F]})})];if(this.widget.props.onAbort)Y.push(new X0({height:2,child:new x0({padding:V0.symmetric(2,0),child:new d({text:new w("",new T({dim:!0}),[new w("Press ",new T({color:$.foreground})),new w("Esc",new T({color:$.info})),new w(" to cancel",new T({color:$.foreground}))])})})}));let Z=new x0({decoration:new R4($.background,D),child:new X0({width:60,height:7,child:new S0({mainAxisAlignment:"start",children:Y})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",child:new v4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:Z})});return Z}}class oG extends u0{props;constructor(A){super();this.props=A}createState(){return new R16}}class R16 extends R0{scrollController=new v6;scrollAreaKey=new Y8("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof l8}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let $=Q.size;if(typeof $.height==="number"&&$.height>0)return this.viewportHeight=$.height,$.height}return this.viewportHeight}build(A){let Q=O0.of(A),$=this.widget.props.message,B=(()=>{if(this.isWidgetMessage($))return{title:$.title,type:$.type};if($ instanceof Error&&$.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:$.message};if($ instanceof Error&&$.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:$.message};let U=dZ0($);return{title:U.title,type:U.type,description:U.description}})(),D=B.type==="error"?Q.app.toolError:Q.app.command,J=d1.all(new p1(Q.colors.border,1,"solid")),F=new x0({padding:V0.symmetric(1,0),child:new d({text:new w(B.title,new T({color:D,bold:!0}))})}),E=this.isWidgetMessage($)?$.widget:new d({text:new w(B.description,new T({color:Q.colors.foreground})),selectable:!0}),Y=new R1({child:new U5({child:new x0({padding:V0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new R1({child:new k6({controller:this.scrollController,autofocus:!0,child:E})}),new z8({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,X=this.scrollController.offset,G=this.getViewportHeight(),V=U+G;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(X,0)}}})]})})})}),Z=new x0({padding:V0.symmetric(1,0),child:new d({text:(()=>{if(this.widget.props.onRetry)return new w("",void 0,[new w("Press ",new T({color:Q.colors.foreground,dim:!0})),new w("R",new T({color:Q.app.keybind})),new w(" to retry, ",new T({color:Q.colors.foreground,dim:!0})),new w("Esc",new T({color:Q.app.keybind})),new w(" to cancel",new T({color:Q.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new w("",new T({color:Q.colors.foreground,dim:!0}));if(U==="help"){let X=new T({color:Q.app.keybind}),G=new T({color:Q.colors.foreground,dim:!0});return new w("",G,[new w("Press ",G),new w("Escape",X),new w(" to close • Use ",G),new w("↑↓",X),new w(" or ",G),new w("j/k",X),new w(" to scroll",G)])}return new w("Press any key to close",new T({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({debugLabel:"MessageDialog",child:new i4({fit:"expand",children:[new O1({onClick:()=>{},child:new X0}),new v4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new x0({decoration:{border:J,color:Q.colors.background},padding:V0.all(1),child:new S0({mainAxisAlignment:"center",children:[F,new X0({height:1}),Y,Z]})})})]})})}}Y5();Q4();class u16 extends u0{props;constructor(A){super();this.props=A}createState(){return new P16}}class P16 extends R0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=i0.file(this.widget.props.cwd),$=B1.relativePath(Q,XA(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return c3(A)}statusIcon(A){let Q=d2.default(),{colors:$,app:B}=Q;switch(A){case"loading":return{icon:"◌",color:$.warning};case"active":return{icon:"✓",color:B.toolSuccess};case"error":return{icon:"✗",color:B.toolError}}}build(A){let Q=O0.of(A),{app:$}=Q;if(this.plugins.length===0)return new d({text:new w("No plugins found.",new T({dim:!0}))});let B=[],D=this.plugins.length,J=this.plugins.filter((Y)=>Y.status==="active").length,F=this.plugins.reduce((Y,Z)=>Y+Z.registeredCommands.length,0),E=this.plugins.reduce((Y,Z)=>Y+Z.registeredTools.length,0);if(B.push(new w(`${J}/${D} ${U4(D,"plugin")} active`,new T({bold:!0}))),F>0||E>0)B.push(new w(` (${F} ${U4(F,"command")}, ${E} ${U4(E,"tool")})`,new T({dim:!0})));B.push(new w(`
7081
+ `))}if(K)X.push(new w(" ",U)),X.push(new w("Total: ",U)),X.push(new w(J(z),Z))}return new x0({decoration:{color:E.background,border:d1.all(new p1(E.border,1,"rounded"))},child:new d({text:new w(void 0,void 0,X)})})}p0();function N16(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Y5();a5();y5();h$();u9();e2();fQ();nH();a4();sv();M_();u1();p0();u9();class k51{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,$])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779686836-g4ef406"},parameters:{metadata:{count:$}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await c50(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class zC extends u0{props;constructor(A){super();this.props=A}createState(){return new C16}}class C16 extends R0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=($)=>{this.setState(()=>{this._state=$(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class w16 extends R0{controller=new P2;focusNode=new r6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=this.widget.props.isRequiredArg??!0,J=this.controller.text.trim().length>0,F=!D||J,E=d1.all(new p1($.foreground,1,"solid")),Y=new ZB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(V)=>{let K=V.trim();if(D&&K.length===0)return;this.widget.props.onSubmit(K)},autofocus:!0,style:{textColor:$.foreground,border:null},maxLines:1}),Z=new r0({children:[new x0({decoration:{color:$.background},child:new d({text:new w(">",new T({color:$.foreground}))})}),new R1({child:Y})]}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:this.widget.props.title?new w(this.widget.props.title,new T({color:B.command,bold:!0})):new w("",void 0,[new w("Command: ",new T({color:$.foreground})),new w(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=[];if(F)X.push(new w("Enter",new T({color:B.keybind}))),X.push(new w(" to submit, ",new T({color:$.foreground,dim:!0})));X.push(new w("Esc",new T({color:B.keybind}))),X.push(new w(" to cancel",new T({color:$.foreground,dim:!0})));let G=new x0({padding:V0.symmetric(1,0),child:new d({text:new w("",void 0,X)})});return new x0({decoration:{border:E,color:$.background},padding:V0.all(1),child:new S0({children:[U,new X0({height:1}),Z,new Z3,G]})})}}class Gt extends u0{props;constructor(A){super();this.props=A}createState(){return new w16}}fQ();class M16 extends R0{controller=new P2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new r6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=_9)return!1;let Q=await pG(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,J=b1.of(A).size.height,F=Math.max(Math.floor(J*0.5),10),E=new sz({controller:this.controller,triggers:[new $Y],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim(),this.imageAttachments)},theme:$,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:z4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),Y=new v4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:E}),Z=new x0({constraints:new w1({maxHeight:F}),padding:V0.symmetric(1,0),child:Y}),U=new x0({padding:V0.symmetric(1,0),child:new d({text:new w("",void 0,[new w("Command: ",new T({color:$.foreground})),new w(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=new x0({padding:V0.symmetric(1,0),child:new d({text:this.isConfirmingClearInput?new w("",void 0,[new w("Esc",new T({color:B.keybind})),new w(" again to clear input",new T({color:$.foreground,dim:!0}))]):new w("",void 0,[new w("Press ",new T({color:$.foreground,dim:!0})),new w("Enter",new T({color:B.keybind})),new w(" to submit, ",new T({color:$.foreground,dim:!0})),new w("Esc",new T({color:B.keybind})),new w(" to clear",new T({color:$.foreground,dim:!0}))])})}),G=[U,new X0({height:1}),new R1({child:Z}),new X0({height:1}),X];return new x0({decoration:{border:d1.all(new p1($.foreground,1,"solid")),color:$.background},padding:V0.all(1),child:new S0({children:G})})}}class S51 extends u0{props;constructor(A){super();this.props=A}createState(){return new M16}}function L16(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),D=Math.floor($/3600000),J=Math.floor($/86400000);if(B<1)return"just now";if(B<60)return`${B}m ago`;if(D<24)return`${D}h ago`;if(J<7)return`${J}d ago`;return A.toLocaleDateString()}class f51 extends H1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((D,J)=>J.pubDate.getTime()-D.pubDate.getTime()),$=Math.max(0,...Q.map((D)=>L16(D.pubDate).length));return new pA({items:Q,getLabel:(D)=>D.title,onAccept:(D)=>this.props.onSelect?.(D),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(D,J,F,E)=>{let Y=O0.of(E),{colors:Z}=Y,U=Y.app,X=J?U.selectionBackground:void 0,G=J?U.selectionForeground:Z.foreground,V=Z.mutedForeground,K=(z,W)=>new X0({width:W,child:r0.end([new d({text:new w(z,new T({color:V}))})])});return new x0({decoration:X?{color:X}:void 0,padding:V0.symmetric(2,0),child:new r0({children:[new R1({child:new d({text:new w(D.title,new T({color:G})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),K(L16(D.pubDate),$)]})})}})}}class W${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!W$._instance)W$._instance=new W$;return W$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class O16 extends R0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){u.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){u.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let $=this.widget.props.currentLabels||[],B=this.labels.some((J)=>J.name===Q),D=$.includes(Q);return!B&&!D}build(A){let Q=O0.of(A),{app:$,colors:B}=Q,D=this.currentQuery.trim().toLowerCase(),J=D.length>0?this.getValidationError(D):null,F=this.getAvailableLabels(),Y=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...F];return new pA({title:"Add Label",items:Y,getLabel:(Z)=>{if("__isCreateMarker"in Z)return this.currentQuery.trim().toLowerCase();return Z.name},onAccept:(Z)=>{if("__isCreateMarker"in Z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:J||"Type to create a new label",renderItem:(Z,U,X,G)=>{let V=U?$.selectionBackground:void 0,K=U?$.selectionForeground:B.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new w("",void 0,[new w("Create new label: ",new T({color:K})),new w(W,new T({color:K,bold:!0}))])})})}return new x0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new w(Z.name,new T({color:K}))})})},filterItem:(Z,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in Z&&Z.__isCreateMarker)return this.shouldShowCreateMarker(U);let G=U.trim().toLowerCase();return G.length===0||Z.name.includes(G)},sortItems:(Z,U,X)=>{let G="__isCreateMarker"in Z.item&&Z.item.__isCreateMarker,V="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(G&&!V)return-1;if(!G&&V)return 1;return U.score-Z.score}})}}class y51 extends u0{props;constructor(A){super();this.props=A}createState(){return new O16}}class eZ extends u0{props;constructor(A){super();this.props=A}createState(){return new j16}}class j16 extends R0{_spinner=new qA;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=d1.all(new p1($.foreground,1,"solid")),J=this._spinner.toBraille(),F=new d({textAlign:"center",text:new w("",void 0,[new w(J,new T({color:B.processing})),new w(" ",void 0),new w(this.widget.props.message,new T({color:$.foreground}))])}),Y=[new R1({child:new S0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[F]})})];if(this.widget.props.onAbort)Y.push(new X0({height:2,child:new x0({padding:V0.symmetric(2,0),child:new d({text:new w("",new T({dim:!0}),[new w("Press ",new T({color:$.foreground})),new w("Esc",new T({color:$.info})),new w(" to cancel",new T({color:$.foreground}))])})})}));let Z=new x0({decoration:new R4($.background,D),child:new X0({width:60,height:7,child:new S0({mainAxisAlignment:"start",children:Y})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",child:new v4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:Z})});return Z}}class oG extends u0{props;constructor(A){super();this.props=A}createState(){return new R16}}class R16 extends R0{scrollController=new v6;scrollAreaKey=new Y8("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof l8}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let $=Q.size;if(typeof $.height==="number"&&$.height>0)return this.viewportHeight=$.height,$.height}return this.viewportHeight}build(A){let Q=O0.of(A),$=this.widget.props.message,B=(()=>{if(this.isWidgetMessage($))return{title:$.title,type:$.type};if($ instanceof Error&&$.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:$.message};if($ instanceof Error&&$.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:$.message};let U=dZ0($);return{title:U.title,type:U.type,description:U.description}})(),D=B.type==="error"?Q.app.toolError:Q.app.command,J=d1.all(new p1(Q.colors.border,1,"solid")),F=new x0({padding:V0.symmetric(1,0),child:new d({text:new w(B.title,new T({color:D,bold:!0}))})}),E=this.isWidgetMessage($)?$.widget:new d({text:new w(B.description,new T({color:Q.colors.foreground})),selectable:!0}),Y=new R1({child:new U5({child:new x0({padding:V0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new R1({child:new k6({controller:this.scrollController,autofocus:!0,child:E})}),new z8({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,X=this.scrollController.offset,G=this.getViewportHeight(),V=U+G;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(X,0)}}})]})})})}),Z=new x0({padding:V0.symmetric(1,0),child:new d({text:(()=>{if(this.widget.props.onRetry)return new w("",void 0,[new w("Press ",new T({color:Q.colors.foreground,dim:!0})),new w("R",new T({color:Q.app.keybind})),new w(" to retry, ",new T({color:Q.colors.foreground,dim:!0})),new w("Esc",new T({color:Q.app.keybind})),new w(" to cancel",new T({color:Q.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new w("",new T({color:Q.colors.foreground,dim:!0}));if(U==="help"){let X=new T({color:Q.app.keybind}),G=new T({color:Q.colors.foreground,dim:!0});return new w("",G,[new w("Press ",G),new w("Escape",X),new w(" to close • Use ",G),new w("↑↓",X),new w(" or ",G),new w("j/k",X),new w(" to scroll",G)])}return new w("Press any key to close",new T({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({debugLabel:"MessageDialog",child:new i4({fit:"expand",children:[new O1({onClick:()=>{},child:new X0}),new v4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new x0({decoration:{border:J,color:Q.colors.background},padding:V0.all(1),child:new S0({mainAxisAlignment:"center",children:[F,new X0({height:1}),Y,Z]})})})]})})}}Y5();Q4();class u16 extends u0{props;constructor(A){super();this.props=A}createState(){return new P16}}class P16 extends R0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=i0.file(this.widget.props.cwd),$=B1.relativePath(Q,XA(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return c3(A)}statusIcon(A){let Q=d2.default(),{colors:$,app:B}=Q;switch(A){case"loading":return{icon:"◌",color:$.warning};case"active":return{icon:"✓",color:B.toolSuccess};case"error":return{icon:"✗",color:B.toolError}}}build(A){let Q=O0.of(A),{app:$}=Q;if(this.plugins.length===0)return new d({text:new w("No plugins found.",new T({dim:!0}))});let B=[],D=this.plugins.length,J=this.plugins.filter((Y)=>Y.status==="active").length,F=this.plugins.reduce((Y,Z)=>Y+Z.registeredCommands.length,0),E=this.plugins.reduce((Y,Z)=>Y+Z.registeredTools.length,0);if(B.push(new w(`${J}/${D} ${U4(D,"plugin")} active`,new T({bold:!0}))),F>0||E>0)B.push(new w(` (${F} ${U4(F,"command")}, ${E} ${U4(E,"tool")})`,new T({dim:!0})));B.push(new w(`
7082
7082
 
7083
7083
  `));for(let Y of this.plugins){let{icon:Z,color:U}=this.statusIcon(Y.status),X=this.getRelativePath(Y.uri);if(B.push(new w(`${Z} `,new T({color:U}))),B.push(new w(X,new T({bold:!0}))),B.push(new w(` ${Y.status}`,new T({dim:!0}))),B.push(new w(`
7084
7084
  `)),Y.status==="active"&&Y.registeredEvents.length>0)B.push(new w(" Events: ",new T({dim:!0}))),B.push(new w(Y.registeredEvents.join(", "),new T({color:$.link}))),B.push(new w(`
@@ -7257,7 +7257,7 @@ ${t.content||""}`:t.content||"",d0=[],b0=t.baseDir.startsWith("file://")?mV0(t.b
7257
7257
  `)}function UA6(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let D=B.optsWithGlobals(),J=await Q(D),F=await J.settings.get("proxy"),E=r04({settings:{url:J.ampURL,proxy:F},secrets:{getToken:(Z,U)=>J.secrets.get(Z,U)}}),Y=await e4.userDisplayBalanceInfo({},{config:E});if(!Y.ok){if(Y.error.code==="auth-required")process.stderr.write(t0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(t0.red("Error: ")+Y.error.message+`
7258
7258
  `),process.exit(1)}process.stdout.write(await Re3(Y.result.displayText)+`
7259
7259
  `),process.exit(0)})}var o65=rt.join(cB,"logs","headless.log"),h91=rt.join(Rd,"device-id.json"),r65=`cli-tui-${b26(16).toString("hex")}`;Q_4();async function s65(){let A=await Promise.all(iM.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return u.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 g26(){s65().then((A)=>{if(A){let Q=G20(A.ideName);if(Q)hM(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => b4(fx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){I$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7260
- `)}function t65(A){process.emitWarning=(Q,$,B,D)=>{let J=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",E=!1;A.warn(J,{name:F,code:B})}}function r8(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")zJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")zJ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)zJ("internal.model",QA5(Q.model))}function T26(A){let Q=A.indexOf(":");if(Q===-1)throw new n1(`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 n1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function e65(A){if(A===void 0)return;let Q=A.trim();if(i50(Q))return Q;throw new n1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function AA5(A,Q){if(n5(A,Q))return;let $=sB(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new n1(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function QA5(A){if(!A.includes("="))return T26(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new n1(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J)throw new n1(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new n1(`Missing model value for mode "${J}". Expected "${J}=provider:model".`,1);T26(F),Q[J]=F}if(Object.keys(Q).length===0)throw new n1("No valid model overrides found in --model flag value.",1);return Q}function _K0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new CF0(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new CF0(`${Q} must be an integer <= ${$.max}`);return B}function $A5(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function BA5(A){try{return await h26(A,"utf-8")}catch{return A}}async function g91(A,Q,$){let B=$A5(A,Q);if(!B)return;let D=e6($)?$.features:[],J=e6($)?$.user.email:void 0;if(!et(D,k$.HARNESS_SYSTEM_PROMPT)&&!(J&&m7(J)))throw new n1("You are not allowed to do this.",1);zJ("systemPrompt",await BA5(B))}function et(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function DA5(A){return A!=="pending"}function NW(A){if(!e6(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function JA5(A){let Q=NW(A);if(Q)return Q.id;if(gY(A))throw Error(A.error.message);throw Error("unreachable")}function FA5(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 EA5(A){let B=FA5(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 n1(`Couldn't connect to the Amp server at ${A}.`,1,B)}function st(A,Q){let $=ro0(Error(A.error.message));if($.message===m9.networkOffline||$.message===m9.networkTimeout)return EA5(Q);if($.message!==m9.internalBug)return new n1($.message,1,$.suggestion);return new n1(A.error.message.replace(/^Error: /,""),1)}async function YA5(){if(process.versions.bun)return!1;try{return await jG()==="npm"}catch(A){return u.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var v26=[{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??dY,description:`Custom settings file path (overrides the default location ${dY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ta})`},{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:N9(),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:pM.SMART.key,description:`Set the agent mode (${rB({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(rB().map((A)=>A.mode))),hiddenChoices:["frontier"]},{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:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",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:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",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}],k26=(A)=>("deprecated"in A)&&A.deprecated===!0,ZA5=(A)=>("hidden"in A)&&A.hidden===!0,UA5=(A)=>("default"in A),XA5=(A)=>("default"in A)?A.default:void 0;function TK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=e65(Q.effort);if($!==void 0)AA5(Q.mode,$);return $}function GA5(A,Q){let $=Q.args[0],B=Q.commands.map((J)=>J.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let J=B.filter((E)=>$.includes(E)||E.includes($)),F="Run amp --help for a list of available commands.";if(J.length>0)F=`Did you mean: ${J.join(", ")}? Or run amp --help for all commands.`;throw new n1(m9.unknownCommand($),1,F)}}async function SK0(A){return{...A,getThreadEnvironment:Cz,getEnvironmentData:(Q,$)=>mK(Q,$),skillService:A.skillService,fileChangeTrackerStorage:new TL,generateThreadTitle:kE4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>oF(A.configService),pluginService:A.pluginService}}function m26(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Cz,getEnvironmentData:(Q,$)=>mK(Q,$)}}var vK0=i0.file(a65.homedir()),m91=process.env.XDG_CONFIG_HOME?i0.file(process.env.XDG_CONFIG_HOME):B1.joinPath(vK0,".config");async function i2(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;w04("0.0.1779668338-g19be90");let J=D20({storage:A.settings,secretStorage:A.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:vK0,userConfigDir:m91}),F=A.secrets.get("apiKey",A.ampURL),E=oF(J),Y=null,Z=()=>{return},U=new Promise((Q0)=>{Z=Q0}),X=F.then(async(Q0)=>{if(!Q0&&!B)await U;return Y??=E.subscribe(()=>{}),k1(E.pipe(l3(DA5)))});X.catch(()=>{return}),Nt4(J);let G=await J.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let V=!1;{let Q0=await F;if(V=Boolean(Q0),u.info("API key lookup before login",{found:Boolean(Q0),ampURL:A.ampURL,deferAuth:B}),!Q0)if(B)u.info("No API key found, continuing startup with deferred auth");else{A3.write(`No API key found. Starting login flow...
7260
+ `)}function t65(A){process.emitWarning=(Q,$,B,D)=>{let J=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",E=!1;A.warn(J,{name:F,code:B})}}function r8(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")zJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")zJ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)zJ("internal.model",QA5(Q.model))}function T26(A){let Q=A.indexOf(":");if(Q===-1)throw new n1(`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 n1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function e65(A){if(A===void 0)return;let Q=A.trim();if(i50(Q))return Q;throw new n1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function AA5(A,Q){if(n5(A,Q))return;let $=sB(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new n1(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function QA5(A){if(!A.includes("="))return T26(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new n1(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J)throw new n1(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new n1(`Missing model value for mode "${J}". Expected "${J}=provider:model".`,1);T26(F),Q[J]=F}if(Object.keys(Q).length===0)throw new n1("No valid model overrides found in --model flag value.",1);return Q}function _K0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new CF0(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new CF0(`${Q} must be an integer <= ${$.max}`);return B}function $A5(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function BA5(A){try{return await h26(A,"utf-8")}catch{return A}}async function g91(A,Q,$){let B=$A5(A,Q);if(!B)return;let D=e6($)?$.features:[],J=e6($)?$.user.email:void 0;if(!et(D,k$.HARNESS_SYSTEM_PROMPT)&&!(J&&m7(J)))throw new n1("You are not allowed to do this.",1);zJ("systemPrompt",await BA5(B))}function et(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function DA5(A){return A!=="pending"}function NW(A){if(!e6(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function JA5(A){let Q=NW(A);if(Q)return Q.id;if(gY(A))throw Error(A.error.message);throw Error("unreachable")}function FA5(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 EA5(A){let B=FA5(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 n1(`Couldn't connect to the Amp server at ${A}.`,1,B)}function st(A,Q){let $=ro0(Error(A.error.message));if($.message===m9.networkOffline||$.message===m9.networkTimeout)return EA5(Q);if($.message!==m9.internalBug)return new n1($.message,1,$.suggestion);return new n1(A.error.message.replace(/^Error: /,""),1)}async function YA5(){if(process.versions.bun)return!1;try{return await jG()==="npm"}catch(A){return u.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var v26=[{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??dY,description:`Custom settings file path (overrides the default location ${dY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ta})`},{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:N9(),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:pM.SMART.key,description:`Set the agent mode (${rB({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(rB().map((A)=>A.mode))),hiddenChoices:["frontier"]},{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:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",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:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",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}],k26=(A)=>("deprecated"in A)&&A.deprecated===!0,ZA5=(A)=>("hidden"in A)&&A.hidden===!0,UA5=(A)=>("default"in A),XA5=(A)=>("default"in A)?A.default:void 0;function TK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=e65(Q.effort);if($!==void 0)AA5(Q.mode,$);return $}function GA5(A,Q){let $=Q.args[0],B=Q.commands.map((J)=>J.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let J=B.filter((E)=>$.includes(E)||E.includes($)),F="Run amp --help for a list of available commands.";if(J.length>0)F=`Did you mean: ${J.join(", ")}? Or run amp --help for all commands.`;throw new n1(m9.unknownCommand($),1,F)}}async function SK0(A){return{...A,getThreadEnvironment:Cz,getEnvironmentData:(Q,$)=>mK(Q,$),skillService:A.skillService,fileChangeTrackerStorage:new TL,generateThreadTitle:kE4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>oF(A.configService),pluginService:A.pluginService}}function m26(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Cz,getEnvironmentData:(Q,$)=>mK(Q,$)}}var vK0=i0.file(a65.homedir()),m91=process.env.XDG_CONFIG_HOME?i0.file(process.env.XDG_CONFIG_HOME):B1.joinPath(vK0,".config");async function i2(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;w04("0.0.1779686836-g4ef406");let J=D20({storage:A.settings,secretStorage:A.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:vK0,userConfigDir:m91}),F=A.secrets.get("apiKey",A.ampURL),E=oF(J),Y=null,Z=()=>{return},U=new Promise((Q0)=>{Z=Q0}),X=F.then(async(Q0)=>{if(!Q0&&!B)await U;return Y??=E.subscribe(()=>{}),k1(E.pipe(l3(DA5)))});X.catch(()=>{return}),Nt4(J);let G=await J.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let V=!1;{let Q0=await F;if(V=Boolean(Q0),u.info("API key lookup before login",{found:Boolean(Q0),ampURL:A.ampURL,deferAuth:B}),!Q0)if(B)u.info("No API key found, continuing startup with deferred auth");else{A3.write(`No API key found. Starting login flow...
7261
7261
  `);let M0=await VA5(A),n=await A.secrets.get("apiKey",A.ampURL);if(u.info("Login flow completed",{success:M0,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!M0)await Nz(),process.exit(1);V=!0,Z()}}{let Q0=await J.getLatest(),M0=Q0.settings.url,n=Q0.secrets.isSet?.[M0];u.info("Config secrets state after login",{configURL:M0,apiKeySet:n?.apiKey??!1})}let K=B?"pending":await X;if(!B)u.info("Server status resolved",{status:"ready",isAuthenticated:e6(K),isError:gY(K),errorMessage:gY(K)?K.error.message:void 0});let z=X.then((Q0)=>JA5(Q0));z.catch(()=>{return});let W=!Q.takeMeBack&&e6(K)&&et(K.features,k$.THREAD_ACTORS_TUI),I=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")u.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let H=I?"off":W?"all":process.env.PLUGINS??"permissions",{toolService:q,dispose:N}=BR4({configService:J}),C=new Map,O=()=>C.clear(),L=new qx0(J,A.settings.getWorkspaceRootPath()),j=YJ4({configService:J}),k=l74({configService:J,trustStore:L,skillMCPServers:j.skillMCPServers,uploadImageAttachments:W,createOAuthProvider:async(Q0,M0,n)=>{let a=`${Q0}:${M0}`,t=C.get(a);if(t)return u.debug("Reusing existing OAuth provider for server",{serverName:Q0,serverUrl:M0}),t;u.debug("Creating OAuth provider for server",{serverName:Q0,serverUrl:M0});let e=(async()=>{let F0=new tM(A.secrets),J0=await F0.getClientInfo(Q0,M0),C0=n?.scopes??J0?.scopes,w0=Cf4();u.info("OAuth headless mode check",{useHeadless:w0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:A3.isTTY});let _0;if(w0)_0=A.executeMode?Nf4():qf4(Q0);let U0=new Pk0({storage:F0,serverName:Q0,serverUrl:M0,clientId:n?.clientId??J0?.clientId,clientSecret:n?.clientSecret??J0?.clientSecret,authUrl:n?.authUrl??J0?.authUrl,tokenUrl:n?.tokenUrl??J0?.tokenUrl,scopes:C0,headlessAuthHandler:_0});return u.debug("OAuth provider created",{serverName:Q0,serverUrl:M0,hasManualClientId:!!(n?.clientId??J0?.clientId),willUseDCR:!(n?.clientId??J0?.clientId),scopes:C0,headlessMode:w0,executeMode:A.executeMode}),U0})();return C.set(a,e),e}}),_=mn0({configService:J,spawn:gJ0}),S=Q.headless?is4():void 0,h=S??new tX0({configService:J}),b=h instanceof tX0?h:void 0;if(b)b.pluginExecutorKind="local";let v=new a1(null),y=null,c=W&&!I?[...os4(G.settings)?[{name:"permissions",entryPoint:j31}]:[],{name:"thread-visibility",entryPoint:ts4(J,()=>X.then(NW),()=>y,(Q0)=>{y=Q0}),alwaysLoad:!0}]:[],p=Sx0({configService:J,platform:h,loadGlobalPlugins:Kt0(J),pluginFilter:H,activeThread$:v,internalPlugins:c}),g=bQ4(p),i=[k,_,g],o;if(D)o=new Map;else if(A.executeMode){let Q0=await iL4({toolService:q,providers:i,initialTimeout:15000});o=Q0.registrations;for(let[M0,n]of Q0.initErrors)u.warn(`${M0} provider initialization slow or failed:`,n)}else o=dn0({toolService:q,providers:i});if(Q.jetbrains)hM("JetBrains");else if(Q.ide&&if4())hM("VS Code");else if(Q.ide&&nf4())hM("Neovim");else if(Q.ide&&(!W||A.executeMode||Q.takeMeBack))g26();if(A.executeMode)M04(!0);let A0,W0=o5.status.pipe(N1((Q0)=>Boolean(Q0.connected&&Q0.authenticated&&Q0.ideName&&O14(Q0.ideName))),T4()).subscribe((Q0)=>{if(Q0){if(!A0)A0=q.registerTool(lL4)}else A0?.dispose(),A0=void 0}),Y0;if(!A.executeMode){let Q0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];Y0=new AY0(process.cwd(),{alwaysIncludePaths:Q0},!0)}else Y0=new class extends AY0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let I0=new yg0(gl(J,{usesThreadActors:!1}),{maxThreads:200});u.info("Starting Amp background services");let $0=new v31,j0={configService:J,toolService:q,mcpService:k,skillService:j,toolboxService:_,trustStore:L,threadService:I0,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:Y0,terminal:$0,pluginService:p,pluginPlatform:b,headlessPluginPlatform:S,activeThread$:v,serverStatus:K,serverStatusPromise:X,viewerUserIDPromise:z,hasAPIKeyAtStartup:V,consumeDraftNewThreadVisibility:()=>{let Q0=y;return y=null,Q0}};return{...j0,async asyncDispose(){if(j0.mcpService.hasAuthenticatingClients())u.info("Waiting for OAuth authentication to complete before exit..."),await j0.mcpService.waitForAuthentication();for(let Q0 of o.values())Q0.dispose();await j0.mcpService.dispose(),O(),await j0.threadService.asyncDispose(),j0.configService.unsubscribe(),Y?.unsubscribe(),N(),j0.fuzzyServer.dispose(),j0.settingsStorage[Symbol.dispose](),W0.unsubscribe(),A0?.dispose(),await j0.pluginService.dispose()}}}async function VA5(A){if(!A.executeMode){if(!await lY0("Would you like to log in to Amp? [(y)es, (n)o]: "))return A3.write(`Login cancelled. Run the command again to retry.
7262
7262
  `),!1}return await d26(A)}async function d26(A){let Q=b26(32).toString("hex"),$=await xf(A.ampURL,Q),B=new AbortController;try{await bY($,B.signal)}catch(J){u.error("Error opening browser",{error:J})}let D=await xf(A.ampURL,Q,!1);A3.write(`If your browser does not open automatically, visit:
7263
7263
 
@@ -7265,7 +7265,7 @@ ${t0.blue.bold(D)}
7265
7265
 
7266
7266
  `);try{return await Yb4(A.ampURL,Q,A.secrets,B),A3.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(J){return u.error("Login failed",{error:J}),I$.write(`
7267
7267
  Login failed: ${J instanceof Error?J.message:String(J)}
7268
- `),!1}}async function KA5(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new n1("No Amp API key found. Run `amp login` first.",1);let D=l65("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((J,F)=>{D.on("error",F),D.on("close",(E)=>J(E??1))})}function zA5(A){let Q=new oq().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)$j(),process.exit(0);let I=W.originalError??W;M_4(I)}),th4(Q,{version:"0.0.1779668338-g19be90",buildTimestamp:"2026-05-25T00:23:23.173Z",buildType:"release"}),Q.addHelpText("after",pf4()),Q.configureHelp({formatHelp:cf4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await OA5(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(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await LA5(q,await u31(H,q.settings))}),N_4(Q,m3);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(...W)=>{let I=W.find((C)=>typeof C==="object"&&C!==null&&typeof C.optsWithGlobals==="function")??B,H=W.filter((C)=>C!==I).flatMap((C)=>Array.isArray(C)?C:typeof C==="string"?[C]:[]),q=I.optsWithGlobals(),N=await m3(q);await KA5(N.ampURL,N.secrets,H),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(W,I,H)=>{let q=H.optsWithGlobals(),N=await m3(q);await Xf4(W??"get",N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await Gf4(q.ampURL,q.secrets),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(W)=>{await Ex4({raw:W.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(`
7268
+ `),!1}}async function KA5(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new n1("No Amp API key found. Run `amp login` first.",1);let D=l65("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((J,F)=>{D.on("error",F),D.on("close",(E)=>J(E??1))})}function zA5(A){let Q=new oq().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)$j(),process.exit(0);let I=W.originalError??W;M_4(I)}),th4(Q,{version:"0.0.1779686836-g4ef406",buildTimestamp:"2026-05-25T05:31:37.501Z",buildType:"release"}),Q.addHelpText("after",pf4()),Q.configureHelp({formatHelp:cf4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await OA5(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(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await LA5(q,await u31(H,q.settings))}),N_4(Q,m3);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(...W)=>{let I=W.find((C)=>typeof C==="object"&&C!==null&&typeof C.optsWithGlobals==="function")??B,H=W.filter((C)=>C!==I).flatMap((C)=>Array.isArray(C)?C:typeof C==="string"?[C]:[]),q=I.optsWithGlobals(),N=await m3(q);await KA5(N.ampURL,N.secrets,H),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(W,I,H)=>{let q=H.optsWithGlobals(),N=await m3(q);await Xf4(W??"get",N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await Gf4(q.ampURL,q.secrets),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(W)=>{await Ex4({raw:W.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(`
7269
7269
  `)).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(W,I,H)=>{if(W&&I.apply)throw new n1("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let q=I.apply??W;if(!q||q.trim().length===0)A3.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.
7270
7270
 
7271
7271
  `),H.outputHelp(),process.exit(0);let N=v8(q)??BB(q),C=H.optsWithGlobals(),O=await m3(C);r8(H,C);let L=await i2(O,C),j=!1;try{if(I.checkout&&I.skipCheckout)throw new n1("Choose either --checkout or --skip-checkout, not both.",1);if(gY(L.serverStatus))throw st(L.serverStatus,O.ampURL);let k=e6(L.serverStatus)?L.serverStatus.features:void 0;if(!et(k,k$.V2))throw new n1("live-sync is not enabled for your user",1);await sx4({ampURL:O.ampURL,threadId:N,configService:L.configService,threadService:L.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof I.apply==="string",checkoutMode:I.checkout?"always":I.skipCheckout?"never":"prompt",promptForYesNo:lY0}),j=!0}finally{if(await L.asyncDispose(),j)process.exit(0)}});let D=async(W,I,H)=>{D20({storage:I.settings,secretStorage:I.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:I.ampURL,homeDir:vK0,userConfigDir:m91});let q={...I,executeMode:!1};await kK0(q,{...W,openThreadSwitcher:!0},H,A)},J=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",(W)=>_K0(W,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(W)=>_K0(W,"--offset",{min:0})).action(async(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await x26(H,q,I)});J.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,I)=>{let H=I.optsWithGlobals(),q=await m3(H);await bA5(H,q,I)}),J.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(W,I,H)=>{let q=H.optsWithGlobals(),N=await m3(q),C=Array.isArray(W)?W:[];if(I.pick)I$.write(`${t0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7298,8 +7298,8 @@ ${O}
7298
7298
  `))}),I.args.length>0)GA5(q,I);await kK0(q,H,I,A)}),Cy4(Q),Q}async function tt(A,Q){await GQ(($)=>mf($,A,Q))}async function S26(A,Q,$){let B=Date.now(),[D,J]=await Promise.all([e4.getThreadLinkInfo({thread:A},{config:Q}),$]);if(u.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-B}ms`),D.ok){let F=D.result.creatorUserID;if(F&&F!==J&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new n1(`Cannot resume thread created by another user.
7299
7299
 
7300
7300
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function p26(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await BG0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await BG0()).trimEnd(),stdinInput:null}}function c26(A,Q,$){if(A.streamJson&&!Q)throw new n1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new n1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new n1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new n1("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 n1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new n1("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 n1("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 n1("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"
7301
- Or pipe via stdin: echo "your message" | amp --execute`)}function WA5(){s64([Q20.parse({tool:"*",action:"allow"})]),M64({bypass:!0})}function IA5(A){if(A.threadId&&!R9(A.threadId))delete A.threadId}async function kK0(A,Q,$,B){if(Q.headless)return HA5(A,Q,$);let D=await i2(A,Q),J=await D.serverStatusPromise,F=e6(J)&&et(J.features,k$.THREAD_ACTORS_TUI),E=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await D.asyncDispose(),new n1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await D.asyncDispose(),new n1("--show-welcome is only available with the new Amp CLI feature flag",1);if(E){let Y=!A.executeMode&&await YA5();return WA5(),IA5(Q),qA5(A,Q,$,D,{showNpmMigrationWelcome:Y})}else{if(Q.threadId&&R9(Q.threadId)){let Y=await e4.getThreadLinkInfo({thread:Q.threadId},{config:D.configService}).catch(()=>null);if(Y?.ok&&Y.result.usesThreadActors)throw await D.asyncDispose(),new n1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return NA5(A,Q,$,B,{dependencies:D})}}async function HA5(A,Q,$){let B=(I,H)=>{let q=Number(process.hrtime.bigint()-H)/1e6,N=go0();u.info("Startup phase",{phase:I,phaseMs:Math.round(q),sinceMainMs:N===null?void 0:Math.round(N)})};r8($,Q);let D=process.hrtime.bigint(),J=await i2(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=J;if(gY(F))throw st(F,A.ampURL);let E=e6(F)?F:null,Y=E?.user.email;await g91($,Q,F);let Z=NW(F),U=ly(Q,Z);if(U instanceof Error)j3(U.message);if(E&&!dM(Q.mode,Y))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!m7(Y)))throw new n1("Headless executor mode is only available for Amp employees",1);AE0();let G=await J.secretStorage.get("apiKey",A.ampURL);if(!G)throw new n1("API key required for headless mode. Please run `amp login` first.",1);let V=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(V&&!R9(V))throw new n1(`Invalid thread ID: ${V}`,1);let K=V?void 0:await yA5({dependencies:J,apiKey:G,visibility:U??void 0}),z=V??K?.threadId;if(!z)throw new n1("Failed to resolve headless thread ID",1);let W=await Of4(z);if(W.status==="already-running")await J.asyncDispose(),await Nz(),process.exit(0);try{await Wf4({ampURL:A.ampURL,apiKey:G,workspaceRoot:process.cwd(),threadId:z,ownerUserId:K?.ownerUserId,threadVersion:K?.threadVersion,agentMode:K?.agentMode,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized,J.pluginService.initialized]).then(()=>{return}),configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,pluginService:J.pluginService,pluginPlatform:J.headlessPluginPlatform})}finally{await W.release(),await J.asyncDispose()}await Nz(),process.exit(0)}async function qA5(A,Q,$,B,D){let{userInput:J,stdinInput:F}=await p26(Q),E=!!Q.streamJson||!!Q.streamJsonThinking;c26({...Q,streamJson:E},A.executeMode,J),r8($,Q),E_4(),AE0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),U=Q.observe?v8(Q.observe)??BB(Q.observe):void 0,X=await B.serverStatusPromise;if(gY(X))throw st(X,A.ampURL);let G=NW(X),V=ly(Q,G);if(V instanceof Error)j3(V.message);let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let q=await va(A.settings,process.cwd(),G,V);if(q instanceof Error)j3(q.message);return q})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new n1("API key required. Please run `amp login` first.",1);let I=e6(X)&&m7(X.user.email);if(A.executeMode){if(Z.length>1)throw new n1("Execute mode can only resume one thread.",1);Ce0(B.mcpService,A.settings);try{let H=TK0($,Q),q=await bz(),N=Y?H:nY0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),C=Y?void 0:aY0(await bf(B.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),O=Y?void 0:await z(),L=await tS4({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:J,stdinInput:F,stats:!!Q.stats,streamJson:E,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:Y,initialThreadMeta:O,initialSettings:C});if(await tt(L,"execute"),Q.archive)await B.threadService.archive(L,!0)}finally{await B.asyncDispose()}await Nz(),process.exit(0)}else{let H=TK0($,Q),q=D.showNpmMigrationWelcome?"npm-migration":"intro",N=KY0("0.0.1779668338-g19be90",B.settingsStorage,{startDelayMs:3000}),C=new iY0(B.mcpService,A.settings.getWorkspaceRootPath()),O=gl(B.configService),L=new Vt(B.fuzzyServer),j=process.cwd();await bs4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??aJ(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>Nf({workspaceRoot:j},k),completionBuilder:L,updateService:N,workspaceRoot:j,listThreads:()=>O.listThreads(),getThreadFromServer:(k)=>O.getThread(k),toolboxes:B.toolboxService.toolboxes,isInternalUser:I,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:C,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return C.dispose(),N.dispose(),B.asyncDispose()}},{initialThreadIDs:U?[U]:Z,initialUserInput:J||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?g26:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!U,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function NA5(A,Q,$,B,D){let J=process.hrtime.bigint(),F=($0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,M0=go0();u.info("Startup phase",{phase:$0,phaseMs:Math.round(Q0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:E,stdinInput:Y}=await p26(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;c26({...Q,streamJson:Z},A.executeMode,E),r8($,Q);let U=process.hrtime.bigint(),X=D?.dependencies??await i2(A,Q),G=X.hasAPIKeyAtStartup,V=X.serverStatus==="pending";if(u.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!D)F("runMainThread:createThreadDependencies",U);let{serverStatus:K}=X;if(!V&&gY(K))throw st(K,A.ampURL);let z=e6(K)?K:null,W=z?.user.email,I=!!(W&&m7(W));if(I)AE0();if(!V)await g91($,Q,K);let H=NW(K),q=H?.features??[],N=H?.team??null,C=ly(Q,H);if(C instanceof Error)j3(C.message);if(z&&!dM(Q.mode,W))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&R9(Q.threadId)?Q.threadId:void 0;U=process.hrtime.bigint();let L=await SK0(X);F("runMainThread:createWorkerDeps",U);let j=A.executeMode?void 0:async($0)=>tt($0,"interactive"),k={threadService:X.threadService,workerDeps:L,createThread:async($0)=>{let j0=V?await X.serverStatusPromise:K,Q0=await va(A.settings,process.cwd(),NW(j0),C);if(Q0 instanceof Error)j3(Q0.message);return G81(L,{threadMeta:Q0,agentMode:$0??Q.mode,onFirstAssistantMessage:j})},validateThreadOwnership:async($0,j0)=>{if(j0?.nonBlockingOwnershipCheck){S26($0,X.configService,X.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof n1){if(j0.onOwnershipError){j0.onOwnershipError(Q0,$0);return}wz(Q0,$0);return}u.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await S26($0,X.configService,X.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof n1)throw Q0;u.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:C,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:j,handleError:wz},_=async()=>{try{return FA6(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof n1)throw $0;throw await wz($0,Q.threadId),Error("handleError should have called process.exit()")}},S=(async()=>{if(V){u.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await X.configService.getLatest(),j0=dm($0),Q0=await e4.getUserFreeTierStatus({},{config:X.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return u.info("User free tier status:",Q0),Q0.result;return}catch($0){u.error("Failed to fetch free tier status:",$0);return}})(),b=!A.executeMode?new x31:null,v,y=null;if(b)v=b,y=(async()=>{let $0=V?await X.serverStatusPromise:X.serverStatus;if(gY($0))throw st($0,A.ampURL);await g91($,Q,$0);let j0=process.hrtime.bigint(),Q0=await _();if(F("runMainThread:createThreadPool",j0),b.attach(Q0),E){let M0=await k1(Q0.threadHandles$);if(!M0)throw new n1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:E}]})}})(),y.catch(async($0)=>{let j0=$0 instanceof Error?$0:Error(String($0));b.setInitError(j0),await wz($0,Q.threadId)});else U=process.hrtime.bigint(),v=await _(),F("runMainThread:createThreadPool",U);let c=Q.notifications!==void 0?Q.notifications:!A.executeMode;U=process.hrtime.bigint();let p=await X.configService.getLatest();if(F("runMainThread:configService.getLatest",U),U=process.hrtime.bigint(),it4({configService:X.configService,threadService:X.threadService,threadPool:v,config:p,useNotifications:c}),F("runMainThread:createLegacyTuiNotificationService",U),A.executeMode){Ce0(X.mcpService,A.settings);let $0=TK0($,Q),j0=await bz(),Q0=O?$0:nY0({agentMode:Q.mode,explicitEffort:$0,sessionState:j0}),M0={userInput:E,stdinInput:Y,dependencies:X,streamJson:Z,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:I,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await c_4({threadPool:v,...M0});if(await tt(n,"execute"),Q.archive)await X.threadService.archive(n,!0);await X.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await K20();let $0=await cY({jetbrainsOnly:Q.jetbrains});if($0.length===0){if(Q.jetbrains)g=!await X.configService.get("jetbrains.skipInstall")}else if($0.length===1){let j0=$0[0];if(j0)o5.selectConfig(j0)}else i=!0}U=process.hrtime.bigint();let o=KY0("0.0.1779668338-g19be90",X.settingsStorage,{startDelayMs:3000});F("runMainThread:createUpdateService",U),U=process.hrtime.bigint();let A0=new iY0(X.mcpService,A.settings.getWorkspaceRootPath());if(F("runMainThread:createMcpTrustHandler",U),E&&A.executeMode){let $0=await k1(v.threadHandles$);if(!$0)throw new n1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:E}]})}U=process.hrtime.bigint();let W0=await bz();F("runMainThread:loadSessionState",U),u.info("Loaded session state:",W0);let Y0=TK0($,Q),I0={...W0,launchCount:W0.launchCount+1,lastReasoningEffortByMode:Y0?{...W0.lastReasoningEffortByMode,[Q.mode]:Y0}:W0.lastReasoningEffortByMode};GQ(($0)=>({...$0,launchCount:$0.launchCount+1}));try{if(U=process.hrtime.bigint(),await qe4({history:new Ho,fuzzyServer:X.fuzzyServer,settingsStorage:X.settingsStorage,threadService:X.threadService,skillService:X.skillService,configService:X.configService,secretStorage:X.secretStorage,internalAPIClient:e4,threadPool:v,createSystemPromptDeps:async()=>m26(X),ideClient:o5,mcpService:X.mcpService,toolboxService:X.toolboxService,mcpTrustHandler:A0,updateService:o,pluginPlatform:X.pluginPlatform,pluginService:X.pluginService},{initialServerStatus:X.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:X.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:r65,logFile:{path:B},sessionState:I0,freeTierStatusPromise:S,workspace:N??null,features:q,isInternalUser:I,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-25T00:23:23.173Z"},($0)=>new c31({...$0,threadPool:$0.threadPool},(j0)=>new U81({...j0,threadState:j0.threadState}))),F("runMainThread:mountApp-returned",U),y)await y}finally{await v.dispose().catch(($0)=>{u.error("Failed to dispose thread pool during shutdown",$0)})}await X.asyncDispose(),F("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function m3(A){if(u.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)I$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7302
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;u.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await r74({get:async(E)=>{if(E!==op)return;try{let Y=await h26(h91,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(E,Y)=>{if(E!==op)return;await i65(rt.dirname(h91),{recursive:!0}),await n65(h91,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:v90()});L04(B);let D=await Wt4({...A,workspaceTrust:{current:!0,changes:pm},getHook:process.env.AMP_URL?(E,Y)=>{if(E==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let E=await Hb4(A.mcpConfig);D=qb4(D,E)}let J=rt.dirname(D.getSettingsFilePath());ER4(Rd,J),D=ts1(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=l7;if(u.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!iI(F))u.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:Ut4(await u31(A,D))}}function CA5(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let J=B.slice(2).replace(/-([a-z])/g,(E,Y)=>Y.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[J]=F,$++}}return Q}function wA5(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=rt.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?o65:Ta));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function MA5(){A_4();let A=CA5(process.argv),Q=wA5(process.argv,A),$=Y_4(Q);lF0("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),J=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!J)t0.level=0;if(t65(u),u.info("Starting Amp CLI.",{version:"0.0.1779668338-g19be90",buildTimestamp:"2026-05-25T00:23:23.173Z"}),process.platform==="win32"&&Lj())zy4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new n1(m9.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await zA5($).parseAsync(process.argv)}JR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await MA5().catch(wz)});async function LA5(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"),A3.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7301
+ Or pipe via stdin: echo "your message" | amp --execute`)}function WA5(){s64([Q20.parse({tool:"*",action:"allow"})]),M64({bypass:!0})}function IA5(A){if(A.threadId&&!R9(A.threadId))delete A.threadId}async function kK0(A,Q,$,B){if(Q.headless)return HA5(A,Q,$);let D=await i2(A,Q),J=await D.serverStatusPromise,F=e6(J)&&et(J.features,k$.THREAD_ACTORS_TUI),E=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await D.asyncDispose(),new n1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await D.asyncDispose(),new n1("--show-welcome is only available with the new Amp CLI feature flag",1);if(E){let Y=!A.executeMode&&await YA5();return WA5(),IA5(Q),qA5(A,Q,$,D,{showNpmMigrationWelcome:Y})}else{if(Q.threadId&&R9(Q.threadId)){let Y=await e4.getThreadLinkInfo({thread:Q.threadId},{config:D.configService}).catch(()=>null);if(Y?.ok&&Y.result.usesThreadActors)throw await D.asyncDispose(),new n1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return NA5(A,Q,$,B,{dependencies:D})}}async function HA5(A,Q,$){let B=(I,H)=>{let q=Number(process.hrtime.bigint()-H)/1e6,N=go0();u.info("Startup phase",{phase:I,phaseMs:Math.round(q),sinceMainMs:N===null?void 0:Math.round(N)})};r8($,Q);let D=process.hrtime.bigint(),J=await i2(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=J;if(gY(F))throw st(F,A.ampURL);let E=e6(F)?F:null,Y=E?.user.email;await g91($,Q,F);let Z=NW(F),U=ly(Q,Z);if(U instanceof Error)j3(U.message);if(E&&!dM(Q.mode,Y))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!m7(Y)))throw new n1("Headless executor mode is only available for Amp employees",1);AE0();let G=await J.secretStorage.get("apiKey",A.ampURL);if(!G)throw new n1("API key required for headless mode. Please run `amp login` first.",1);let V=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(V&&!R9(V))throw new n1(`Invalid thread ID: ${V}`,1);let K=V?void 0:await yA5({dependencies:J,apiKey:G,visibility:U??void 0}),z=V??K?.threadId;if(!z)throw new n1("Failed to resolve headless thread ID",1);let W=await Of4(z);if(W.status==="already-running")await J.asyncDispose(),await Nz(),process.exit(0);try{await Wf4({ampURL:A.ampURL,apiKey:G,workspaceRoot:process.cwd(),threadId:z,ownerUserId:K?.ownerUserId,threadVersion:K?.threadVersion,agentMode:K?.agentMode,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized,J.pluginService.initialized]).then(()=>{return}),configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,pluginService:J.pluginService,pluginPlatform:J.headlessPluginPlatform})}finally{await W.release(),await J.asyncDispose()}await Nz(),process.exit(0)}async function qA5(A,Q,$,B,D){let{userInput:J,stdinInput:F}=await p26(Q),E=!!Q.streamJson||!!Q.streamJsonThinking;c26({...Q,streamJson:E},A.executeMode,J),r8($,Q),E_4(),AE0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),U=Q.observe?v8(Q.observe)??BB(Q.observe):void 0,X=await B.serverStatusPromise;if(gY(X))throw st(X,A.ampURL);let G=NW(X),V=ly(Q,G);if(V instanceof Error)j3(V.message);let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let q=await va(A.settings,process.cwd(),G,V);if(q instanceof Error)j3(q.message);return q})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new n1("API key required. Please run `amp login` first.",1);let I=e6(X)&&m7(X.user.email);if(A.executeMode){if(Z.length>1)throw new n1("Execute mode can only resume one thread.",1);Ce0(B.mcpService,A.settings);try{let H=TK0($,Q),q=await bz(),N=Y?H:nY0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),C=Y?void 0:aY0(await bf(B.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),O=Y?void 0:await z(),L=await tS4({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:J,stdinInput:F,stats:!!Q.stats,streamJson:E,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:Y,initialThreadMeta:O,initialSettings:C});if(await tt(L,"execute"),Q.archive)await B.threadService.archive(L,!0)}finally{await B.asyncDispose()}await Nz(),process.exit(0)}else{let H=TK0($,Q),q=D.showNpmMigrationWelcome?"npm-migration":"intro",N=KY0("0.0.1779686836-g4ef406",B.settingsStorage,{startDelayMs:3000}),C=new iY0(B.mcpService,A.settings.getWorkspaceRootPath()),O=gl(B.configService),L=new Vt(B.fuzzyServer),j=process.cwd();await bs4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??aJ(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>Nf({workspaceRoot:j},k),completionBuilder:L,updateService:N,workspaceRoot:j,listThreads:()=>O.listThreads(),getThreadFromServer:(k)=>O.getThread(k),toolboxes:B.toolboxService.toolboxes,isInternalUser:I,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:C,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return C.dispose(),N.dispose(),B.asyncDispose()}},{initialThreadIDs:U?[U]:Z,initialUserInput:J||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?g26:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!U,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function NA5(A,Q,$,B,D){let J=process.hrtime.bigint(),F=($0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,M0=go0();u.info("Startup phase",{phase:$0,phaseMs:Math.round(Q0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:E,stdinInput:Y}=await p26(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;c26({...Q,streamJson:Z},A.executeMode,E),r8($,Q);let U=process.hrtime.bigint(),X=D?.dependencies??await i2(A,Q),G=X.hasAPIKeyAtStartup,V=X.serverStatus==="pending";if(u.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!D)F("runMainThread:createThreadDependencies",U);let{serverStatus:K}=X;if(!V&&gY(K))throw st(K,A.ampURL);let z=e6(K)?K:null,W=z?.user.email,I=!!(W&&m7(W));if(I)AE0();if(!V)await g91($,Q,K);let H=NW(K),q=H?.features??[],N=H?.team??null,C=ly(Q,H);if(C instanceof Error)j3(C.message);if(z&&!dM(Q.mode,W))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&R9(Q.threadId)?Q.threadId:void 0;U=process.hrtime.bigint();let L=await SK0(X);F("runMainThread:createWorkerDeps",U);let j=A.executeMode?void 0:async($0)=>tt($0,"interactive"),k={threadService:X.threadService,workerDeps:L,createThread:async($0)=>{let j0=V?await X.serverStatusPromise:K,Q0=await va(A.settings,process.cwd(),NW(j0),C);if(Q0 instanceof Error)j3(Q0.message);return G81(L,{threadMeta:Q0,agentMode:$0??Q.mode,onFirstAssistantMessage:j})},validateThreadOwnership:async($0,j0)=>{if(j0?.nonBlockingOwnershipCheck){S26($0,X.configService,X.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof n1){if(j0.onOwnershipError){j0.onOwnershipError(Q0,$0);return}wz(Q0,$0);return}u.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await S26($0,X.configService,X.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof n1)throw Q0;u.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:C,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:j,handleError:wz},_=async()=>{try{return FA6(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof n1)throw $0;throw await wz($0,Q.threadId),Error("handleError should have called process.exit()")}},S=(async()=>{if(V){u.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await X.configService.getLatest(),j0=dm($0),Q0=await e4.getUserFreeTierStatus({},{config:X.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return u.info("User free tier status:",Q0),Q0.result;return}catch($0){u.error("Failed to fetch free tier status:",$0);return}})(),b=!A.executeMode?new x31:null,v,y=null;if(b)v=b,y=(async()=>{let $0=V?await X.serverStatusPromise:X.serverStatus;if(gY($0))throw st($0,A.ampURL);await g91($,Q,$0);let j0=process.hrtime.bigint(),Q0=await _();if(F("runMainThread:createThreadPool",j0),b.attach(Q0),E){let M0=await k1(Q0.threadHandles$);if(!M0)throw new n1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:E}]})}})(),y.catch(async($0)=>{let j0=$0 instanceof Error?$0:Error(String($0));b.setInitError(j0),await wz($0,Q.threadId)});else U=process.hrtime.bigint(),v=await _(),F("runMainThread:createThreadPool",U);let c=Q.notifications!==void 0?Q.notifications:!A.executeMode;U=process.hrtime.bigint();let p=await X.configService.getLatest();if(F("runMainThread:configService.getLatest",U),U=process.hrtime.bigint(),it4({configService:X.configService,threadService:X.threadService,threadPool:v,config:p,useNotifications:c}),F("runMainThread:createLegacyTuiNotificationService",U),A.executeMode){Ce0(X.mcpService,A.settings);let $0=TK0($,Q),j0=await bz(),Q0=O?$0:nY0({agentMode:Q.mode,explicitEffort:$0,sessionState:j0}),M0={userInput:E,stdinInput:Y,dependencies:X,streamJson:Z,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:I,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await c_4({threadPool:v,...M0});if(await tt(n,"execute"),Q.archive)await X.threadService.archive(n,!0);await X.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await K20();let $0=await cY({jetbrainsOnly:Q.jetbrains});if($0.length===0){if(Q.jetbrains)g=!await X.configService.get("jetbrains.skipInstall")}else if($0.length===1){let j0=$0[0];if(j0)o5.selectConfig(j0)}else i=!0}U=process.hrtime.bigint();let o=KY0("0.0.1779686836-g4ef406",X.settingsStorage,{startDelayMs:3000});F("runMainThread:createUpdateService",U),U=process.hrtime.bigint();let A0=new iY0(X.mcpService,A.settings.getWorkspaceRootPath());if(F("runMainThread:createMcpTrustHandler",U),E&&A.executeMode){let $0=await k1(v.threadHandles$);if(!$0)throw new n1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:E}]})}U=process.hrtime.bigint();let W0=await bz();F("runMainThread:loadSessionState",U),u.info("Loaded session state:",W0);let Y0=TK0($,Q),I0={...W0,launchCount:W0.launchCount+1,lastReasoningEffortByMode:Y0?{...W0.lastReasoningEffortByMode,[Q.mode]:Y0}:W0.lastReasoningEffortByMode};GQ(($0)=>({...$0,launchCount:$0.launchCount+1}));try{if(U=process.hrtime.bigint(),await qe4({history:new Ho,fuzzyServer:X.fuzzyServer,settingsStorage:X.settingsStorage,threadService:X.threadService,skillService:X.skillService,configService:X.configService,secretStorage:X.secretStorage,internalAPIClient:e4,threadPool:v,createSystemPromptDeps:async()=>m26(X),ideClient:o5,mcpService:X.mcpService,toolboxService:X.toolboxService,mcpTrustHandler:A0,updateService:o,pluginPlatform:X.pluginPlatform,pluginService:X.pluginService},{initialServerStatus:X.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:X.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:r65,logFile:{path:B},sessionState:I0,freeTierStatusPromise:S,workspace:N??null,features:q,isInternalUser:I,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-25T05:31:37.501Z"},($0)=>new c31({...$0,threadPool:$0.threadPool},(j0)=>new U81({...j0,threadState:j0.threadState}))),F("runMainThread:mountApp-returned",U),y)await y}finally{await v.dispose().catch(($0)=>{u.error("Failed to dispose thread pool during shutdown",$0)})}await X.asyncDispose(),F("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function m3(A){if(u.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)I$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7302
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;u.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await r74({get:async(E)=>{if(E!==op)return;try{let Y=await h26(h91,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(E,Y)=>{if(E!==op)return;await i65(rt.dirname(h91),{recursive:!0}),await n65(h91,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:v90()});L04(B);let D=await Wt4({...A,workspaceTrust:{current:!0,changes:pm},getHook:process.env.AMP_URL?(E,Y)=>{if(E==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let E=await Hb4(A.mcpConfig);D=qb4(D,E)}let J=rt.dirname(D.getSettingsFilePath());ER4(Rd,J),D=ts1(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=l7;if(u.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!iI(F))u.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:Ut4(await u31(A,D))}}function CA5(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let J=B.slice(2).replace(/-([a-z])/g,(E,Y)=>Y.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[J]=F,$++}}return Q}function wA5(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=rt.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?o65:Ta));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function MA5(){A_4();let A=CA5(process.argv),Q=wA5(process.argv,A),$=Y_4(Q);lF0("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),J=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!J)t0.level=0;if(t65(u),u.info("Starting Amp CLI.",{version:"0.0.1779686836-g4ef406",buildTimestamp:"2026-05-25T05:31:37.501Z"}),process.platform==="win32"&&Lj())zy4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new n1(m9.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await zA5($).parseAsync(process.argv)}JR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await MA5().catch(wz)});async function LA5(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"),A3.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7303
7303
  `);else if(!iI(A.ampURL))A3.write(`Logging in to ${new URL(A.ampURL).hostname}
7304
7304
  `);let B=process.env.AMP_API_KEY;if(B)A3.write(`API key found in environment variable, storing...
7305
7305
  `),await Q.set("apiKey",B,A.ampURL),A3.write(`API key successfully stored.