@sourcegraph/amp 0.0.1774286630-gfbf924 → 0.0.1774310664-gcb98ac

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 +14 -12
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -101,7 +101,7 @@ Expected format:
101
101
  `),K.newLines.join(`
102
102
  `))));Q.push({path:Y.movePath??Y.path,diffStat:X})}return Q}function Q40(J){let Z=0,Q=0,Y=0;return J.messages.forEach((X)=>{if(X.role!=="assistant")return;X.content.forEach((K)=>{let V=Qu1(K);if(!V)return;let{name:G,input:F}=V,z=null;if(G==="edit_file"){if("old_str"in F&&"new_str"in F){let{old_str:q,new_str:U}=F;z=oH(q,U)}}else if(G==="apply_patch"){let q=Yu1(F);z=OR0(q.map((U)=>U.diffStat))}else if((G==="write_file"||G==="create_file")&&"content"in F&&typeof F.content==="string")z=rH(F.content);if(z)Z+=z.added,Y+=z.deleted,Q+=z.changed})}),{added:Z,changed:Q,deleted:Y}}function Xu1(J){let Z=new Map;return J.messages.forEach((Q)=>{if(Q.role!=="assistant")return;Q.content.forEach((Y)=>{let X=Qu1(Y);if(!X)return;let{name:K,input:V}=X,G,F=null;if(K==="edit_file"){if("path"in V&&typeof V.path==="string"&&"old_str"in V&&"new_str"in V){G=V.path;let{old_str:z,new_str:q}=V;F=oH(z,q)}}else if(K==="apply_patch"){for(let z of Yu1(V)){let q=tf1(z.path,J.env?.initial?.trees);if(q){let U=Z.get(q)??{added:0,changed:0,deleted:0};U.added+=z.diffStat.added,U.changed+=z.diffStat.changed,U.deleted+=z.diffStat.deleted,Z.set(q,U)}}return}else if((K==="write_file"||K==="create_file")&&"path"in V&&typeof V.path==="string"&&"content"in V&&typeof V.content==="string")G=V.path,F=rH(V.content);if(G&&F){let z=tf1(G,J.env?.initial?.trees);if(z){let q=Z.get(z)??{added:0,changed:0,deleted:0};q.added+=F.added,q.changed+=F.changed,q.deleted+=F.deleted,Z.set(z,q)}}})}),Z}function tf1(J,Z){let Q=J.startsWith("/"),Y=/^[a-zA-Z]:[\\/]/.test(J);if(!Q&&!Y)return J;let X=J.replace(/\\/g,"/");if(Z&&Z.length>0)for(let G of Z){if(!G.uri)continue;let F=G.uri.match(/^file:\/\/(.+)$/);if(!F?.[1])continue;let z=decodeURIComponent(F[1]).replace(/\\/g,"/"),q=z.startsWith("/")&&/^\/[a-zA-Z]:/.test(z)?z.slice(1):z;if(X.startsWith(q)){let U=X.slice(q.length);return U.startsWith("/")?U.slice(1):U}}let K=X.match(/\/(?:Users|home)\/[^/]+\/[^/]+\/(.+)/);if(K?.[1])return K[1];let V=X.match(/^[a-zA-Z]:\/Users\/[^/]+\/[^/]+\/(.+)/);if(V?.[1])return V[1];return null}function Y40(){return T10((J,Z,Q)=>{if(Q===0){if(Z instanceof Array)throw Error("expected first event to be a full thread");return Z}if(!(Z instanceof Array))throw Error("expected all but first event to be a patch");return Wf1(J,Z)})}function UC(J,Z){let Q=J.relationships?.filter((K)=>K.role==="child")??[],Y=ub(J),X=[...Q,...Y];return Z?X.filter((K)=>K.type===Z):X}function X40(J,Z){return UC(J,Z)[0]}function JQ(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user")return Q}return}function fb(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user"&&Q.agentMode)return Q.agentMode}return}function ub(J){let Z=[],Q=new Set;if(!J.messages)return Z;return J.messages.forEach((Y,X)=>{if(Y.role!=="assistant")return;Y.content.forEach((K)=>{if(K.type!=="tool_use")return;if(K.name!==SU)return;if(!u8(K))return;let V=K.input;if(V.threadID&&b9(V.threadID)&&!Q.has(V.threadID))Q.add(V.threadID),Z.push({threadID:V.threadID,type:"mention",role:"parent",messageIndex:X,createdAt:Date.now()})})}),Z}var f4=Z0(()=>{w1();QJ();HR0();g0();P4();BE();v10()});var D4=Z0(()=>{wb();j10();VE()});import Rv6 from"os";import K40 from"path";var tH,wE,eH,WC,Gu1,W68,D68,Iv6,Pv6;var bb=Z0(()=>{tH=Rv6.homedir(),{env:wE}=process,eH=wE.XDG_DATA_HOME||(tH?K40.join(tH,".local","share"):void 0),WC=wE.XDG_CONFIG_HOME||(tH?K40.join(tH,".config"):void 0),Gu1=wE.XDG_STATE_HOME||(tH?K40.join(tH,".local","state"):void 0),W68=wE.XDG_CACHE_HOME||(tH?K40.join(tH,".cache"):void 0),D68=wE.XDG_RUNTIME_DIR||void 0,Iv6=(wE.XDG_DATA_DIRS||"/usr/local/share/:/usr/share/").split(":");if(eH)Iv6.unshift(eH);Pv6=(wE.XDG_CONFIG_DIRS||"/etc/xdg").split(":");if(WC)Pv6.unshift(WC)});import{homedir as V40}from"node:os";import yU from"node:path";var Fu1,Cv6,zu1,_v6,DC,Tv6,HC,Sv6,ZQ;var xX=Z0(()=>{bb();Fu1=yU.join(V40(),".local/share"),Cv6=process.platform==="win32"||process.platform==="darwin"?Fu1:eH??Fu1,zu1=yU.join(V40(),".config"),_v6=process.platform==="win32"||process.platform==="darwin"?zu1:WC??zu1,DC=yU.join(Cv6,"amp"),Tv6=yU.join(_v6,"amp"),HC=yU.join(Tv6,"tools"),Sv6=process.platform==="win32"?yU.join(process.env.LOCALAPPDATA??yU.join(V40(),"AppData","Local"),"amp"):yU.join(process.env.XDG_CACHE_HOME??yU.join(V40(),".cache"),"amp"),ZQ=Sv6});function yv6(){return!1}function qu1(J){return J.trim().toLowerCase()}function vv6(J){if(!J.endsWith("@sourcegraph.com"))return!1;if(yv6())return!0;return kv6.has(J)}function G40(J){let Z=qu1(J);if(Z.length===0)return!1;return Z.endsWith("@sourcegraph.com")||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}function JZ(J){let Z=qu1(J);if(Z.length===0)return!1;return vv6(Z)||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}var kv6;var LE=Z0(()=>{kv6=new Set(["alex.kemper@sourcegraph.com","beyang@sourcegraph.com","brady.jeong@sourcegraph.com","brett.jones@sourcegraph.com","camden@sourcegraph.com","connor.obrien@sourcegraph.com","dario.hamidi@sourcegraph.com","hamish.bultitude@sourcegraph.com","harry.charlesworth@sourcegraph.com","hitesh.sagtani@sourcegraph.com","isuru.fonseka@sourcegraph.com","jesse.edelstein@sourcegraph.com","jim.espelico@sourcegraph.com","karl.clement@sourcegraph.com","lewis.metcalf@sourcegraph.com","nicolay.gerold@sourcegraph.com","sqs@sourcegraph.com","thorsten@sourcegraph.com","tim.culverhouse@sourcegraph.com","tim.lucas@sourcegraph.com","will.dollman@sourcegraph.com","devsqs@sourcegraph.com"])});function d4(J,Z,Q=Z+"s"){return J===1?Z:Q}var T2=()=>{};function CR0(J){return F40[J]??0}function xv6(J){return typeof J==="number"&&Number.isInteger(J)&&J>=1&&J<=3600}function Wu1(J){let Z=J.settings["tools.inactivityTimeout"],Q=J.settings["tools.stopTimeout"],Y=Z;if(Y===void 0&&Q!==void 0)Y=Q;if(Y===void 0)Y=CR0("amp.tools.inactivityTimeout");if(!xv6(Y))return null;return Y*1000}function Du1(J){let Z=J.settings["tools.stopTimeout"],Q=CR0("amp.tools.stopTimeout");return(Z??Q)*1000}function hb(J){let Z=J.settings["network.timeout"],Q=CR0("amp.network.timeout");return(Z??Q)*1000}var F40,Uu1;var BC=Z0(()=>{F40={"amp.tools.inactivityTimeout":300,"amp.tools.stopTimeout":300,"amp.network.timeout":30},Uu1={"amp.tools.inactivityTimeout":{default:F40["amp.tools.inactivityTimeout"]},"amp.tools.stopTimeout":{default:F40["amp.tools.stopTimeout"]},"amp.network.timeout":{default:F40["amp.network.timeout"]}}});function tv6(J){return ju1.safeParse(J)}function $B(J){return sv6.safeParse(J)}function OC(J){if(!J||!Array.isArray(J))return[];let Z=[];for(let[Q,Y]of J.entries()){let X=tv6(Y);if(X.success)Z.push(X.data);else{let K=typeof Y==="object"&&Y!==null&&"tool"in Y?String(Y.tool):`entry at index ${Q}`;P.warn(`Permission entry for tool "${K}" is invalid: ${X.error.issues.map((V)=>`${V.path.join(".")}: ${V.message}`).join(", ")}`)}}return Z}var uR0,ju1,sv6;var EE=Z0(()=>{JJ();g0();uR0=y.lazy(()=>y.union([y.string().describe('Pattern match where "*" matches any number of any characters'),y.array(uR0).min(1).describe("OR match of each entry"),y.boolean().describe("A literal boolean match"),y.number().describe("A literal number match"),y.null().describe("A literal null match"),y.undefined().describe("A literal undefined match"),y.record(y.string(),uR0).describe("Matching individual keys of an object")])),ju1=y.object({tool:y.string().min(1).describe("The name of the tool to which this entry applies"),matches:y.record(y.string(),uR0).optional().describe("Maps tool inputs to conditions"),action:y.enum(["allow","reject","ask","delegate"]).describe("How Amp should proceed in case of a match"),context:y.enum(["thread","subagent"]).optional().describe("Only apply this entry in this context"),to:y.string().min(1).optional().describe('Command to delegate to when action is "delegate"'),message:y.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((J,Z)=>{if(J.action==="delegate"&&!J.to)Z.addIssue({code:"custom",message:'delegate action requires "to" field',path:["to"]});if(J.action!=="delegate"&&J.to)Z.addIssue({code:"custom",message:'"to" field only allowed with delegate action',path:["to"]});if(J.message&&J.action!=="reject")Z.addIssue({code:"custom",message:'"message" field only allowed with reject action',path:["message"]})}),sv6=y.array(ju1).describe("Entries checked in sequence to configure tool permissions")});function t8(J,Z){let Q=ev6(J,Z);return typeof Q==="string"?Q:Q.toString()}function ev6(J,Z,Q=!0){if(!Z)Z=$x6();let{workspaceFolders:Y,isWindows:X,homeDir:K}=Z,V=typeof J==="string"?X1.parse(J):X1.from(J);if(Y)for(let G of Y){let F=S6(G);if(K1.hasPrefix(V,F)){let z=F.path.endsWith("/")?F.path.slice(0,-1):F.path,U=Q&&Y&&Y.length>=2?_U(F.path)+(X?"\\":"/"):"";return bR0(U+V.path.slice(z.length+1),X,V.scheme)}}if(V?.scheme==="file"){if(K){let G=S6(K);if(K1.hasPrefix(V,G)){let F=G.path.endsWith("/")?G.path.slice(0,-1):G.path,z=V.path.slice(F.length+1);return bR0("~"+(X?"\\":"/")+z,X,V.scheme)}}return bR0(V.fsPath,X,V.scheme)}return V}function bR0(J,Z,Q){return Z&&Q==="file"?J.replaceAll("/","\\"):J}function H40(J){let Z=D40;return D40=J,Z}function $x6(){if(D40)return D40;throw Error("must call setDisplayPathEnvInfo before calling displayPath() and related functions")}var D40=null;var TV=Z0(()=>{D4();VE();j10()});function S2(J){if(!J)return{};return{[hR0]:J.id,[Jx6]:J.agentMode??""}}var q2="x-amp-feature",hR0="x-amp-thread-id",YJ="x-amp-message-id",Jx6="x-amp-mode",Ru1="X-Amp-Client-Application",cb="X-Amp-Client-Type",Iu1="X-Amp-Client-Version",Pu1="X-Amp-Installation-ID",Cu1="X-Amp-Device-Fingerprint";var QQ=()=>{};function Su1(J){_u1=J}function ME(J){lb=J}function ku1(J){Tu1=J}function yu1(J){ib=J.installationID,nb=J.deviceFingerprint}function vu1(){if(!ib||!nb)return;return{installationID:ib,deviceFingerprint:nb}}function AE(){let J=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(J)return{type:"cli",name:"AmpSDK",version:J};let Z;if(!lb)Z="CLI";else if(["Neovim","JetBrains","Zed"].includes(lb))Z=lb;else Z=`${lb} CLI`;return{type:"cli",name:Tu1?`${Z} Execute Mode`:Z,version:_u1}}function k2(){let J=AE(),Z={};if(Z[Ru1]=J.name,Z[cb]=J.type,ib)Z[Pu1]=ib;if(nb)Z[Cu1]=nb;if(J.version)Z[Iu1]=J.version;return Z}var _u1=null,lb=null,Tu1=!1,ib=null,nb=null;var XJ=Z0(()=>{QQ()});function Zx6(J){if(typeof process>"u"||!process.versions?.node)return"unknown";try{switch(J){case"darwin":{try{let{execSync:Q}=R0("node:child_process"),X=Q("/usr/bin/sw_vers -productVersion",{encoding:"utf8",timeout:3000,stdio:["ignore","pipe","ignore"]}).trim();if(X&&/^\d+\.\d+/.test(X))return X}catch{}return R0("node:os").release()}case"linux":try{let Y=R0("node:fs").readFileSync("/etc/os-release","utf8").split(`
103
103
  `);for(let K of Y)if(K.startsWith("PRETTY_NAME=")){let V=K.match(/PRETTY_NAME="?([^"]*)"?/);if(V?.[1])return V[1]}return R0("node:os").release()}catch{return R0("node:os").release()}case"windows":try{let{execSync:Z}=R0("node:child_process"),Y=Z('systeminfo | findstr /B /C:"OS Name" /C:"OS Version"',{encoding:"utf8",timeout:5000}).split(`
104
- `),X=Y.find((G)=>G.includes("OS Name")),K=Y.find((G)=>G.includes("OS Version"));if(X&&K){let G=X.split(":")[1]?.trim(),F=K.split(":")[1]?.trim();return`${G} ${F}`}return R0("node:os").release()}catch{return R0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function dF(){if(!gR0){let J=typeof process<"u"&&process.versions?.node,Z=!J,Q="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Q="darwin";else if(process.platform==="win32")Q="windows";Y=Zx6(Q),X=process.arch}else if(typeof navigator<"u"){let K=navigator.platform.toLowerCase();if(K.includes("mac")||K.includes("ios"))Q="darwin";else if(K.includes("win"))Q="windows";let V=navigator.userAgent;if(Q==="darwin"){let G=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(G?.[1])Y=G[1].replace(/_/g,".")}else if(Q==="windows"){let G=V.match(/Windows NT (\d+\.\d+)/);if(G?.[1])Y=G[1]}else{let G=V.match(/Linux.*?(\d+\.\d+)/);if(G?.[1])Y=G[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}gR0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:AE().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return gR0}var gR0;var EC=Z0(()=>{XJ()});function n3(J){let Z=Z5[J];return`${Z.provider}/${Z.name}`}function cF(J){let Z=J.indexOf("/");if(Z===-1)throw Error(`Invalid provider/model format: ${J}`);return{provider:J.slice(0,Z),model:J.slice(Z+1)}}function L$(J){let{provider:Z,model:Q}=cF(J);for(let Y of Object.values(Z5))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return Z5.CLAUDE_SONNET_4_5;case"openai":return Z5.GPT_5;case"xai":return Z5.GROK_CODE_FAST_1;case"cerebras":return Z5.Z_AI_GLM_4_7;case"fireworks":return Z5.FIREWORKS_GLM_4P6;case"baseten":return Z5.BASETEN_KIMI_K2P5;case"moonshotai":return Z5.KIMI_K2_INSTRUCT;case"openrouter":return Z5.SONOMA_SKY_ALPHA;case"groq":return Z5.GPT_OSS_120B;case"vertexai":return Z5.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function ab(J){for(let Q of Object.values(Z5))if(Q.name===J)return Q;let Z=J.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Z){let Q=Z[1];for(let Y of Object.values(Z5))if(Y.name===Q)return Y}return}function b8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function KJ(J){let Z=L$(J);return Z.contextWindow-Z.maxOutputTokens}function B40(J){return L$(J).maxOutputTokens}var h6,Z5,mR0;var _7=Z0(()=>{h6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},Z5={CLAUDE_SONNET_4:{provider:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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_HAIKU_4_5:{provider:h6.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:h6.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:h6.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:h6.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:h6.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_CODEX:{provider:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:h6.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:h6.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:h6.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:h6.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:h6.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:h6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:h6.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:h6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:h6.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:h6.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:h6.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:h6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:h6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:h6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:h6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:h6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:h6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};mR0={FINDER:"finder"}});function w40(J){return J===N40}function UY(J){return J==="deep"||J===N40}function JB(J,Z){if(!w40(J))return!0;return Boolean(Z&&JZ(Z))}function dR0(J,Z){let Q=VJ(Z);if(!Q)return!1;if(Qx6.has(J)){let Y=Q.finder??mR0.FINDER,X=Yx6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function gu1(J,Z){let Q=VJ(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function SV(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(lF).filter((G)=>{if(!JB(G.key,Q?.userEmail))return!1;if(G.key===L40)return!1;if(K.includes(`!${G.key}`))return!1;if(Z===!1&&E8(G.key))return!1;if(V.has(G.key))return!1;if(Q?.v2&&!(("visibleInV2"in G)&&G.visibleInV2))return!1;let z="visible"in G?G.visible:!1,q=K.includes(G.key);return z||q}).map((G)=>({mode:G.key,description:"description"in G?G.description:void 0})).sort((G,F)=>G.mode.localeCompare(F.mode))}function VJ(J){return Object.values(lF).find((Z)=>Z.key===J)}function fX(J){return VJ(J)?.primaryModel??n3("CLAUDE_SONNET_4_5")}function ob(J){let Z=VJ(J);if(!Z)return!1;return L$(Z.primaryModel).capabilities?.vision??!1}function E8(J){return J==="free"||J.startsWith("free-")}function cR0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function lR0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var Qx6,Yx6,bu1,hu1,N40="internal",Xx6,Kx6,xu1,fu1,uu1,Vx6,Gx6,Fx6,lF,L40,pR0;var O$=Z0(()=>{LE();_7();Qx6=new Set(["finder"]),Yx6={finder:"finder"},bu1={r:0,g:55,b:0},hu1={r:0,g:255,b:136};Xx6=["Read","Grep","glob","finder","Bash","create_file","edit_file","get_diagnostics","web_search","read_web_page","task_list","read_thread","find_thread","mermaid","chart","skill"],Kx6=["Read","Grep","glob","finder","Bash","create_file","edit_file","undo_edit","get_diagnostics","web_search","read_web_page","read_mcp_resource","mermaid","chart","read_thread","find_thread","skill","oracle","handoff","librarian","Task","task_list","look_at","painter"],xu1=["Read","finder","Bash","repl","create_file","edit_file","undo_edit","web_search","read_web_page","task_list","read_thread","find_thread","skill","oracle","code_tour","librarian","Task","Grep","glob","read_mcp_resource","mermaid","chart","look_at","get_diagnostics","handoff","painter","restore_snapshot","slack_write","slack_read"],fu1=["code_tour","code_review","walkthrough","walkthrough_diagram"],uu1=["code_tour","code_review"],Vx6=["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"],Gx6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],Fx6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],lF={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:n3("CLAUDE_OPUS_4_6"),includeTools:xu1,deferredTools:fu1,visible:!0,visibleInV2:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},FREE:{key:"free",displayName:"Free",description:"Amp Free",primaryModel:n3("CLAUDE_HAIKU_4_5"),includeTools:Xx6,visible:!0,uiHints:{primaryColor:{r:0,g:26,b:51},secondaryColor:{r:0,g:184,b:255}}},RUSH:{key:"rush",displayName:"Rush",description:"Faster and cheaper for small, well-defined tasks",primaryModel:n3("CLAUDE_HAIKU_4_5"),includeTools:Kx6,visible:!0,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:n3("CLAUDE_OPUS_4_6"),includeTools:Vx6,visible:!1,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:n3("CLAUDE_OPUS_4_6"),includeTools:xu1,deferredTools:fu1,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.3 Codex",primaryModel:n3("GPT_5_3_CODEX"),includeTools:Gx6,deferredTools:uu1,visible:!0,visibleInV2:!0,reasoningEffort:"high",uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},INTERNAL:{key:N40,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:n3("GPT_5_4"),includeTools:Fx6,deferredTools:uu1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},L40=lF.AGG.key,pR0=Object.values(lF).map((J)=>J.key)});var a3=Z0(()=>{O$();_7()});function rb(J){return J["agent.deepReasoningEffort"]??"high"}function iR0(J){let Z=zx6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function nR0(J){return qx6.includes(J)}function pu1(J){let Z=J["internal.model"];if(Z&&typeof Z==="object"){let Q=Z.oracle?.trim();if(Q&&Q.length>0){let Y=Q.indexOf(":");return Y===-1?Q:Q.slice(Y+1).trim()}}return Z5.GPT_5_4.name}function du1(J,Z){let Q=J["internal.model"];if(!Q)return null;let Y;if(typeof Q==="string")Y=Q.trim();else Y=Q[Z]?.trim();if(!Y||Y.length===0)return null;let X=Y.indexOf(":");if(X===-1)return null;let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K||!V)return null;return`${K}/${V}`}var zx6,qx6,O40,mu1;var vU=Z0(()=>{a3();zx6=["agent.deepReasoningEffort","agent.skipTitleGenerationIfMessageContains","anthropic.effort","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.speed","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.openai.websocket.enabled","internal.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];qx6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];O40=["mcpServers","mcpPermissions","url"],mu1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var T7;var jE=Z0(()=>{T7={AD_IMPRESSION_ESTIMATES:"ad-impression-estimates",AD_LOADING_ANIMATION:"ad-loading-animation",ANTHROPIC_FAST:"anthropic-fast",AGENTS_VIEW:"agents-view",BITBUCKET_ENTERPRISE:"bitbucket-enterprise",FILE_CHANGE_SYNC:"file-change-sync",HARNESS_SYSTEM_PROMPT:"harness-system-prompt",OPENAI_FAST:"openai-fast",PAYMENT_METHOD_EXEMPT:"payment-method-exempt",V2:"v2",V2_CHANGES_ARTIFACT_PANEL:"v2-changes-artifact-panel",DTW_TUI:"dtw-tui",GRAVITY:"gravity",REPOS_PLUGINS_OVERVIEW:"repos-plugins-overview",PLUGIN_API:"plugin-api",TASK_LIST:"task-list",THREAD_TIMING:"thread-timing",THREAD_TRACE_VIEWER:"thread-trace-viewer",TEAM_LABELS_FILTER:"team-labels-filter",UNIFIED_AD_RANKING:"unified-ad-ranking",USE_GENERATED_AD_CONTEXT:"use-generated-ad-context",PLUGINS:"plugins"}});var lu1;var aR0=Z0(()=>{Nb();Nb();lu1=y});var uX;var R9=Z0(()=>{aR0();aR0();uX=lu1});function M40(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function xU(J){if(J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){let Q=Z?.code;if(Q==="ESRCH")return!1;if(Q==="EPERM"||Q==="EACCES")return!0;return P.debug("PID check error",{pid:J,code:Q}),!1}}var RE=Z0(()=>{g0()});import{execFile as Ux6,spawnSync as tb}from"node:child_process";import MC from"node:fs";import oR0 from"node:os";import YQ from"node:path";import{promisify as Wx6}from"node:util";async function Mx6(J){try{if(!await cx6())return[];let Z=await mx6(J);if(!Z)return[];let Q=await $b1(J);return(await eu1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return P.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function Ax6(J,Z){if(!Z.pid||!xU(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await $b1(J),K=(await eu1(J,Y)).find((G)=>j40(G.workspaceFolder)===j40(Q));if(!K)return null;let V=await Cx6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function jx6(J,Z){let{filePath:Q,line:Y,column:X}=Ix6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=lx6(J);if(!V)return nu1(J,Q,Y,X);if(tb(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return nu1(J,Q,Y,X)}function nu1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((q)=>encodeURIComponent(q)).join("/"),G=Q?`:${Q}${Y?`:${Y}`:""}`:"",F=`${J.urlScheme}://file${V}${G}`,z=Rx6(F);if(z.status===0)return!0;return P.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:F,status:z.status,stderr:z.stderr?.toString().trim()}),!1}function Rx6(J){if(process.platform==="darwin")return tb("open",[J],{stdio:"ignore"});if(process.platform==="win32")return tb("cmd.exe",["/c","start","",J],{stdio:"ignore"});return tb("xdg-open",[J],{stdio:"ignore"})}function Ix6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return{};let Q=Px6(Z.fragment);return{filePath:Z.fsPath,line:Q?.line,column:Q?.column}}catch{return{}}}function Px6(J){let Z=J.match(Hx6),Q=Z?.groups?.line;if(!Q)return null;return{line:Number.parseInt(Q,10),column:Z.groups?.column?Number.parseInt(Z.groups.column,10):void 0}}async function Cx6(J){let Z=await hx6(J,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Z.length===0)return null;let Q=_x6(Z.find((F)=>F.key==="memento/workbench.parts.editor")?.value);if(!Q)return null;let Y=Q.leaves.flatMap((F)=>F.editors),X=Q.leaves.find((F)=>F.id===Q.activeGroup)??Q.leaves[0],K=X?Sx6(X):void 0,V=kx6(Z.find((F)=>F.key==="memento/workbench.editors.files.textFileEditor")?.value),G=K?await yx6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:G}}function _x6(J){if(!J)return null;try{let Z=JSON.parse(J),Q=Z["editorpart.state"]??Z.editorpart?.state,Y=Q?.activeGroup;if(typeof Y!=="number")return null;let X=Q?.serializedGrid,K=tu1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return P.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function tu1(J){if(!J||typeof J!=="object")return[];let Z=J;if(Z.type==="leaf"){let Q=Z.data;if(typeof Q?.id!=="number")return[];let Y=Q.editors?.map((X)=>Tx6(X.value)).filter((X)=>Boolean(X))??[];return[{id:Q.id,editors:Y,preview:typeof Q.preview==="number"?Q.preview:void 0,mru:Array.isArray(Q.mru)?Q.mru.filter((X)=>Number.isInteger(X)):[]}]}if(Z.type==="branch")return(Array.isArray(Z.data??[])?Z.data??[]:[]).flatMap((Y)=>tu1(Y));return[]}function Tx6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return l1(X1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return l1(X1.file(Z.resourceJSON.path))}catch(Z){P.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function Sx6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function kx6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return P.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function yx6(J,Z,Q){let Y=Q.get(J)??Q.get(decodeURIComponent(J))??Q.get(encodeURI(J));if(!Y)return;let K=(Y[String(Z)]??Object.values(Y)[0])?.cursorState?.[0];if(!K)return;let V=await vx6(J);if(V===void 0)return;let G=au1(K.selectionStart.lineNumber,K.selectionStart.column),F=au1(K.position.lineNumber,K.position.column),z=ou1(G,F)<=0?G:F,q=ou1(G,F)<=0?F:G,W=z.line===q.line&&z.character===q.character?xx6(V,z.line):fx6(V,z.line,z.character,q.line,q.character);return{range:{startLine:z.line,startCharacter:z.character,endLine:q.line,endCharacter:q.character},content:W}}async function vx6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return;return await MC.promises.readFile(Z.fsPath,"utf-8")}catch(Z){P.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function au1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function ou1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function xx6(J,Z){return J.split(`
104
+ `),X=Y.find((G)=>G.includes("OS Name")),K=Y.find((G)=>G.includes("OS Version"));if(X&&K){let G=X.split(":")[1]?.trim(),F=K.split(":")[1]?.trim();return`${G} ${F}`}return R0("node:os").release()}catch{return R0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function dF(){if(!gR0){let J=typeof process<"u"&&process.versions?.node,Z=!J,Q="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Q="darwin";else if(process.platform==="win32")Q="windows";Y=Zx6(Q),X=process.arch}else if(typeof navigator<"u"){let K=navigator.platform.toLowerCase();if(K.includes("mac")||K.includes("ios"))Q="darwin";else if(K.includes("win"))Q="windows";let V=navigator.userAgent;if(Q==="darwin"){let G=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(G?.[1])Y=G[1].replace(/_/g,".")}else if(Q==="windows"){let G=V.match(/Windows NT (\d+\.\d+)/);if(G?.[1])Y=G[1]}else{let G=V.match(/Linux.*?(\d+\.\d+)/);if(G?.[1])Y=G[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}gR0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:AE().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return gR0}var gR0;var EC=Z0(()=>{XJ()});function n3(J){let Z=Z5[J];return`${Z.provider}/${Z.name}`}function cF(J){let Z=J.indexOf("/");if(Z===-1)throw Error(`Invalid provider/model format: ${J}`);return{provider:J.slice(0,Z),model:J.slice(Z+1)}}function L$(J){let{provider:Z,model:Q}=cF(J);for(let Y of Object.values(Z5))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return Z5.CLAUDE_SONNET_4_5;case"openai":return Z5.GPT_5;case"xai":return Z5.GROK_CODE_FAST_1;case"cerebras":return Z5.Z_AI_GLM_4_7;case"fireworks":return Z5.FIREWORKS_GLM_4P6;case"baseten":return Z5.BASETEN_KIMI_K2P5;case"moonshotai":return Z5.KIMI_K2_INSTRUCT;case"openrouter":return Z5.SONOMA_SKY_ALPHA;case"groq":return Z5.GPT_OSS_120B;case"vertexai":return Z5.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function ab(J){for(let Q of Object.values(Z5))if(Q.name===J)return Q;let Z=J.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Z){let Q=Z[1];for(let Y of Object.values(Z5))if(Y.name===Q)return Y}return}function b8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function KJ(J){let Z=L$(J);return Z.contextWindow-Z.maxOutputTokens}function B40(J){return L$(J).maxOutputTokens}var h6,Z5,mR0;var _7=Z0(()=>{h6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},Z5={CLAUDE_SONNET_4:{provider:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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_HAIKU_4_5:{provider:h6.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:h6.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:h6.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:h6.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:h6.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_CODEX:{provider:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.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:h6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:h6.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:h6.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:h6.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:h6.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:h6.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:h6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:h6.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:h6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:h6.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:h6.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:h6.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:h6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:h6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:h6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:h6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:h6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:h6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};mR0={FINDER:"finder"}});function w40(J){return J===N40}function UY(J){return J==="deep"||J===N40}function JB(J,Z){if(!w40(J))return!0;return Boolean(Z&&JZ(Z))}function dR0(J,Z){let Q=VJ(Z);if(!Q)return!1;if(Qx6.has(J)){let Y=Q.finder??mR0.FINDER,X=Yx6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function gu1(J,Z){let Q=VJ(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function SV(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(lF).filter((G)=>{if(!JB(G.key,Q?.userEmail))return!1;if(G.key===L40)return!1;if(K.includes(`!${G.key}`))return!1;if(Z===!1&&E8(G.key))return!1;if(V.has(G.key))return!1;if(Q?.v2&&!(("visibleInV2"in G)&&G.visibleInV2))return!1;let z="visible"in G?G.visible:!1,q=K.includes(G.key);return z||q}).map((G)=>({mode:G.key,description:"description"in G?G.description:void 0})).sort((G,F)=>G.mode.localeCompare(F.mode))}function VJ(J){return Object.values(lF).find((Z)=>Z.key===J)}function fX(J){return VJ(J)?.primaryModel??n3("CLAUDE_SONNET_4_5")}function ob(J){let Z=VJ(J);if(!Z)return!1;return L$(Z.primaryModel).capabilities?.vision??!1}function E8(J){return J==="free"||J.startsWith("free-")}function cR0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function lR0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var Qx6,Yx6,bu1,hu1,N40="internal",Xx6,Kx6,xu1,fu1,uu1,Vx6,Gx6,Fx6,lF,L40,pR0;var O$=Z0(()=>{LE();_7();Qx6=new Set(["finder"]),Yx6={finder:"finder"},bu1={r:0,g:55,b:0},hu1={r:0,g:255,b:136};Xx6=["Read","Grep","glob","finder","Bash","create_file","edit_file","get_diagnostics","web_search","read_web_page","task_list","read_thread","find_thread","mermaid","chart","skill"],Kx6=["Read","Grep","glob","finder","Bash","create_file","edit_file","undo_edit","get_diagnostics","web_search","read_web_page","read_mcp_resource","mermaid","chart","read_thread","find_thread","skill","oracle","handoff","librarian","Task","task_list","look_at","painter"],xu1=["Read","finder","Bash","repl","create_file","edit_file","undo_edit","web_search","read_web_page","task_list","read_thread","find_thread","skill","oracle","code_tour","librarian","Task","Grep","glob","read_mcp_resource","mermaid","chart","look_at","get_diagnostics","handoff","painter","restore_snapshot","slack_write","slack_read"],fu1=["code_tour","code_review","walkthrough","walkthrough_diagram"],uu1=["code_tour","code_review"],Vx6=["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"],Gx6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],Fx6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],lF={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:n3("CLAUDE_OPUS_4_6"),includeTools:xu1,deferredTools:fu1,visible:!0,visibleInV2:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},FREE:{key:"free",displayName:"Free",description:"Amp Free",primaryModel:n3("CLAUDE_HAIKU_4_5"),includeTools:Xx6,visible:!0,uiHints:{primaryColor:{r:0,g:26,b:51},secondaryColor:{r:0,g:184,b:255}}},RUSH:{key:"rush",displayName:"Rush",description:"Faster and cheaper for small, well-defined tasks",primaryModel:n3("CLAUDE_HAIKU_4_5"),includeTools:Kx6,visible:!0,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:n3("CLAUDE_OPUS_4_6"),includeTools:Vx6,visible:!1,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:n3("CLAUDE_OPUS_4_6"),includeTools:xu1,deferredTools:fu1,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.3 Codex",primaryModel:n3("GPT_5_3_CODEX"),includeTools:Gx6,deferredTools:uu1,visible:!0,visibleInV2:!0,reasoningEffort:"high",uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},INTERNAL:{key:N40,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:n3("GPT_5_4"),includeTools:Fx6,deferredTools:uu1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},L40=lF.AGG.key,pR0=Object.values(lF).map((J)=>J.key)});var a3=Z0(()=>{O$();_7()});function rb(J){return J["agent.deepReasoningEffort"]??"high"}function iR0(J){let Z=zx6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function nR0(J){return qx6.includes(J)}function pu1(J){let Z=J["internal.model"];if(Z&&typeof Z==="object"){let Q=Z.oracle?.trim();if(Q&&Q.length>0){let Y=Q.indexOf(":");return Y===-1?Q:Q.slice(Y+1).trim()}}return Z5.GPT_5_4.name}function du1(J,Z){let Q=J["internal.model"];if(!Q)return null;let Y;if(typeof Q==="string")Y=Q.trim();else Y=Q[Z]?.trim();if(!Y||Y.length===0)return null;let X=Y.indexOf(":");if(X===-1)return null;let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K||!V)return null;return`${K}/${V}`}var zx6,qx6,O40,mu1;var vU=Z0(()=>{a3();zx6=["agent.deepReasoningEffort","agent.skipTitleGenerationIfMessageContains","anthropic.effort","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.speed","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.openai.websocket.enabled","internal.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];qx6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];O40=["mcpServers","mcpPermissions","url"],mu1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var T7;var jE=Z0(()=>{T7={AD_IMPRESSION_ESTIMATES:"ad-impression-estimates",AD_LOADING_ANIMATION:"ad-loading-animation",ANTHROPIC_FAST:"anthropic-fast",AGENTS_VIEW:"agents-view",BITBUCKET_ENTERPRISE:"bitbucket-enterprise",FILE_CHANGE_SYNC:"file-change-sync",HARNESS_SYSTEM_PROMPT:"harness-system-prompt",OPENAI_FAST:"openai-fast",PAYMENT_METHOD_EXEMPT:"payment-method-exempt",V2:"v2",DTW_TUI:"dtw-tui",GRAVITY:"gravity",REPOS_PLUGINS_OVERVIEW:"repos-plugins-overview",PLUGIN_API:"plugin-api",TASK_LIST:"task-list",THREAD_TIMING:"thread-timing",THREAD_TRACE_VIEWER:"thread-trace-viewer",TEAM_LABELS_FILTER:"team-labels-filter",UNIFIED_AD_RANKING:"unified-ad-ranking",USE_GENERATED_AD_CONTEXT:"use-generated-ad-context",PLUGINS:"plugins"}});var lu1;var aR0=Z0(()=>{Nb();Nb();lu1=y});var uX;var R9=Z0(()=>{aR0();aR0();uX=lu1});function M40(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function xU(J){if(J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){let Q=Z?.code;if(Q==="ESRCH")return!1;if(Q==="EPERM"||Q==="EACCES")return!0;return P.debug("PID check error",{pid:J,code:Q}),!1}}var RE=Z0(()=>{g0()});import{execFile as Ux6,spawnSync as tb}from"node:child_process";import MC from"node:fs";import oR0 from"node:os";import YQ from"node:path";import{promisify as Wx6}from"node:util";async function Mx6(J){try{if(!await cx6())return[];let Z=await mx6(J);if(!Z)return[];let Q=await $b1(J);return(await eu1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return P.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function Ax6(J,Z){if(!Z.pid||!xU(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await $b1(J),K=(await eu1(J,Y)).find((G)=>j40(G.workspaceFolder)===j40(Q));if(!K)return null;let V=await Cx6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function jx6(J,Z){let{filePath:Q,line:Y,column:X}=Ix6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=lx6(J);if(!V)return nu1(J,Q,Y,X);if(tb(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return nu1(J,Q,Y,X)}function nu1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((q)=>encodeURIComponent(q)).join("/"),G=Q?`:${Q}${Y?`:${Y}`:""}`:"",F=`${J.urlScheme}://file${V}${G}`,z=Rx6(F);if(z.status===0)return!0;return P.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:F,status:z.status,stderr:z.stderr?.toString().trim()}),!1}function Rx6(J){if(process.platform==="darwin")return tb("open",[J],{stdio:"ignore"});if(process.platform==="win32")return tb("cmd.exe",["/c","start","",J],{stdio:"ignore"});return tb("xdg-open",[J],{stdio:"ignore"})}function Ix6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return{};let Q=Px6(Z.fragment);return{filePath:Z.fsPath,line:Q?.line,column:Q?.column}}catch{return{}}}function Px6(J){let Z=J.match(Hx6),Q=Z?.groups?.line;if(!Q)return null;return{line:Number.parseInt(Q,10),column:Z.groups?.column?Number.parseInt(Z.groups.column,10):void 0}}async function Cx6(J){let Z=await hx6(J,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Z.length===0)return null;let Q=_x6(Z.find((F)=>F.key==="memento/workbench.parts.editor")?.value);if(!Q)return null;let Y=Q.leaves.flatMap((F)=>F.editors),X=Q.leaves.find((F)=>F.id===Q.activeGroup)??Q.leaves[0],K=X?Sx6(X):void 0,V=kx6(Z.find((F)=>F.key==="memento/workbench.editors.files.textFileEditor")?.value),G=K?await yx6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:G}}function _x6(J){if(!J)return null;try{let Z=JSON.parse(J),Q=Z["editorpart.state"]??Z.editorpart?.state,Y=Q?.activeGroup;if(typeof Y!=="number")return null;let X=Q?.serializedGrid,K=tu1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return P.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function tu1(J){if(!J||typeof J!=="object")return[];let Z=J;if(Z.type==="leaf"){let Q=Z.data;if(typeof Q?.id!=="number")return[];let Y=Q.editors?.map((X)=>Tx6(X.value)).filter((X)=>Boolean(X))??[];return[{id:Q.id,editors:Y,preview:typeof Q.preview==="number"?Q.preview:void 0,mru:Array.isArray(Q.mru)?Q.mru.filter((X)=>Number.isInteger(X)):[]}]}if(Z.type==="branch")return(Array.isArray(Z.data??[])?Z.data??[]:[]).flatMap((Y)=>tu1(Y));return[]}function Tx6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return l1(X1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return l1(X1.file(Z.resourceJSON.path))}catch(Z){P.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function Sx6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function kx6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return P.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function yx6(J,Z,Q){let Y=Q.get(J)??Q.get(decodeURIComponent(J))??Q.get(encodeURI(J));if(!Y)return;let K=(Y[String(Z)]??Object.values(Y)[0])?.cursorState?.[0];if(!K)return;let V=await vx6(J);if(V===void 0)return;let G=au1(K.selectionStart.lineNumber,K.selectionStart.column),F=au1(K.position.lineNumber,K.position.column),z=ou1(G,F)<=0?G:F,q=ou1(G,F)<=0?F:G,W=z.line===q.line&&z.character===q.character?xx6(V,z.line):fx6(V,z.line,z.character,q.line,q.character);return{range:{startLine:z.line,startCharacter:z.character,endLine:q.line,endCharacter:q.character},content:W}}async function vx6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return;return await MC.promises.readFile(Z.fsPath,"utf-8")}catch(Z){P.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function au1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function ou1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function xx6(J,Z){return J.split(`
105
105
  `)[Z]??""}function fx6(J,Z,Q,Y,X){let K=ru1(J,Z,Q),V=ru1(J,Y,X);if(V<=K)return"";return J.slice(K,V)}function ru1(J,Z,Q){let Y=0,X=0;for(let K=0;K<J.length;K+=1){if(Y===Z&&X===Q)return K;if(J[K]===`
106
106
  `)Y+=1,X=0;else X+=1}return J.length}async function eu1(J,Z){if(Z?.size===0)return[];let Q=YQ.join(Jb1(J),"workspaceStorage");if(!await sb(Q))return[];let Y=await MC.promises.readdir(Q,{withFileTypes:!0});return(await Promise.all(Y.filter((V)=>V.isDirectory()).map(async(V)=>{let G=V.name,F=YQ.join(Q,G),z=YQ.join(F,"state.vscdb"),q=YQ.join(F,"workspace.json");if(!await sb(z)||!await sb(q))return null;let U=await bx6(q);if(!U||!await sb(U))return null;if(Z&&!Z.has(j40(U)))return null;let W=await MC.promises.stat(z);return{storageID:G,workspaceFolder:U,stateDBPath:z,mtime:W.mtimeMs}}))).filter((V)=>V!==null).sort((V,G)=>G.mtime-V.mtime).slice(0,Dx6)}async function $b1(J){let Z=YQ.join(Jb1(J),"globalStorage","storage.json");if(!await sb(Z))return null;try{let Q=await MC.promises.readFile(Z,"utf-8"),X=JSON.parse(Q).windowsState,K=Array.isArray(X?.openedWindows)?X.openedWindows:[],V=K.length>0?K:[X?.lastActiveWindow],G=new Set;for(let F of V){if(!F)continue;let z=ux6(F);if(!z)continue;G.add(j40(z))}return G}catch(Q){return P.debug(`Failed to parse ${J.ideName} windowsState`,{storageFilePath:Z,error:Q instanceof Error?Q.message:String(Q)}),null}}function ux6(J){if(J.folder)return su1(J.folder);let Z=J.workspaceIdentifier?.configURIPath;if(!Z)return null;let Q=su1(Z);return Q?YQ.dirname(Q):null}function su1(J){try{return X1.parse(J).fsPath}catch{if(YQ.isAbsolute(J))return J;return null}}async function bx6(J){try{let Z=await MC.promises.readFile(J,"utf-8"),Q=JSON.parse(Z);if(Q.folder)return X1.parse(Q.folder).fsPath;if(Q.configuration)return YQ.dirname(X1.parse(Q.configuration).fsPath)}catch(Z){P.debug("Failed to parse VS Code workspace metadata",{workspaceMetadataPath:J,error:Z instanceof Error?Z.message:String(Z)})}return null}async function sb(J){try{return await MC.promises.access(J),!0}catch{return!1}}async function hx6(J,Z){let Q=await A40("sqlite3",["-readonly","-json",gx6(J),Z],{timeout:Ox6});if(Q.status!==0)return P.debug("sqlite3 query failed for VS Code database",{status:Q.status,stderr:Q.stderr?.trim()}),[];let Y=Q.stdout?.trim();if(!Y)return[];try{return JSON.parse(Y).filter((K)=>typeof K.key==="string"&&typeof K.value==="string")}catch(X){return P.debug("Failed to parse sqlite3 JSON output for VS Code database",{error:X instanceof Error?X.message:String(X)}),[]}}function gx6(J){let Q=J.replaceAll("\\","/").split("/").map((X)=>encodeURIComponent(X)).join("/");return`file:${Q.startsWith("/")?Q:`/${Q}`}?immutable=1`}async function mx6(J){return(await px6()).find((Y)=>dx6(J,Y.command))?.pid??null}async function px6(){if(process.platform==="win32"){let Z=await A40("tasklist",["/FO","CSV"]);if(Z.status!==0)return[];return Z.stdout.split(`
107
107
  `).slice(1).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{let[Y,X]=Q.replaceAll('"',"").split(",");return{pid:Number.parseInt(X??"",10),command:Y??""}}).filter((Q)=>Number.isFinite(Q.pid)&&Q.command)}let J=await A40("ps",["-ax","-o","pid=","-o","command="]);if(J.status!==0)return[];return J.stdout.split(`
@@ -3253,12 +3253,12 @@ ${Y.trim()}`;let F=mJ0(G),z=K.run(gJ0({thinkingConfig:{thinkingLevel:"HIGH"}}),V
3253
3253
  Focus areas:
3254
3254
  ${Q}`;return Y+=`
3255
3255
 
3256
- First call eval_git_diff with a bash command that computes this diff (for example: git diff --no-color ${Z}).`,Y+=" After retrieving the raw diff, inspect relevant files and then use post_explanation to emit the walkthrough in ordered sections. Start each section with a short sentence that states what the new code does, then use concise bullets. If relevant, explain what the old code did before.",Y}var Eq4=`You are Code Tour, a specialized subagent for explaining diffs.
3256
+ First call eval_git_diff with a bash command that computes this diff (for example: git diff --no-color ${Z}).`,Y+=" After retrieving the raw diff, inspect relevant files and then use post_explanation to emit the walkthrough in ordered sections. Start each section with a short sentence that states what the new code does, then use concise bullets. If relevant, explain what the old code did before.",Y}var Eq4=`You are a specialized subagent that explains diffs.
3257
3257
 
3258
3258
  Your job is to produce a clear walkthrough of what changed and why it matters.
3259
3259
 
3260
- Use the post_explanation tool to emit every section of your explanation. Do not rely on your final
3261
- assistant message for the tour content.
3260
+ Use the post_explanation tool to emit every section of your explanation. Do not use your final
3261
+ assistant message to explain (it should just read "I am done").
3262
3262
 
3263
3263
  Optimistically emit explanations in two batches:
3264
3264
  1. Early overview: after light inspection (without over-analyzing), once you understand the
@@ -3271,6 +3271,8 @@ Guidelines:
3271
3271
  - Always call eval_git_diff first to capture the raw diff for this tour.
3272
3272
  - Focus on high-level behavior and intent; avoid describing the obvious or line-level code mechanics.
3273
3273
  - When relevant, contrast the old behavior with the new behavior.
3274
+ - Do not use Markdown titles.
3275
+ - Preface the overview explanation with "**Overview:**".
3274
3276
  - Prefer short markdown bullet lists. Each explanation should usually be a short sentence followed by 0-3 concise bullets.
3275
3277
  - Avoid sentence fragments. Use complete sentences, but keep them concise and pithy.
3276
3278
  - Highlight important interactions between files when applicable.
@@ -6212,11 +6214,11 @@ ${D}`))}},error:(W)=>{if(!U)U=!0,G(Error(`Failed to spawn brew: ${W.message}`))}
6212
6214
  ${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))H+=`
6213
6215
 
6214
6216
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6215
- npm install -g @sourcegraph/amp`;G(Error(H))}},error:(W)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${W.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();VA();async function sX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=HT4(J,z),U=q<0,W,D;if(F.time){let H=F.time[J],B=F.time[z],N=Date.now();if(H)W=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:U,currentVersionAge:W,latestVersionAge:D}),{hasUpdate:U,latestVersion:z,currentVersion:J,currentVersionAge:W,latestVersionAge:D,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var sX3="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function tX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${sX3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=HT4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var tX3=604800000;function DT4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>tX3)return{ageMs:Q};return null}function HT4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function wr0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?kz(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function Lr0(J,Z,Q={}){let Y=new t1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new bF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await zz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await zz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await rX0(),U=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:U});let W=U?await tX0(J):await sX0(J,cj());if(!(W.latestVersion&&W.hasUpdate)){K.debug("no update available");return}let D=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let H=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ur0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await _n(W.latestVersion,q);let H=await vw(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await zz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}VA();import{stderr as Rq}from"node:process";function BT4(J){let Z=new $w().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(Y)=>{await Gr0(Y.force||!1,Y.verbose||!1,"0.0.1774286630-gfbf924"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new $w("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(Y)=>{await eX3(Y.targetVersion)});J.addCommand(Q)}async function eX3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Rq.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6217
+ npm install -g @sourcegraph/amp`;G(Error(H))}},error:(W)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${W.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();VA();async function sX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=HT4(J,z),U=q<0,W,D;if(F.time){let H=F.time[J],B=F.time[z],N=Date.now();if(H)W=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:U,currentVersionAge:W,latestVersionAge:D}),{hasUpdate:U,latestVersion:z,currentVersion:J,currentVersionAge:W,latestVersionAge:D,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var sX3="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function tX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${sX3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=HT4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var tX3=604800000;function DT4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>tX3)return{ageMs:Q};return null}function HT4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function wr0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?kz(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function Lr0(J,Z,Q={}){let Y=new t1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new bF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await zz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await zz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await rX0(),U=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:U});let W=U?await tX0(J):await sX0(J,cj());if(!(W.latestVersion&&W.hasUpdate)){K.debug("no update available");return}let D=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let H=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ur0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await _n(W.latestVersion,q);let H=await vw(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await zz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}VA();import{stderr as Rq}from"node:process";function BT4(J){let Z=new $w().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(Y)=>{await Gr0(Y.force||!1,Y.verbose||!1,"0.0.1774310664-gcb98ac"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new $w("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(Y)=>{await eX3(Y.targetVersion)});J.addCommand(Q)}async function eX3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Rq.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6216
6218
 
6217
6219
  `));try{if(!J){Rq.write(c0.blue(`Checking for updates...
6218
- `));let{hasUpdate:Y,latestVersion:X}=Fr0()?await tX0("0.0.1774286630-gfbf924"):await sX0("0.0.1774286630-gfbf924",cj());if(!Y){let K=wr0("0.0.1774286630-gfbf924"),V=K?.age?`released ${K.age} ago`:`built ${kz(new Date("2026-03-23T17:27:39.620Z"))} ago`;Rq.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774286630-gfbf924"} (${V})
6219
- `));let G=await vw("0.0.1774286630-gfbf924");if(G.warning)Rq.write(`
6220
+ `));let{hasUpdate:Y,latestVersion:X}=Fr0()?await tX0("0.0.1774310664-gcb98ac"):await sX0("0.0.1774310664-gcb98ac",cj());if(!Y){let K=wr0("0.0.1774310664-gcb98ac"),V=K?.age?`released ${K.age} ago`:`built ${kz(new Date("2026-03-24T00:08:19.172Z"))} ago`;Rq.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774310664-gcb98ac"} (${V})
6221
+ `));let G=await vw("0.0.1774310664-gcb98ac");if(G.warning)Rq.write(`
6220
6222
  `+c0.yellow(G.warning)+`
6221
6223
  `);process.exit(0)}if(!X)Rq.write(c0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Rq.write(c0.blue(`Updating to version ${J}...
6222
6224
  `)),await _n(J,void 0,(Y)=>{Rq.write(c0.dim(`Running: ${Y}
@@ -7387,7 +7389,7 @@ Ctrl-X, Y, Z to unlock`;if(W){let u=z.text.replace(/`([^`]+)`/g,"$1")+`
7387
7389
  `),K=[];for(let V=0;V<X.length;V++){let z=X[V].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 q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7388
7390
  `))}return new i0({decoration:{color:Q.colorScheme.background,border:c1.all(new h1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new J0({text:new C(void 0,void 0,K)})})})}}class f11 extends u${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=mF0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new v11({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function Wp4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?v9:0,F=Y-G;if(F<=0)return null;let z=Z-G;if(z<0||z>=F)return null;let q=Math.max(1,Math.floor(F/K)),U=Math.floor(z/q);return U>=0&&U<K?U:null}case"line":case"sparkline":case"stacked-area":{let G=V?v9:0,F=Y-G;if(F<=0)return null;let z=Math.max(0,Math.min(F-1,Z-G));if(K===1)return 0;let q=F/(K-1),U=Math.round(z/q);return Math.max(0,Math.min(K-1,U))}default:return null}}function bC3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=K?v9:0,q=Q-z,U=Y-(K?F:0);if(q<=0||U<=0)return null;let W=Math.max(1,Math.floor(q/X)),D=z+Z*W+Math.floor(W/2),H=G>0?V/G:0,B=Math.round((1-H)*(U-1));return{x:D,y:B}}case"line":case"sparkline":case"stacked-area":{let z=K?v9:0,q=Q-z,U=Y-(K?F:0);if(q<=0||U<=0)return null;let W=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),D=G>0?V/G:0,H=Math.round((1-D)*(U-1));return{x:W,y:H}}default:return null}}function hC3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function gC3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+F.length}let K=J.label.length,V=0;for(let G of Q){let F=G.points[Z];if(!F)continue;V+=F.value;let z=2+G.name.length+2+Y(F.value).length;K=Math.max(K,z)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function mC3(J,Z,Q,Y,X,K,V){let G;try{let H=T1.of(J),B=f0.of(J);G={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new g({color:G.foreground,bold:!0}),z=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),U=[],W=new g({color:G.foreground,underline:!0}),D=(H,B)=>new C(B,W,void 0,FK0(H),()=>{$8(J,H)});if(Y.length<=1){if(U.push(new C(`${Z.label}: `,F)),Z.link)U.push(D(Z.link,K(Z.value)));else U.push(new C(K(Z.value),z));if(Z.meta)U.push(new C(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";U.push(new C(`${Z.label}
7389
7391
  `,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(U.push(new C("● ",new g({color:O}))),U.push(new C(`${w.name}: `,q)),L.link)U.push(D(L.link,K(L.value)));else U.push(new C(K(L.value),z));if(N<Y.length-1||H)U.push(new C(`
7390
- `))}if(H)U.push(new C(" ",q)),U.push(new C("Total: ",q)),U.push(new C(K(B),z))}return new i0({decoration:{color:G.background,border:c1.all(new h1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,U)})})}LE();g0();T2();import{execSync as H_3}from"node:child_process";jE();O$();a3();_7();Fc();VA();TV();GJ();YZ();BY();hA();f4();Om();wb();w1();var Wd4=G4(VW(),1);import{writeFile as Gd4}from"fs/promises";import Fd4 from"path";g0();GJ();class u11{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774286630-gfbf924"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await W60(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ML extends l0{props;constructor(J){super();this.props=J}createState(){return new Dp4}}class Dp4 extends d0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Hp4 extends d0{controller=new X$;focusNode=new U6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new h1(Q.foreground,1,"solid")),F=new xZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),U=[];if(V)U.push(new C("Enter",new g({color:Y.keybind}))),U.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));U.push(new C("Esc",new g({color:Y.keybind}))),U.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let W=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,U)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),z,new h3,W]})})}}class Eo extends l0{props;constructor(J){super();this.props=J}createState(){return new Hp4}}import{isDeepStrictEqual as b11}from"node:util";var pC3=/[\\/_ +.#"@[({&]/,dC3=/[\\/_ +.#"@[({&]/g,cC3=/[\s-]/,Bp4=/[\s-]/g;function cF0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let F=Y.charAt(K),z=Q.indexOf(F,X),q=0,U,W,D,H;while(z>=0){if(U=cF0(J,Z,Q,Y,z+1,K+1,V),U>q){if(z===X)U*=1;else if(cC3.test(J.charAt(z-1))){if(U*=0.9,H=J.slice(X,z-1).match(Bp4),H&&X>0)U*=0.999**H.length}else if(pC3.test(J.charAt(z-1))){if(U*=0.8,D=J.slice(X,z-1).match(dC3),D&&X>0)U*=0.999**D.length}else if(U*=0.3,X>0)U*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(K))U*=0.9999}if(U<0.1&&(Q.charAt(z-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(z-1)!==Y.charAt(K))){if(W=cF0(J,Z,Q,Y,z+1,K+2,V),W*0.1>U)U=W*0.1}if(U>q)q=U;z=Q.indexOf(F,z+1)}return V[G]=q,q}function dF0(J){return J.toLowerCase().replace(Bp4," ")}function Np4(J,Z){let Q=cF0(J,Z,dF0(J),dF0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let F=cF0(J,G,dF0(J),dF0(G),0,0,{});if(F===0)return Q;X+=F,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class pv{}class dv{}class lF0{}class iF0{}class wp4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Lp4}}class Lp4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function lC3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Np4(Z,J);return{matches:Q>0.15,score:Q}}class r2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Op4}}class Op4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new X$(this.widget.props.controller?.query??""),this.focusNode=new U6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>b11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!b11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>b11(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof pv){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof dv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof lF0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof iF0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...lC3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;fv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new xZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),F=new d$({shortcuts:new Map([[new H4("ArrowDown"),new pv],[new H4("ArrowUp"),new dv],[new H4("Tab"),new pv],[new H4("Tab",{shift:!0}),new dv],[new H4("n",{ctrl:!0}),new pv],[new H4("p",{ctrl:!0}),new dv],[new H4("Enter"),new lF0],[new H4("Escape"),new iF0]]),focusNode:this.focusNode,child:G}),z=new A2({actions:new Map([[pv,new W6(this.invoke)],[dv,new W6(this.invoke)],[lF0,new W6(this.invoke)],[iF0,new W6(this.invoke)]]),child:F}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]});this.itemContexts=[];let U;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";U=new I0({height:10,child:new J4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)U=new k1({child:new J4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new wp4(new $4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});U=new x0({children:N,crossAxisAlignment:"start"})}let W=new $4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:U})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:W}),new i0({padding:C0.only({top:1}),child:new J4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:W}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function Ep4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class h11 extends e1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Ep4(X.pubDate).length));return new r2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,U=K?q.selectionBackground:void 0,W=K?q.selectionForeground:z.foreground,D=z.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new J0({text:new C(B,new g({color:D}))})])});return new i0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new J0({text:new C(X.title,new g({color:W})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(Ep4(X.pubDate),Q)]})})}})}}class g11 extends l0{createState(){return new Mp4}}class Mp4 extends d0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function iC3(J){return PY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function nC3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return LG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function m11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function aC3(J,Z,Q,Y){return[m11("+",J,Y.success),h3.horizontal(1),m11("~",Z,Y.warning),h3.horizontal(1),m11("-",Q,Y.destructive)]}function oC3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class nF0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Ap4}}class Ap4 extends d0{spinner=new F3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=nC3(z),U=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),W=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new J4({child:new J0({text:new C("",new g({color:W.colors.foreground,dim:!0}),[new C("Ctrl+T",new g({color:W.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:W.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(L)=>{if(L!==H)H=L,B=iC3(L);return B};return new r2({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!oC3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,S=O?j.selectionBackground:void 0,_=O?j.selectionForeground:R.foreground,f=R.mutedForeground,m=(s,z0)=>new I0({width:z0,child:q1.end([new J0({text:new C(s,new g({color:f}))})])}),x=Z.threadViewStates[L.id],T=[],u=L.relationshipType==="handoff",p=new na({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],z0=L.ancestorsAreLast.slice(1);for(let w0 of z0)s.push(new C(p.getAncestorPrefix(w0),new g({color:p.connectorColor,dim:p.connectorDim})));let a=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(a);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),T.push(new J0({text:new C("",void 0,s)}))}let d=[],h=F===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(kN(x))d.push(new g11),d.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(u)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:_})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:f,warning:f,destructive:f}:R;d.push(...aC3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,U)),new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...T,...d]})})}})}}function jp4(J){return 1-(1-J)**3}function Rp4(J,Z,Q){return J+(Z-J)*Q}function Mo(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=jp4(Y),V=jp4(X);return{x:Rp4(J.startOffset.x,J.targetOffset.x,K),y:Rp4(J.startOffset.y,J.targetOffset.y,V)}}var rC3={nodeWidth:3,horizontalSpacing:3};class cv{options;constructor(J={}){this.options={...rC3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,F)=>{let z=Z.get(G.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(z.length===0){Y.push({node:q,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let U=[];for(let B of z)U.push(V(B,F+1));let W=Math.min(...U),D=Math.max(...U),H=Math.floor((W+D)/2);return Y.push({node:q,position:{x:H,y:F}}),H};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var sC3={nodeWidth:3,nodeHeight:2};class lv{options;constructor(J={}){this.options={...sC3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var tC3={nodeWidth:3,nodeHeight:2},eC3={x:0,y:0};class oF0{options;constructor(J={}){this.options={...tC3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=eC3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],_=0;for(let f of R){if(f.position.x>_)S.push(new I0({width:f.position.x-_}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,T=K?.activeFlashOn??!1,u=f.node.id===K?.copyFlashNodeId;S.push(this.renderNode(m,x,T,u,q,z)),_=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,_=O+R*B+1,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:_,child:this.renderInfoBox(j,f,z,q)}))}return new i0({padding:C0.horizontal(2),child:new iG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,z=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",G="┗━┛",z=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:F,bold:z}))}),new J0({text:new C(G,new g({color:F,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((W)=>W.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,U=[new J0({text:new C(G,new g({color:z}))})];for(let W of X){let D=" ".repeat(K-W.length);U.push(new J0({text:new C("│ ",new g({color:z}),[new C(W+D,new g({color:q??z})),new C(" │",new g({color:z}))])}))}return U.push(new J0({text:new C(F,new g({color:z}))})),new x0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let W of Z){let D=W.position.x+G;if(D>=0&&D<Y)z[D]="▲"}V.push(new J0({text:new C(z.join(""),new g({color:F}))}));let q=Array(Y).fill(" ");for(let W of J){let D=Z.filter((L)=>L.node.parentID===W.node.id);if(D.length===0)continue;let H=W.position.x+G,B=D.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===H)if(D.length===1&&B[0]===H)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:F}))}));let U=Array(Y).fill(" ");for(let W of J){if(Z.filter((B)=>B.node.parentID===W.node.id).length===0)continue;let H=W.position.x+G;if(H>=0&&H<Y)U[H]="│"}return V.push(new J0({text:new C(U.join(""),new g({color:F}))})),V}}var $_3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},J_3={x:0,y:0};class p11{options;constructor(J={}){this.options={...$_3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=J_3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],_=0;for(let f of R){if(f.position.x>_)S.push(new I0({width:f.position.x-_}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,T=K?.activeFlashOn??!1;S.push(this.renderNode(m,x,T,q,z)),_=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,_=O+R*B,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:_,child:this.renderInfoBox(j,f,z)}))}return new i0({padding:C0.horizontal(2),child:new iG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new J0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let U=Z.filter((N)=>N.node.parentID===q.node.id);if(U.length===0)continue;let W=q.position.x+G,D=U.map((N)=>N.position.x+G),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===W,L=D.includes(N);if(w&&L)if(U.length===1)z[N]="│";else if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┼";else if(w)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┬";else if(L)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┴";else if(z[N]===" ")z[N]="─"}}return V.push(new J0({text:new C(z.join(""),new g({color:F}))})),V}}class Ao extends s3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Ip4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Ip4 extends v4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class hR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new _p4}}var Pp4=400,Cp4=300,Z_3=16;class _p4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new cv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new lv;renderer=new p11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let z=this.widget.props.threads.find((q)=>q.id===K);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),G=this.widget.props.threads.some((F)=>F.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Pp4,durationY:Cp4};let Z=Math.max(Pp4,Cp4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Mo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Z_3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,F=Math.floor(this.viewportHeight/2),q=Math.floor(F/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((U)=>U.node.id===this.selectedNodeId):null)??this.positionedNodes.find((U)=>!U.node.parentID);if(q){let U=Math.max(...this.positionedNodes.map((W)=>W.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,U)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),F=new Ao({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Sp4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new kp4}}class kp4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var Tp4=30,Q_3=30;class iv{}class nv{}class rF0{}class sF0{}class d11 extends l0{props;constructor(J){super();this.props=J}createState(){return new yp4}}class yp4 extends d0{highlightedIndex=0;controller=new X$;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new U6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;fv(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof iv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof nv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof rF0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof sF0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=Q_3+Tp4,F=c1.all(new h1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),U=new xZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new d$({shortcuts:new Map([[new H4("ArrowDown"),new iv],[new H4("ArrowUp"),new nv],[new H4("Tab"),new iv],[new H4("Tab",{shift:!0}),new nv],[new H4("n",{ctrl:!0}),new iv],[new H4("p",{ctrl:!0}),new nv],[new H4("Enter"),new rF0],[new H4("Escape"),new sF0]]),focusNode:this.focusNode,child:U}),D=new A2({actions:new Map([[iv,new W6(this.invoke)],[nv,new W6(this.invoke)],[rF0,new W6(this.invoke)],[sF0,new W6(this.invoke)]]),child:W}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,S=j?X.selectionBackground:void 0,_=j?X.selectionForeground:Y.foreground,f=[new C(M.label,new g({color:_})),new C(` (${M.threads.length})`,new g({color:_,dim:!0}))];if(R)f.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Sp4(new $4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,f)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new $4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=z?z.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=z?new i0({padding:C0.all(1),child:new hR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:Tp4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new $4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class hJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!hJ._instance)hJ._instance=new hJ;return hJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}g0();class vp4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new r2({title:"Add Label",items:F,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:K||"Type to create a new label",renderItem:(z,q,U,W)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:H})),new C(N,new g({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(z.name,new g({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let W=q.trim().toLowerCase();return W.length===0||z.name.includes(W)},sortItems:(z,q,U)=>{let W="__isCreateMarker"in z.item&&z.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(W&&!D)return-1;if(!W&&D)return 1;return q.score-z.score}})}}class c11 extends l0{props;constructor(J){super();this.props=J}createState(){return new vp4}}class $F extends l0{props;constructor(J){super();this.props=J}createState(){return new xp4}}class xp4 extends d0{_spinner=new F3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=c1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),F=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let z=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}var jo={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},tF0=["workspace","global","flag","default","external","skill","other"];function Y_3(J){return Array.from(new Set(J))}function fp4(J){return Y_3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function av(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return fp4(J).length>0?"skill":"other"}function l11(J){return av(J)==="skill"}function up4(J){let Z=fp4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=av(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${jo[Y].description}: ${Q}`}function bp4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var hp4=process.platform==="win32"?" ":"█",gp4=process.platform==="win32"?"░":"█";class O9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=hp4,thumbChar:K=gp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createState(){return new mp4}}class mp4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),G=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),z=X-G,q=Math.max(0,z*F),U=q+G;return J>=q&&J<=U}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,G=Math.min(1,Q/Z),F=Math.max(1,K*G),z=K-F;if(z<=0)return;let q=Z-Q,U=z/q,W=V/U,D=Math.max(0,Math.min(q,this._dragStartOffset+W));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let G=Math.min(1,Y/Q),F=Math.max(1,V*G),z=Q-Y,q=V-F,U=Math.max(0,Math.min(1,X/(Q-Y))),W=Math.max(0,q*U),D=W+F;if(Z>=W&&Z<=D)return;if(Z<W)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new $4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?d5.POINTER:d5.DEFAULT,child:new pp4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class pp4 extends ky{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=hp4,thumbChar:K=gp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createRenderObject(){return new dp4(this)}updateRenderObject(J){J.updateWidget(this)}}class dp4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,G=this._widget.thumbColor,F=process.platform==="win32",z=Y,q=Y+X;if(!F){let U=["▁","▂","▃","▄","▅","▆","▇","█"];for(let W=0;W<this.size.height;W++){let D="█",H=!0;if(W===Math.floor(z)){let B=1-(z-W),N=Math.floor(B*8);D=U[N]||"█",H=!1}else if(W===Math.floor(q)){let B=1-(q-W),N=Math.floor(B*8);D=U[N]||"█"}else if(W>z&&W<q)H=!1;J.setChar(Z,Q+W,D,{fg:G,bg:V,reverse:H},1)}return}for(let U=0;U<this.size.height;U++){let W=U+0.5,D=W>=z&&W<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+U,H,{fg:D?G:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class gR extends l0{props;constructor(J){super();this.props=J}createState(){return new cp4}}class cp4 extends d0{scrollController=new j5;scrollAreaKey=new $$("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(J){return J instanceof o2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=IF0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),F=new k1({child:new c$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new O9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,U=this.scrollController.offset,W=this.getViewportHeight(),D=q+W;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(W,1),scrollOffset:Math.max(U,0)}}})]})})})}),z=new i0({padding:C0.symmetric(1,0),child:new J0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let U=new g({color:Z.app.keybind}),W=new g({color:Z.colors.foreground,dim:!0});return new C("",W,[new C("Press ",W),new C("Escape",U),new C(" to close • Use ",W),new C("↑↓",U),new C(" or ",W),new C("j/k",U),new C(" to scroll",W)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.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 i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),F,z]})})})}}T2();class lp4 extends l0{props;constructor(J){super();this.props=J}createState(){return new ip4}}class ip4 extends d0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=k9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,z)=>F+z.registeredCommands.length,0),G=this.plugins.reduce((F,z)=>F+z.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${G} ${d4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
7392
+ `))}if(H)U.push(new C(" ",q)),U.push(new C("Total: ",q)),U.push(new C(K(B),z))}return new i0({decoration:{color:G.background,border:c1.all(new h1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,U)})})}LE();g0();T2();import{execSync as H_3}from"node:child_process";jE();O$();a3();_7();Fc();VA();TV();GJ();YZ();BY();hA();f4();Om();wb();w1();var Wd4=G4(VW(),1);import{writeFile as Gd4}from"fs/promises";import Fd4 from"path";g0();GJ();class u11{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774310664-gcb98ac"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await W60(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ML extends l0{props;constructor(J){super();this.props=J}createState(){return new Dp4}}class Dp4 extends d0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Hp4 extends d0{controller=new X$;focusNode=new U6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new h1(Q.foreground,1,"solid")),F=new xZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),U=[];if(V)U.push(new C("Enter",new g({color:Y.keybind}))),U.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));U.push(new C("Esc",new g({color:Y.keybind}))),U.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let W=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,U)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),z,new h3,W]})})}}class Eo extends l0{props;constructor(J){super();this.props=J}createState(){return new Hp4}}import{isDeepStrictEqual as b11}from"node:util";var pC3=/[\\/_ +.#"@[({&]/,dC3=/[\\/_ +.#"@[({&]/g,cC3=/[\s-]/,Bp4=/[\s-]/g;function cF0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let F=Y.charAt(K),z=Q.indexOf(F,X),q=0,U,W,D,H;while(z>=0){if(U=cF0(J,Z,Q,Y,z+1,K+1,V),U>q){if(z===X)U*=1;else if(cC3.test(J.charAt(z-1))){if(U*=0.9,H=J.slice(X,z-1).match(Bp4),H&&X>0)U*=0.999**H.length}else if(pC3.test(J.charAt(z-1))){if(U*=0.8,D=J.slice(X,z-1).match(dC3),D&&X>0)U*=0.999**D.length}else if(U*=0.3,X>0)U*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(K))U*=0.9999}if(U<0.1&&(Q.charAt(z-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(z-1)!==Y.charAt(K))){if(W=cF0(J,Z,Q,Y,z+1,K+2,V),W*0.1>U)U=W*0.1}if(U>q)q=U;z=Q.indexOf(F,z+1)}return V[G]=q,q}function dF0(J){return J.toLowerCase().replace(Bp4," ")}function Np4(J,Z){let Q=cF0(J,Z,dF0(J),dF0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let F=cF0(J,G,dF0(J),dF0(G),0,0,{});if(F===0)return Q;X+=F,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class pv{}class dv{}class lF0{}class iF0{}class wp4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Lp4}}class Lp4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function lC3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Np4(Z,J);return{matches:Q>0.15,score:Q}}class r2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Op4}}class Op4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new X$(this.widget.props.controller?.query??""),this.focusNode=new U6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>b11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!b11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>b11(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof pv){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof dv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof lF0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof iF0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...lC3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;fv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new xZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),F=new d$({shortcuts:new Map([[new H4("ArrowDown"),new pv],[new H4("ArrowUp"),new dv],[new H4("Tab"),new pv],[new H4("Tab",{shift:!0}),new dv],[new H4("n",{ctrl:!0}),new pv],[new H4("p",{ctrl:!0}),new dv],[new H4("Enter"),new lF0],[new H4("Escape"),new iF0]]),focusNode:this.focusNode,child:G}),z=new A2({actions:new Map([[pv,new W6(this.invoke)],[dv,new W6(this.invoke)],[lF0,new W6(this.invoke)],[iF0,new W6(this.invoke)]]),child:F}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]});this.itemContexts=[];let U;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";U=new I0({height:10,child:new J4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)U=new k1({child:new J4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new wp4(new $4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});U=new x0({children:N,crossAxisAlignment:"start"})}let W=new $4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:U})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:W}),new i0({padding:C0.only({top:1}),child:new J4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:W}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function Ep4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class h11 extends e1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Ep4(X.pubDate).length));return new r2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,U=K?q.selectionBackground:void 0,W=K?q.selectionForeground:z.foreground,D=z.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new J0({text:new C(B,new g({color:D}))})])});return new i0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new J0({text:new C(X.title,new g({color:W})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(Ep4(X.pubDate),Q)]})})}})}}class g11 extends l0{createState(){return new Mp4}}class Mp4 extends d0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function iC3(J){return PY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function nC3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return LG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function m11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function aC3(J,Z,Q,Y){return[m11("+",J,Y.success),h3.horizontal(1),m11("~",Z,Y.warning),h3.horizontal(1),m11("-",Q,Y.destructive)]}function oC3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class nF0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Ap4}}class Ap4 extends d0{spinner=new F3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=nC3(z),U=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),W=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new J4({child:new J0({text:new C("",new g({color:W.colors.foreground,dim:!0}),[new C("Ctrl+T",new g({color:W.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:W.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(L)=>{if(L!==H)H=L,B=iC3(L);return B};return new r2({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!oC3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,S=O?j.selectionBackground:void 0,_=O?j.selectionForeground:R.foreground,f=R.mutedForeground,m=(s,z0)=>new I0({width:z0,child:q1.end([new J0({text:new C(s,new g({color:f}))})])}),x=Z.threadViewStates[L.id],T=[],u=L.relationshipType==="handoff",p=new na({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],z0=L.ancestorsAreLast.slice(1);for(let w0 of z0)s.push(new C(p.getAncestorPrefix(w0),new g({color:p.connectorColor,dim:p.connectorDim})));let a=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(a);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),T.push(new J0({text:new C("",void 0,s)}))}let d=[],h=F===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(kN(x))d.push(new g11),d.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(u)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:_})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:f,warning:f,destructive:f}:R;d.push(...aC3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,U)),new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...T,...d]})})}})}}function jp4(J){return 1-(1-J)**3}function Rp4(J,Z,Q){return J+(Z-J)*Q}function Mo(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=jp4(Y),V=jp4(X);return{x:Rp4(J.startOffset.x,J.targetOffset.x,K),y:Rp4(J.startOffset.y,J.targetOffset.y,V)}}var rC3={nodeWidth:3,horizontalSpacing:3};class cv{options;constructor(J={}){this.options={...rC3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,F)=>{let z=Z.get(G.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(z.length===0){Y.push({node:q,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let U=[];for(let B of z)U.push(V(B,F+1));let W=Math.min(...U),D=Math.max(...U),H=Math.floor((W+D)/2);return Y.push({node:q,position:{x:H,y:F}}),H};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var sC3={nodeWidth:3,nodeHeight:2};class lv{options;constructor(J={}){this.options={...sC3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var tC3={nodeWidth:3,nodeHeight:2},eC3={x:0,y:0};class oF0{options;constructor(J={}){this.options={...tC3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=eC3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],_=0;for(let f of R){if(f.position.x>_)S.push(new I0({width:f.position.x-_}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,T=K?.activeFlashOn??!1,u=f.node.id===K?.copyFlashNodeId;S.push(this.renderNode(m,x,T,u,q,z)),_=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,_=O+R*B+1,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:_,child:this.renderInfoBox(j,f,z,q)}))}return new i0({padding:C0.horizontal(2),child:new iG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,z=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",G="┗━┛",z=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:F,bold:z}))}),new J0({text:new C(G,new g({color:F,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((W)=>W.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,U=[new J0({text:new C(G,new g({color:z}))})];for(let W of X){let D=" ".repeat(K-W.length);U.push(new J0({text:new C("│ ",new g({color:z}),[new C(W+D,new g({color:q??z})),new C(" │",new g({color:z}))])}))}return U.push(new J0({text:new C(F,new g({color:z}))})),new x0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let W of Z){let D=W.position.x+G;if(D>=0&&D<Y)z[D]="▲"}V.push(new J0({text:new C(z.join(""),new g({color:F}))}));let q=Array(Y).fill(" ");for(let W of J){let D=Z.filter((L)=>L.node.parentID===W.node.id);if(D.length===0)continue;let H=W.position.x+G,B=D.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===H)if(D.length===1&&B[0]===H)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:F}))}));let U=Array(Y).fill(" ");for(let W of J){if(Z.filter((B)=>B.node.parentID===W.node.id).length===0)continue;let H=W.position.x+G;if(H>=0&&H<Y)U[H]="│"}return V.push(new J0({text:new C(U.join(""),new g({color:F}))})),V}}var $_3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},J_3={x:0,y:0};class p11{options;constructor(J={}){this.options={...$_3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=J_3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],_=0;for(let f of R){if(f.position.x>_)S.push(new I0({width:f.position.x-_}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,T=K?.activeFlashOn??!1;S.push(this.renderNode(m,x,T,q,z)),_=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,_=O+R*B,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:_,child:this.renderInfoBox(j,f,z)}))}return new i0({padding:C0.horizontal(2),child:new iG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new J0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let U=Z.filter((N)=>N.node.parentID===q.node.id);if(U.length===0)continue;let W=q.position.x+G,D=U.map((N)=>N.position.x+G),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===W,L=D.includes(N);if(w&&L)if(U.length===1)z[N]="│";else if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┼";else if(w)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┬";else if(L)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┴";else if(z[N]===" ")z[N]="─"}}return V.push(new J0({text:new C(z.join(""),new g({color:F}))})),V}}class Ao extends s3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Ip4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Ip4 extends v4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class hR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new _p4}}var Pp4=400,Cp4=300,Z_3=16;class _p4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new cv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new lv;renderer=new p11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let z=this.widget.props.threads.find((q)=>q.id===K);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),G=this.widget.props.threads.some((F)=>F.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Pp4,durationY:Cp4};let Z=Math.max(Pp4,Cp4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Mo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Z_3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,F=Math.floor(this.viewportHeight/2),q=Math.floor(F/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((U)=>U.node.id===this.selectedNodeId):null)??this.positionedNodes.find((U)=>!U.node.parentID);if(q){let U=Math.max(...this.positionedNodes.map((W)=>W.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,U)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),F=new Ao({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Sp4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new kp4}}class kp4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var Tp4=30,Q_3=30;class iv{}class nv{}class rF0{}class sF0{}class d11 extends l0{props;constructor(J){super();this.props=J}createState(){return new yp4}}class yp4 extends d0{highlightedIndex=0;controller=new X$;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new U6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;fv(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof iv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof nv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof rF0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof sF0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=Q_3+Tp4,F=c1.all(new h1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),U=new xZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new d$({shortcuts:new Map([[new H4("ArrowDown"),new iv],[new H4("ArrowUp"),new nv],[new H4("Tab"),new iv],[new H4("Tab",{shift:!0}),new nv],[new H4("n",{ctrl:!0}),new iv],[new H4("p",{ctrl:!0}),new nv],[new H4("Enter"),new rF0],[new H4("Escape"),new sF0]]),focusNode:this.focusNode,child:U}),D=new A2({actions:new Map([[iv,new W6(this.invoke)],[nv,new W6(this.invoke)],[rF0,new W6(this.invoke)],[sF0,new W6(this.invoke)]]),child:W}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,S=j?X.selectionBackground:void 0,_=j?X.selectionForeground:Y.foreground,f=[new C(M.label,new g({color:_})),new C(` (${M.threads.length})`,new g({color:_,dim:!0}))];if(R)f.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Sp4(new $4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,f)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new $4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=z?z.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=z?new i0({padding:C0.all(1),child:new hR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:Tp4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new $4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class hJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!hJ._instance)hJ._instance=new hJ;return hJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}g0();class vp4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new r2({title:"Add Label",items:F,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:K||"Type to create a new label",renderItem:(z,q,U,W)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:H})),new C(N,new g({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(z.name,new g({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let W=q.trim().toLowerCase();return W.length===0||z.name.includes(W)},sortItems:(z,q,U)=>{let W="__isCreateMarker"in z.item&&z.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(W&&!D)return-1;if(!W&&D)return 1;return q.score-z.score}})}}class c11 extends l0{props;constructor(J){super();this.props=J}createState(){return new vp4}}class $F extends l0{props;constructor(J){super();this.props=J}createState(){return new xp4}}class xp4 extends d0{_spinner=new F3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=c1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),F=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let z=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}var jo={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},tF0=["workspace","global","flag","default","external","skill","other"];function Y_3(J){return Array.from(new Set(J))}function fp4(J){return Y_3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function av(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return fp4(J).length>0?"skill":"other"}function l11(J){return av(J)==="skill"}function up4(J){let Z=fp4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=av(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${jo[Y].description}: ${Q}`}function bp4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var hp4=process.platform==="win32"?" ":"█",gp4=process.platform==="win32"?"░":"█";class O9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=hp4,thumbChar:K=gp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createState(){return new mp4}}class mp4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),G=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),z=X-G,q=Math.max(0,z*F),U=q+G;return J>=q&&J<=U}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,G=Math.min(1,Q/Z),F=Math.max(1,K*G),z=K-F;if(z<=0)return;let q=Z-Q,U=z/q,W=V/U,D=Math.max(0,Math.min(q,this._dragStartOffset+W));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let G=Math.min(1,Y/Q),F=Math.max(1,V*G),z=Q-Y,q=V-F,U=Math.max(0,Math.min(1,X/(Q-Y))),W=Math.max(0,q*U),D=W+F;if(Z>=W&&Z<=D)return;if(Z<W)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new $4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?d5.POINTER:d5.DEFAULT,child:new pp4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class pp4 extends ky{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=hp4,thumbChar:K=gp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createRenderObject(){return new dp4(this)}updateRenderObject(J){J.updateWidget(this)}}class dp4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,G=this._widget.thumbColor,F=process.platform==="win32",z=Y,q=Y+X;if(!F){let U=["▁","▂","▃","▄","▅","▆","▇","█"];for(let W=0;W<this.size.height;W++){let D="█",H=!0;if(W===Math.floor(z)){let B=1-(z-W),N=Math.floor(B*8);D=U[N]||"█",H=!1}else if(W===Math.floor(q)){let B=1-(q-W),N=Math.floor(B*8);D=U[N]||"█"}else if(W>z&&W<q)H=!1;J.setChar(Z,Q+W,D,{fg:G,bg:V,reverse:H},1)}return}for(let U=0;U<this.size.height;U++){let W=U+0.5,D=W>=z&&W<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+U,H,{fg:D?G:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class gR extends l0{props;constructor(J){super();this.props=J}createState(){return new cp4}}class cp4 extends d0{scrollController=new j5;scrollAreaKey=new $$("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(J){return J instanceof o2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=IF0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),F=new k1({child:new c$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new O9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,U=this.scrollController.offset,W=this.getViewportHeight(),D=q+W;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(W,1),scrollOffset:Math.max(U,0)}}})]})})})}),z=new i0({padding:C0.symmetric(1,0),child:new J0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let U=new g({color:Z.app.keybind}),W=new g({color:Z.colors.foreground,dim:!0});return new C("",W,[new C("Press ",W),new C("Escape",U),new C(" to close • Use ",W),new C("↑↓",U),new C(" or ",W),new C("j/k",U),new C(" to scroll",W)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.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 i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),F,z]})})})}}T2();class lp4 extends l0{props;constructor(J){super();this.props=J}createState(){return new ip4}}class ip4 extends d0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=k9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,z)=>F+z.registeredCommands.length,0),G=this.plugins.reduce((F,z)=>F+z.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${G} ${d4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
7391
7393
 
7392
7394
  `));for(let F of this.plugins){let{icon:z,color:q}=this.statusIcon(F.status),U=this.getRelativePath(F.uri.toString());if(Y.push(new C(`${z} `,new g({color:q}))),Y.push(new C(U,new g({bold:!0}))),Y.push(new C(` ${F.status}`,new g({dim:!0}))),Y.push(new C(`
7393
7395
  `)),F.status==="active"&&F.registeredEvents.length>0)Y.push(new C(" Events: ",new g({dim:!0}))),Y.push(new C(F.registeredEvents.join(", "),new g({color:Q.link}))),Y.push(new C(`
@@ -7616,7 +7618,7 @@ ${Y0.content||""}`:Y0.content||"",$1=[],B1=Y0.baseDir.startsWith("file://")?fz0(
7616
7618
  `),process.exit(1)}process.stdout.write(await ny3(F.result.displayText)+`
7617
7619
  `),process.exit(0)})}VA();import{stdout as ay3}from"node:process";function oy3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${kz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function xi4(J){ay3.write(`${oy3(J)}
7618
7620
  `)}function fi4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{xi4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{xi4(Z),process.exit(0)})}var Bb3=pL.join(ZQ,"logs","headless.log"),w31=pL.join(Sy,"device-id.json");async function Nb3(){for(let J of IE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => G4(Ax(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){j7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7619
- `)}function wb3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function t2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")ZZ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")ZZ("experimental.agentMode",Z.mode)}function Dr4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Lb3(J){try{return await Ur4(J,"utf-8")}catch{return J}}async function L31(J,Z,Q){let Y=Dr4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!j31(X,T7.HARNESS_SYSTEM_PROMPT)&&!Hr4(K))throw new P1("You are not allowed to do this.",1);ZZ("systemPrompt",await Lb3(Y))}function Hr4(J){return!!(J&&G40(J))}function j31(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function O31(J){return(J.userEmail?JZ(J.userEmail):!1)||j31(J.features,T7.DTW_TUI)}function Yr4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function E31(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return O31({userEmail:Z.user.email,features:Z.features})}function M31(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ob3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function Iq0(J){let Y=Ob3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Xr4(J){if(!V5.write(J))await Ub3(V5,"drain")}var Kr4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??hK,description:`Custom settings file path (overrides the default location ${hK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Yj})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:n2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:lF.SMART.key,description:`Set the agent mode (${SV().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SV().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"optional-option",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",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}],Vr4=(J)=>("deprecated"in J)&&J.deprecated===!0,Eb3=(J)=>("hidden"in J)&&J.hidden===!0,Mb3=(J)=>("default"in J),Ab3=(J)=>("default"in J)?J.default:void 0,Br4=[{name:"toggle-skills-count",entryPoint:er0}];function jb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(M3.unknownCommand(Q),1,V)}}async function R31(J){return{...J,getThreadEnvironment:AZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new aV(J.fileSystem),generateThreadTitle:y90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>VQ(J.configService),pluginService:J.pluginService}}function Nr4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:AZ,filesystem:J.fileSystem,threadService:J.threadService}}var Pq0=X1.file(Wr4.homedir()),A31=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(Pq0,".config");function Rb3(J){return SW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){TW4(Z);let Q=hK0(),Y=Ds0();if((!Q||Y||Ok4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(TD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(TD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(hK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Ib3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function J2(J,Z,Q){let Y=Q?.deferAuth??!1;Su1("0.0.1774286630-gfbf924");let X=E40({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(X1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Pq0,userConfigDir:A31});Lk4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let z0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(z0),P.info("API key lookup before login",{found:Boolean(z0),ampURL:J.ampURL,deferAuth:Y}),!z0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{V5.write(`No API key found. Starting login flow...
7621
+ `)}function wb3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function t2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")ZZ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")ZZ("experimental.agentMode",Z.mode)}function Dr4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Lb3(J){try{return await Ur4(J,"utf-8")}catch{return J}}async function L31(J,Z,Q){let Y=Dr4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!j31(X,T7.HARNESS_SYSTEM_PROMPT)&&!Hr4(K))throw new P1("You are not allowed to do this.",1);ZZ("systemPrompt",await Lb3(Y))}function Hr4(J){return!!(J&&G40(J))}function j31(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function O31(J){return(J.userEmail?JZ(J.userEmail):!1)||j31(J.features,T7.DTW_TUI)}function Yr4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function E31(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return O31({userEmail:Z.user.email,features:Z.features})}function M31(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ob3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function Iq0(J){let Y=Ob3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Xr4(J){if(!V5.write(J))await Ub3(V5,"drain")}var Kr4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??hK,description:`Custom settings file path (overrides the default location ${hK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Yj})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:n2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:lF.SMART.key,description:`Set the agent mode (${SV().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SV().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"optional-option",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",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}],Vr4=(J)=>("deprecated"in J)&&J.deprecated===!0,Eb3=(J)=>("hidden"in J)&&J.hidden===!0,Mb3=(J)=>("default"in J),Ab3=(J)=>("default"in J)?J.default:void 0,Br4=[{name:"toggle-skills-count",entryPoint:er0}];function jb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(M3.unknownCommand(Q),1,V)}}async function R31(J){return{...J,getThreadEnvironment:AZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new aV(J.fileSystem),generateThreadTitle:y90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>VQ(J.configService),pluginService:J.pluginService}}function Nr4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:AZ,filesystem:J.fileSystem,threadService:J.threadService}}var Pq0=X1.file(Wr4.homedir()),A31=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(Pq0,".config");function Rb3(J){return SW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){TW4(Z);let Q=hK0(),Y=Ds0();if((!Q||Y||Ok4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(TD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(TD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(hK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Ib3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function J2(J,Z,Q){let Y=Q?.deferAuth??!1;Su1("0.0.1774310664-gcb98ac");let X=E40({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(X1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Pq0,userConfigDir:A31});Lk4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let z0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(z0),P.info("API key lookup before login",{found:Boolean(z0),ampURL:J.ampURL,deferAuth:Y}),!z0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{V5.write(`No API key found. Starting login flow...
7620
7622
  `);let a=await Pb3(J),q0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:a,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!a)await YD(),process.exit(1);V=!0}}{let z0=await X.getLatest(),a=z0.settings.url,q0=z0.secrets.isSet?.[a];P.info("Config secrets state after login",{configURL:a,apiKeySet:q0?.apiKey??!1})}let G=M1(VQ(X).pipe(E5((z0)=>z0!=="pending"))),F=Y?"pending":await G;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(F),isError:iU(F),errorMessage:iU(F)?F.error.message:void 0});let{toolService:z,dispose:q}=RW4({configService:X}),U=new Map,W=()=>U.clear(),D=new XS0(X,J.settings.getWorkspaceRootPath()),H=Te1({configService:X,filesystem:j8}),B=Ro1({configService:X,trustStore:D,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(z0,a,q0)=>{let w0=`${z0}:${a}`,F0=U.get(w0);if(F0)return P.debug("Reusing existing OAuth provider for server",{serverName:z0,serverUrl:a}),F0;P.debug("Creating OAuth provider for server",{serverName:z0,serverUrl:a});let $0=(async()=>{let W0=new xE(J.secrets),i=await W0.getClientInfo(z0,a),o=q0?.scopes??i?.scopes,e=eC4();P.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:V5.isTTY});let Q0;if(e)Q0=J.executeMode?tC4():sC4(z0);let Y0=new hI0({storage:W0,serverName:z0,serverUrl:a,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:o,headlessAuthHandler:Q0});return P.debug("OAuth provider created",{serverName:z0,serverUrl:a,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:o,headlessMode:e,executeMode:J.executeMode}),Y0})();return U.set(w0,$0),$0}}),N=Wp0({configService:X,filesystem:j8,spawn:yJ0}),w;if(J.executeMode){let z0=await _z4({toolService:z,providers:[B,N],initialTimeout:15000});w=z0.registrations;for(let[a,q0]of z0.initErrors)P.warn(`${a} provider initialization slow or failed:`,q0)}else w=Dp0({toolService:z,providers:[B,N]});if(Z.jetbrains)ME("JetBrains");else if(Z.ide&&u_4())ME("VS Code");else if(Z.ide&&b_4())ME("Neovim");else if(Z.ide){let z0=await Nb3();if(z0){let a=T40(z0.ideName);if(a)ME(a)}}if(J.executeMode)ku1(!0);let L,O=E$.status.pipe(U1((z0)=>Boolean(z0.connected&&z0.authenticated&&z0.ideName&&Bb1(z0.ideName))),y4()).subscribe((z0)=>{if(z0){if(!L)L=z.registerTool(Cz4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let z0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new HQ0(process.cwd(),{alwaysIncludePaths:z0},!0)}else E=new class extends HQ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await fe1({isDevelopment:!1}),A=new Kv0(M,X),j=new rk0(M,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=Z.takeMeBack?!1:void 0,S=E31(R,F),_=Boolean(S||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let f=_?Ib3():H14({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;E$.status.subscribe((z0)=>{m=z0});let x=new RR0({workspaceRoots:[X1.file(process.cwd())],fileSystem:j8,getCurrentFile:()=>{if(!m?.openFile)return;try{return X1.parse(m.openFile)}catch(z0){P.warn("Failed to parse current file URI",{uri:m.openFile,error:z0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let z0=m.openFile;return m.visibleFiles.filter((a)=>a!==z0).map((a)=>{try{return X1.parse(a)}catch(q0){return P.warn("Failed to parse visible file URI",{uri:a,error:q0}),null}}).filter((a)=>a!==null)}}),T=new Ns0,u=process.env.PLUGINS??"off",p=Z.headless?Qk4():void 0,d=p??new yK0({configService:X}),h=d instanceof yK0?d:void 0;if(h)h.pluginExecutorKind=S?"local":"unknown";let n=ES0({configService:X,fileSystem:j8,platform:d,internalPlugins:Br4,pluginFilter:u}),c=Lr1({pluginService:n,toolService:z}),s={codebaseContextService:x,configService:X,toolService:z,mcpService:B,skillService:H,toolboxService:N,trustStore:D,threadService:A,threadHistoryService:j,threadSyncService:f,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:j8,terminal:T,pluginService:n,pluginPlatform:h,headlessPluginPlatform:p,serverStatus:F,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let z0 of w.values())z0.dispose();await s.mcpService.dispose(),W(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),q(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function Pb3(J){if(!J.executeMode){if(!await TK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return V5.write(`Login cancelled. Run the command again to retry.
7621
7623
  `),!1}return await wr4(J)}async function wr4(J){let Z=qb3(32).toString("hex"),Q=await hy(J.ampURL,Z),Y=new AbortController;try{await CV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await hy(J.ampURL,Z,!1);V5.write(`If your browser does not open automatically, visit:
7622
7624
 
@@ -7624,7 +7626,7 @@ ${c0.blue.bold(X)}
7624
7626
 
7625
7627
  `);try{return await fS4(J.ampURL,Z,J.secrets,Y),V5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),j7.write(`
7626
7628
  Login failed: ${K instanceof Error?K.message:String(K)}
7627
- `),!1}}function Gr4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Cb3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function _b3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Tb3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!_b3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Sb3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function kb3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function yb3(){let J=new $w().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Kj(),process.exit(0);let B=H.originalError??H;OL4(B)}),fi4(J,{version:"0.0.1774286630-gfbf924",buildTimestamp:"2026-03-23T17:27:39.620Z",buildType:"'release'"}),J.addHelpText("after",v_4()),J.configureHelp({formatHelp:x_4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await p3(N);await gb3(w)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await p3(N);await hb3(w,await eo0(N,w.settings))}),J.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(H,B,N)=>{let w=N.optsWithGlobals(),L=await p3(w);await iL4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),J.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(H,B)=>{let N=B.optsWithGlobals(),w=await p3(N);await nL4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7629
+ `),!1}}function Gr4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Cb3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function _b3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Tb3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!_b3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Sb3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function kb3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function yb3(){let J=new $w().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Kj(),process.exit(0);let B=H.originalError??H;OL4(B)}),fi4(J,{version:"0.0.1774310664-gcb98ac",buildTimestamp:"2026-03-24T00:08:19.172Z",buildType:"'release'"}),J.addHelpText("after",v_4()),J.configureHelp({formatHelp:x_4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await p3(N);await gb3(w)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await p3(N);await hb3(w,await eo0(N,w.settings))}),J.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(H,B,N)=>{let w=N.optsWithGlobals(),L=await p3(w);await iL4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),J.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(H,B)=>{let N=B.optsWithGlobals(),w=await p3(N);await nL4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7628
7630
  Actions:
7629
7631
  create Create a new DTW thread and print its ID
7630
7632
  add-message <message> Send a user message and wait for message_added
@@ -7688,8 +7690,8 @@ ${E}
7688
7690
 
7689
7691
  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 vb3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new aa({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:AZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new aV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function xb3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await cy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await cy()).trimEnd(),stdinInput:null}}function fb3(J,Z,Q){if(J.remote&&!Z)throw new P1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new P1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new P1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new P1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new P1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new P1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new P1("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(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new P1("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"
7690
7692
  Or pipe via stdin: echo "your message" | amp --execute`)}async function Cq0(J,Z,Q){let Y=process.hrtime.bigint(),X=(F0,$0)=>{let W0=Number(process.hrtime.bigint()-$0)/1e6,i=OD4();P.info("Startup phase",{phase:F0,phaseMs:Math.round(W0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await xb3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;fb3({...Z,streamJson:G},J.executeMode,K),t2(Q,Z);let F=process.hrtime.bigint(),z=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&!Z.threadActors&&z;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:z,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await J2(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let W=await R31(U);X("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!q&&iU(D)){let F0=Sk(Error(D.error.message));if(F0.message===M3.networkOffline||F0.message===M3.networkTimeout)throw Iq0(J.ampURL);throw new P1(M3.invalidAPIKey,1)}let H=m6(D)?D:null,B=H?.user.email,N=Hr4(B),w=O31({userEmail:B,features:H?.features}),L=Z.takeMeBack?!1:void 0,O=H!==null&&E31(L,H);if(!q)await L31(Q,Z,D);let E=M31(D),M=E?.features??[],A=E?.team??null,j=SK0(Z,E);if(j instanceof Error)d3(j.message);if((J.executeMode||G)&&E8(Z.mode)&&!N)throw new P1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!JB(Z.mode,B))throw new P1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Kk4(K,V,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!JZ(B))throw new P1("Headless DTW mode is only available for Amp employees",1);let F0=await U.secretStorage.get("apiKey",J.ampURL);if(!F0)throw new P1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!b9($0))throw new P1(`Invalid thread ID: ${$0}`,1);let W0=$0??await ab3({dependencies:U,visibility:j??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=await Q_4(W0);if(i.status==="already-running")await U.asyncDispose(),await YD(),process.exit(0);try{await rC4({ampURL:J.ampURL,apiKey:F0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:W0,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await i.release(),await U.asyncDispose()}await YD(),process.exit(0)}let R=J.executeMode?void 0:async(F0)=>Br(F0,"interactive"),S={threadService:U.threadService,workerDeps:W,createThread:async()=>{let F0=q?await U.serverStatusPromise:D,$0=await $Q0(J.settings,process.cwd(),M31(F0),j);if($0 instanceof Error)d3($0.message);return k01(W,{threadMeta:$0?dG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(F0,$0)=>{if($0?.nonBlockingOwnershipCheck){Fr4(F0,U.configService).catch((W0)=>{if(W0 instanceof P1){if($0.onOwnershipError){$0.onOwnershipError(W0,F0);return}kk(W0,F0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})});return}try{await Fr4(F0,U.configService)}catch(W0){if(W0 instanceof P1)throw W0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:R},_=async(F0)=>{try{if(F0==="dtw")return vb3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Dh4(S,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof P1)throw $0;throw await kk($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")j7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7691
- `),await YD(),process.exit(1);let f=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await U.configService.getLatest(),$0=hb(F0),W0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout($0)});if(W0.ok)return P.info("User free tier status:",W0),W0.result;return}catch(F0){P.error("Failed to fetch free tier status:",F0);return}})(),x=!J.executeMode?new I01:null,T,u=null;if(x)T=x,u=(async()=>{let F0=q?await U.serverStatusPromise:U.serverStatus;await L31(Q,Z,F0);let $0=process.hrtime.bigint(),W0=E31(L,F0),i=m6(F0)?O31({userEmail:F0.user.email,features:F0.features}):!1;Yr4({dtwEnabled:W0,hasV2TUIAccess:i});let o=await _(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(o),K){let e=await M1(o.threadHandles$);if(!e)throw new P1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));x.setInitError($0),await kk(F0,Z.threadId)});else F=process.hrtime.bigint(),Yr4({dtwEnabled:O,hasV2TUIAccess:w}),T=await _(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let d=await U.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),Rb3({configService:U.configService,threadService:U.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>T.threadHandles$.pipe(q4((F0)=>{if(!F0)return k0.of({});return F5(F0.thread$,F0.threadViewState$).pipe(U1(([$0,W0])=>({[$0.id]:W0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){aS4(U.mcpService,J.settings);let F0={userInput:K,stdinInput:V,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await SL4({threadPool:T,...F0});if(await Br($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Mb1();let F0=await CE({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)h=!await U.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)E$.selectConfig($0)}else n=!0}F=process.hrtime.bigint();let c=Lr0("0.0.1774286630-gfbf924",U.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let s=new ok0(U.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let z0=new tr0(U.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let F0=await M1(T.threadHandles$);if(!F0)throw new P1("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let a=await xK0();X("runMainThread:loadSessionState",F),P.info("Loaded session state:",a);let q0={...a,launchCount:a.launchCount+1};rj((F0)=>({...F0,launchCount:F0.launchCount+1}));let w0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Qg4({codebaseContextService:U.codebaseContextService,history:new Sl0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,threadHistoryService:U.threadHistoryService,threadFuzzyIndexer:s,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:T,createSystemPromptDeps:async()=>Nr4(U),ideClient:E$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:z0,updateService:c,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:w0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:f,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-23T17:27:39.620Z"},(F0)=>new l01({...F0,threadPool:F0.threadPool},($0)=>new c61({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await U.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function p3(J){if(P.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)}),J.interactive)j7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7692
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await To1({get:async(G)=>{if(G!==yg)return;try{let F=await Ur4(w31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==yg)return;await qr4(pL.dirname(w31),{recursive:!0}),await Wb3(w31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:dF()});yu1(Y);let X=await B_4({...J,workspaceTrust:{current:!0,changes:Ob},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await iS4(J.mcpConfig);X=nS4(X,G)}let K=pL.dirname(X.getSettingsFilePath());_W4(Sy,K);let V=await X.get("url","global");if(!V)V=z2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!_V(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Au1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:qk4(await eo0(J,X))}}function ub3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function bb3(){LD4();let J=ub3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));kw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Bb3:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)c0.level=0;if(wb3(P),P.info("Starting Amp CLI.",{version:"0.0.1774286630-gfbf924",buildTimestamp:"2026-03-23T17:27:39.620Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await yb3().parseAsync(process.argv)}PW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await bb3().catch(kk)});async function hb3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),V5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7693
+ `),await YD(),process.exit(1);let f=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await U.configService.getLatest(),$0=hb(F0),W0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout($0)});if(W0.ok)return P.info("User free tier status:",W0),W0.result;return}catch(F0){P.error("Failed to fetch free tier status:",F0);return}})(),x=!J.executeMode?new I01:null,T,u=null;if(x)T=x,u=(async()=>{let F0=q?await U.serverStatusPromise:U.serverStatus;await L31(Q,Z,F0);let $0=process.hrtime.bigint(),W0=E31(L,F0),i=m6(F0)?O31({userEmail:F0.user.email,features:F0.features}):!1;Yr4({dtwEnabled:W0,hasV2TUIAccess:i});let o=await _(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(o),K){let e=await M1(o.threadHandles$);if(!e)throw new P1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));x.setInitError($0),await kk(F0,Z.threadId)});else F=process.hrtime.bigint(),Yr4({dtwEnabled:O,hasV2TUIAccess:w}),T=await _(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let d=await U.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),Rb3({configService:U.configService,threadService:U.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>T.threadHandles$.pipe(q4((F0)=>{if(!F0)return k0.of({});return F5(F0.thread$,F0.threadViewState$).pipe(U1(([$0,W0])=>({[$0.id]:W0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){aS4(U.mcpService,J.settings);let F0={userInput:K,stdinInput:V,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await SL4({threadPool:T,...F0});if(await Br($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Mb1();let F0=await CE({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)h=!await U.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)E$.selectConfig($0)}else n=!0}F=process.hrtime.bigint();let c=Lr0("0.0.1774310664-gcb98ac",U.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let s=new ok0(U.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let z0=new tr0(U.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let F0=await M1(T.threadHandles$);if(!F0)throw new P1("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let a=await xK0();X("runMainThread:loadSessionState",F),P.info("Loaded session state:",a);let q0={...a,launchCount:a.launchCount+1};rj((F0)=>({...F0,launchCount:F0.launchCount+1}));let w0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Qg4({codebaseContextService:U.codebaseContextService,history:new Sl0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,threadHistoryService:U.threadHistoryService,threadFuzzyIndexer:s,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:T,createSystemPromptDeps:async()=>Nr4(U),ideClient:E$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:z0,updateService:c,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:w0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:f,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-24T00:08:19.172Z"},(F0)=>new l01({...F0,threadPool:F0.threadPool},($0)=>new c61({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await U.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function p3(J){if(P.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)}),J.interactive)j7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7694
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await To1({get:async(G)=>{if(G!==yg)return;try{let F=await Ur4(w31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==yg)return;await qr4(pL.dirname(w31),{recursive:!0}),await Wb3(w31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:dF()});yu1(Y);let X=await B_4({...J,workspaceTrust:{current:!0,changes:Ob},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await iS4(J.mcpConfig);X=nS4(X,G)}let K=pL.dirname(X.getSettingsFilePath());_W4(Sy,K);let V=await X.get("url","global");if(!V)V=z2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!_V(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Au1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:qk4(await eo0(J,X))}}function ub3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function bb3(){LD4();let J=ub3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));kw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Bb3:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)c0.level=0;if(wb3(P),P.info("Starting Amp CLI.",{version:"0.0.1774310664-gcb98ac",buildTimestamp:"2026-03-24T00:08:19.172Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await yb3().parseAsync(process.argv)}PW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await bb3().catch(kk)});async function hb3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),V5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7693
7695
  `);else if(!_V(J.ampURL))V5.write(`Logging in to ${new URL(J.ampURL).hostname}
7694
7696
  `);let Y=process.env.AMP_API_KEY;if(Y)V5.write(`API key found in environment variable, storing...
7695
7697
  `),await Z.set("apiKey",Y,J.ampURL),V5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1774286630-gfbf924",
3
+ "version": "0.0.1774310664-gcb98ac",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {