@sourcegraph/amp 0.0.1773982701-g41d390 → 0.0.1773994045-ge5da52

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/main.js +41 -83
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -11,7 +11,7 @@ Amp has [3 agent modes](https://ampcode.com/models):
11
11
 
12
12
  - `smart`: unconstrained state-of-the-art model use (Claude Opus 4.6, GPT-5.4, and more)
13
13
  - `rush`: fast and efficient, for narrowly defined tasks (Claude Haiku 4.5)
14
- - `deep`: deep reasoning with GPT-5.4 for extended thinking on complex problems
14
+ - `deep`: deep reasoning with GPT-5.3 Codex for extended thinking on complex problems
15
15
 
16
16
  <br/>
17
17
 
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 Xr(J){let Z=0,Q=0,Y=0;return J.messages.forEach((X)=>{if(X.role!=="assistant")return;X.content.forEach((K)=>{let V=Tj1(K);if(!V)return;let{name:z,input:F}=V,q=null;if(z==="edit_file"){if("old_str"in F&&"new_str"in F){let{old_str:G,new_str:D}=F;q=KU(G,D)}}else if(z==="apply_patch"){let G=_j1(F);q=KN0(G.map((D)=>D.diffStat))}else if((z==="write_file"||z==="create_file")&&"content"in F&&typeof F.content==="string")q=VU(F.content);if(q)Z+=q.added,Y+=q.deleted,Q+=q.changed})}),{added:Z,changed:Q,deleted:Y}}function Sj1(J){let Z=new Map;return J.messages.forEach((Q)=>{if(Q.role!=="assistant")return;Q.content.forEach((Y)=>{let X=Tj1(Y);if(!X)return;let{name:K,input:V}=X,z,F=null;if(K==="edit_file"){if("path"in V&&typeof V.path==="string"&&"old_str"in V&&"new_str"in V){z=V.path;let{old_str:q,new_str:G}=V;F=KU(q,G)}}else if(K==="apply_patch"){for(let q of _j1(V)){let G=Aj1(q.path,J.env?.initial?.trees);if(G){let D=Z.get(G)??{added:0,changed:0,deleted:0};D.added+=q.diffStat.added,D.changed+=q.diffStat.changed,D.deleted+=q.diffStat.deleted,Z.set(G,D)}}return}else if((K==="write_file"||K==="create_file")&&"path"in V&&typeof V.path==="string"&&"content"in V&&typeof V.content==="string")z=V.path,F=VU(V.content);if(z&&F){let q=Aj1(z,J.env?.initial?.trees);if(q){let G=Z.get(q)??{added:0,changed:0,deleted:0};G.added+=F.added,G.changed+=F.changed,G.deleted+=F.deleted,Z.set(q,G)}}})}),Z}function Aj1(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 z of Z){if(!z.uri)continue;let F=z.uri.match(/^file:\/\/(.+)$/);if(!F?.[1])continue;let q=decodeURIComponent(F[1]).replace(/\\/g,"/"),G=q.startsWith("/")&&/^\/[a-zA-Z]:/.test(q)?q.slice(1):q;if(X.startsWith(G)){let D=X.slice(G.length);return D.startsWith("/")?D.slice(1):D}}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 Kr(){return _o((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 bA1(J,Z)})}function Mj(J,Z){let Q=J.relationships?.filter((K)=>K.role==="child")??[],Y=ty(J),X=[...Q,...Y];return Z?X.filter((K)=>K.type===Z):X}function Vr(J,Z){return Mj(J,Z)[0]}function xJ(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user")return Q}return}function sy(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 ty(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!==Vq)return;if(!X8(K))return;let V=K.input;if(V.threadID&&N8(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 A4=Q0(()=>{H1();n7();JN0();h0();H4();Yw();vo()});var K4=Q0(()=>{vy();jo();zj()});import rD6 from"os";import zr from"path";var FU,Kw,qU,Aj,vj1,pH3,dH3,sD6,tD6;var ey=Q0(()=>{FU=rD6.homedir(),{env:Kw}=process,qU=Kw.XDG_DATA_HOME||(FU?zr.join(FU,".local","share"):void 0),Aj=Kw.XDG_CONFIG_HOME||(FU?zr.join(FU,".config"):void 0),vj1=Kw.XDG_STATE_HOME||(FU?zr.join(FU,".local","state"):void 0),pH3=Kw.XDG_CACHE_HOME||(FU?zr.join(FU,".cache"):void 0),dH3=Kw.XDG_RUNTIME_DIR||void 0,sD6=(Kw.XDG_DATA_DIRS||"/usr/local/share/:/usr/share/").split(":");if(qU)sD6.unshift(qU);tD6=(Kw.XDG_CONFIG_DIRS||"/etc/xdg").split(":");if(Aj)tD6.unshift(Aj)});import{homedir as Fr}from"node:os";import Fq from"node:path";var xj1,eD6,uj1,$U6,jj,JU6,Rj,ZU6,uJ;var KY=Q0(()=>{ey();xj1=Fq.join(Fr(),".local/share"),eD6=process.platform==="win32"||process.platform==="darwin"?xj1:qU??xj1,uj1=Fq.join(Fr(),".config"),$U6=process.platform==="win32"||process.platform==="darwin"?uj1:Aj??uj1,jj=Fq.join(eD6,"amp"),JU6=Fq.join($U6,"amp"),Rj=Fq.join(JU6,"tools"),ZU6=process.platform==="win32"?Fq.join(process.env.LOCALAPPDATA??Fq.join(Fr(),"AppData","Local"),"amp"):Fq.join(process.env.XDG_CACHE_HOME??Fq.join(Fr(),".cache"),"amp"),uJ=ZU6});function YU6(){return!1}function fj1(J){return J.trim().toLowerCase()}function XU6(J){if(!J.endsWith("@sourcegraph.com"))return!1;if(YU6())return!0;return QU6.has(J)}function qr(J){let Z=fj1(J);if(Z.length===0)return!1;return Z.endsWith("@sourcegraph.com")||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}function bZ(J){let Z=fj1(J);if(Z.length===0)return!1;return XU6(Z)||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}var QU6;var Vw=Q0(()=>{QU6=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 _4(J,Z,Q=Z+"s"){return J===1?Z:Q}var m9=()=>{};function WN0(J){return Gr[J]??0}function KU6(J){return typeof J==="number"&&Number.isInteger(J)&&J>=1&&J<=3600}function hj1(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=WN0("amp.tools.inactivityTimeout");if(!KU6(Y))return null;return Y*1000}function gj1(J){let Z=J.settings["tools.stopTimeout"],Q=WN0("amp.tools.stopTimeout");return(Z??Q)*1000}function $v(J){let Z=J.settings["network.timeout"],Q=WN0("amp.network.timeout");return(Z??Q)*1000}var Gr,bj1;var Ij=Q0(()=>{Gr={"amp.tools.inactivityTimeout":300,"amp.tools.stopTimeout":300,"amp.network.timeout":30},bj1={"amp.tools.inactivityTimeout":{default:Gr["amp.tools.inactivityTimeout"]},"amp.tools.stopTimeout":{default:Gr["amp.tools.stopTimeout"]},"amp.network.timeout":{default:Gr["amp.network.timeout"]}}});function AU6(J){return rj1.safeParse(J)}function DU(J){return MU6.safeParse(J)}function _j(J){if(!J||!Array.isArray(J))return[];let Z=[];for(let[Q,Y]of J.entries()){let X=AU6(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}`;R.warn(`Permission entry for tool "${K}" is invalid: ${X.error.issues.map((V)=>`${V.path.join(".")}: ${V.message}`).join(", ")}`)}}return Z}var AN0,rj1,MU6;var Fw=Q0(()=>{kJ();h0();AN0=m.lazy(()=>m.union([m.string().describe('Pattern match where "*" matches any number of any characters'),m.array(AN0).min(1).describe("OR match of each entry"),m.boolean().describe("A literal boolean match"),m.number().describe("A literal number match"),m.null().describe("A literal null match"),m.undefined().describe("A literal undefined match"),m.record(m.string(),AN0).describe("Matching individual keys of an object")])),rj1=m.object({tool:m.string().min(1).describe("The name of the tool to which this entry applies"),matches:m.record(m.string(),AN0).optional().describe("Maps tool inputs to conditions"),action:m.enum(["allow","reject","ask","delegate"]).describe("How Amp should proceed in case of a match"),context:m.enum(["thread","subagent"]).optional().describe("Only apply this entry in this context"),to:m.string().min(1).optional().describe('Command to delegate to when action is "delegate"'),message:m.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"]})}),MU6=m.array(rj1).describe("Entries checked in sequence to configure tool permissions")});function E9(J,Z){let Q=jU6(J,Z);return typeof Q==="string"?Q:Q.toString()}function jU6(J,Z,Q=!0){if(!Z)Z=RU6();let{workspaceFolders:Y,isWindows:X,homeDir:K}=Z,V=typeof J==="string"?V1.parse(J):V1.from(J);if(Y)for(let z of Y){let F=w6(z);if(X1.hasPrefix(V,F)){let q=F.path.endsWith("/")?F.path.slice(0,-1):F.path,D=Q&&Y&&Y.length>=2?oN(F.path)+(X?"\\":"/"):"";return jN0(D+V.path.slice(q.length+1),X,V.scheme)}}if(V?.scheme==="file"){if(K){let z=w6(K);if(X1.hasPrefix(V,z)){let F=z.path.endsWith("/")?z.path.slice(0,-1):z.path,q=V.path.slice(F.length+1);return jN0("~"+(X?"\\":"/")+q,X,V.scheme)}}return jN0(V.fsPath,X,V.scheme)}return V}function jN0(J,Z,Q){return Z&&Q==="file"?J.replaceAll("/","\\"):J}function Nr(J){let Z=Br;return Br=J,Z}function RU6(){if(Br)return Br;throw Error("must call setDisplayPathEnvInfo before calling displayPath() and related functions")}var Br=null;var mX=Q0(()=>{K4();zj();jo()});function p9(J){if(!J)return{};return{[RN0]:J.id,[IU6]:J.agentMode??""}}var O9="x-amp-feature",RN0="x-amp-thread-id",a7="x-amp-message-id",IU6="x-amp-mode",sj1="X-Amp-Client-Application",tj1="X-Amp-Client-Type",ej1="X-Amp-Client-Version",$R1="X-Amp-Installation-ID",JR1="X-Amp-Device-Fingerprint";var gZ=()=>{};function YR1(J){ZR1=J}function qw(J){Xv=J}function XR1(J){QR1=J}function KR1(J){Kv=J.installationID,Vv=J.deviceFingerprint}function VR1(){if(!Kv||!Vv)return;return{installationID:Kv,deviceFingerprint:Vv}}function Gw(){let J=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(J)return{type:"cli",name:"AmpSDK",version:J};let Z;if(!Xv)Z="CLI";else if(["Neovim","JetBrains","Zed"].includes(Xv))Z=Xv;else Z=`${Xv} CLI`;return{type:"cli",name:QR1?`${Z} Execute Mode`:Z,version:ZR1}}function d9(){let J=Gw(),Z={};if(Z[sj1]=J.name,Z[tj1]=J.type,Kv)Z[$R1]=Kv;if(Vv)Z[JR1]=Vv;if(J.version)Z[ej1]=J.version;return Z}var ZR1=null,Xv=null,QR1=!1,Kv=null,Vv=null;var o7=Q0(()=>{gZ()});function PU6(J){if(typeof process>"u"||!process.versions?.node)return"unknown";try{switch(J){case"darwin":{try{let{execSync:Q}=I0("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 I0("node:os").release()}case"linux":try{let Y=I0("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 I0("node:os").release()}catch{return I0("node:os").release()}case"windows":try{let{execSync:Z}=I0("node:child_process"),Y=Z('systeminfo | findstr /B /C:"OS Name" /C:"OS Version"',{encoding:"utf8",timeout:5000}).split(`
104
- `),X=Y.find((z)=>z.includes("OS Name")),K=Y.find((z)=>z.includes("OS Version"));if(X&&K){let z=X.split(":")[1]?.trim(),F=K.split(":")[1]?.trim();return`${z} ${F}`}return I0("node:os").release()}catch{return I0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function hV(){if(!IN0){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=PU6(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 z=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(z?.[1])Y=z[1].replace(/_/g,".")}else if(Q==="windows"){let z=V.match(/Windows NT (\d+\.\d+)/);if(z?.[1])Y=z[1]}else{let z=V.match(/Linux.*?(\d+\.\d+)/);if(z?.[1])Y=z[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"}IN0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:Gw().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return IN0}var IN0;var Sj=Q0(()=>{o7()});function B3(J){let Z=b6[J];return`${Z.provider}/${Z.name}`}function gV(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 G7(J){let{provider:Z,model:Q}=gV(J);for(let Y of Object.values(b6))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return b6.CLAUDE_SONNET_4_5;case"openai":return b6.GPT_5;case"xai":return b6.GROK_CODE_FAST_1;case"cerebras":return b6.Z_AI_GLM_4_7;case"fireworks":return b6.FIREWORKS_GLM_4P6;case"baseten":return b6.BASETEN_KIMI_K2P5;case"moonshotai":return b6.KIMI_K2_INSTRUCT;case"openrouter":return b6.SONOMA_SKY_ALPHA;case"groq":return b6.GPT_OSS_120B;case"vertexai":return b6.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function zv(J){for(let Q of Object.values(b6))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(b6))if(Y.name===Q)return Y}return}function V8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function r7(J){let Z=G7(J);return Z.contextWindow-Z.maxOutputTokens}function wr(J){return G7(J).maxOutputTokens}var O6,b6,PN0;var _2=Q0(()=>{O6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},b6={CLAUDE_SONNET_4:{provider:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:O6.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:O6.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:O6.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:O6.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:O6.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:O6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:O6.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:O6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:O6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:O6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:O6.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:O6.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:O6.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:O6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:O6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:O6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:O6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:O6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:O6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};PN0={FINDER:"finder"}});function Or(J){return J===Er}function mZ(J){return J==="deep"||J===Er}function UU(J,Z){if(!Or(J))return!0;return Boolean(Z&&bZ(Z))}function TN0(J,Z){let Q=s7(Z);if(!Q)return!1;if(CU6.has(J)){let Y=Q.finder??PN0.FINDER,X=TU6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function UR1(J,Z){let Q=s7(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function pX(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(mV).filter((z)=>{if(!UU(z.key,Q?.userEmail))return!1;if(z.key===Lr)return!1;if(K.includes(`!${z.key}`))return!1;if(Z===!1&&d3(z.key))return!1;if(V.has(z.key))return!1;if(Q?.v2&&!(("visibleInV2"in z)&&z.visibleInV2))return!1;let q="visible"in z?z.visible:!1,G=K.includes(z.key);return q||G}).map((z)=>({mode:z.key,description:"description"in z?z.description:void 0})).sort((z,F)=>z.mode.localeCompare(F.mode))}function s7(J){return Object.values(mV).find((Z)=>Z.key===J)}function VY(J){return s7(J)?.primaryModel??B3("CLAUDE_SONNET_4_5")}function Fv(J){let Z=s7(J);if(!Z)return!1;return G7(Z.primaryModel).capabilities?.vision??!1}function d3(J){return J==="free"||J.startsWith("free-")}function _N0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function SN0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var CU6,TU6,GR1,DR1,Er="internal",_U6,SU6,zR1,FR1,qR1,kU6,yU6,vU6,mV,Lr,CN0;var D7=Q0(()=>{Vw();_2();CU6=new Set(["finder"]),TU6={finder:"finder"},GR1={r:0,g:55,b:0},DR1={r:0,g:255,b:136};_U6=["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"],SU6=["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"],zR1=["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"],FR1=["code_tour","code_review","walkthrough","walkthrough_diagram"],qR1=["code_tour","code_review"],kU6=["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"],yU6=["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"],vU6=["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"],mV={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:B3("CLAUDE_OPUS_4_6"),includeTools:zR1,deferredTools:FR1,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:B3("CLAUDE_HAIKU_4_5"),includeTools:_U6,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:B3("CLAUDE_HAIKU_4_5"),includeTools:SU6,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:B3("CLAUDE_OPUS_4_6"),includeTools:kU6,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:B3("CLAUDE_OPUS_4_6"),includeTools:zR1,deferredTools:FR1,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.4",primaryModel:B3("GPT_5_4"),includeTools:yU6,deferredTools:qR1,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:Er,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:B3("GPT_5_4"),includeTools:vU6,deferredTools:qR1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},Lr=mV.AGG.key,CN0=Object.values(mV).map((J)=>J.key)});var N3=Q0(()=>{D7();_2()});function qv(J){return J["agent.deepReasoningEffort"]??"high"}function kN0(J){let Z=xU6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function yN0(J){return uU6.includes(J)}function HR1(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 b6.GPT_5_4.name}function BR1(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 xU6,uU6,Mr,WR1;var qq=Q0(()=>{N3();xU6=["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.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];uU6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];Mr=["mcpServers","mcpPermissions","url"],WR1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var S2;var Dw=Q0(()=>{S2={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 wR1=Q0(()=>{yy();yy()});var dX=Q0(()=>{wR1()});function jr(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function Gq(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 R.debug("PID check error",{pid:J,code:Q}),!1}}var Uw=Q0(()=>{h0()});import{execFile as fU6,spawnSync as Dv}from"node:child_process";import kj from"node:fs";import vN0 from"node:os";import fJ from"node:path";import{promisify as bU6}from"node:util";async function iU6(J){try{if(!await UW6())return[];let Z=await qW6(J);if(!Z)return[];let Q=await PR1(J);return(await IR1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return R.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function nU6(J,Z){if(!Z.pid||!Gq(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await PR1(J),K=(await IR1(J,Y)).find((z)=>Ir(z.workspaceFolder)===Ir(Q));if(!K)return null;let V=await sU6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function aU6(J,Z){let{filePath:Q,line:Y,column:X}=rU6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=WW6(J);if(!V)return OR1(J,Q,Y,X);if(Dv(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return OR1(J,Q,Y,X)}function OR1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((G)=>encodeURIComponent(G)).join("/"),z=Q?`:${Q}${Y?`:${Y}`:""}`:"",F=`${J.urlScheme}://file${V}${z}`,q=oU6(F);if(q.status===0)return!0;return R.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:F,status:q.status,stderr:q.stderr?.toString().trim()}),!1}function oU6(J){if(process.platform==="darwin")return Dv("open",[J],{stdio:"ignore"});if(process.platform==="win32")return Dv("cmd.exe",["/c","start","",J],{stdio:"ignore"});return Dv("xdg-open",[J],{stdio:"ignore"})}function rU6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return{};let Q=Z.fragment?.match(/^L(\d+)(?::(\d+))?(?:-L(\d+)(?::(\d+))?)?$/),Y=Q?.[1]?Number.parseInt(Q[1],10):void 0,X=Q?.[2]?Number.parseInt(Q[2],10):void 0;return{filePath:Z.fsPath,line:Y,column:X}}catch{return{}}}async function sU6(J){let Z=await zW6(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=tU6(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?$W6(X):void 0,V=JW6(Z.find((F)=>F.key==="memento/workbench.editors.files.textFileEditor")?.value),z=K?await ZW6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:z}}function tU6(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=RR1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return R.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function RR1(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)=>eU6(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)=>RR1(Y));return[]}function eU6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return p1(V1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return p1(V1.file(Z.resourceJSON.path))}catch(Z){R.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function $W6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function JW6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return R.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function ZW6(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 QW6(J);if(V===void 0)return;let z=LR1(K.selectionStart.lineNumber,K.selectionStart.column),F=LR1(K.position.lineNumber,K.position.column),q=MR1(z,F)<=0?z:F,G=MR1(z,F)<=0?F:z,U=q.line===G.line&&q.character===G.character?YW6(V,q.line):XW6(V,q.line,q.character,G.line,G.character);return{range:{startLine:q.line,startCharacter:q.character,endLine:G.line,endCharacter:G.character},content:U}}async function QW6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return;return await kj.promises.readFile(Z.fsPath,"utf-8")}catch(Z){R.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function LR1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function MR1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function YW6(J,Z){return J.split(`
104
+ `),X=Y.find((z)=>z.includes("OS Name")),K=Y.find((z)=>z.includes("OS Version"));if(X&&K){let z=X.split(":")[1]?.trim(),F=K.split(":")[1]?.trim();return`${z} ${F}`}return I0("node:os").release()}catch{return I0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function hV(){if(!IN0){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=PU6(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 z=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(z?.[1])Y=z[1].replace(/_/g,".")}else if(Q==="windows"){let z=V.match(/Windows NT (\d+\.\d+)/);if(z?.[1])Y=z[1]}else{let z=V.match(/Linux.*?(\d+\.\d+)/);if(z?.[1])Y=z[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"}IN0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:Gw().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return IN0}var IN0;var Sj=Q0(()=>{o7()});function B3(J){let Z=b6[J];return`${Z.provider}/${Z.name}`}function gV(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 G7(J){let{provider:Z,model:Q}=gV(J);for(let Y of Object.values(b6))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return b6.CLAUDE_SONNET_4_5;case"openai":return b6.GPT_5;case"xai":return b6.GROK_CODE_FAST_1;case"cerebras":return b6.Z_AI_GLM_4_7;case"fireworks":return b6.FIREWORKS_GLM_4P6;case"baseten":return b6.BASETEN_KIMI_K2P5;case"moonshotai":return b6.KIMI_K2_INSTRUCT;case"openrouter":return b6.SONOMA_SKY_ALPHA;case"groq":return b6.GPT_OSS_120B;case"vertexai":return b6.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function zv(J){for(let Q of Object.values(b6))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(b6))if(Y.name===Q)return Y}return}function V8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function r7(J){let Z=G7(J);return Z.contextWindow-Z.maxOutputTokens}function wr(J){return G7(J).maxOutputTokens}var O6,b6,PN0;var _2=Q0(()=>{O6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},b6={CLAUDE_SONNET_4:{provider:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.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:O6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:O6.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:O6.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:O6.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:O6.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:O6.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:O6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:O6.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:O6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:O6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:O6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:O6.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:O6.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:O6.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:O6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:O6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:O6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:O6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:O6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:O6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};PN0={FINDER:"finder"}});function Or(J){return J===Er}function mZ(J){return J==="deep"||J===Er}function UU(J,Z){if(!Or(J))return!0;return Boolean(Z&&bZ(Z))}function TN0(J,Z){let Q=s7(Z);if(!Q)return!1;if(CU6.has(J)){let Y=Q.finder??PN0.FINDER,X=TU6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function UR1(J,Z){let Q=s7(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function pX(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(mV).filter((z)=>{if(!UU(z.key,Q?.userEmail))return!1;if(z.key===Lr)return!1;if(K.includes(`!${z.key}`))return!1;if(Z===!1&&d3(z.key))return!1;if(V.has(z.key))return!1;if(Q?.v2&&!(("visibleInV2"in z)&&z.visibleInV2))return!1;let q="visible"in z?z.visible:!1,G=K.includes(z.key);return q||G}).map((z)=>({mode:z.key,description:"description"in z?z.description:void 0})).sort((z,F)=>z.mode.localeCompare(F.mode))}function s7(J){return Object.values(mV).find((Z)=>Z.key===J)}function VY(J){return s7(J)?.primaryModel??B3("CLAUDE_SONNET_4_5")}function Fv(J){let Z=s7(J);if(!Z)return!1;return G7(Z.primaryModel).capabilities?.vision??!1}function d3(J){return J==="free"||J.startsWith("free-")}function _N0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function SN0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var CU6,TU6,GR1,DR1,Er="internal",_U6,SU6,zR1,FR1,qR1,kU6,yU6,vU6,mV,Lr,CN0;var D7=Q0(()=>{Vw();_2();CU6=new Set(["finder"]),TU6={finder:"finder"},GR1={r:0,g:55,b:0},DR1={r:0,g:255,b:136};_U6=["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"],SU6=["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"],zR1=["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"],FR1=["code_tour","code_review","walkthrough","walkthrough_diagram"],qR1=["code_tour","code_review"],kU6=["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"],yU6=["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"],vU6=["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"],mV={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:B3("CLAUDE_OPUS_4_6"),includeTools:zR1,deferredTools:FR1,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:B3("CLAUDE_HAIKU_4_5"),includeTools:_U6,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:B3("CLAUDE_HAIKU_4_5"),includeTools:SU6,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:B3("CLAUDE_OPUS_4_6"),includeTools:kU6,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:B3("CLAUDE_OPUS_4_6"),includeTools:zR1,deferredTools:FR1,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:B3("GPT_5_3_CODEX"),includeTools:yU6,deferredTools:qR1,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:Er,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:B3("GPT_5_4"),includeTools:vU6,deferredTools:qR1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},Lr=mV.AGG.key,CN0=Object.values(mV).map((J)=>J.key)});var N3=Q0(()=>{D7();_2()});function qv(J){return J["agent.deepReasoningEffort"]??"high"}function kN0(J){let Z=xU6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function yN0(J){return uU6.includes(J)}function HR1(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 b6.GPT_5_4.name}function BR1(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 xU6,uU6,Mr,WR1;var qq=Q0(()=>{N3();xU6=["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.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];uU6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];Mr=["mcpServers","mcpPermissions","url"],WR1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var S2;var Dw=Q0(()=>{S2={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 wR1=Q0(()=>{yy();yy()});var dX=Q0(()=>{wR1()});function jr(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function Gq(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 R.debug("PID check error",{pid:J,code:Q}),!1}}var Uw=Q0(()=>{h0()});import{execFile as fU6,spawnSync as Dv}from"node:child_process";import kj from"node:fs";import vN0 from"node:os";import fJ from"node:path";import{promisify as bU6}from"node:util";async function iU6(J){try{if(!await UW6())return[];let Z=await qW6(J);if(!Z)return[];let Q=await PR1(J);return(await IR1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return R.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function nU6(J,Z){if(!Z.pid||!Gq(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await PR1(J),K=(await IR1(J,Y)).find((z)=>Ir(z.workspaceFolder)===Ir(Q));if(!K)return null;let V=await sU6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function aU6(J,Z){let{filePath:Q,line:Y,column:X}=rU6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=WW6(J);if(!V)return OR1(J,Q,Y,X);if(Dv(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return OR1(J,Q,Y,X)}function OR1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((G)=>encodeURIComponent(G)).join("/"),z=Q?`:${Q}${Y?`:${Y}`:""}`:"",F=`${J.urlScheme}://file${V}${z}`,q=oU6(F);if(q.status===0)return!0;return R.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:F,status:q.status,stderr:q.stderr?.toString().trim()}),!1}function oU6(J){if(process.platform==="darwin")return Dv("open",[J],{stdio:"ignore"});if(process.platform==="win32")return Dv("cmd.exe",["/c","start","",J],{stdio:"ignore"});return Dv("xdg-open",[J],{stdio:"ignore"})}function rU6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return{};let Q=Z.fragment?.match(/^L(\d+)(?::(\d+))?(?:-L(\d+)(?::(\d+))?)?$/),Y=Q?.[1]?Number.parseInt(Q[1],10):void 0,X=Q?.[2]?Number.parseInt(Q[2],10):void 0;return{filePath:Z.fsPath,line:Y,column:X}}catch{return{}}}async function sU6(J){let Z=await zW6(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=tU6(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?$W6(X):void 0,V=JW6(Z.find((F)=>F.key==="memento/workbench.editors.files.textFileEditor")?.value),z=K?await ZW6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:z}}function tU6(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=RR1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return R.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function RR1(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)=>eU6(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)=>RR1(Y));return[]}function eU6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return p1(V1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return p1(V1.file(Z.resourceJSON.path))}catch(Z){R.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function $W6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function JW6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return R.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function ZW6(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 QW6(J);if(V===void 0)return;let z=LR1(K.selectionStart.lineNumber,K.selectionStart.column),F=LR1(K.position.lineNumber,K.position.column),q=MR1(z,F)<=0?z:F,G=MR1(z,F)<=0?F:z,U=q.line===G.line&&q.character===G.character?YW6(V,q.line):XW6(V,q.line,q.character,G.line,G.character);return{range:{startLine:q.line,startCharacter:q.character,endLine:G.line,endCharacter:G.character},content:U}}async function QW6(J){try{let Z=V1.parse(J);if(Z.scheme!=="file")return;return await kj.promises.readFile(Z.fsPath,"utf-8")}catch(Z){R.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function LR1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function MR1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function YW6(J,Z){return J.split(`
105
105
  `)[Z]??""}function XW6(J,Z,Q,Y,X){let K=AR1(J,Z,Q),V=AR1(J,Y,X);if(V<=K)return"";return J.slice(K,V)}function AR1(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 IR1(J,Z){if(Z?.size===0)return[];let Q=fJ.join(CR1(J),"workspaceStorage");if(!await Gv(Q))return[];let Y=await kj.promises.readdir(Q,{withFileTypes:!0});return(await Promise.all(Y.filter((V)=>V.isDirectory()).map(async(V)=>{let z=V.name,F=fJ.join(Q,z),q=fJ.join(F,"state.vscdb"),G=fJ.join(F,"workspace.json");if(!await Gv(q)||!await Gv(G))return null;let D=await VW6(G);if(!D||!await Gv(D))return null;if(Z&&!Z.has(Ir(D)))return null;let U=await kj.promises.stat(q);return{storageID:z,workspaceFolder:D,stateDBPath:q,mtime:U.mtimeMs}}))).filter((V)=>V!==null).sort((V,z)=>z.mtime-V.mtime).slice(0,hU6)}async function PR1(J){let Z=fJ.join(CR1(J),"globalStorage","storage.json");if(!await Gv(Z))return null;try{let Q=await kj.promises.readFile(Z,"utf-8"),X=JSON.parse(Q).windowsState,K=Array.isArray(X?.openedWindows)?X.openedWindows:[],V=K.length>0?K:[X?.lastActiveWindow],z=new Set;for(let F of V){if(!F)continue;let q=KW6(F);if(!q)continue;z.add(Ir(q))}return z}catch(Q){return R.debug(`Failed to parse ${J.ideName} windowsState`,{storageFilePath:Z,error:Q instanceof Error?Q.message:String(Q)}),null}}function KW6(J){if(J.folder)return jR1(J.folder);let Z=J.workspaceIdentifier?.configURIPath;if(!Z)return null;let Q=jR1(Z);return Q?fJ.dirname(Q):null}function jR1(J){try{return V1.parse(J).fsPath}catch{if(fJ.isAbsolute(J))return J;return null}}async function VW6(J){try{let Z=await kj.promises.readFile(J,"utf-8"),Q=JSON.parse(Z);if(Q.folder)return V1.parse(Q.folder).fsPath;if(Q.configuration)return fJ.dirname(V1.parse(Q.configuration).fsPath)}catch(Z){R.debug("Failed to parse VS Code workspace metadata",{workspaceMetadataPath:J,error:Z instanceof Error?Z.message:String(Z)})}return null}async function Gv(J){try{return await kj.promises.access(J),!0}catch{return!1}}async function zW6(J,Z){let Q=await Rr("sqlite3",["-readonly","-json",FW6(J),Z],{timeout:cU6});if(Q.status!==0)return R.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 R.debug("Failed to parse sqlite3 JSON output for VS Code database",{error:X instanceof Error?X.message:String(X)}),[]}}function FW6(J){let Q=J.replaceAll("\\","/").split("/").map((X)=>encodeURIComponent(X)).join("/");return`file:${Q.startsWith("/")?Q:`/${Q}`}?immutable=1`}async function qW6(J){return(await GW6()).find((Y)=>DW6(J,Y.command))?.pid??null}async function GW6(){if(process.platform==="win32"){let Z=await Rr("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 Rr("ps",["-ax","-o","pid=","-o","command="]);if(J.status!==0)return[];return J.stdout.split(`
@@ -962,7 +962,7 @@ ${N$5(J.progress)}
962
962
  `);if(typeof J==="object"&&"output"in J&&typeof J.output==="string")return J.output;return iq(J,"progress")}function w$5(J){return J.map((Z)=>{let Q=[];if(Z.message)Q.push(Z.message);if(Z.tool_uses?.length)for(let Y of Z.tool_uses){let X=Y.status==="done"?E$5(Y.result):`(${Y.status})`;Q.push(`- ${Y.tool_name}: ${X}`)}return Q.join(`
963
963
  `)}).join(`
964
964
 
965
- `)}function E$5(J){if(J===void 0||J===null)return"done";if(typeof J==="string")return J.length>200?J.slice(0,200)+"...":J;if(typeof J==="object"){let Z=J;if("exitCode"in Z){let Y=typeof Z.output==="string"?Z.output:"",X=Y.length>200?Y.slice(0,200)+"...":Y;return X?`exit ${Z.exitCode}: ${X}`:`exit ${Z.exitCode}`}let Q=JSON.stringify(J);return Q.length>200?Q.slice(0,200)+"...":Q}return String(J)}function O$5({model:J,status:Z,usage:Q}){if(!Q)return;let Y=Q.input_tokens_details.cached_tokens,X=Q.input_tokens-Y,K=zv(J);if(!K)R.warn("[openai-responses] Unknown response model in usage data",{model:J});if(Z==="completed"&&(Q.input_tokens===0||Q.output_tokens===0))R.warn("[openai-responses] Missing token counts in completed response",{model:J,rawInputTokens:Q.input_tokens,rawOutputTokens:Q.output_tokens,cachedTokens:Y,cacheCreationInputTokens:X,outputTokensDetails:Q.output_tokens_details});return{model:J,maxInputTokens:K?K.contextWindow-K.maxOutputTokens:-1,inputTokens:0,outputTokens:Q.output_tokens,cacheCreationInputTokens:X,cacheReadInputTokens:Y,totalInputTokens:Q.input_tokens,timestamp:new Date().toISOString()}}class n_0{async*stream(J){let Z=D2(J.serviceAuthToken),Q=await hW({configService:J.configService},J.signal,Z?{defaultHeaders:Z}:void 0),Y=await J.configService.getLatest(J.signal),X=J.serverStatus&&M6(J.serverStatus)?J.serverStatus.features:void 0,K=a60(J.thread.agentMode,Y.settings["openai.speed"],X),V=await A$5({...J,serviceTier:K}),z,F=Date.now();try{R.debug("[openai-responses] Creating Responses stream",{model:V.model,threadId:J.thread.id}),z=await Q.responses.create(V,{signal:J.signal,headers:{...xP(J.thread,void 0,J.requestHeaders),...Z??{}}}),R.debug("[openai-responses] Responses.create returned",{model:V.model,threadId:J.thread.id})}catch(N){if(g8(N))throw new DOMException("Aborted","AbortError");throw N}let q,G=0,D=Date.now(),U=Date.now(),W;R.debug("[openai-responses] Stream started",{model:V.model,threadId:J.thread.id});let H=30000,B;try{for await(let N of wI(z,L$5)){G++,B=N.type;let w=Date.now();if(W===void 0)W=w-F,R.debug("[openai-responses] Time to first byte",{model:V.model,threadId:J.thread.id,firstEventType:N.type,timeToFirstByteMs:W});let E=w-D;if(E>H)R.warn("[openai-responses] Long gap between events",{eventType:N.type,eventCount:G,timeSinceLastEventMs:E,totalElapsedMs:w-U});if(D=w,q=R$5(q,N),q)yield j$5(q)}if(q&&q.status==="in_progress"&&!J.signal.aborted)throw R.warn("[openai-responses] Stream ended without terminal event",{eventCount:G,totalElapsedMs:Date.now()-U,timeToFirstByteMs:W,responseStatus:q.status,outputCount:q.output.length}),Error("Response incomplete: stream ended unexpectedly");if(q&&q.status==="incomplete"){let N=q.incomplete_details?.reason??"unknown reason";throw Error(`Response incomplete: ${N}`)}R.debug("[openai-responses] Stream completed",{eventCount:G,totalElapsedMs:Date.now()-U,timeToFirstByteMs:W})}catch(N){throw R.error("[openai-responses] Stream error",{threadId:J.thread.id,eventCount:G,lastEventType:B,durationMs:Date.now()-U,timeToFirstByteMs:W,error:N instanceof Error?N.message:String(N),errorName:N instanceof Error?N.name:void 0}),N}}}function M$5(J){let Z=["none","minimal","low","medium","high","xhigh"];if(!J)return"medium";return Z.includes(J)?J:"medium"}async function A$5({model:J,thread:Z,systemPrompt:Q,tools:Y,reasoningEffort:X,serviceTier:K}){let V=Y,z=Mh(Z),F=zv(J),q="auto",G=[{role:"system",content:Q.map((H)=>H.text).join(`
965
+ `)}function E$5(J){if(J===void 0||J===null)return"done";if(typeof J==="string")return J.length>200?J.slice(0,200)+"...":J;if(typeof J==="object"){let Z=J;if("exitCode"in Z){let Y=typeof Z.output==="string"?Z.output:"",X=Y.length>200?Y.slice(0,200)+"...":Y;return X?`exit ${Z.exitCode}: ${X}`:`exit ${Z.exitCode}`}let Q=JSON.stringify(J);return Q.length>200?Q.slice(0,200)+"...":Q}return String(J)}function O$5({model:J,status:Z,usage:Q}){if(!Q)return;let Y=Q.input_tokens_details.cached_tokens,X=Q.input_tokens-Y,K=zv(J);if(!K)R.warn("[openai-responses] Unknown response model in usage data",{model:J});if(Z==="completed"&&(Q.input_tokens===0||Q.output_tokens===0))R.warn("[openai-responses] Missing token counts in completed response",{model:J,rawInputTokens:Q.input_tokens,rawOutputTokens:Q.output_tokens,cachedTokens:Y,cacheCreationInputTokens:X,outputTokensDetails:Q.output_tokens_details});return{model:J,maxInputTokens:K?K.contextWindow-K.maxOutputTokens:-1,inputTokens:0,outputTokens:Q.output_tokens,cacheCreationInputTokens:X,cacheReadInputTokens:Y,totalInputTokens:Q.input_tokens,timestamp:new Date().toISOString()}}class n_0{async*stream(J){let Z=D2(J.serviceAuthToken),Q=await hW({configService:J.configService},J.signal,Z?{defaultHeaders:Z}:void 0),Y=await J.configService.getLatest(J.signal),X=J.serverStatus&&M6(J.serverStatus)?J.serverStatus.features:void 0,K=a60(J.thread.agentMode,Y.settings["openai.speed"],X),V=await A$5({...J,serviceTier:K}),z,F=Date.now();try{R.debug("[openai-responses] Creating Responses stream",{model:V.model,threadId:J.thread.id}),z=await Q.responses.create(V,{signal:J.signal,headers:{...xP(J.thread,void 0,J.requestHeaders),...Z??{}}}),R.debug("[openai-responses] Responses.create returned",{model:V.model,threadId:J.thread.id})}catch(w){if(g8(w))throw new DOMException("Aborted","AbortError");throw w}let q,G=0,D=Date.now(),U=Date.now(),W,H;R.debug("[openai-responses] Stream started",{model:V.model,threadId:J.thread.id});let B=30000,N;try{for await(let w of wI(z,L$5)){G++,N=w.type;let E=Date.now();if(W===void 0)W=E-F,R.debug("[openai-responses] Time to first byte",{model:V.model,threadId:J.thread.id,firstEventType:w.type,timeToFirstByteMs:W});let O=E-D;if(O>B)R.warn("[openai-responses] Long gap between events",{eventType:w.type,eventCount:G,timeSinceLastEventMs:O,totalElapsedMs:E-U});if(D=E,q=R$5(q,w),q){let L=j$5(q),M=L.content.find((A)=>A.type==="text"&&A.text.length>0||A.type==="thinking"&&A.thinking.length>0);if(H===void 0&&M)H=E-F,R.debug("[openai-responses] Time to first token",{model:V.model,threadId:J.thread.id,eventType:w.type,firstContentType:M.type,timeToFirstTokenMs:H});yield L}}if(q&&q.status==="in_progress"&&!J.signal.aborted)throw R.warn("[openai-responses] Stream ended without terminal event",{eventCount:G,totalElapsedMs:Date.now()-U,timeToFirstByteMs:W,timeToFirstTokenMs:H,responseStatus:q.status,outputCount:q.output.length}),Error("Response incomplete: stream ended unexpectedly");if(q&&q.status==="incomplete"){let w=q.incomplete_details?.reason??"unknown reason";throw Error(`Response incomplete: ${w}`)}R.debug("[openai-responses] Stream completed",{eventCount:G,totalElapsedMs:Date.now()-U,timeToFirstByteMs:W,timeToFirstTokenMs:H})}catch(w){throw R.error("[openai-responses] Stream error",{threadId:J.thread.id,eventCount:G,lastEventType:N,durationMs:Date.now()-U,timeToFirstByteMs:W,timeToFirstTokenMs:H,error:w instanceof Error?w.message:String(w),errorName:w instanceof Error?w.name:void 0}),w}}}function M$5(J){let Z=["none","minimal","low","medium","high","xhigh"];if(!J)return"medium";return Z.includes(J)?J:"medium"}async function A$5({model:J,thread:Z,systemPrompt:Q,tools:Y,reasoningEffort:X,serviceTier:K}){let V=Y,z=Mh(Z),F=zv(J),q="auto",G=[{role:"system",content:Q.map((H)=>H.text).join(`
966
966
 
967
967
  `)},...P6(z)],D=Math.min(oe1,F?.maxOutputTokens??oe1),U=F?.capabilities?.reasoning??!0,W={model:J,input:G,store:!1,include:["reasoning.encrypted_content"],tools:V.map(Ah),stream:!0,max_output_tokens:D,prompt_cache_key:Z.id,...U?{reasoning:{effort:M$5(X),summary:"auto"}}:{temperature:0.1}};if(K){let H=W;H.service_tier=K}return W}function Mh(J){let Z=[],{summaryBlock:Q,index:Y}=vJ(J)??{summaryBlock:void 0,index:-1},X=Y+1;if(Q&&Q.summary.type==="message")Z.push({type:"message",role:"assistant",content:Q.summary.summary.trimEnd()});for(let K=X;K<J.messages.length;K++){let V=J.messages[K];if(!V)continue;switch(V.role){case"user":{let z=[],F=[],q=[];if(V.fileMentions&&V.fileMentions.files.length>0)z.push({type:"input_text",text:$Z(V.fileMentions)});if(V.userState)z.push({type:"input_text",text:CY(V.userState)});for(let G of V.content)switch(G.type){case"tool_result":{if(G.run?.status==="done"){let D=G.run.result;if(typeof D==="object"&&D!==null&&"discoveredGuidanceFiles"in D&&Array.isArray(D.discoveredGuidanceFiles))q.push(...D.discoveredGuidanceFiles)}F.push({type:"function_call_output",call_id:G.toolUseID,output:U$5(G.run,!0)});break}case"image":{let D=qW(G);if(D){z.push({type:"input_text",text:D});break}if(z.push({type:"input_text",text:Fz(G)}),G.source.type==="url")z.push({type:"input_image",detail:"auto",image_url:G.source.url});else if(G.source.type==="base64")z.push({type:"input_image",detail:"auto",image_url:`data:${G.source.mediaType};base64,${G.source.data}`});break}case"text":if(G.text.trim())z.push({type:"input_text",text:G.text});break}if(V.discoveredGuidanceFiles)q.push(...V.discoveredGuidanceFiles);if(q.length>0)z.unshift({type:"input_text",text:$I(q,"deep")});if(z.length>0)Z.push({type:"message",role:"user",content:z});Z.push(...F);break}case"assistant":{let z=V.meta?.openAIResponsePhase,F=new Set;for(let q of V.content)if(q.type==="text"){let G={type:"message",role:"assistant",content:q.text};if(z)G.phase=z;Z.push(G)}else if(q.type==="thinking"){let G=q.thinking.match(/<ENCRYPTED>([\s\S]*?)<\/ENCRYPTED><ID>([\s\S]*?)<\/ID>/),D=q.openAIReasoning?.encryptedContent??G?.[1]??"",U=q.openAIReasoning?.id??G?.[2]??"",W=q.openAIReasoning?q.thinking:q.thinking.replace(/<ENCRYPTED>[\s\S]*?<\/ENCRYPTED><ID>[\s\S]*?<\/ID>/g,"");if(U.length>0&&D.length>0&&!F.has(U))F.add(U),Z.push({type:"reasoning",summary:[{text:W,type:"summary_text"}],encrypted_content:D,id:U})}else if(q.type==="tool_use")Z.push({type:"function_call",name:q.name,call_id:q.id,arguments:JSON.stringify(q.input)});break}case"info":{let z=[];for(let F of V.content)if(F.type==="manual_bash_invocation"){let q=TY(F);for(let G of q)z.push({type:"input_text",text:G.text})}else if(F.type==="text"&&F.text.trim().length>0)z.push({type:"input_text",text:F.text});if(z.length>0)Z.push({type:"message",role:"user",content:z});break}}}return u$(Z)}function Ah(J){let Z=J.inputSchema?.properties??{},Q=J.inputSchema?.required??[],Y={type:J.inputSchema?.type??"object",properties:Z,required:Q,additionalProperties:!0};return{type:"function",name:J.name,description:J.description||"",parameters:Y,strict:!1}}function j$5(J){function Z(K){if(K.incomplete_details?.reason==="max_output_tokens")return"max_tokens";if(K.incomplete_details?.reason==="content_filter")return"refusal";if(K.output.some((V)=>V.type==="function_call"))return"tool_use";return"end_turn"}function Q(K){return O$5({model:J.model,status:J.status,usage:K})}function Y(K){let V=[];for(let z of K)switch(z.type){case"message":for(let F of z.content)if(F.type==="refusal")V.push({type:"text",text:F.refusal});else V.push({type:"text",text:F.text});break;case"function_call":try{let F=JSON.parse(z.arguments);V.push({type:"tool_use",complete:!0,id:z.call_id,name:z.name,input:F})}catch{V.push({type:"tool_use",complete:!1,id:z.call_id,name:z.name,inputPartialJSON:{json:z.arguments},input:YW(z.arguments||"{}"),inputIncomplete:OI(z.arguments||"{}")})}break;case"reasoning":{let F=z.summary&&z.summary.length>0?z.summary.map((q)=>q.text):(z.content??[]).filter((q)=>q.type==="reasoning_text").map((q)=>q.text);for(let q of F)V.push({type:"thinking",thinking:q,signature:z.encrypted_content??"",provider:"openai",...z.encrypted_content&&z.id?{openAIReasoning:{id:z.id,encryptedContent:z.encrypted_content}}:{}});break}case"file_search_call":case"web_search_call":case"computer_call":case"image_generation_call":case"code_interpreter_call":case"local_shell_call":case"mcp_call":case"mcp_list_tools":case"mcp_approval_request":case"custom_tool_call":throw Error(`unsupported content block type ${z.type}`)}return V}function X(K){switch(K.status){case"completed":return{type:"complete",stopReason:Z(K)};case"in_progress":return{type:"streaming"};case"failed":return{type:"error",error:K.error??{message:"unknown"}};case"incomplete":return{type:"error",error:{message:`Response incomplete: ${K.incomplete_details?.reason??"unknown reason"}`}};case"cancelled":return{type:"cancelled"};default:return{type:"streaming"}}}return{role:"assistant",messageId:0,content:Y(J.output),meta:(()=>{let K=[...J.output].reverse().map(D$5).find((V)=>V!==void 0);if(!K)return;return{openAIResponsePhase:K}})(),state:X(J),usage:Q(J.usage)}}function R$5(J,Z){return z7(J,(Q)=>{if(!Q){if(Z.type!=="response.created")throw Error(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Z.type}`);return Z.response}if(Z.type==="keepalive")return;switch(Z.type){case"response.output_item.added":{if(Z.item.type==="function_call")R.debug("[openai-responses] function_call item added",{name:Z.item.name,hasName:!!Z.item.name,callId:Z.item.call_id,outputIndex:Z.output_index});Q.output[Z.output_index]=Z.item;break}case"response.output_item.done":{if(!Q.output[Z.output_index])throw Error(`missing output at index ${Z.output_index}`);Q.output[Z.output_index]=Z.item;break}case"response.function_call_arguments.delta":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type!=="function_call")throw Error(`expected output to be 'function_call', got ${X.type}`);X.arguments+=Z.delta;break}case"response.function_call_arguments.done":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type!=="function_call")throw Error(`expected output to be 'function_call', got ${X.type}`);R.debug("[openai-responses] function_call arguments done",{eventName:Z.name,existingName:X.name,nameChanged:X.name!==Z.name,outputIndex:Z.output_index}),X.arguments=Z.arguments,X.name=Z.name;break}case"response.content_part.added":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="message"&&(Z.part.type==="output_text"||Z.part.type==="refusal"))X.content[Z.content_index]=Z.part;else if(X.type==="reasoning"&&Z.part.type==="reasoning_text"){if(!X.content)X.content=[];X.content[Z.content_index]=Z.part}else throw Error(`unexpected content_part.added for output ${X.type}: ${Z.part.type}`);break}case"response.content_part.done":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="message"){if(!X.content[Z.content_index])throw Error(`missing content at index ${Z.content_index}`);if(Z.part.type==="output_text"||Z.part.type==="refusal")X.content[Z.content_index]=Z.part;else throw Error(`unexpected content_part.done for message: ${Z.part.type}`)}else if(X.type==="reasoning"&&Z.part.type==="reasoning_text"){if(!X.content)X.content=[];X.content[Z.content_index]=Z.part}else throw Error(`unexpected content_part.done for output ${X.type}: ${Z.part.type}`);break}case"response.output_text.delta":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="message"){let K=X.content[Z.content_index];if(!K)throw Error(`missing content at index ${Z.content_index}`);if(K.type!=="output_text")throw Error(`expected content to be 'output_text', got ${K.type}`);K.text+=Z.delta}else throw Error(`unexpected output for output_text.delta: ${X.type}`);break}case"response.output_text.done":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="message"){let K=X.content[Z.content_index];if(!K)throw Error(`missing content at index ${Z.content_index}`);if(K.type!=="output_text")throw Error(`expected content to be 'output_text', got ${K.type}`);K.text=Z.text}else throw Error(`unexpected output for output_text.done: ${X.type}`);break}case"response.reasoning_text.delta":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="reasoning"){let K=X.content?.[Z.content_index];if(!K)throw Error(`missing content at index ${Z.content_index}`);if(K.type!=="reasoning_text")throw Error(`expected content to be 'reasoning_text', got ${K.type}`);K.text+=Z.delta}else throw Error(`unexpected output for reasoning_text.delta: ${X.type}`);break}case"response.reasoning_text.done":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="reasoning"){if(!X.content)X.content=[];let K=X.content[Z.content_index];if(!K)throw Error(`missing content at index ${Z.content_index}`);if(K.type!=="reasoning_text")throw Error(`expected content to be 'reasoning_text', got ${K.type}`);K.text=Z.text}else throw Error(`unexpected output for reasoning_text.done: ${X.type}`);break}case"response.reasoning_summary_text.delta":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="reasoning"){let K=X.summary[Z.summary_index];if(!K)throw Error(`missing summary at index ${Z.summary_index}`);if(K.type!=="summary_text")throw Error(`expected summary to be 'summary_text', got ${K.type}`);K.text+=Z.delta}else throw Error(`unexpected output for reasoning_summary_text.delta: ${X.type}`);break}case"response.reasoning_summary_part.added":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="reasoning")X.summary[Z.summary_index]=Z.part;else throw Error(`unexpected output for reasoning_summary_part.added: ${X.type}`);break}case"response.reasoning_summary_part.done":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="reasoning")X.summary[Z.summary_index]=Z.part;else throw Error(`unexpected output for reasoning_summary_part.done: ${X.type}`);break}case"response.reasoning_summary_text.done":{let X=Q.output[Z.output_index];if(!X)throw Error(`missing output at index ${Z.output_index}`);if(X.type==="reasoning"){let K=X.summary[Z.summary_index];if(!K)throw Error(`missing summary at index ${Z.summary_index}`);K.text=Z.text}else throw Error(`unexpected output for reasoning_summary_text.done: ${X.type}`);break}case"response.completed":case"response.failed":case"response.incomplete":return Z.response;case"error":{let X=Z;throw Error(`OpenAI stream error (${X.code}): ${X.message}`)}case"response.in_progress":case"response.refusal.delta":case"response.refusal.done":break;default:R.debug("[openai-responses] Unhandled stream event type",{eventType:Z.type})}})}var oe1=32000,L$5=300000;var jh=Q0(()=>{Jf();n7();WY();L10();h0();l5();lq();DY();A4();LI();aq();_2();Lh();NE();Eh();gW()});function re1(J){return J.filter((Z)=>Z.type!=="thinking"&&Z.type!=="redacted_thinking")}function se1(J){let Z=new Set;return J.filter((Q)=>{if(Z.has(Q.name))return!1;return Z.add(Q.name),!0}).map((Q)=>({type:"function",function:{name:Q.name,description:Q.description??"",parameters:Q.inputSchema}}))}async function r60(J,Z,Q,Y,X,K,V,z,F,q,G){let D=await te1(K,V,q),U=[{role:"system",content:Q},...J],W={model:X,messages:U,tools:se1(Z),temperature:0.7,top_p:0.95,stream:!1,...F&&{tool_choice:F}};try{return{message:await D.chat.completions.create(W,{signal:V,headers:{...ee1(Y,z),...G??{}}})}}catch(H){if(g8(H))throw new DOMException("Aborted","AbortError");throw R.error("xAI API call failed",{model:X,error:H instanceof Error?H.message:String(H),status:H?.status,code:H?.code,type:H?.type}),R.error("xAI API call failed",{model:X,error:H instanceof Error?H.message:String(H),params:{...W,messages:W.messages.map((B)=>({...B,content:typeof B.content==="string"?B.content.substring(0,100)+"...":B.content}))}}),$04(H)}}async function*I$5(J,Z,Q,Y,X,K,V,z,F,q){let G=await te1(K,V,F),D=[{role:"system",content:Q},...J],U={model:X,messages:D,tools:se1(Z),stream:!0,stream_options:{include_usage:!0}};try{yield*await G.chat.completions.create(U,{signal:V,headers:{...ee1(Y,z),...q??{}}})}catch(W){if(g8(W))throw new DOMException("Aborted","AbortError");throw $04(W)}}function P$5(J){if(J.status==="done")return typeof J.result==="string"?J.result:JSON.stringify(J.result);else if(J.status==="error")return`<tool_execution_error>${J.error?.message||"Unknown error"}</tool_execution_error>`;else if(J.status==="cancelled")return"<tool_call_cancelled>Tool call was cancelled by the user</tool_call_cancelled>";else if(J.status==="rejected-by-user")return"<tool_rejection>User rejected the tool call, disallowing it from running</tool_rejection>";else return`<tool_status>${J.status}</tool_status>`}function Rh(J){let Z=[],{summaryBlock:Q,index:Y}=vJ(J)??{summaryBlock:void 0,index:0};if(Q&&Q.summary.type==="message")Z.push({role:"assistant",content:[{type:"text",text:Q.summary.summary.trimEnd()}]});for(let X=Y+(Q?1:0);X<J.messages.length;X++){let K=J.messages[X];if(!K)continue;switch(K.role){case"user":{let V=[],z=[];if(K.fileMentions&&K.fileMentions.files.length>0)V.push({type:"text",text:$Z(K.fileMentions)});if(K.userState)V.push({type:"text",text:CY(K.userState)});for(let F of K.content)switch(F.type){case"tool_result":z.push({role:"tool",content:P$5(F.run),tool_call_id:F.toolUseID.replace(/^toolu_/,"")});break;case"image":break;case"text":if(F.text.trim())V.push({type:"text",text:F.text});break}if(V.length>0)Z.push({role:"user",content:V});Z.push(...z);break}case"assistant":{let z=re1(K.content).filter((q)=>q.type==="text").map((q)=>({type:"text",text:q.text})),F=K.content.filter((q)=>q.type==="tool_use").map((q)=>({id:q.id.replace(/^toolu_/,""),type:"function",function:{name:q.name,arguments:JSON.stringify(q.input)}}));if(z.length>0||F.length>0)Z.push({role:"assistant",content:z.length>0?z:null,tool_calls:F.length>0?F:void 0});break}case"info":{let V=[];for(let z of K.content)if(z.type==="manual_bash_invocation"){let F=TY(z);V.push(...F)}else if(z.type==="text"&&z.text.trim().length>0)V.push({type:"text",text:z.text});if(V.length>0)Z.push({role:"user",content:V});break}}}return u$(Z)}function C$5(J,Z){let Q=J.pipe(Z4((Y)=>M8((async()=>{let X=await Y.secrets.getToken("apiKey",Y.settings.url);return{url:Y.settings.url,apiKey:X}})())),L4((Y,X)=>Y.url===X.url&&Y.apiKey===X.apiKey),F1(({url:Y,apiKey:X})=>{if(!X)throw Error("API key not found. You must provide an API key in settings.");return new l4({apiKey:X,baseURL:new URL("/api/provider/xai/v1",Y).toString(),defaultHeaders:Z})}));return Z?Q:Q.pipe(I6({shouldCountRefs:!0}))}function te1(J,Z,Q){return O1(C$5(J.configService.config,Q?.defaultHeaders),Z)}function ee1(J,Z){return{...d9(),[O9]:"amp.chat",...Z!=null?{[a7]:String(Z)}:{},"x-grok-conv-id":J.id,...p9(J)}}function $04(J){let Z=J?.message;if(typeof Z==="string"){if(Z.includes("This model's maximum prompt length is")&&Z.includes("but the request contains")&&Z.includes("tokens."))return new o$("Token limit exceeded.")}return J}class a_0{async*stream({model:J,thread:Z,systemPrompt:Q,tools:Y,configService:X,signal:K,serviceAuthToken:V}){let z=Y,F=Rh(Z),q=D2(V),G=I$5(F,z,Q.map((W)=>W.text).join(`
968
968
 
@@ -1231,51 +1231,13 @@ If the user asks for a "review", default to a code review mindset: prioritise id
1231
1231
 
1232
1232
  ## Frontend tasks
1233
1233
 
1234
- When designing or changing user interfaces, prioritize clarity, stability, and
1235
- accessibility before stylistic novelty.
1236
- - Make the next step obvious. Each screen should have a clear focal point and a clear
1237
- primary action.
1238
- - Design for the user's context and likely state of mind. High-stakes, repetitive, or
1239
- stressful flows need more clarity, reassurance, and speed than flourish.
1240
- - Preserve spatial stability. Avoid unnecessary movement, resizing, or layout jumps
1241
- when content loads or state changes.
1242
- - Create real hierarchy. Important elements should not compete equally for attention.
1243
- - Design complete interaction states intentionally: default, focus, active, disabled,
1244
- loading, error, and success.
1245
- - Use progressive disclosure. Start with the minimum needed for the current task and
1246
- reveal complexity only when it becomes relevant.
1247
- - Give immediate, local feedback. Show progress, results, and errors near where the
1248
- user acted.
1249
- - Prefer reversible flows for low-risk actions. Use undo when practical; reserve
1250
- confirmations for destructive or irreversible actions.
1251
- - Treat accessibility as a default quality bar. Support keyboard and assistive
1252
- technology, maintain readable contrast, provide comfortable target sizes, and offer
1253
- reduced-motion or lower-motion fallbacks.
1254
- - Use motion, color, and decoration to clarify hierarchy and state changes, not as
1255
- ornament.
1256
-
1257
- When doing frontend design tasks, avoid collapsing into "AI slop" or safe, average-looking layouts.
1258
- Aim for interfaces that feel intentional, bold, and a bit surprising.
1259
- - Visual Reduction: Remove redundant icons, duplicate labels, and decorative chrome when
1260
- spacing, alignment, or typography already communicate the meaning.
1261
- - Surfaces & Dividers: Prefer whitespace, alignment, and subtle contrast over heavy
1262
- borders, nested cards, and loud separators.
1234
+ When doing frontend design tasks, avoid collapsing into "AI slop" or safe, average-looking layouts. Aim for interfaces that feel intentional, bold, and a bit surprising.
1263
1235
  - Typography: Use expressive, purposeful fonts and avoid default stacks (Inter, Roboto, Arial, system).
1264
- - Technical Type: Reserve monospace styling for genuinely technical content such as
1265
- code, IDs, and timestamps.
1266
1236
  - Color & Look: Choose a clear visual direction; define CSS variables; avoid purple-on-white defaults. No purple bias or dark mode bias.
1267
- - Tokens & Themes: Use semantic design tokens or CSS variables for colors and states,
1268
- and handle light and dark appearances intentionally rather than by naive inversion.
1269
- - Density: Simplify dense interfaces by combining related metadata, truncating
1270
- secondary content cleanly, and hiding non-essential detail on smaller screens.
1271
- - States & Layering: Keep hover, selection, and layering treatments subtle and
1272
- deliberate; prefer background, opacity, and shadow changes over border or layout
1273
- shifts.
1274
1237
  - Motion: Use a few meaningful animations (page-load, staggered reveals) instead of generic micro-motions.
1275
1238
  - Background: Don't rely on flat, single-color backgrounds; use gradients, shapes, or subtle patterns to build atmosphere.
1276
- - Ensure the page loads properly on both desktop and mobile
1277
- - For React code, prefer modern patterns including useEffectEvent, startTransition, and useDeferredValue when appropriate if used by the team. Do not add useMemo/useCallback by default unless already used; follow the repo's React Compiler guidance.
1278
1239
  - Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
1240
+ - Ensure the page loads properly on both desktop and mobile.
1279
1241
 
1280
1242
  Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
1281
1243
 
@@ -1285,13 +1247,15 @@ Intermediary updates go to the \`commentary\` channel. These are short updates w
1285
1247
 
1286
1248
  Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done —", "Got it", "Great question") or framing phrases.
1287
1249
 
1288
- Before doing substantial work, you start with a user update explaining your first step. Avoid commenting on the request or using starters such as "Got it" or "Understood".
1250
+ Before exploring or doing substantial work, you start with a user update explaining your first step. Avoid commenting on the request or using starters such as "Got it" or "Understood".
1251
+
1252
+ When exploring the codebase, provide user updates as you go. Explain what context you are gathering and what you've learned. Vary your sentence structure when providing these updates to avoid sounding repetitive - in particular, don't start each sentence the same way.
1289
1253
 
1290
1254
  After you have sufficient context, and the work is substantial you provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).
1291
1255
 
1292
1256
  Before performing file edits of any kind, you provide updates explaining what edits you are making.
1293
1257
 
1294
- Provide updates after major milestones or major discoveries. Do not provide an update if there is nothing interesting to say.
1258
+ As you are thinking, you semi-regularly provide updates even if not taking any actions, informing the user of your progress. Provide updates after major milestones or major discoveries. Do not provide an update if there is nothing interesting to say.
1295
1259
  `}var a34=Q0(()=>{l5();H4()});function o34({enableTaskList:J=!1,enableTask:Z=!1,enableOracle:Q=!1,enableDiagnostics:Y=!1,enableAutoSnapshot:X=!1,enableChart:K=!1}){return`You are Amp, a powerful AI coding agent. You help the user with software engineering tasks. Use the instructions below and the tools available to you to help the user.
1296
1260
 
1297
1261
  # Agency
@@ -2116,13 +2080,23 @@ Fixed auth crash in [\`auth.js\`](file:///workspace/auth.js#L42) by guarding und
2116
2080
  `}var Y84=Q0(()=>{l5()});function X84(){return`You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals.
2117
2081
 
2118
2082
  # General
2083
+
2119
2084
  As an expert coding agent, your primary focus is writing code, answering questions, and helping the user complete their task in the current environment. You build context by examining the codebase first without making assumptions or jumping to conclusions. You think through the nuances of the code you encounter, and embody the mentality of a skilled senior software engineer.
2120
2085
 
2121
2086
  - When searching for text or files, prefer using \`rg\` or \`rg--files\` respectively because \`rg\` is much faster than alternatives like \`grep\`. (If the \`rg\` command is not found, then use alternatives.)
2122
2087
  - Parallelize tool calls whenever possible - especially file reads, such as \`cat\`, \`rg\`, \`sed\`, \`ls\`, \`git show\`, \`nl\`, \`wc\`. Use \`multi_tool_use.parallel\` to parallelize tool calls and only this. Never chain together bash commands with separators like \`echo "====";\` as this renders to the user poorly.
2123
2088
  - Use ${r5} for complex, multi-step codebase discovery: behavior-level questions, flows spanning multiple modules, or correlating related patterns. For direct symbol, path, or exact-string lookups, use \`rg\` first.
2124
2089
  - Use ${Y2} when you need understanding outside the local workspace: dependency internals, reference implementations on GitHub, multi-repo architecture, or commit-history context. Don't use it for simple local file reads.
2125
- - Pull in external references when uncertainty or risk is meaningful: unclear APIs/behavior, security-sensitive flows, migrations, performance-critical paths, or best-in-class patterns proven in open source or other language ecosystems. Prefer official docs first, then source.
2090
+ - Pull in external references when uncertainty or risk is meaningful: unclear APIs/behavior, security-sensitive flows, migrations, performance-critical paths, or best-in-class patterns proven in open source or other language ecosystems. prefer official docs first, then source.
2091
+
2092
+ ## Pragmatism and Scope
2093
+
2094
+ - The best change is often the smallest correct change.
2095
+ - When two approaches are both correct, prefer the one with fewer new names, helpers, layers, and tests.
2096
+ - Keep obvious single-use logic inline. Do not extract a helper unless it is reused, hides meaningful complexity, or names a real domain concept.
2097
+ - A small amount of duplication is better than speculative abstraction.
2098
+ - Do not assume work-in-progress changes in the current thread need backward compatibility; earlier unreleased shapes in the same thread are drafts, not legacy contracts. Preserve old formats only when they already exist outside the current edit, such as persisted data, shipped behavior, external consumers, or an explicit user requirement; if unclear, ask one short question instead of adding speculative compatibility code.
2099
+ - Add or update tests only when they protect meaningful behavior: bug fixes, non-trivial logic, boundary contracts, invariants, or realistic failure paths. Do not add tests for trivial refactors, obvious inline expressions, one-line helpers, constant reshaping, or plumbing already covered by existing behavior or the type system; no new test needed is an acceptable outcome.
2126
2100
 
2127
2101
  ## Editing constraints
2128
2102
 
@@ -2147,6 +2121,7 @@ As an expert coding agent, your primary focus is writing code, answering questio
2147
2121
  - If the user asks for a "review", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.
2148
2122
 
2149
2123
  ## Autonomy and persistence
2124
+
2150
2125
  Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
2151
2126
 
2152
2127
  Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.
@@ -2224,40 +2199,23 @@ You are producing plain text that will later be styled by the program you run in
2224
2199
  * Do not use URIs like file://, vscode://, or https://.
2225
2200
  * Do not provide range of lines
2226
2201
  - Don't use emojis or em dashes unless explicitly instructed.
2202
+ - Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the \`1. 2. 3.\` style markers (with a period), never \`1)\`.
2227
2203
 
2228
- ## Final answer instructions
2204
+ ## Intermediary updates
2229
2205
 
2230
- Always favor conciseness in your final answer - you should usually avoid long-winded explanations and focus only on the most important details. For casual chit-chat, just chat. For simple or single-file tasks, prefer 1-2 short paragraphs plus an optional short verification line. Do not default to bullets. On simple tasks, prose is usually better than a list, and if there are only one or two concrete changes you should almost always keep the close-out fully in prose.
2206
+ Intermediary updates go to the \`commentary\` channel. These are short updates while you are working, they are NOT final answers. Keep updates to 1-2 sentence to communicate progress and new information to the user as you are doing work.
2231
2207
 
2232
- On larger tasks, use at most 2-3 high-level sections when helpful. Each section can be a short paragraph or a few flat bullets. Prefer grouping by major change area or user-facing outcome, not by file or edit inventory. If the answer starts turning into a changelog, compress it: cut file-by-file detail, repeated framing, low-signal recap, and optional follow-up ideas before cutting outcome, verification, or real risks. Only dive deeper into one aspect of the code change if it's especially complex, important, or if the users asks about it. This also holds true for PR explanations, codebase walkthroughs, or architectural decisions: provide a high-level walkthrough unless specifically asked and cap answers at 2-3 sections.
2208
+ Send an update only when it changes the user's understanding of the work: a meaningful discovery, a decision with tradeoffs, a blocker, a substantial plan, or the start of a non-trivial edit or verification step.
2233
2209
 
2234
- Requirements for your final answer:
2235
- - Prefer short paragraphs by default.
2236
- - When explaining something, optimize for fast, high-level comprehension rather than completeness-by-default.
2237
- - Use lists only when the content is inherently list-shaped: enumerating distinct items, steps, options, categories, comparisons, ideas. Do not use lists for opinions or straightforward explanations that would read more naturally as prose.
2238
- - Do not turn simple explanations into outlines or taxonomies unless the user asks for depth. If a list is used, each bullet should be a complete standalone point.
2239
- - Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done -", "Got it", "Great question, ", "You're right to call that out") or framing phrases.
2240
- - The user does not see command execution outputs. When asked to show the output of a command (e.g. \`git show\`), relay the important details in your answer or summarize the key lines so the user understands the result.
2241
- - Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have.
2242
- - If the user asks for a code explanation, include code references as appropriate.
2243
- - If you weren't able to do something, for example run tests, tell the user.
2244
- - Never overwhelm the user with answers that are over 50-70 lines long; provide the highest-signal context instead of describing everything exhaustively.
2245
- - Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the \`1. 2. 3.\` style markers (with a period), never \`1)\`.
2210
+ Do not narrate routine searching, file reads, obvious next steps, or incremental confirmations. Combine related progress into a single update instead of a sequence of small status messages.
2246
2211
 
2247
- ## Intermediary updates
2212
+ Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done —", "Got it", "Great question") or framing phrases.
2213
+
2214
+ Before doing substantial work, you start with a user update explaining your first step. Avoid commenting on the request or using starters such as "Got it" or "Understood".
2215
+
2216
+ After you have sufficient context, and the work is substantial you can provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).
2248
2217
 
2249
- - Intermediary updates go to the \`commentary\` channel.
2250
- - User updates are short updates while you are working, they are NOT final answers.
2251
- - You use 1-2 sentence user updates to communicated progress and new information to the user as you are doing work.
2252
- - Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done -", "Got it", "Great question, ") or framing phrases.
2253
- - Before exploring or doing substantial work, you start with a user update acknowledging the request and explaining your first step. You should include your understanding of the user request and explain what you will do. Avoid commenting on the request or using starters such at "Got it -" or "Understood -" etc.
2254
- - You provide user updates on important steps, do not be too chatty.
2255
- - When exploring, e.g. searching, reading files you provide user updates as you go, explaining what context you are gathering and what you've learned. Vary your sentence structure when providing these updates to avoid sounding repetitive - in particular, don't start each sentence the same way.
2256
- - When working for a while, keep updates informative and varied, but stay concise.
2257
- - After you have sufficient context, and the work is substantial you provide a longer plan (this is the only user update that may be longer than 2 sentences and can contain formatting).
2258
- - Before performing file edits of any kind, you provide updates explaining what edits you are making.
2259
- - As you are thinking, you very frequently provide updates even if not taking any actions, informing the user of your progress. You interrupt your thinking and send multiple updates in a row if thinking for more than 100 words.
2260
- - Tone of your updates MUST match your personality.
2218
+ Before performing file edits of any kind, provide updates explaining what edits you are making.
2261
2219
  `}var K84=Q0(()=>{H4()});function V84({enableTaskList:J=!1}={}){return`You are Amp, a powerful AI coding agent, optimized for speed and efficiency.
2262
2220
 
2263
2221
  # Agency
@@ -6082,7 +6040,7 @@ password=${K}
6082
6040
  `).length-1});throw new j1(`Invalid JSON in settings file ${Z}`,1,`Fix the JSON syntax errors. Errors found on lines [${I.join(", ")}].`)}R.debug("readSettings",{settingsPath:Z,rawConfig:A});let j={};for(let[I,_]of Object.entries(A))if(I.startsWith("amp.")){let S=I.substring(4);j[S]=_}return z=j,j}catch(L){if(L.code==="ENOENT")return z={},z;throw R.error(`Failed to read settings: ${L}`),L}}async function H(O){await k90.acquire();try{await U(),await Om(Z,(L)=>{let M=L;for(let[A,j]of Object.entries(O)){let I=ON0(M,[`amp.${A}`],j,{formattingOptions:{tabSize:2,insertSpaces:!0}});if(I.length>0)M=LN0(M,I)}return{newContent:M}},{mode:384}),z=O}catch(L){throw R.error(`Failed to write settings: ${L}`),L}finally{k90.release()}}function B(){if(G)return;if(process.versions.bun){try{D=Y(Z,(O,L)=>{R.debug("Settings file change detected (fallback watcher)",{settingsPath:Z,curr:O,prev:L}),N()}),G=!0,R.debug("Started watching settings file with fallback watcher (Bun)",{settingsPath:Z})}catch(O){R.error("Failed to start fallback file watcher",{settingsPath:Z,error:O})}return}try{let O=AQ.dirname(Z),L=AQ.basename(Z);F=Q(O,(M,A)=>{if(A!==L)return;R.debug("Settings file change detected",{eventType:M,filename:A,settingsPath:Z}),N()}),F.on("error",(M)=>{R.debug("transient file watcher error",{error:M}),N()}),R.debug("Started watching settings directory",{dir:O,targetFilename:L})}catch(O){if(O.code==="ENOENT"){if(!D)D=Y(Z,(L,M)=>{if(L.ino===0)return;R.debug("Settings file created, starting file watcher",{settingsPath:Z}),B(),D?.close(),D=void 0})}else R.warn("Failed to start watching settings directory",{settingsPath:Z,error:O})}G=!0}function N(){if(q)clearTimeout(q);q=setTimeout(w,X)}async function w(){try{let O=z;z=void 0,await new Promise((A)=>setTimeout(A,K));let L=await W(!0),M=dV4(O,L);if(M.length>0)z=void 0,V.next(M),R.info("Settings reloaded",{changedKeys:M})}catch(O){R.warn("Failed to handle settings file change",{settingsPath:Z,error:O})}}function E(){if(F)F.close(),F=void 0;if(D)D.close(),D=void 0;if(q)clearTimeout(q),q=void 0;G=!1,R.debug("Stopped watching settings directory",{settingsPath:Z})}return{async get(O){return(await W())[O]},async set(O,L,M){let A=await W();A[O]=L,await H(A),V.next([O])},async delete(O,L){await k90.acquire();try{await Om(Z,(A)=>{let j=`amp.${O}`,I=ON0(A,[j],void 0,{formattingOptions:{tabSize:2,insertSpaces:!0}});return{newContent:I.length>0?LN0(A,I):A}},{mode:384});let M=await W();delete M[O],z=M,V.next([O])}catch(M){throw R.error(`Failed to delete setting: ${M}`),M}finally{k90.release()}},async keys(){let O=await W();return Object.keys(O)},getSettingsFilePath(){return Z},changes:V,[Symbol.dispose](){E()}}}async function UP5(J){let Z=await pV4(J.settingsFile??tY,tY),Q=await cV4({...J,settingsFile:Z});return{...Q,async set(Y,X){return nC(Y,"global"),Q.set(Y,X)},async delete(Y){return nC(Y,"global"),Q.delete(Y)}}}async function WP5(J){let{workspaceRootPath:Z,workspaceSettingsPath:Q}=await qP5(J.cwd),Y=await cV4({...J,settingsFile:Q}),X=new c1,K=Y.changes.subscribe((F)=>X.next(F)),V=J.workspaceTrust?.current??!1,z=J.workspaceTrust?.changes?.subscribe(async(F)=>{let q=V;if(V=F,!q&&F){let D=(await Y.keys()).filter((U)=>Mr.includes(U));if(D.length>0)X.next(D)}});return{...Y,changes:X,getWorkspaceRootPath(){return Z},async get(F){if(!V&&Mr.includes(F))return;return Y.get(F)},async set(F,q){return nC(F,"workspace"),Y.set(F,q)},async delete(F){return nC(F,"workspace"),Y.delete(F)},async keys(){let F=await Y.keys();if(!V)return F.filter((q)=>!Mr.includes(q));return F},[Symbol.dispose](){K.unsubscribe(),z?.unsubscribe(),Y[Symbol.dispose]()}}}async function lV4(J){let Z=J.getHook,Q=new c1,Y=await UP5(J),X=await WP5({...J,cwd:J.cwd||process.cwd()});R.info("Using settings file",{settingsPath:Y.getSettingsFilePath(),workspaceSettingsPath:X.getSettingsFilePath(),workspaceRootPath:X.getWorkspaceRootPath()});let K=Y.changes.subscribe((z)=>Q.next(z)),V=X.changes.subscribe((z)=>Q.next(z));return{async get(z,F){let q=async()=>{switch(F){case"global":return Y.get(z);case"workspace":return X.get(z);case"admin":throw Error("Cannot get admin settings from file storage");case void 0:break}let[G,D]=await Promise.all([Y.get(z),X.get(z)]);return hV4(z,{global:G,workspace:D})};return Z?Z(z,q):q()},async set(z,F,q="workspace"){switch(nC(z,q),q){case"workspace":await X.set(z,F);break;case"global":await Y.set(z,F);break;default:}Q.next([z])},async delete(z,F="workspace"){switch(nC(z,F),F){case"workspace":await X.delete(z);break;case"global":await Y.delete(z);break;default:}Q.next([z])},async keys(){let z=await Y.keys(),F=await X.keys(),q=new Set([...z,...F]);return Array.from(q)},getSettingsFilePath(){return Y.getSettingsFilePath()},getWorkspaceRootPath(){return X.getWorkspaceRootPath()},getWorkspaceSettingsPath(){return X.getSettingsFilePath()},changes:Q,[Symbol.dispose](){K.unsubscribe(),V.unsubscribe(),Y[Symbol.dispose](),X[Symbol.dispose]()}}}h0();import HP5,{promises as y90}from"node:fs";import BP5 from"node:path";import{stderr as iV4,stdout as NP5}from"node:process";H1();var wP5="secrets.json";function nV4(J){return BP5.join(J.dataDir,wP5)}function aV4(J){let Z=new vV(R).scoped("secrets.file"),Q=new c1,Y,X=nV4(J),K=new wQ;async function V(){try{await y90.mkdir(J.dataDir,{recursive:!0})}catch(q){throw Z.error(`Failed to create data directory: ${q}`),q}}async function z(){if(Y)return Y;try{await V();let q=await y90.readFile(X,"utf-8");return Y=JSON.parse(q),Y}catch(q){if(q.code==="ENOENT")return Y={},Y;throw Z.error("Failed to read secrets",{secretsPath:X,error:q}),q}}async function F(q){await K.acquire();try{await V(),await Om(X,()=>({newContent:JSON.stringify(q,null,2)}),{mode:384}),Y=q}catch(G){throw Z.error("Failed to write secrets",{secretsPath:X,error:G}),G}finally{K.release()}}return{async get(q,G){let D=await z(),U=Tj(G);return D[`${q}@${U}`]},async set(q,G,D){let U=Tj(D),W=`${q}@${U}`,H=await z();H[W]=G,await F(H),Q.next(W)},changes:Q}}async function oV4(J,Z){let Q=new vV(R).scoped("secrets.file.migrate"),Y=nV4(J);if(!HP5.existsSync(Y))return;let X=await y90.readFile(Y,"utf-8"),K=JSON.parse(X);if(Object.keys(K).length===0)return;if(!J.quiet)NP5.write(`Migrating secrets from file storage to native secret storage...
6083
6041
  `);let V=[];for(let[z,F]of Object.entries(K))if(typeof F==="string"){let q=z.match(/^(.+)@(.+)$/);if(q){let[,G,D]=q;if(G&&D)try{await Z.set(G,F,D),V.push(z),Q.debug(`Successfully migrated secret: ${z}`)}catch(U){throw iV4.write(`Failed to migrate secret ${z} to native secret storage
6084
6042
  `),U}}}if(V.length>0)try{await y90.rm(Y),Q.info("Successfully migrated secrets and removed file storage",{migratedKeys:V,removed:Y})}catch(z){throw iV4.write(`Failed to remove file storage after migration
6085
- `),z}}h0();H1();async function rV4(){let J=new vV(R).scoped("secrets.native"),Z=new c1,Q={},Y=(await import("@napi-rs/keyring")).Entry;async function X(K,V){let z;try{z=new URL(V).hostname}catch{z=V}return new Y(`amp.cli.${K}`,z)}return{async get(K,V){let z=Tj(V),F=`${K}@${z}`;if(F in Q)return Q[F];let q=await X(K,z);try{let D=q.getPassword()||void 0;return Q[F]=D,D}catch(G){J.warn("failed to get secret",{name:K,url:V,error:G}),Q[F]=void 0;return}},async set(K,V,z){let F=Tj(z),q=await X(K,F);if(V)q.setPassword(V);else q.deleteCredential();let G=`${K}@${F}`;Q[G]=V,Z.next(G)},changes:Z}}async function _f0(J,Z){let Q={dataDir:J.dataDir||aC};if(!await Z.get("experimental.cli.nativeSecretsStorage.enabled","global"))return R.info("using file-based secrets storage",Q),aV4(Q);R.info("using native secrets storage");let Y;try{Y=await rV4()}catch(X){throw R.error("failed to initialize native secrets storage",{error:X,platform:process.platform}),Error("Native secret storage is not supported on this machine")}return await oV4(Q,Y),Y}async function sV4(J){return lV4(J)}var tV4={"agent.deepReasoningEffort":{value:"high",visible:!0,description:"Default GPT-5.4 reasoning effort for new deep-mode threads (medium, high, xhigh)."},"agent.skipTitleGenerationIfMessageContains":{value:[],visible:!1,description:"List of strings that, if present in a message, will skip title generation"},"anthropic.effort":{value:"high",visible:!1,description:"Effort level for Anthropic models that support auto-thinking (low, medium, high, max). Higher effort means more thinking and better performance."},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"anthropic.speed":{value:void 0,visible:!1,description:"Fast speed toggle for smart mode (Anthropic fast mode)"},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},bitbucketToken:{value:void 0,visible:!0,description:"Personal access token for Bitbucket Enterprise. Used with a workspace-level Bitbucket connection configured by an admin."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},defaultVisibility:{value:{"github.com/sourcegraph/amp":"workspace"},visible:!0,description:["Define default thread visibility per repository origin using mappings like ",'"github.com/org/repo": "workspace". Values: private, public, workspace, group.'].join("")},"experimental.cli.nativeSecretsStorage.enabled":{value:!1,visible:!1,description:"Use native secret storage instead of the plain-text secrets configuration file"},"experimental.modes":{value:[],visible:!0,description:"Enable experimental agent modes by name. Available modes: deep"},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name"},"fuzzy.alwaysIncludePaths":{value:[],visible:!0,description:"Glob patterns for paths that should always be included in fuzzy file search, even if gitignored"},"gemini.thinkingLevel":{value:void 0,visible:!1,description:"Thinking level for Gemini models (minimal, low, medium, high, or undefined)"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"guardedFiles.allowlist":{value:[],visible:!0,description:"Array of file glob patterns that are allowed to be accessed without confirmation. Takes precedence over the built-in denylist."},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"jetbrains.skipInstall":{value:!1,visible:!1,description:"Skip JetBrains plugin installation"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"network.timeout":{value:30,visible:!0,description:"How many seconds to wait for network requests to the Amp server before timing out"},"notifications.enabled":{value:!0,visible:!0,description:"Enable system sound notifications when agent completes tasks"},"notifications.system.enabled":{value:!0,visible:!0,description:"Enable system notifications when terminal is not focused"},"openai.speed":{value:void 0,visible:!1,description:"Fast speed toggle for deep/internal modes (OpenAI priority tier)"},permissions:{value:[{tool:"Bash",action:"ask",matches:{cmd:["git push*","git commit*","git branch -D*","git checkout HEAD*"]}}],visible:!0,description:"Permission rules for tool calls. See amp permissions --help"},proxy:{value:void 0,visible:!0,description:"Proxy URL used for both HTTP and HTTPS requests to the Amp server"},showCosts:{value:!0,visible:!0,description:"Set to false to hide costs while working on a thread"},"skills.path":{value:void 0,visible:!0,description:"Path to additional directories containing skills. Supports colon-separated paths (semicolon on Windows). Use ~ for home directory."},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},systemPrompt:{value:void 0,visible:!1,description:"Custom system prompt text to append (SDK use only)"},"terminal.animation":{value:!0,visible:!0,description:"Set to false to disable terminal animations (or use the equivalent NO_ANIMATION=1 env var)"},"terminal.commands.nodeSpawn.loadProfile":{value:"daily",visible:!1,description:"How often to load shell profile in node-spawn mode (always, daily, never)"},"terminal.theme":{value:"terminal",visible:!0,description:"Color theme for the CLI. Built-in: terminal, dark, light, catppuccin-mocha, solarized-dark, solarized-light, gruvbox-dark-hard, nord. Custom themes: ~/.config/amp/themes/<name>/colors.toml"},"toolbox.path":{value:void 0,visible:!0,description:"Path to the directory containing toolbox scripts. Supports colon-separated paths."},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.enable":{value:void 0,visible:!0,description:"Array of tool name patterns to enable. Supports glob patterns (e.g., 'mcp__metabase__*'). If not set, all tools are enabled. If set, only matching tools are enabled."},"tools.inactivityTimeout":{value:300,visible:!1,description:"How many seconds of no output to wait before canceling bash commands"},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},"updates.mode":{value:"auto",visible:!0,description:'Control update checking behavior: "warn" shows update notifications, "disabled" turns off checking, "auto" automatically runs update.'},"windowsPasteHook.enabled":{value:!0,visible:!0,description:"Enable the Windows Ctrl+V clipboard hook integration for reliable text and image paste."},url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"}},EP5=Object.fromEntries(Object.entries(tV4).filter(([,J])=>J.visible).map(([J,Z])=>[`amp.${J}`,Z.value])),Mm={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
6043
+ `),z}}h0();H1();async function rV4(){let J=new vV(R).scoped("secrets.native"),Z=new c1,Q={},Y=(await import("@napi-rs/keyring")).Entry;async function X(K,V){let z;try{z=new URL(V).hostname}catch{z=V}return new Y(`amp.cli.${K}`,z)}return{async get(K,V){let z=Tj(V),F=`${K}@${z}`;if(F in Q)return Q[F];let q=await X(K,z);try{let D=q.getPassword()||void 0;return Q[F]=D,D}catch(G){J.warn("failed to get secret",{name:K,url:V,error:G}),Q[F]=void 0;return}},async set(K,V,z){let F=Tj(z),q=await X(K,F);if(V)q.setPassword(V);else q.deleteCredential();let G=`${K}@${F}`;Q[G]=V,Z.next(G)},changes:Z}}async function _f0(J,Z){let Q={dataDir:J.dataDir||aC};if(!await Z.get("experimental.cli.nativeSecretsStorage.enabled","global"))return R.info("using file-based secrets storage",Q),aV4(Q);R.info("using native secrets storage");let Y;try{Y=await rV4()}catch(X){throw R.error("failed to initialize native secrets storage",{error:X,platform:process.platform}),Error("Native secret storage is not supported on this machine")}return await oV4(Q,Y),Y}async function sV4(J){return lV4(J)}var tV4={"agent.deepReasoningEffort":{value:"high",visible:!0,description:"Default GPT-5.3 Codex reasoning effort for new deep-mode threads (medium, high, xhigh)."},"agent.skipTitleGenerationIfMessageContains":{value:[],visible:!1,description:"List of strings that, if present in a message, will skip title generation"},"anthropic.effort":{value:"high",visible:!1,description:"Effort level for Anthropic models that support auto-thinking (low, medium, high, max). Higher effort means more thinking and better performance."},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"anthropic.speed":{value:void 0,visible:!1,description:"Fast speed toggle for smart mode (Anthropic fast mode)"},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},bitbucketToken:{value:void 0,visible:!0,description:"Personal access token for Bitbucket Enterprise. Used with a workspace-level Bitbucket connection configured by an admin."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},defaultVisibility:{value:{"github.com/sourcegraph/amp":"workspace"},visible:!0,description:["Define default thread visibility per repository origin using mappings like ",'"github.com/org/repo": "workspace". Values: private, public, workspace, group.'].join("")},"experimental.cli.nativeSecretsStorage.enabled":{value:!1,visible:!1,description:"Use native secret storage instead of the plain-text secrets configuration file"},"experimental.modes":{value:[],visible:!0,description:"Enable experimental agent modes by name. Available modes: deep"},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name"},"fuzzy.alwaysIncludePaths":{value:[],visible:!0,description:"Glob patterns for paths that should always be included in fuzzy file search, even if gitignored"},"gemini.thinkingLevel":{value:void 0,visible:!1,description:"Thinking level for Gemini models (minimal, low, medium, high, or undefined)"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"guardedFiles.allowlist":{value:[],visible:!0,description:"Array of file glob patterns that are allowed to be accessed without confirmation. Takes precedence over the built-in denylist."},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"jetbrains.skipInstall":{value:!1,visible:!1,description:"Skip JetBrains plugin installation"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"network.timeout":{value:30,visible:!0,description:"How many seconds to wait for network requests to the Amp server before timing out"},"notifications.enabled":{value:!0,visible:!0,description:"Enable system sound notifications when agent completes tasks"},"notifications.system.enabled":{value:!0,visible:!0,description:"Enable system notifications when terminal is not focused"},"openai.speed":{value:void 0,visible:!1,description:"Fast speed toggle for deep/internal modes (OpenAI priority tier)"},permissions:{value:[{tool:"Bash",action:"ask",matches:{cmd:["git push*","git commit*","git branch -D*","git checkout HEAD*"]}}],visible:!0,description:"Permission rules for tool calls. See amp permissions --help"},proxy:{value:void 0,visible:!0,description:"Proxy URL used for both HTTP and HTTPS requests to the Amp server"},showCosts:{value:!0,visible:!0,description:"Set to false to hide costs while working on a thread"},"skills.path":{value:void 0,visible:!0,description:"Path to additional directories containing skills. Supports colon-separated paths (semicolon on Windows). Use ~ for home directory."},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},systemPrompt:{value:void 0,visible:!1,description:"Custom system prompt text to append (SDK use only)"},"terminal.animation":{value:!0,visible:!0,description:"Set to false to disable terminal animations (or use the equivalent NO_ANIMATION=1 env var)"},"terminal.commands.nodeSpawn.loadProfile":{value:"daily",visible:!1,description:"How often to load shell profile in node-spawn mode (always, daily, never)"},"terminal.theme":{value:"terminal",visible:!0,description:"Color theme for the CLI. Built-in: terminal, dark, light, catppuccin-mocha, solarized-dark, solarized-light, gruvbox-dark-hard, nord. Custom themes: ~/.config/amp/themes/<name>/colors.toml"},"toolbox.path":{value:void 0,visible:!0,description:"Path to the directory containing toolbox scripts. Supports colon-separated paths."},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.enable":{value:void 0,visible:!0,description:"Array of tool name patterns to enable. Supports glob patterns (e.g., 'mcp__metabase__*'). If not set, all tools are enabled. If set, only matching tools are enabled."},"tools.inactivityTimeout":{value:300,visible:!1,description:"How many seconds of no output to wait before canceling bash commands"},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},"updates.mode":{value:"auto",visible:!0,description:'Control update checking behavior: "warn" shows update notifications, "disabled" turns off checking, "auto" automatically runs update.'},"windowsPasteHook.enabled":{value:!0,visible:!0,description:"Enable the Windows Ctrl+V clipboard hook integration for reliable text and image paste."},url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"}},EP5=Object.fromEntries(Object.entries(tV4).filter(([,J])=>J.visible).map(([J,Z])=>[`amp.${J}`,Z.value])),Mm={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
6086
6044
 
6087
6045
  - README.md (root)
6088
6046
  - AGENT.md (root)
@@ -6193,11 +6151,11 @@ ${W}`))}},error:(U)=>{if(!D)D=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
6193
6151
  ${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
6194
6152
 
6195
6153
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6196
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!G)G=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!G)G=!0,V()}})})}h0();h0();gP();async function h90(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await z.json(),q=F.version??F["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=rz4(J,q),D=G<0,U,W;if(F.time){let H=F.time[J],B=F.time[q],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)W=Math.floor((N-new Date(B).getTime())/3600000)}return R.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:D,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:D,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(z){return R.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var pC5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function g90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${pC5}?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=rz4(J,X),V=K<0;return R.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return R.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var dC5=604800000;function oz4(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>dC5)return{ageMs:Q};return null}function rz4(J,Z){let Q=(V)=>{let[z,F]=V.split("-");return{parts:z?.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 z=Y.parts[V]||0,F=X.parts[V]||0;if(z<F)return-1;if(z>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 of0(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?pW(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function rf0(J,Z,Q={}){let Y=new c1,X=Y.pipe(I6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new vV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await Kz(V);let z=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 Kz(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 q=await Z.get("updates.mode");if(q==="disabled"){K.debug("checking disabled");return}let G=await b90(),D=G==="binary"||G==="brew";K.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:D});let U=D?await g90(J):await h90(J,JL());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let W=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!W())Y.next("update-available-brew");return}if(G==="binary"&&process.execPath!==df0()){if(K.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(q==="warn"){if(!W())Y.next("update-available");return}if(!G){if(K.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Tm(U.latestVersion,G);let H=await LH(U.latestVersion),B={from:U.currentVersion,to:U.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 Kz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}gP();import{stderr as $F}from"node:process";function sz4(J){let Z=new qH().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 hf0(Y.force||!1,Y.verbose||!1,"0.0.1773982701-g41d390"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new qH("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 cC5(Y.targetVersion)});J.addCommand(Q)}async function cC5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")$F.write(d0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6154
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!G)G=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!G)G=!0,V()}})})}h0();h0();gP();async function h90(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await z.json(),q=F.version??F["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=rz4(J,q),D=G<0,U,W;if(F.time){let H=F.time[J],B=F.time[q],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)W=Math.floor((N-new Date(B).getTime())/3600000)}return R.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:D,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:D,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(z){return R.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var pC5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function g90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${pC5}?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=rz4(J,X),V=K<0;return R.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return R.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var dC5=604800000;function oz4(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>dC5)return{ageMs:Q};return null}function rz4(J,Z){let Q=(V)=>{let[z,F]=V.split("-");return{parts:z?.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 z=Y.parts[V]||0,F=X.parts[V]||0;if(z<F)return-1;if(z>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 of0(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?pW(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function rf0(J,Z,Q={}){let Y=new c1,X=Y.pipe(I6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new vV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await Kz(V);let z=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 Kz(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 q=await Z.get("updates.mode");if(q==="disabled"){K.debug("checking disabled");return}let G=await b90(),D=G==="binary"||G==="brew";K.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:D});let U=D?await g90(J):await h90(J,JL());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let W=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!W())Y.next("update-available-brew");return}if(G==="binary"&&process.execPath!==df0()){if(K.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(q==="warn"){if(!W())Y.next("update-available");return}if(!G){if(K.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Tm(U.latestVersion,G);let H=await LH(U.latestVersion),B={from:U.currentVersion,to:U.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 Kz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}gP();import{stderr as $F}from"node:process";function sz4(J){let Z=new qH().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 hf0(Y.force||!1,Y.verbose||!1,"0.0.1773994045-ge5da52"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new qH("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 cC5(Y.targetVersion)});J.addCommand(Q)}async function cC5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")$F.write(d0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6197
6155
 
6198
6156
  `));try{if(!J){$F.write(d0.blue(`Checking for updates...
6199
- `));let{hasUpdate:Y,latestVersion:X}=gf0()?await g90("0.0.1773982701-g41d390"):await h90("0.0.1773982701-g41d390",JL());if(!Y){let K=of0("0.0.1773982701-g41d390"),V=K?.age?`released ${K.age} ago`:`built ${pW(new Date("2026-03-20T05:02:03.107Z"))} ago`;$F.write(d0.green(`✓ Amp is already up to date on version ${"0.0.1773982701-g41d390"} (${V})
6200
- `));let z=await LH("0.0.1773982701-g41d390");if(z.warning)$F.write(`
6157
+ `));let{hasUpdate:Y,latestVersion:X}=gf0()?await g90("0.0.1773994045-ge5da52"):await h90("0.0.1773994045-ge5da52",JL());if(!Y){let K=of0("0.0.1773994045-ge5da52"),V=K?.age?`released ${K.age} ago`:`built ${pW(new Date("2026-03-20T08:11:11.923Z"))} ago`;$F.write(d0.green(`✓ Amp is already up to date on version ${"0.0.1773994045-ge5da52"} (${V})
6158
+ `));let z=await LH("0.0.1773994045-ge5da52");if(z.warning)$F.write(`
6201
6159
  `+d0.yellow(z.warning)+`
6202
6160
  `);process.exit(0)}if(!X)$F.write(d0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}$F.write(d0.blue(`Updating to version ${J}...
6203
6161
  `)),await Tm(J,void 0,(Y)=>{$F.write(d0.dim(`Running: ${Y}
@@ -7368,7 +7326,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let u=q.text.replace(/`([^`]+)`/g,"$1")+`
7368
7326
  `),K=[];for(let V=0;V<X.length;V++){let q=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 G of q)if(G.startsWith("\x00")&&G.endsWith("\x01"))K.push(new C(G.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else K.push(new C(G,new h({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7369
7327
  `))}return new l0({decoration:{color:Q.colorScheme.background,border:f1.all(new y1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class qd0 extends P7{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=IJ0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new zd0({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 dO4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?n8:0,F=Y-z;if(F<=0)return null;let q=Z-z;if(q<0||q>=F)return null;let G=Math.max(1,Math.floor(F/K)),D=Math.floor(q/G);return D>=0&&D<K?D:null}case"line":case"sparkline":case"stacked-area":{let z=V?n8:0,F=Y-z;if(F<=0)return null;let q=Math.max(0,Math.min(F-1,Z-z));if(K===1)return 0;let G=F/(K-1),D=Math.round(q/G);return Math.max(0,Math.min(K-1,D))}default:return null}}function Ns5(J,Z,Q,Y,X,K,V,z){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 q=K?n8:0,G=Q-q,D=Y-(K?F:0);if(G<=0||D<=0)return null;let U=Math.max(1,Math.floor(G/X)),W=q+Z*U+Math.floor(U/2),H=z>0?V/z:0,B=Math.round((1-H)*(D-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let q=K?n8:0,G=Q-q,D=Y-(K?F:0);if(G<=0||D<=0)return null;let U=X>1?q+Math.round(Z/(X-1)*(G-1)):q+Math.floor(G/2),W=z>0?V/z:0,H=Math.round((1-W)*(D-1));return{x:U,y:H}}default:return null}}function ws5(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 Es5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+F.length}let K=J.label.length,V=0;for(let z of Q){let F=z.points[Z];if(!F)continue;V+=F.value;let q=2+z.name.length+2+Y(F.value).length;K=Math.max(K,q)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function Os5(J,Z,Q,Y,X,K,V){let z;try{let H=R1.of(J),B=u0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new h({color:z.foreground,bold:!0}),q=new h({color:z.foreground}),G=new h({color:z.foreground,dim:!0}),D=[],U=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,U,void 0,s90(H),()=>{t3(J,H)});if(Y.length<=1){if(D.push(new C(`${Z.label}: `,F)),Z.link)D.push(W(Z.link,K(Z.value)));else D.push(new C(K(Z.value),q));if(Z.meta)D.push(new C(` (${Z.meta})`,G))}else{let H=V==="stacked-bar"||V==="stacked-area";D.push(new C(`${Z.label}
7370
7328
  `,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],E=w.points[Q];if(!E)continue;B+=E.value;let O=w.color??X[N%X.length]??z.foreground;if(D.push(new C("● ",new h({color:O}))),D.push(new C(`${w.name}: `,G)),E.link)D.push(W(E.link,K(E.value)));else D.push(new C(K(E.value),q));if(N<Y.length-1||H)D.push(new C(`
7371
- `))}if(H)D.push(new C(" ",G)),D.push(new C("Total: ",G)),D.push(new C(K(B),q))}return new l0({decoration:{color:z.background,border:f1.all(new y1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,D)})})}Vw();h0();m9();import{execSync as os5}from"node:child_process";Dw();D7();N3();_2();Lh();mX();t7();g$();lZ();PO();A4();yu();vy();H1();var dL4=O4(fq(),1);import{writeFile as bL4}from"fs/promises";import hL4 from"path";h0();t7();class Gd0{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.1773982701-g41d390"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Hs(Z,this.configService)}catch(Z){R.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 qB extends c0{props;constructor(J){super();this.props=J}createState(){return new cO4}}class cO4 extends p0{_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 lO4 extends p0{controller=new s2;focusNode=new o4({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=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=f1.all(new y1(Q.foreground,1,"solid")),F=new WJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),q=new G1({children:[new l0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:F})]}),G=new l0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(V)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let U=new l0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,D)})});return new l0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[G,new R0({height:1}),q,new F3,U]})})}}class Od extends c0{props;constructor(J){super();this.props=J}createState(){return new lO4}}import{isDeepStrictEqual as Dd0}from"node:util";var Ls5=/[\\/_ +.#"@[({&]/,Ms5=/[\\/_ +.#"@[({&]/g,As5=/[\s-]/,iO4=/[\s-]/g;function TJ0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let F=Y.charAt(K),q=Q.indexOf(F,X),G=0,D,U,W,H;while(q>=0){if(D=TJ0(J,Z,Q,Y,q+1,K+1,V),D>G){if(q===X)D*=1;else if(As5.test(J.charAt(q-1))){if(D*=0.9,H=J.slice(X,q-1).match(iO4),H&&X>0)D*=0.999**H.length}else if(Ls5.test(J.charAt(q-1))){if(D*=0.8,W=J.slice(X,q-1).match(Ms5),W&&X>0)D*=0.999**W.length}else if(D*=0.3,X>0)D*=0.999**(q-X);if(J.charAt(q)!==Z.charAt(K))D*=0.9999}if(D<0.1&&(Q.charAt(q-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(q-1)!==Y.charAt(K))){if(U=TJ0(J,Z,Q,Y,q+1,K+2,V),U*0.1>D)D=U*0.1}if(D>G)G=D;q=Q.indexOf(F,q+1)}return V[z]=G,G}function CJ0(J){return J.toLowerCase().replace(iO4," ")}function nO4(J,Z){let Q=TJ0(J,Z,CJ0(J),CJ0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let F=TJ0(J,z,CJ0(J),CJ0(z),0,0,{});if(F===0)return Q;X+=F,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class X_{}class K_{}class _J0{}class SJ0{}class aO4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new oO4}}class oO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function js5(J,Z){if(J==="")return{matches:!0,score:1};let Q=nO4(Z,J);return{matches:Q>0.15,score:Q}}class e9 extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new rO4}}class rO4 extends p0{textController;focusNode;scrollController=new Q5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s2(this.widget.props.controller?.query??""),this.focusNode=new o4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),G6.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)=>Dd0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Dd0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Dd0(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 X_){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof K_){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof _J0){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 SJ0)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,...js5(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;eT(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(),G6.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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new y1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new WJ({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 y7({shortcuts:new Map([[new Y4("ArrowDown"),new X_],[new Y4("ArrowUp"),new K_],[new Y4("Tab"),new X_],[new Y4("Tab",{shift:!0}),new K_],[new Y4("n",{ctrl:!0}),new X_],[new Y4("p",{ctrl:!0}),new K_],[new Y4("Enter"),new _J0],[new Y4("Escape"),new SJ0]]),focusNode:this.focusNode,child:z}),q=new k9({actions:new Map([[X_,new r4(this.invoke)],[K_,new r4(this.invoke)],[_J0,new r4(this.invoke)],[SJ0,new r4(this.invoke)]]),child:F}),G=new G1({children:[new l0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:q})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";D=new R0({height:10,child:new i1({child:new e({text:new C(N,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new _1({child:new i1({child:new e({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,L,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new l0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new h({color:j,dim:L}))})})}return new aO4(new a1({onClick:(A)=>this.handleItemClick(E,A.clickCount),child:M}),(A)=>{this.itemContexts[E]=A})});D=new x0({children:N,crossAxisAlignment:"start"})}let U=new a1({onScroll:this.handleScroll,opaque:!1,child:new R6({controller:this.scrollController,autofocus:!1,child:D})}),W=[];if(this.widget.props.title){let N=new l0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(N)}if(!K)W.push(G,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);W.push(new _1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new _1({child:U}),new l0({padding:C0.only({top:1}),child:new i1({child:w??new R0({height:1})})})]})}))}else W.push(new _1({child:U}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new l0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:W})})}}function sO4(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 Ud0 extends l1{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)=>sO4(X.pubDate).length));return new e9({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,z)=>{let F=u0.of(z),{colors:q}=F,G=F.app,D=K?G.selectionBackground:void 0,U=K?G.selectionForeground:q.foreground,W=q.mutedForeground,H=(B,N)=>new R0({width:N,child:G1.end([new e({text:new C(B,new h({color:W}))})])});return new l0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new G1({children:[new _1({child:new e({text:new C(X.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(sO4(X.pubDate),Q)]})})}})}}A4();class Wd0 extends c0{createState(){return new tO4}}class tO4 extends p0{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=u0.of(J).colors;return new e({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Rs5=/\/threads\/(T-[^/?#\s<>]+)/i;function Is5(J){let Z=J.trim(),Y=Z.match(Rs5)?.[1];if(Y&&N8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(N8(X))return X;return null}function Ps5(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 z=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(z){Y.set(V.id,z.type);let F=z.threadID,q=Q.get(F)||[];q.push(V),Q.set(F,q)}else X.push(V)}return F$0.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 Hd0(J,Z,Q){return new e({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function Cs5(J,Z,Q,Y){return[Hd0("+",J,Y.success),F3.horizontal(1),Hd0("~",Z,Y.warning),F3.horizontal(1),Hd0("-",Q,Y.destructive)]}function Ts5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class kJ0 extends c0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new eO4}}class eO4 extends p0{spinner=new a5;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((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((E)=>E.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),F=Z.currentThreadID,q=[...K].sort((E,O)=>{if(F){if(E.id===F)return-1;if(O.id===F)return 1}let L=V.indexOf(E.id),M=V.indexOf(O.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),G=Ps5(q),D=Math.max(0,...G.map((E)=>E.description.timeAgo.length)),U=u0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new i1({child:new e({text:new C("",new h({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(E)=>{if(E!==H)H=E,B=Is5(E);return B};return new e9({items:G,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=N(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>N(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!Ts5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(E,O,L,M)=>{let A=u0.of(M),{app:j,colors:I}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:I.foreground,v=I.mutedForeground,g=(t,W0)=>new R0({width:W0,child:G1.end([new e({text:new C(t,new h({color:v}))})])}),b=Z.threadViewStates[E.id],k=[],u=E.relationshipType==="handoff",p=new np({connectorColor:I.mutedForeground});if(E.depth>0){let t=[],W0=E.ancestorsAreLast.slice(1);for(let w0 of W0)t.push(new C(p.getAncestorPrefix(w0),new h({color:p.connectorColor,dim:p.connectorDim})));let n=E.isLast?p.elbow:p.tee,D0=p.getConnectorText(n);t.push(new C(D0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new e({text:new C("",void 0,t)}))}let c=[],f=F===E.id?new C("(current) ",new h({color:I.success})):z.has(E.id)?new C("(visited) ",new h({color:I.foreground,dim:!0})):null;if(f)c.push(new e({text:f}));if(mW(b))c.push(new Wd0),c.push(new R0({width:1}));let o=E.title;if(E.relationshipType==="fork"){let t=o.match(/^Forked\((\d+)\): /);if(t)o=o.slice(t[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);c.push(new e({text:new C("[fork] ",new h({color:I.primary}))}))}else if(u)c.push(new e({text:new C("[handoff] ",new h({color:I.accent}))}));if(c.push(new _1({child:new e({text:new C(o,new h({color:S})),overflow:"ellipsis",maxLines:1})})),c.push(new R0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let t=O?{success:v,warning:v,destructive:v}:I;c.push(...Cs5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,t)),c.push(new R0({width:2}))}return c.push(g(E.description.timeAgo,D)),new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new G1({children:[...k,...c]})})}})}}function $L4(J){return 1-(1-J)**3}function JL4(J,Z,Q){return J+(Z-J)*Q}function Ld(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=$L4(Y),V=$L4(X);return{x:JL4(J.startOffset.x,J.targetOffset.x,K),y:JL4(J.startOffset.y,J.targetOffset.y,V)}}var _s5={nodeWidth:3,horizontalSpacing:3};class V_{options;constructor(J={}){this.options={..._s5,...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=(z,F)=>{let q=Z.get(z.id)??[];if(this.options.comparator)q.sort(this.options.comparator);let G={...z,parentID:Q.get(z.id)};if(q.length===0){Y.push({node:G,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of q)D.push(V(B,F+1));let U=Math.min(...D),W=Math.max(...D),H=Math.floor((U+W)/2);return Y.push({node:G,position:{x:H,y:F}}),H};for(let z of X)V(z,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,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}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 Ss5={nodeWidth:3,nodeHeight:2};class z_{options;constructor(J={}){this.options={...Ss5,...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 z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var ks5={nodeWidth:3,nodeHeight:2},ys5={x:0,y:0};class vJ0{options;constructor(J={}){this.options={...ks5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ys5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=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=U;j>=0;j--){let I=J.filter((v)=>v.position.y===j);I.sort((v,g)=>v.position.x-g.position.x);let _=[],S=0;for(let v of I){if(v.position.x>S)_.push(new R0({width:v.position.x-S}));let g=v.node.id===Q,b=V?.(v.node.data)??!1,k=K?.activeFlashOn??!1,u=v.node.id===K?.copyFlashNodeId;_.push(this.renderNode(g,b,k,u,G,q)),S=v.position.x+this.options.nodeWidth}if(N.push(new G1({crossAxisAlignment:"start",children:_})),j>0){let v=J.filter((k)=>k.position.y===j-1),g=I,b=this.renderConnectors(v,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new R0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),I=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+I*B+1,v=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)v=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(j,v,q,G)}))}return new l0({padding:C0.horizontal(2),child:new uH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,q=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",z="┗━┛",q=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new h({color:F,bold:q}))}),new e({text:new C(z,new h({color:F,bold:q}))})]})}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((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",q=Q?.border??Y?.threadGraphConnector??Q?.foreground,G=Q?.foreground,D=[new e({text:new C(z,new h({color:q}))})];for(let U of X){let W=" ".repeat(K-U.length);D.push(new e({text:new C("│ ",new h({color:q}),[new C(U+W,new h({color:G??q})),new C(" │",new h({color:q}))])}))}return D.push(new e({text:new C(F,new h({color:q}))})),new x0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let U of Z){let W=U.position.x+z;if(W>=0&&W<Y)q[W]="▲"}V.push(new e({text:new C(q.join(""),new h({color:F}))}));let G=Array(Y).fill(" ");for(let U of J){let W=Z.filter((E)=>E.node.parentID===U.node.id);if(W.length===0)continue;let H=U.position.x+z,B=W.map((E)=>E.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let E=N;E<=w;E++)if(E>=0&&E<Y){if(E===H)if(W.length===1&&B[0]===H)G[E]="│";else if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┬";else if(B.includes(E))if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┴";else if(G[E]===" ")G[E]="─"}}V.push(new e({text:new C(G.join(""),new h({color:F}))}));let D=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)D[H]="│"}return V.push(new e({text:new C(D.join(""),new h({color:F}))})),V}}var vs5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},xs5={x:0,y:0};class Bd0{options;constructor(J={}){this.options={...vs5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=xs5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=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=U;j>=0;j--){let I=J.filter((v)=>v.position.y===j);I.sort((v,g)=>v.position.x-g.position.x);let _=[],S=0;for(let v of I){if(v.position.x>S)_.push(new R0({width:v.position.x-S}));let g=v.node.id===Q,b=V?.(v.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(g,b,k,G,q)),S=v.position.x+this.options.nodeWidth}if(N.push(new G1({crossAxisAlignment:"start",children:_})),j>0){let v=J.filter((k)=>k.position.y===j-1),g=I,b=this.renderConnectors(v,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new R0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),I=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+I*B,v=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)v=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(j,v,q)}))}return new l0({padding:C0.horizontal(2),child:new uH(new i6({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 e({text:new C(K,new h({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 e({text:new C(V,new h({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let G of J){let D=Z.filter((N)=>N.node.parentID===G.node.id);if(D.length===0)continue;let U=G.position.x+z,W=D.map((N)=>N.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,E=W.includes(N);if(w&&E)if(D.length===1)q[N]="│";else if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┼";else if(w)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┬";else if(E)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┴";else if(q[N]===" ")q[N]="─"}}return V.push(new e({text:new C(q.join(""),new h({color:F}))})),V}}class Md extends E3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new ZL4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class ZL4 extends M4{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 rL extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new XL4}}var QL4=400,YL4=300,us5=16;class XL4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new V_({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new z_;renderer=new Bd0;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 q=this.widget.props.threads.find((G)=>G.id===K);if(q)this.selectedNodeId=q.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),z=this.widget.props.threads.some((F)=>F.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:QL4,durationY:YL4};let Z=Math.max(QL4,YL4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ld(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},us5)}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,z=2,F=Math.floor(this.viewportHeight/2),G=Math.floor(F/2)-V;return{x:K,y:G}}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,z)=>V.position.x-z.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 G=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(G){let D=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(G.position.x,G.position.y,D)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(q)=>q.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(q)=>q.isActive??!1,J),F=new Md({onWidth:(q)=>{if(this.viewportWidth!==q)this.viewportWidth=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(q)=>{if(this.viewportHeight!==q)this.viewportHeight=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new x4({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 VL4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new zL4}}class zL4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var KL4=30,fs5=30;class F_{}class q_{}class xJ0{}class uJ0{}class Nd0 extends c0{props;constructor(J){super();this.props=J}createState(){return new FL4}}class FL4 extends p0{highlightedIndex=0;controller=new s2;focusNode;scrollController=new Q5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new o4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),G6.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;eT(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 F_){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof q_){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof xJ0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof uJ0)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(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=u0.of(J),{colors:Y,app:X}=Q,z=e1.of(J).size.width>=fs5+KL4,F=f1.all(new y1(Y.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,G=new l0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new WJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new y7({shortcuts:new Map([[new Y4("ArrowDown"),new F_],[new Y4("ArrowUp"),new q_],[new Y4("Tab"),new F_],[new Y4("Tab",{shift:!0}),new q_],[new Y4("n",{ctrl:!0}),new F_],[new Y4("p",{ctrl:!0}),new q_],[new Y4("Enter"),new xJ0],[new Y4("Escape"),new uJ0]]),focusNode:this.focusNode,child:D}),W=new k9({actions:new Map([[F_,new r4(this.invoke)],[q_,new r4(this.invoke)],[xJ0,new r4(this.invoke)],[uJ0,new r4(this.invoke)]]),child:U}),H=new G1({children:[new l0({decoration:{color:Y.background},child:new e({text:new C(">",new h({color:Y.foreground}))})}),new _1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,I=Z?M.threads.some((g)=>g.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,v=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(I)v.push(new C(" (current)",new h({color:j?X.selectionForeground:Y.success})));return new VL4(new a1({onClick:(g)=>this.handleItemClick(A,g.clickCount),child:new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,v)})})}),(g)=>{this.itemContexts[A]=g})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new _1({child:new a1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})}),E=q?q.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=q?new l0({padding:C0.all(1),child:new rL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(z){let M=O?new _1({child:O}):new R0({width:KL4});L=new G1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new _1({child:new a1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new _1({child:O}));L=new x0({crossAxisAlignment:"stretch",children:M})}return new l0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[G,H,new R0({height:1}),new _1({child:L})]})})}}class M${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!M$._instance)M$._instance=new M$;return M$._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()}}h0();class qL4 extends p0{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){R.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){R.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=u0.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 e9({title:"Add Label",items:F,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(q,G,D,U)=>{let W=G?Q.selectionBackground:void 0,H=G?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(N,new h({color:H,bold:!0}))])})})}return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(q.name,new h({color:H}))})})},filterItem:(q,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||q.name.includes(U)},sortItems:(q,G,D)=>{let U="__isCreateMarker"in q.item&&q.item.__isCreateMarker,W="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!W)return-1;if(!U&&W)return 1;return G.score-q.score}})}}class wd0 extends c0{props;constructor(J){super();this.props=J}createState(){return new qL4}}class sK extends c0{props;constructor(J){super();this.props=J}createState(){return new GL4}}class GL4 extends p0{_spinner=new a5;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=u0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new y1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new e({textAlign:"center",text:new C("",void 0,[new C(K,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),F=[new _1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new R0({height:2,child:new l0({padding:C0.symmetric(2,0),child:new e({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let q=new l0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new x4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}var Ad={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"}},fJ0=["workspace","global","flag","default","external","skill","other"];function bs5(J){return Array.from(new Set(J))}function DL4(J){return bs5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function G_(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 DL4(J).length>0?"skill":"other"}function Ed0(J){return G_(J)==="skill"}function UL4(J){let Z=DL4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=G_(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Ad[Y].description}: ${Q}`}function WL4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var HL4=process.platform==="win32"?" ":"█",BL4=process.platform==="win32"?"░":"█";class x8 extends c0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=HL4,thumbChar:K=BL4,showTrack:V=!0,thumbColor:z,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=z,this.trackColor=F}createState(){return new NL4}}class NL4 extends p0{_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),z=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),q=X-z,G=Math.max(0,q*F),D=G+z;return J>=G&&J<=D}_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,z=Math.min(1,Q/Z),F=Math.max(1,K*z),q=K-F;if(q<=0)return;let G=Z-Q,D=q/G,U=V/D,W=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(W)};_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 z=Math.min(1,Y/Q),F=Math.max(1,V*z),q=Q-Y,G=V-F,D=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,G*D),W=U+F;if(Z>=U&&Z<=W)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(q,X+Y))};build(J){return new a1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?w5.POINTER:w5.DEFAULT,child:new wL4({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 wL4 extends oC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=HL4,thumbChar:K=BL4,showTrack:V=!0,thumbColor:z,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=z,this.trackColor=F}createRenderObject(){return new EL4(this)}updateRenderObject(J){J.updateWidget(this)}}class EL4 extends M4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!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,z=this._widget.thumbColor,F=process.platform==="win32",q=Y,G=Y+X;if(!F){let D=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let W="█",H=!0;if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);W=D[N]||"█",H=!1}else if(U===Math.floor(G)){let B=1-(G-U),N=Math.floor(B*8);W=D[N]||"█"}else if(U>q&&U<G)H=!1;J.setChar(Z,Q+U,W,{fg:z,bg:V,reverse:H},1)}return}for(let D=0;D<this.size.height;D++){let U=D+0.5,W=U>=q&&U<G,H=W?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+D,H,{fg:W?z: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),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class sL extends c0{props;constructor(J){super();this.props=J}createState(){return new OL4}}class OL4 extends p0{scrollController=new Q5;scrollAreaKey=new i2("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 u7}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=u0.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 G=DJ0(Q);return{title:G.title,type:G.type,description:G.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=f1.all(new y1(Z.colors.border,1,"solid")),V=new l0({padding:C0.symmetric(1,0),child:new e({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new e({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),F=new _1({child:new v7({child:new l0({padding:C0.symmetric(1,0),child:new G1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new R6({controller:this.scrollController,autofocus:!0,child:z})}),new x8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,D=this.scrollController.offset,U=this.getViewportHeight(),W=G+U;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(D,0)}}})]})})})}),q=new l0({padding:C0.symmetric(1,0),child:new e({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(G==="help"){let D=new h({color:Z.app.keybind}),U=new h({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",D),new C(" to close • Use ",U),new C("↑↓",D),new C(" or ",U),new C("j/k",D),new C(" to scroll",U)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new x4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.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 l0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new R0({height:1}),F,q]})})})}}m9();class LL4 extends c0{props;constructor(J){super();this.props=J}createState(){return new ML4}}class ML4 extends p0{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=l8.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=u0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new e({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,q)=>F+q.registeredCommands.length,0),z=this.plugins.reduce((F,q)=>F+q.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${_4(X,"plugin")} active`,new h({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${_4(V,"command")}, ${z} ${_4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7329
+ `))}if(H)D.push(new C(" ",G)),D.push(new C("Total: ",G)),D.push(new C(K(B),q))}return new l0({decoration:{color:z.background,border:f1.all(new y1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,D)})})}Vw();h0();m9();import{execSync as os5}from"node:child_process";Dw();D7();N3();_2();Lh();mX();t7();g$();lZ();PO();A4();yu();vy();H1();var dL4=O4(fq(),1);import{writeFile as bL4}from"fs/promises";import hL4 from"path";h0();t7();class Gd0{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.1773994045-ge5da52"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Hs(Z,this.configService)}catch(Z){R.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 qB extends c0{props;constructor(J){super();this.props=J}createState(){return new cO4}}class cO4 extends p0{_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 lO4 extends p0{controller=new s2;focusNode=new o4({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=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=f1.all(new y1(Q.foreground,1,"solid")),F=new WJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),q=new G1({children:[new l0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:F})]}),G=new l0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(V)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let U=new l0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,D)})});return new l0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[G,new R0({height:1}),q,new F3,U]})})}}class Od extends c0{props;constructor(J){super();this.props=J}createState(){return new lO4}}import{isDeepStrictEqual as Dd0}from"node:util";var Ls5=/[\\/_ +.#"@[({&]/,Ms5=/[\\/_ +.#"@[({&]/g,As5=/[\s-]/,iO4=/[\s-]/g;function TJ0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let F=Y.charAt(K),q=Q.indexOf(F,X),G=0,D,U,W,H;while(q>=0){if(D=TJ0(J,Z,Q,Y,q+1,K+1,V),D>G){if(q===X)D*=1;else if(As5.test(J.charAt(q-1))){if(D*=0.9,H=J.slice(X,q-1).match(iO4),H&&X>0)D*=0.999**H.length}else if(Ls5.test(J.charAt(q-1))){if(D*=0.8,W=J.slice(X,q-1).match(Ms5),W&&X>0)D*=0.999**W.length}else if(D*=0.3,X>0)D*=0.999**(q-X);if(J.charAt(q)!==Z.charAt(K))D*=0.9999}if(D<0.1&&(Q.charAt(q-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(q-1)!==Y.charAt(K))){if(U=TJ0(J,Z,Q,Y,q+1,K+2,V),U*0.1>D)D=U*0.1}if(D>G)G=D;q=Q.indexOf(F,q+1)}return V[z]=G,G}function CJ0(J){return J.toLowerCase().replace(iO4," ")}function nO4(J,Z){let Q=TJ0(J,Z,CJ0(J),CJ0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let F=TJ0(J,z,CJ0(J),CJ0(z),0,0,{});if(F===0)return Q;X+=F,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class X_{}class K_{}class _J0{}class SJ0{}class aO4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new oO4}}class oO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function js5(J,Z){if(J==="")return{matches:!0,score:1};let Q=nO4(Z,J);return{matches:Q>0.15,score:Q}}class e9 extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new rO4}}class rO4 extends p0{textController;focusNode;scrollController=new Q5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s2(this.widget.props.controller?.query??""),this.focusNode=new o4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),G6.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)=>Dd0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Dd0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Dd0(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 X_){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof K_){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof _J0){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 SJ0)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,...js5(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;eT(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(),G6.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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new y1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new WJ({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 y7({shortcuts:new Map([[new Y4("ArrowDown"),new X_],[new Y4("ArrowUp"),new K_],[new Y4("Tab"),new X_],[new Y4("Tab",{shift:!0}),new K_],[new Y4("n",{ctrl:!0}),new X_],[new Y4("p",{ctrl:!0}),new K_],[new Y4("Enter"),new _J0],[new Y4("Escape"),new SJ0]]),focusNode:this.focusNode,child:z}),q=new k9({actions:new Map([[X_,new r4(this.invoke)],[K_,new r4(this.invoke)],[_J0,new r4(this.invoke)],[SJ0,new r4(this.invoke)]]),child:F}),G=new G1({children:[new l0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:q})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";D=new R0({height:10,child:new i1({child:new e({text:new C(N,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new _1({child:new i1({child:new e({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,L,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new l0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new h({color:j,dim:L}))})})}return new aO4(new a1({onClick:(A)=>this.handleItemClick(E,A.clickCount),child:M}),(A)=>{this.itemContexts[E]=A})});D=new x0({children:N,crossAxisAlignment:"start"})}let U=new a1({onScroll:this.handleScroll,opaque:!1,child:new R6({controller:this.scrollController,autofocus:!1,child:D})}),W=[];if(this.widget.props.title){let N=new l0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(N)}if(!K)W.push(G,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);W.push(new _1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new _1({child:U}),new l0({padding:C0.only({top:1}),child:new i1({child:w??new R0({height:1})})})]})}))}else W.push(new _1({child:U}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new l0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:W})})}}function sO4(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 Ud0 extends l1{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)=>sO4(X.pubDate).length));return new e9({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,z)=>{let F=u0.of(z),{colors:q}=F,G=F.app,D=K?G.selectionBackground:void 0,U=K?G.selectionForeground:q.foreground,W=q.mutedForeground,H=(B,N)=>new R0({width:N,child:G1.end([new e({text:new C(B,new h({color:W}))})])});return new l0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new G1({children:[new _1({child:new e({text:new C(X.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(sO4(X.pubDate),Q)]})})}})}}A4();class Wd0 extends c0{createState(){return new tO4}}class tO4 extends p0{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=u0.of(J).colors;return new e({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Rs5=/\/threads\/(T-[^/?#\s<>]+)/i;function Is5(J){let Z=J.trim(),Y=Z.match(Rs5)?.[1];if(Y&&N8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(N8(X))return X;return null}function Ps5(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 z=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(z){Y.set(V.id,z.type);let F=z.threadID,q=Q.get(F)||[];q.push(V),Q.set(F,q)}else X.push(V)}return F$0.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 Hd0(J,Z,Q){return new e({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function Cs5(J,Z,Q,Y){return[Hd0("+",J,Y.success),F3.horizontal(1),Hd0("~",Z,Y.warning),F3.horizontal(1),Hd0("-",Q,Y.destructive)]}function Ts5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class kJ0 extends c0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new eO4}}class eO4 extends p0{spinner=new a5;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((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((E)=>E.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),F=Z.currentThreadID,q=[...K].sort((E,O)=>{if(F){if(E.id===F)return-1;if(O.id===F)return 1}let L=V.indexOf(E.id),M=V.indexOf(O.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),G=Ps5(q),D=Math.max(0,...G.map((E)=>E.description.timeAgo.length)),U=u0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new i1({child:new e({text:new C("",new h({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(E)=>{if(E!==H)H=E,B=Is5(E);return B};return new e9({items:G,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=N(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>N(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!Ts5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(E,O,L,M)=>{let A=u0.of(M),{app:j,colors:I}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:I.foreground,v=I.mutedForeground,g=(t,W0)=>new R0({width:W0,child:G1.end([new e({text:new C(t,new h({color:v}))})])}),b=Z.threadViewStates[E.id],k=[],u=E.relationshipType==="handoff",p=new np({connectorColor:I.mutedForeground});if(E.depth>0){let t=[],W0=E.ancestorsAreLast.slice(1);for(let w0 of W0)t.push(new C(p.getAncestorPrefix(w0),new h({color:p.connectorColor,dim:p.connectorDim})));let n=E.isLast?p.elbow:p.tee,D0=p.getConnectorText(n);t.push(new C(D0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new e({text:new C("",void 0,t)}))}let c=[],f=F===E.id?new C("(current) ",new h({color:I.success})):z.has(E.id)?new C("(visited) ",new h({color:I.foreground,dim:!0})):null;if(f)c.push(new e({text:f}));if(mW(b))c.push(new Wd0),c.push(new R0({width:1}));let o=E.title;if(E.relationshipType==="fork"){let t=o.match(/^Forked\((\d+)\): /);if(t)o=o.slice(t[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);c.push(new e({text:new C("[fork] ",new h({color:I.primary}))}))}else if(u)c.push(new e({text:new C("[handoff] ",new h({color:I.accent}))}));if(c.push(new _1({child:new e({text:new C(o,new h({color:S})),overflow:"ellipsis",maxLines:1})})),c.push(new R0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let t=O?{success:v,warning:v,destructive:v}:I;c.push(...Cs5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,t)),c.push(new R0({width:2}))}return c.push(g(E.description.timeAgo,D)),new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new G1({children:[...k,...c]})})}})}}function $L4(J){return 1-(1-J)**3}function JL4(J,Z,Q){return J+(Z-J)*Q}function Ld(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=$L4(Y),V=$L4(X);return{x:JL4(J.startOffset.x,J.targetOffset.x,K),y:JL4(J.startOffset.y,J.targetOffset.y,V)}}var _s5={nodeWidth:3,horizontalSpacing:3};class V_{options;constructor(J={}){this.options={..._s5,...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=(z,F)=>{let q=Z.get(z.id)??[];if(this.options.comparator)q.sort(this.options.comparator);let G={...z,parentID:Q.get(z.id)};if(q.length===0){Y.push({node:G,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of q)D.push(V(B,F+1));let U=Math.min(...D),W=Math.max(...D),H=Math.floor((U+W)/2);return Y.push({node:G,position:{x:H,y:F}}),H};for(let z of X)V(z,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,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}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 Ss5={nodeWidth:3,nodeHeight:2};class z_{options;constructor(J={}){this.options={...Ss5,...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 z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var ks5={nodeWidth:3,nodeHeight:2},ys5={x:0,y:0};class vJ0{options;constructor(J={}){this.options={...ks5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ys5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=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=U;j>=0;j--){let I=J.filter((v)=>v.position.y===j);I.sort((v,g)=>v.position.x-g.position.x);let _=[],S=0;for(let v of I){if(v.position.x>S)_.push(new R0({width:v.position.x-S}));let g=v.node.id===Q,b=V?.(v.node.data)??!1,k=K?.activeFlashOn??!1,u=v.node.id===K?.copyFlashNodeId;_.push(this.renderNode(g,b,k,u,G,q)),S=v.position.x+this.options.nodeWidth}if(N.push(new G1({crossAxisAlignment:"start",children:_})),j>0){let v=J.filter((k)=>k.position.y===j-1),g=I,b=this.renderConnectors(v,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new R0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),I=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+I*B+1,v=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)v=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(j,v,q,G)}))}return new l0({padding:C0.horizontal(2),child:new uH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,q=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",z="┗━┛",q=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new h({color:F,bold:q}))}),new e({text:new C(z,new h({color:F,bold:q}))})]})}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((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",q=Q?.border??Y?.threadGraphConnector??Q?.foreground,G=Q?.foreground,D=[new e({text:new C(z,new h({color:q}))})];for(let U of X){let W=" ".repeat(K-U.length);D.push(new e({text:new C("│ ",new h({color:q}),[new C(U+W,new h({color:G??q})),new C(" │",new h({color:q}))])}))}return D.push(new e({text:new C(F,new h({color:q}))})),new x0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let U of Z){let W=U.position.x+z;if(W>=0&&W<Y)q[W]="▲"}V.push(new e({text:new C(q.join(""),new h({color:F}))}));let G=Array(Y).fill(" ");for(let U of J){let W=Z.filter((E)=>E.node.parentID===U.node.id);if(W.length===0)continue;let H=U.position.x+z,B=W.map((E)=>E.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let E=N;E<=w;E++)if(E>=0&&E<Y){if(E===H)if(W.length===1&&B[0]===H)G[E]="│";else if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┬";else if(B.includes(E))if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┴";else if(G[E]===" ")G[E]="─"}}V.push(new e({text:new C(G.join(""),new h({color:F}))}));let D=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)D[H]="│"}return V.push(new e({text:new C(D.join(""),new h({color:F}))})),V}}var vs5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},xs5={x:0,y:0};class Bd0{options;constructor(J={}){this.options={...vs5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=xs5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=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=U;j>=0;j--){let I=J.filter((v)=>v.position.y===j);I.sort((v,g)=>v.position.x-g.position.x);let _=[],S=0;for(let v of I){if(v.position.x>S)_.push(new R0({width:v.position.x-S}));let g=v.node.id===Q,b=V?.(v.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(g,b,k,G,q)),S=v.position.x+this.options.nodeWidth}if(N.push(new G1({crossAxisAlignment:"start",children:_})),j>0){let v=J.filter((k)=>k.position.y===j-1),g=I,b=this.renderConnectors(v,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new R0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),I=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+I*B,v=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)v=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(j,v,q)}))}return new l0({padding:C0.horizontal(2),child:new uH(new i6({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 e({text:new C(K,new h({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 e({text:new C(V,new h({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let G of J){let D=Z.filter((N)=>N.node.parentID===G.node.id);if(D.length===0)continue;let U=G.position.x+z,W=D.map((N)=>N.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,E=W.includes(N);if(w&&E)if(D.length===1)q[N]="│";else if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┼";else if(w)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┬";else if(E)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┴";else if(q[N]===" ")q[N]="─"}}return V.push(new e({text:new C(q.join(""),new h({color:F}))})),V}}class Md extends E3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new ZL4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class ZL4 extends M4{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 rL extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new XL4}}var QL4=400,YL4=300,us5=16;class XL4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new V_({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new z_;renderer=new Bd0;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 q=this.widget.props.threads.find((G)=>G.id===K);if(q)this.selectedNodeId=q.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),z=this.widget.props.threads.some((F)=>F.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:QL4,durationY:YL4};let Z=Math.max(QL4,YL4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ld(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},us5)}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,z=2,F=Math.floor(this.viewportHeight/2),G=Math.floor(F/2)-V;return{x:K,y:G}}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,z)=>V.position.x-z.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 G=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(G){let D=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(G.position.x,G.position.y,D)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(q)=>q.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(q)=>q.isActive??!1,J),F=new Md({onWidth:(q)=>{if(this.viewportWidth!==q)this.viewportWidth=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(q)=>{if(this.viewportHeight!==q)this.viewportHeight=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new x4({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 VL4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new zL4}}class zL4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var KL4=30,fs5=30;class F_{}class q_{}class xJ0{}class uJ0{}class Nd0 extends c0{props;constructor(J){super();this.props=J}createState(){return new FL4}}class FL4 extends p0{highlightedIndex=0;controller=new s2;focusNode;scrollController=new Q5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new o4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),G6.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;eT(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 F_){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof q_){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof xJ0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof uJ0)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(),G6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=u0.of(J),{colors:Y,app:X}=Q,z=e1.of(J).size.width>=fs5+KL4,F=f1.all(new y1(Y.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,G=new l0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new WJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new y7({shortcuts:new Map([[new Y4("ArrowDown"),new F_],[new Y4("ArrowUp"),new q_],[new Y4("Tab"),new F_],[new Y4("Tab",{shift:!0}),new q_],[new Y4("n",{ctrl:!0}),new F_],[new Y4("p",{ctrl:!0}),new q_],[new Y4("Enter"),new xJ0],[new Y4("Escape"),new uJ0]]),focusNode:this.focusNode,child:D}),W=new k9({actions:new Map([[F_,new r4(this.invoke)],[q_,new r4(this.invoke)],[xJ0,new r4(this.invoke)],[uJ0,new r4(this.invoke)]]),child:U}),H=new G1({children:[new l0({decoration:{color:Y.background},child:new e({text:new C(">",new h({color:Y.foreground}))})}),new _1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,I=Z?M.threads.some((g)=>g.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,v=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(I)v.push(new C(" (current)",new h({color:j?X.selectionForeground:Y.success})));return new VL4(new a1({onClick:(g)=>this.handleItemClick(A,g.clickCount),child:new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,v)})})}),(g)=>{this.itemContexts[A]=g})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new _1({child:new a1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})}),E=q?q.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=q?new l0({padding:C0.all(1),child:new rL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(z){let M=O?new _1({child:O}):new R0({width:KL4});L=new G1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new _1({child:new a1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new _1({child:O}));L=new x0({crossAxisAlignment:"stretch",children:M})}return new l0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[G,H,new R0({height:1}),new _1({child:L})]})})}}class M${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!M$._instance)M$._instance=new M$;return M$._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()}}h0();class qL4 extends p0{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){R.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){R.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=u0.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 e9({title:"Add Label",items:F,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(q,G,D,U)=>{let W=G?Q.selectionBackground:void 0,H=G?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(N,new h({color:H,bold:!0}))])})})}return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(q.name,new h({color:H}))})})},filterItem:(q,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||q.name.includes(U)},sortItems:(q,G,D)=>{let U="__isCreateMarker"in q.item&&q.item.__isCreateMarker,W="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!W)return-1;if(!U&&W)return 1;return G.score-q.score}})}}class wd0 extends c0{props;constructor(J){super();this.props=J}createState(){return new qL4}}class sK extends c0{props;constructor(J){super();this.props=J}createState(){return new GL4}}class GL4 extends p0{_spinner=new a5;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=u0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new y1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new e({textAlign:"center",text:new C("",void 0,[new C(K,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),F=[new _1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new R0({height:2,child:new l0({padding:C0.symmetric(2,0),child:new e({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let q=new l0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new x4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}var Ad={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"}},fJ0=["workspace","global","flag","default","external","skill","other"];function bs5(J){return Array.from(new Set(J))}function DL4(J){return bs5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function G_(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 DL4(J).length>0?"skill":"other"}function Ed0(J){return G_(J)==="skill"}function UL4(J){let Z=DL4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=G_(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Ad[Y].description}: ${Q}`}function WL4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var HL4=process.platform==="win32"?" ":"█",BL4=process.platform==="win32"?"░":"█";class x8 extends c0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=HL4,thumbChar:K=BL4,showTrack:V=!0,thumbColor:z,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=z,this.trackColor=F}createState(){return new NL4}}class NL4 extends p0{_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),z=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),q=X-z,G=Math.max(0,q*F),D=G+z;return J>=G&&J<=D}_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,z=Math.min(1,Q/Z),F=Math.max(1,K*z),q=K-F;if(q<=0)return;let G=Z-Q,D=q/G,U=V/D,W=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(W)};_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 z=Math.min(1,Y/Q),F=Math.max(1,V*z),q=Q-Y,G=V-F,D=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,G*D),W=U+F;if(Z>=U&&Z<=W)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(q,X+Y))};build(J){return new a1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?w5.POINTER:w5.DEFAULT,child:new wL4({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 wL4 extends oC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=HL4,thumbChar:K=BL4,showTrack:V=!0,thumbColor:z,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=z,this.trackColor=F}createRenderObject(){return new EL4(this)}updateRenderObject(J){J.updateWidget(this)}}class EL4 extends M4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!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,z=this._widget.thumbColor,F=process.platform==="win32",q=Y,G=Y+X;if(!F){let D=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let W="█",H=!0;if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);W=D[N]||"█",H=!1}else if(U===Math.floor(G)){let B=1-(G-U),N=Math.floor(B*8);W=D[N]||"█"}else if(U>q&&U<G)H=!1;J.setChar(Z,Q+U,W,{fg:z,bg:V,reverse:H},1)}return}for(let D=0;D<this.size.height;D++){let U=D+0.5,W=U>=q&&U<G,H=W?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+D,H,{fg:W?z: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),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class sL extends c0{props;constructor(J){super();this.props=J}createState(){return new OL4}}class OL4 extends p0{scrollController=new Q5;scrollAreaKey=new i2("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 u7}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=u0.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 G=DJ0(Q);return{title:G.title,type:G.type,description:G.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=f1.all(new y1(Z.colors.border,1,"solid")),V=new l0({padding:C0.symmetric(1,0),child:new e({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new e({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),F=new _1({child:new v7({child:new l0({padding:C0.symmetric(1,0),child:new G1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new R6({controller:this.scrollController,autofocus:!0,child:z})}),new x8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,D=this.scrollController.offset,U=this.getViewportHeight(),W=G+U;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(D,0)}}})]})})})}),q=new l0({padding:C0.symmetric(1,0),child:new e({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(G==="help"){let D=new h({color:Z.app.keybind}),U=new h({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",D),new C(" to close • Use ",U),new C("↑↓",D),new C(" or ",U),new C("j/k",D),new C(" to scroll",U)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new x4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.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 l0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new R0({height:1}),F,q]})})})}}m9();class LL4 extends c0{props;constructor(J){super();this.props=J}createState(){return new ML4}}class ML4 extends p0{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=l8.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=u0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new e({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,q)=>F+q.registeredCommands.length,0),z=this.plugins.reduce((F,q)=>F+q.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${_4(X,"plugin")} active`,new h({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${_4(V,"command")}, ${z} ${_4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7372
7330
 
7373
7331
  `));for(let F of this.plugins){let{icon:q,color:G}=this.statusIcon(F.status),D=this.getRelativePath(F.uri.toString());if(Y.push(new C(`${q} `,new h({color:G}))),Y.push(new C(D,new h({bold:!0}))),Y.push(new C(` ${F.status}`,new h({dim:!0}))),Y.push(new C(`
7374
7332
  `)),F.status==="active"&&F.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(F.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
@@ -7394,7 +7352,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let u=q.text.replace(/`([^`]+)`/g,"$1")+`
7394
7352
  `));if(F.tools.length===0)X.push(new C(` └─ No tools available
7395
7353
  `,new h({dim:!0})));else for(let D of F.tools){let{icon:U,color:W}=this.statusIcon(D.status);if(X.push(new C(` ${U} `,new h({color:W}))),X.push(new C(D.name,new h({color:D.status==="pending"?Q.warning:Y.link}))),D.status==="pending")X.push(new C(" discovering...",new h({dim:!0})));else if(D.description){let H=D.description.replace(/\s+/g," ").trim();if(H.length>50)H=H.slice(0,47)+"...";X.push(new C(` ${H}`,new h({dim:!0})))}if(D.error){let H=D.error.replace(/\s+/g," ").trim();if(H.length>40)H=H.slice(0,37)+"...";X.push(new C(` ${H}`,new h({color:Y.toolError})))}X.push(new C(`
7396
7354
  `))}X.push(new C(`
7397
- `))}return new R6({child:new e({text:new C("",void 0,X)})})}}function gL4(J){return J.startsWith("agent-mode-")}var mL4=120;function pL4(J){if(!J||J.length<=mL4)return J;return J.slice(0,mL4-1)+"…"}class Td0{configService;onExecute;onExecutionComplete;commands=new Map;telemetrySubmitter;initialConfig;constructor(J,Z,Q,Y){this.configService=J;this.onExecute=Z;this.onExecutionComplete=Q;this.initialConfig=Y,this.registerCommands(Y),this.telemetrySubmitter=new Gd0(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}isDogfoodingEnabled(J){if(J.userEmail)return qr(J.userEmail);return NZ.maybeOf(J.contextFallback)?.isDogfooding??!1}async execute(J,Z,Q=[],Y){this.telemetrySubmitter.submit(J).catch((z)=>{R.debug("Failed to submit command telemetry",z)});let X=Date.now(),K=`command-${X}-${Math.random().toString(36).substring(7)}`,V=this.commands.get(J);if(V){this.onExecute({id:K,name:V.id,noun:V.noun,verb:V.verb,startTime:X,abortController:Y});try{return await V.execute(Z,Y,Q)}finally{this.onExecutionComplete()}}if(J.startsWith("plugin-command-")){let F=this.getAllCommands(Z).find((q)=>q.id===J);if(F?.pluginExecution&&Z.executePluginCommand){let{pluginName:q,commandId:G}=F.pluginExecution;try{await Z.executePluginCommand(q,G,Z.currentThreadID)}catch(D){return D instanceof Error?D:Error(String(D))}return}}}getPriority(J,Z){if(Z.editorState.hasSelection)switch(J){case"copy-selection":return 60}if(this.canChangeAgentMode(Z)){if(J==="help")return 60;if(gL4(J))return 59;switch(J){case"set-agent-mode":return 58;case"toggle-agent-mode":return 57}}if(this.hasPromptText(Z)&&Z.isProcessing)switch(J){case"queue":return 39;case"send-queued-message":return 38;case"dequeue":return 37}if(Z.isProcessing)switch(J){case"queue":return 29;case"send-queued-message":return 28;case"dequeue":return 27}if(this.hasPromptText(Z))switch(J){case"handoff":return 19;case"editor":return 18;case"clear":return 17}if(J==="thread-map"){if(gJ0(Z))return 16}if(gL4(J))return 0;switch(J){case"help":return 10;case"continue":return 9;case"new":return 8;case"handoff":return 7;case"editor":return 6;case"browser":case"url":case"visibility":case"toggle-thinking-blocks":case"queue":case"clear":case"copy-selection":case"paste-image":case"dequeue":case"send-queued-message":case"generate-agent-file":case"agent-files":case"connect":case"disconnect":case"settings":case"permissions":case"permissions-workspace":case"permissions-enable":case"permissions-disable":case"ide":case"test-error":case"toggle-agent-mode":case"toggle-openai-speed":case"set-agent-mode":case"set-theme":case"show-costs":case"refresh":case"debug-thread-json":return 1;case"quit":return 0}return 1}getCommandFollows(J){switch(J){case"handoff":return["new"];case"browse-news":return["new"];case"quit":return["queue","send-queued-message","dequeue"];case"set-agent-mode":case"toggle-agent-mode":return pX().map(({mode:Z})=>`agent-mode-${Z}`);case"set-theme":return["continue"];default:return[]}}registerCommands(J){this.register({id:"new",noun:"thread",verb:"new",description:"Start new thread",aliases:["start"],execute:async(Q)=>{if(!this.isThreadEmpty(Q))await Q.createThread()}}),this.register({id:"continue",noun:"thread",verb:"switch",description:"Switch to existing thread",aliases:["continue"],customFlow:(Q,Y,X)=>{let K=()=>{X(),Q.previewController.clear()},V=Q.commandPaletteMode==="standalone",z=async(q,G)=>{try{if(await Y(q),V&&!G?.hasUserInteracted)Q.showToast("Tip: use `amp threads continue --last` to continue the latest thread","warning");K()}catch(D){R.error("Failed to switch thread from command palette",{threadID:q,error:D});let U=D instanceof Error?D.message:"Unknown error";Q.showToast(`Failed to switch thread: ${U}`,"error")}},F=Q.threads.filter((q)=>!q.archived);return new kJ0({threads:F,title:"Select a thread",onSelect:z,onDismiss:K,previewController:Q.previewController,isLoading:Q.isLoadingThreads,currentWorkspaceURI:Q.currentWorkspace,filterByWorkspace:Q.filterByWorkspace,threadViewStates:Q.threadViewStates,recentThreadIDs:Q.recentThreadIDs,currentThreadID:Q.currentThreadID})},execute:async(Q,Y,X)=>{await Q.switchToThread(X)}});let Z={width:120,height:30};this.register({id:"thread-map",noun:"thread",verb:"map",description:"View thread clusters",customFlowDimensions:Z,customFlow:(Q,Y,X,K,V)=>{let z=gJ0(Q);if(!z)return X(),new R0;let F=()=>{X(),Q.previewController.clear()},q=async(G)=>{await Y(G.id),F()};return new hJ0({cluster:z.cluster,onSelect:q,onDismiss:F,previewController:Q.previewController,initialSelectedThreadID:z.threadID,onUpdateDimensions:(G)=>V?.updateDimensions(G),defaultDimensions:Z})},execute:async(Q,Y,X)=>{await Q.switchToThread(X)},isShown:(Q)=>{if(!gJ0(Q)){if(Q.clusters.filter((K)=>K.threads.length>=2).length===0)return"No thread clusters found (need at least 2 related threads)";return"Current thread is not part of a cluster"}return!0}}),this.register({id:"switch-cluster",noun:"thread",verb:"switch to cluster",description:"Switch to a thread cluster",customFlowDimensions:{width:120,height:30},customFlow:(Q,Y,X)=>{let K=Q.clusters.filter((V)=>V.threads.length>=2).sort((V,z)=>{if(!V.mostRecentDate&&!z.mostRecentDate)return 0;if(!V.mostRecentDate)return 1;if(!z.mostRecentDate)return-1;return z.mostRecentDate.localeCompare(V.mostRecentDate)});if(K.length===0)return X(),new R0;return new qB({initialState:{selectedCluster:null},builder:(V,z,F)=>{let q=()=>{X(),Q.previewController.clear()};if(F.selectedCluster){let G=F.selectedCluster.threads.find((H)=>H.id===Q.currentThreadID),D=F.selectedCluster.threads.find((H)=>!H.parentID)??F.selectedCluster.threads[0],U=G??D,W=async(H)=>{await Y(H.id),q()};return new hJ0({cluster:F.selectedCluster,onSelect:W,onDismiss:q,previewController:Q.previewController,initialSelectedThreadID:U?.id})}return new Nd0({clusters:K,currentThreadID:Q.currentThreadID,onAccept:(G)=>{z((D)=>({...D,selectedCluster:G}))},onDismiss:q})}})},execute:async(Q,Y,X)=>{await Q.switchToThread(X)},isShown:(Q)=>{if(Q.clusters.filter((X)=>X.threads.length>=2).length===0)return"No thread clusters found (need at least 2 related threads)";return!0}}),this.register({id:"context-analyze",noun:"context",verb:"analyze",description:"Analyze context token usage",execute:async(Q)=>{Q.openContextAnalyze()},isShown:(Q)=>{let Y=Q.getEffectiveAgentMode(),X=VY(Y);if(![B3("CLAUDE_OPUS_4_6"),B3("CLAUDE_OPUS_4_5"),B3("GPT_5_4")].includes(X))return"Context analysis requires Claude Opus 4.6 (smart) or GPT-5.4 (deep)";return!0}}),this.register({id:"handoff",noun:"thread",verb:"handoff",description:"Draft a new thread based on current thread",execute:async(Q)=>{Q.enterHandoffMode();let Y=Q.editorState.text.trim();if(Y.length>0)Q.submitMessage(Y)},isShown:(Q)=>this.isThreadEmpty(Q)?"Cannot use thread: handoff from an empty thread":!0}),this.register({id:"browser",noun:"thread",verb:"open in browser",description:"Open thread in browser",execute:async({thread:Q,ampURL:Y,context:X})=>{let K=ej(new URL(Y),Q.id).toString();if(X)await t3(X,K)},isShown:(Q)=>this.isThreadEmpty(Q)?"Cannot use thread: open in browser from an empty thread":!0}),this.register({id:"browse-news",noun:"news",verb:"open in browser",description:"Open Amp announcements",customFlow:(Q,Y,X)=>{let K=async(V)=>{await Y(V),X()};return new Ud0({entries:Q.newsFeedEntries,title:"Amp News",onSelect:K,onDismiss:X})},execute:async({context:Q},Y,X)=>{try{if(Q)await t3(Q,X.link)}catch(K){R.error("Failed to open browser",{error:K})}},isShown:(Q)=>Q.newsFeedEntries.length>0||"No news entries available"}),this.register({id:"url",noun:"thread",verb:"copy URL",description:"Copy thread URL",execute:async(Q)=>{let Y=ej(new URL(Q.ampURL),Q.thread.id).toString();try{await p4.instance.tuiInstance.clipboard.writeText(Y);let K=Q.context?u0.of(Q.context).app.link:l8.default().app.link;return new u7(new x0({children:[new V5({uri:Y,text:Y,style:new h({color:K,underline:!0})}),new e({text:new C("(Copied to clipboard)",new h({color:K,dim:!0}))})]}),"Thread URL")}catch(X){return R.error("Failed to copy URL to clipboard",{error:X}),Error(`Thread URL: ${Y}
7355
+ `))}return new R6({child:new e({text:new C("",void 0,X)})})}}function gL4(J){return J.startsWith("agent-mode-")}var mL4=120;function pL4(J){if(!J||J.length<=mL4)return J;return J.slice(0,mL4-1)+"…"}class Td0{configService;onExecute;onExecutionComplete;commands=new Map;telemetrySubmitter;initialConfig;constructor(J,Z,Q,Y){this.configService=J;this.onExecute=Z;this.onExecutionComplete=Q;this.initialConfig=Y,this.registerCommands(Y),this.telemetrySubmitter=new Gd0(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}isDogfoodingEnabled(J){if(J.userEmail)return qr(J.userEmail);return NZ.maybeOf(J.contextFallback)?.isDogfooding??!1}async execute(J,Z,Q=[],Y){this.telemetrySubmitter.submit(J).catch((z)=>{R.debug("Failed to submit command telemetry",z)});let X=Date.now(),K=`command-${X}-${Math.random().toString(36).substring(7)}`,V=this.commands.get(J);if(V){this.onExecute({id:K,name:V.id,noun:V.noun,verb:V.verb,startTime:X,abortController:Y});try{return await V.execute(Z,Y,Q)}finally{this.onExecutionComplete()}}if(J.startsWith("plugin-command-")){let F=this.getAllCommands(Z).find((q)=>q.id===J);if(F?.pluginExecution&&Z.executePluginCommand){let{pluginName:q,commandId:G}=F.pluginExecution;try{await Z.executePluginCommand(q,G,Z.currentThreadID)}catch(D){return D instanceof Error?D:Error(String(D))}return}}}getPriority(J,Z){if(Z.editorState.hasSelection)switch(J){case"copy-selection":return 60}if(this.canChangeAgentMode(Z)){if(J==="help")return 60;if(gL4(J))return 59;switch(J){case"set-agent-mode":return 58;case"toggle-agent-mode":return 57}}if(this.hasPromptText(Z)&&Z.isProcessing)switch(J){case"queue":return 39;case"send-queued-message":return 38;case"dequeue":return 37}if(Z.isProcessing)switch(J){case"queue":return 29;case"send-queued-message":return 28;case"dequeue":return 27}if(this.hasPromptText(Z))switch(J){case"handoff":return 19;case"editor":return 18;case"clear":return 17}if(J==="thread-map"){if(gJ0(Z))return 16}if(gL4(J))return 0;switch(J){case"help":return 10;case"continue":return 9;case"new":return 8;case"handoff":return 7;case"editor":return 6;case"browser":case"url":case"visibility":case"toggle-thinking-blocks":case"queue":case"clear":case"copy-selection":case"paste-image":case"dequeue":case"send-queued-message":case"generate-agent-file":case"agent-files":case"connect":case"disconnect":case"settings":case"permissions":case"permissions-workspace":case"permissions-enable":case"permissions-disable":case"ide":case"test-error":case"toggle-agent-mode":case"toggle-openai-speed":case"set-agent-mode":case"set-theme":case"show-costs":case"refresh":case"debug-thread-json":return 1;case"quit":return 0}return 1}getCommandFollows(J){switch(J){case"handoff":return["new"];case"browse-news":return["new"];case"quit":return["queue","send-queued-message","dequeue"];case"set-agent-mode":case"toggle-agent-mode":return pX().map(({mode:Z})=>`agent-mode-${Z}`);case"set-theme":return["continue"];default:return[]}}registerCommands(J){this.register({id:"new",noun:"thread",verb:"new",description:"Start new thread",aliases:["start"],execute:async(Q)=>{if(!this.isThreadEmpty(Q))await Q.createThread()}}),this.register({id:"continue",noun:"thread",verb:"switch",description:"Switch to existing thread",aliases:["continue"],customFlow:(Q,Y,X)=>{let K=()=>{X(),Q.previewController.clear()},V=Q.commandPaletteMode==="standalone",z=async(q,G)=>{try{if(await Y(q),V&&!G?.hasUserInteracted)Q.showToast("Tip: use `amp threads continue --last` to continue the latest thread","warning");K()}catch(D){R.error("Failed to switch thread from command palette",{threadID:q,error:D});let U=D instanceof Error?D.message:"Unknown error";Q.showToast(`Failed to switch thread: ${U}`,"error")}},F=Q.threads.filter((q)=>!q.archived);return new kJ0({threads:F,title:"Select a thread",onSelect:z,onDismiss:K,previewController:Q.previewController,isLoading:Q.isLoadingThreads,currentWorkspaceURI:Q.currentWorkspace,filterByWorkspace:Q.filterByWorkspace,threadViewStates:Q.threadViewStates,recentThreadIDs:Q.recentThreadIDs,currentThreadID:Q.currentThreadID})},execute:async(Q,Y,X)=>{await Q.switchToThread(X)}});let Z={width:120,height:30};this.register({id:"thread-map",noun:"thread",verb:"map",description:"View thread clusters",customFlowDimensions:Z,customFlow:(Q,Y,X,K,V)=>{let z=gJ0(Q);if(!z)return X(),new R0;let F=()=>{X(),Q.previewController.clear()},q=async(G)=>{await Y(G.id),F()};return new hJ0({cluster:z.cluster,onSelect:q,onDismiss:F,previewController:Q.previewController,initialSelectedThreadID:z.threadID,onUpdateDimensions:(G)=>V?.updateDimensions(G),defaultDimensions:Z})},execute:async(Q,Y,X)=>{await Q.switchToThread(X)},isShown:(Q)=>{if(!gJ0(Q)){if(Q.clusters.filter((K)=>K.threads.length>=2).length===0)return"No thread clusters found (need at least 2 related threads)";return"Current thread is not part of a cluster"}return!0}}),this.register({id:"switch-cluster",noun:"thread",verb:"switch to cluster",description:"Switch to a thread cluster",customFlowDimensions:{width:120,height:30},customFlow:(Q,Y,X)=>{let K=Q.clusters.filter((V)=>V.threads.length>=2).sort((V,z)=>{if(!V.mostRecentDate&&!z.mostRecentDate)return 0;if(!V.mostRecentDate)return 1;if(!z.mostRecentDate)return-1;return z.mostRecentDate.localeCompare(V.mostRecentDate)});if(K.length===0)return X(),new R0;return new qB({initialState:{selectedCluster:null},builder:(V,z,F)=>{let q=()=>{X(),Q.previewController.clear()};if(F.selectedCluster){let G=F.selectedCluster.threads.find((H)=>H.id===Q.currentThreadID),D=F.selectedCluster.threads.find((H)=>!H.parentID)??F.selectedCluster.threads[0],U=G??D,W=async(H)=>{await Y(H.id),q()};return new hJ0({cluster:F.selectedCluster,onSelect:W,onDismiss:q,previewController:Q.previewController,initialSelectedThreadID:U?.id})}return new Nd0({clusters:K,currentThreadID:Q.currentThreadID,onAccept:(G)=>{z((D)=>({...D,selectedCluster:G}))},onDismiss:q})}})},execute:async(Q,Y,X)=>{await Q.switchToThread(X)},isShown:(Q)=>{if(Q.clusters.filter((X)=>X.threads.length>=2).length===0)return"No thread clusters found (need at least 2 related threads)";return!0}}),this.register({id:"context-analyze",noun:"context",verb:"analyze",description:"Analyze context token usage",execute:async(Q)=>{Q.openContextAnalyze()},isShown:(Q)=>{let Y=Q.getEffectiveAgentMode(),X=VY(Y);if(![B3("CLAUDE_OPUS_4_6"),B3("CLAUDE_OPUS_4_5"),B3("GPT_5_3_CODEX")].includes(X))return"Context analysis requires Claude Opus 4.6 (smart) or GPT-5.3 Codex (deep)";return!0}}),this.register({id:"handoff",noun:"thread",verb:"handoff",description:"Draft a new thread based on current thread",execute:async(Q)=>{Q.enterHandoffMode();let Y=Q.editorState.text.trim();if(Y.length>0)Q.submitMessage(Y)},isShown:(Q)=>this.isThreadEmpty(Q)?"Cannot use thread: handoff from an empty thread":!0}),this.register({id:"browser",noun:"thread",verb:"open in browser",description:"Open thread in browser",execute:async({thread:Q,ampURL:Y,context:X})=>{let K=ej(new URL(Y),Q.id).toString();if(X)await t3(X,K)},isShown:(Q)=>this.isThreadEmpty(Q)?"Cannot use thread: open in browser from an empty thread":!0}),this.register({id:"browse-news",noun:"news",verb:"open in browser",description:"Open Amp announcements",customFlow:(Q,Y,X)=>{let K=async(V)=>{await Y(V),X()};return new Ud0({entries:Q.newsFeedEntries,title:"Amp News",onSelect:K,onDismiss:X})},execute:async({context:Q},Y,X)=>{try{if(Q)await t3(Q,X.link)}catch(K){R.error("Failed to open browser",{error:K})}},isShown:(Q)=>Q.newsFeedEntries.length>0||"No news entries available"}),this.register({id:"url",noun:"thread",verb:"copy URL",description:"Copy thread URL",execute:async(Q)=>{let Y=ej(new URL(Q.ampURL),Q.thread.id).toString();try{await p4.instance.tuiInstance.clipboard.writeText(Y);let K=Q.context?u0.of(Q.context).app.link:l8.default().app.link;return new u7(new x0({children:[new V5({uri:Y,text:Y,style:new h({color:K,underline:!0})}),new e({text:new C("(Copied to clipboard)",new h({color:K,dim:!0}))})]}),"Thread URL")}catch(X){return R.error("Failed to copy URL to clipboard",{error:X}),Error(`Thread URL: ${Y}
7398
7356
 
7399
7357
  (Could not copy to clipboard)`)}},isShown:(Q)=>this.isThreadEmpty(Q)?"Cannot use thread: copy URL from an empty thread":!0}),this.register({id:"copy-id",noun:"thread",verb:"copy ID",description:"Copy thread ID",execute:async(Q)=>{let Y=Q.thread.id;try{await p4.instance.tuiInstance.clipboard.writeText(Y);let K=Q.context?u0.of(Q.context).colors.foreground:l8.default().colors.foreground;return new u7(new x0({children:[new e({text:new C(Y,new h({color:K})),selectable:!0}),new e({text:new C("(Copied to clipboard)",new h({color:K,dim:!0}))})]}),"Thread ID")}catch(X){return R.error("Failed to copy thread ID to clipboard",{error:X}),Error(`Thread ID: ${Y}
7400
7358
 
@@ -7587,7 +7545,7 @@ ${X0.content||""}`:X0.content||"",$1=[],D1=X0.baseDir.startsWith("file://")?LZ0(
7587
7545
  `),process.exit(1)}process.stdout.write(await M43(F.result.displayText)+`
7588
7546
  `),process.exit(0)})}gP();import{stdout as A43}from"node:process";function j43({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${pW(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function KR4(J){A43.write(`${j43(J)}
7589
7547
  `)}function VR4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{KR4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{KR4(Z),process.exit(0)})}var l83=_B.join(uJ,"logs","headless.log"),ci0=_B.join(aC,"device-id.json");async function i83(){for(let J of Ww)try{if((await J.listConfigs()).length>0)return J}catch(Z){R.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => O4(g_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){R2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7590
- `)}function n83(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function J2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")b$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")b$("experimental.agentMode",Z.mode)}function hC4(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 a83(J){try{return await fC4(J,"utf-8")}catch{return J}}async function li0(J,Z,Q){let Y=hC4(J,Z);if(!Y)return;let X=M6(Q)?Q.features:[],K=M6(Q)?Q.user.email:void 0;if(!ri0(X,S2.HARNESS_SYSTEM_PROMPT)&&!gC4(K))throw new j1("You are not allowed to do this.",1);b$("systemPrompt",await a83(Y))}function gC4(J){return!!(J&&qr(J))}function ri0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function ii0(J){return(J.userEmail?bZ(J.userEmail):!1)||ri0(J.features,S2.DTW_TUI)}function TC4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new j1("This TUI mode is not enabled for your user;",1)}function ni0(J,Z){if(typeof J==="boolean")return J;if(!M6(Z))return!1;return ii0({userEmail:Z.user.email,features:Z.features})}function ai0(J){if(!M6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function o83(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 GQ0(J){let Y=o83(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 j1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function _C4(J){if(!p6.write(J))await m83(p6,"drain")}var SC4=[{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??tY,description:`Custom settings file path (overrides the default location ${tY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(R).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${iO})`},{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:t9(),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:mV.SMART.key,description:`Set the agent mode (${pX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:pX().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:"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}],kC4=(J)=>("deprecated"in J)&&J.deprecated===!0,r83=(J)=>("hidden"in J)&&J.hidden===!0,s83=(J)=>("default"in J),t83=(J)=>("default"in J)?J.default:void 0,mC4=[{name:"toggle-skills-count",entryPoint:Tb0}];function e83(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((z)=>Q.includes(z)||z.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 j1(V3.unknownCommand(Q),1,V)}}async function si0(J){return{...J,getThreadEnvironment:XJ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new KK(J.fileSystem),generateThreadTitle:y10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>gJ(J.configService),pluginService:J.pluginService}}function pC4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:XJ,filesystem:J.fileSystem,threadService:J.threadService}}var DQ0=V1.file(bC4.homedir()),oi0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(DQ0,".config");function $93(J){return o$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){a$4(Z);let Q=P20(),Y=db0();if((!Q||Y||sq4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(mG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(mG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(P20()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function J93(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function G9(J,Z,Q){let Y=Q?.deferAuth??!1;YR1("0.0.1773982701-g41d390");let X=Ar({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:DQ0,userConfigDir:oi0});rq4(X);let K=await X.getLatest();R.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let W0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(W0),R.info("API key lookup before login",{found:Boolean(W0),ampURL:J.ampURL,deferAuth:Y}),!W0)if(Y)R.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7548
+ `)}function n83(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function J2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")b$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")b$("experimental.agentMode",Z.mode)}function hC4(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 a83(J){try{return await fC4(J,"utf-8")}catch{return J}}async function li0(J,Z,Q){let Y=hC4(J,Z);if(!Y)return;let X=M6(Q)?Q.features:[],K=M6(Q)?Q.user.email:void 0;if(!ri0(X,S2.HARNESS_SYSTEM_PROMPT)&&!gC4(K))throw new j1("You are not allowed to do this.",1);b$("systemPrompt",await a83(Y))}function gC4(J){return!!(J&&qr(J))}function ri0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function ii0(J){return(J.userEmail?bZ(J.userEmail):!1)||ri0(J.features,S2.DTW_TUI)}function TC4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new j1("This TUI mode is not enabled for your user;",1)}function ni0(J,Z){if(typeof J==="boolean")return J;if(!M6(Z))return!1;return ii0({userEmail:Z.user.email,features:Z.features})}function ai0(J){if(!M6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function o83(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 GQ0(J){let Y=o83(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 j1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function _C4(J){if(!p6.write(J))await m83(p6,"drain")}var SC4=[{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??tY,description:`Custom settings file path (overrides the default location ${tY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(R).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${iO})`},{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:t9(),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:mV.SMART.key,description:`Set the agent mode (${pX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:pX().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:"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}],kC4=(J)=>("deprecated"in J)&&J.deprecated===!0,r83=(J)=>("hidden"in J)&&J.hidden===!0,s83=(J)=>("default"in J),t83=(J)=>("default"in J)?J.default:void 0,mC4=[{name:"toggle-skills-count",entryPoint:Tb0}];function e83(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((z)=>Q.includes(z)||z.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 j1(V3.unknownCommand(Q),1,V)}}async function si0(J){return{...J,getThreadEnvironment:XJ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new KK(J.fileSystem),generateThreadTitle:y10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>gJ(J.configService),pluginService:J.pluginService}}function pC4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:XJ,filesystem:J.fileSystem,threadService:J.threadService}}var DQ0=V1.file(bC4.homedir()),oi0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(DQ0,".config");function $93(J){return o$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){a$4(Z);let Q=P20(),Y=db0();if((!Q||Y||sq4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(mG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(mG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(P20()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function J93(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function G9(J,Z,Q){let Y=Q?.deferAuth??!1;YR1("0.0.1773994045-ge5da52");let X=Ar({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:DQ0,userConfigDir:oi0});rq4(X);let K=await X.getLatest();R.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let W0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(W0),R.info("API key lookup before login",{found:Boolean(W0),ampURL:J.ampURL,deferAuth:Y}),!W0)if(Y)R.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7591
7549
  `);let n=await Z93(J),D0=await J.secrets.get("apiKey",J.ampURL);if(R.info("Login flow completed",{success:n,storedKeyPresent:Boolean(D0),ampURL:J.ampURL}),!n)await kG(),process.exit(1);V=!0}}{let W0=await X.getLatest(),n=W0.settings.url,D0=W0.secrets.isSet?.[n];R.info("Config secrets state after login",{configURL:n,apiKeySet:D0?.apiKey??!1})}let z=O1(gJ(X).pipe(Y5((W0)=>W0!=="pending"))),F=Y?"pending":await z;if(!Y)R.info("Server status resolved",{status:"ready",isAuthenticated:M6(F),isError:Mq(F),errorMessage:Mq(F)?F.error.message:void 0});let{toolService:q,dispose:G}=d$4({configService:X}),D=new Map,U=()=>D.clear(),W=new cM0(X,J.settings.getWorkspaceRootPath()),H=Qm1({configService:X,filesystem:i3}),B=tu1({configService:X,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(W0,n,D0)=>{let w0=`${W0}:${n}`,F0=D.get(w0);if(F0)return R.debug("Reusing existing OAuth provider for server",{serverName:W0,serverUrl:n}),F0;R.debug("Creating OAuth provider for server",{serverName:W0,serverUrl:n});let $0=(async()=>{let G0=new Aw(J.secrets),i=await G0.getClientInfo(W0,n),a=D0?.scopes??i?.scopes,s=vV4();R.info("OAuth headless mode check",{useHeadless:s,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let J0;if(s)J0=J.executeMode?yV4():kV4(W0);let X0=new jw0({storage:G0,serverName:W0,serverUrl:n,clientId:D0?.clientId??i?.clientId,clientSecret:D0?.clientSecret??i?.clientSecret,authUrl:D0?.authUrl??i?.authUrl,tokenUrl:D0?.tokenUrl??i?.tokenUrl,scopes:a,headlessAuthHandler:J0});return R.debug("OAuth provider created",{serverName:W0,serverUrl:n,hasManualClientId:!!(D0?.clientId??i?.clientId),willUseDCR:!(D0?.clientId??i?.clientId),scopes:a,headlessMode:s,executeMode:J.executeMode}),X0})();return D.set(w0,$0),$0}}),N=ny0({configService:X,filesystem:i3,spawn:v30}),w;if(J.executeMode){let W0=await i94({toolService:q,providers:[B,N],initialTimeout:15000});w=W0.registrations;for(let[n,D0]of W0.initErrors)R.warn(`${n} provider initialization slow or failed:`,D0)}else w=ay0({toolService:q,providers:[B,N]});if(Z.jetbrains)qw("JetBrains");else if(Z.ide&&wz4())qw("VS Code");else if(Z.ide&&Ez4())qw("Neovim");else if(Z.ide){let W0=await i83();if(W0){let n=kr(W0.ideName);if(n)qw(n)}}if(J.executeMode)XR1(!0);let E,O=U7.status.pipe(F1((W0)=>Boolean(W0.connected&&W0.authenticated&&W0.ideName&&dR1(W0.ideName))),L4()).subscribe((W0)=>{if(W0){if(!E)E=q.registerTool(l94)}else E?.dispose(),E=void 0}),L;if(!J.executeMode){let W0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new H90(process.cwd(),{alwaysIncludePaths:W0},!0)}else L=new class extends H90{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Fm1({isDevelopment:!1}),A=new cR0(M,X),j=new xj0(M,{lazy:!0,maxThreads:200});R.info("Starting Amp background services");let I=Z.takeMeBack?!1:void 0,_=ni0(I,F),S=Boolean(_||Z.headless);if(S)R.info("DTW mode enabled: thread sync service disabled");let v=S?J93():hp1({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),g;U7.status.subscribe((W0)=>{g=W0});let b=new GN0({workspaceRoots:[V1.file(process.cwd())],fileSystem:i3,getCurrentFile:()=>{if(!g?.openFile)return;try{return V1.parse(g.openFile)}catch(W0){R.warn("Failed to parse current file URI",{uri:g.openFile,error:W0});return}},getOpenFiles:()=>{if(!g?.visibleFiles?.length)return[];let W0=g.openFile;return g.visibleFiles.filter((n)=>n!==W0).map((n)=>{try{return V1.parse(n)}catch(D0){return R.warn("Failed to parse visible file URI",{uri:n,error:D0}),null}}).filter((n)=>n!==null)}}),k=new ib0,u=process.env.PLUGINS??"off",p=Z.headless?vq4():void 0,c=p??new L20({configService:X}),f=c instanceof L20?c:void 0;if(f)f.pluginExecutorKind=_?"local":"unknown";let o=KA0({configService:X,fileSystem:i3,platform:c,internalPlugins:mC4,pluginFilter:u}),l=if1({pluginService:o,toolService:q}),t={codebaseContextService:b,configService:X,toolService:q,mcpService:B,skillService:H,toolboxService:N,trustStore:W,threadService:A,threadHistoryService:j,threadSyncService:v,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,fileSystem:i3,terminal:k,pluginService:o,pluginPlatform:f,headlessPluginPlatform:p,serverStatus:F,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...t,async asyncDispose(){if(t.mcpService.hasAuthenticatingClients())R.info("Waiting for OAuth authentication to complete before exit..."),await t.mcpService.waitForAuthentication();for(let W0 of w.values())W0.dispose();await t.mcpService.dispose(),U(),await t.threadService.asyncDispose(),t.configService.unsubscribe(),G(),t.fuzzyServer.dispose(),t.threadSyncService.dispose(),t.settingsStorage[Symbol.dispose](),O.unsubscribe(),E?.dispose(),l.dispose(),await t.pluginService.dispose()}}}async function Z93(J){if(!J.executeMode){if(!await w20("Would you like to log in to Amp? [(y)es, (n)o]: "))return p6.write(`Login cancelled. Run the command again to retry.
7592
7550
  `),!1}return await dC4(J)}async function dC4(J){let Z=g83(32).toString("hex"),Q=await JT(J.ampURL,Z),Y=new AbortController;try{await gX(Q,Y.signal)}catch(K){R.error("Error opening browser",{error:K})}let X=await JT(J.ampURL,Z,!1);p6.write(`If your browser does not open automatically, visit:
7593
7551
 
@@ -7595,7 +7553,7 @@ ${d0.blue.bold(X)}
7595
7553
 
7596
7554
  `);try{return await Uq4(J.ampURL,Z,J.secrets,Y),p6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return R.error("Login failed",{error:K}),R2.write(`
7597
7555
  Login failed: ${K instanceof Error?K.message:String(K)}
7598
- `),!1}}function yC4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Q93(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 j1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!N8(Y.threadId))throw new j1("Create response did not include a valid thread ID",1);return Y.threadId}function Y93(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function X93(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 j1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Y93(Q))throw new j1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function K93(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 V93(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 j1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function z93(){let J=new qH().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)aO(),process.exit(0);let B=H.originalError??H;bK4(B)}),VR4(J,{version:"0.0.1773982701-g41d390",buildTimestamp:"2026-03-20T05:02:03.107Z",buildType:"'release'"}),J.addHelpText("after",Hz4()),J.configureHelp({formatHelp:Bz4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await D3(N);await H93(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 D3(N);await W93(w,await _f0(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(),E=await D3(w);await qV4(H??"get",E.ampURL,E.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 D3(N);await GV4(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",`
7556
+ `),!1}}function yC4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Q93(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 j1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!N8(Y.threadId))throw new j1("Create response did not include a valid thread ID",1);return Y.threadId}function Y93(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function X93(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 j1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Y93(Q))throw new j1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function K93(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 V93(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 j1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function z93(){let J=new qH().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)aO(),process.exit(0);let B=H.originalError??H;bK4(B)}),VR4(J,{version:"0.0.1773994045-ge5da52",buildTimestamp:"2026-03-20T08:11:11.923Z",buildType:"'release'"}),J.addHelpText("after",Hz4()),J.configureHelp({formatHelp:Bz4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await D3(N);await H93(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 D3(N);await W93(w,await _f0(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(),E=await D3(w);await qV4(H??"get",E.ampURL,E.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 D3(N);await GV4(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",`
7599
7557
  Actions:
7600
7558
  create Create a new DTW thread and print its ID
7601
7559
  add-message <message> Send a user message and wait for message_added
@@ -7659,8 +7617,8 @@ ${L}
7659
7617
 
7660
7618
  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 F93(J){R.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new $p({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:XJ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new KK(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw R.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function q93(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await KT()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await KT()).trimEnd(),stdinInput:null}}function G93(J,Z,Q){if(J.remote&&!Z)throw new j1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new j1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new j1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new j1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new j1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new j1("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 j1("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 j1("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"
7661
7619
  Or pipe via stdin: echo "your message" | amp --execute`)}async function UQ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(F0,$0)=>{let G0=Number(process.hrtime.bigint()-$0)/1e6,i=bJ4();R.info("Startup phase",{phase:F0,phaseMs:Math.round(G0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await q93(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;G93({...Z,streamJson:z},J.executeMode,K),J2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),G=!J.executeMode&&!Z.headless&&q;R.info("Interactive auth startup mode",{deferInteractiveAuth:G,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await G9(J,Z,{deferAuth:G});X("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let U=await si0(D);X("runMainThread:createWorkerDeps",F);let{serverStatus:W}=D;if(!G&&Mq(W)){let F0=gC(Error(W.error.message));if(F0.message===V3.networkOffline||F0.message===V3.networkTimeout)throw GQ0(J.ampURL);throw new j1(V3.invalidAPIKey,1)}let H=M6(W)?W:null,B=H?.user.email,N=gC4(B),w=ii0({userEmail:B,features:H?.features}),E=Z.takeMeBack?!1:void 0,O=H!==null&&ni0(E,H);if(!G)await li0(Q,Z,W);let L=ai0(W),M=L?.features??[],A=L?.team??null,j=E20(Z,L);if(j instanceof Error)U3(j.message);if((J.executeMode||z)&&d3(Z.mode)&&!N)throw new j1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!UU(Z.mode,B))throw new j1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await fq4(K,V,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!bZ(B))throw new j1("Headless DTW mode is only available for Amp employees",1);let F0=await D.secretStorage.get("apiKey",J.ampURL);if(!F0)throw new j1("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&&!N8($0))throw new j1(`Invalid thread ID: ${$0}`,1);let G0=$0??await A93({dependencies:D,visibility:j??void 0}),i=await bV4(G0);if(i.status==="already-running")await D.asyncDispose(),await kG(),process.exit(0);try{await SV4({ampURL:J.ampURL,apiKey:F0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:G0,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform})}finally{await i.release(),await D.asyncDispose()}await kG(),process.exit(0)}let I=J.executeMode?void 0:async(F0)=>Wc(F0,"interactive"),_={threadService:D.threadService,workerDeps:U,createThread:async()=>{let F0=G?await D.serverStatusPromise:W,$0=await $90(J.settings,process.cwd(),ai0(F0),j);if($0 instanceof Error)U3($0.message);return Xp0(U,{threadMeta:$0?mK($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:I})},validateThreadOwnership:async(F0,$0)=>{if($0?.nonBlockingOwnershipCheck){vC4(F0,D.configService).catch((G0)=>{if(G0 instanceof j1){if($0.onOwnershipError){$0.onOwnershipError(G0,F0);return}mC(G0,F0);return}R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})});return}try{await vC4(F0,D.configService)}catch(G0){if(G0 instanceof j1)throw G0;R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:I},S=async(F0)=>{try{if(F0==="dtw")return F93({ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId});return cN4(_,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof j1)throw $0;throw await mC($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")R2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7662
- `),await kG(),process.exit(1);let v=(async()=>{if(G){R.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await D.configService.getLatest(),$0=$v(F0),G0=await L6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(G0.ok)return R.info("User free tier status:",G0),G0.result;return}catch(F0){R.error("Failed to fetch free tier status:",F0);return}})(),b=!J.executeMode?new Zh0:null,k,u=null;if(b)k=b,u=(async()=>{let F0=G?await D.serverStatusPromise:D.serverStatus;await li0(Q,Z,F0);let $0=process.hrtime.bigint(),G0=ni0(E,F0),i=M6(F0)?ii0({userEmail:F0.user.email,features:F0.features}):!1;TC4({dtwEnabled:G0,hasV2TUIAccess:i});let a=await S(G0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),b.attach(a),K){let s=await O1(a.threadHandles$);if(!s)throw new j1("No active thread is available yet.",1);await s.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));b.setInitError($0),await mC(F0,Z.threadId)});else F=process.hrtime.bigint(),TC4({dtwEnabled:O,hasV2TUIAccess:w}),k=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let c=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),$93({configService:D.configService,threadService:D.threadService,config:c,useNotificationsForService:p,threadViewStates$:()=>k.threadHandles$.pipe(Z4((F0)=>{if(!F0)return k0.of({});return c6(F0.thread$,F0.threadViewState$).pipe(F1(([$0,G0])=>({[$0.id]:G0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){Rq4(D.mcpService,J.settings);let F0={userInput:K,stdinInput:V,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await oK4({threadPool:k,...F0});if(await Wc($0,"execute"),Z.archive)await L6.archiveThread({thread:$0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let f=!1,o=!1;if(Z.jetbrains||Z.ide){await oR1();let F0=await Bw({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)f=!await D.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)U7.selectConfig($0)}else o=!0}F=process.hrtime.bigint();let l=rf0("0.0.1773982701-g41d390",D.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let t=new vj0(D.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let W0=new Cb0(D.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let F0=await O1(k.threadHandles$);if(!F0)throw new j1("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let n=await A20();X("runMainThread:loadSessionState",F),R.info("Loaded session state:",n);let D0={...n,launchCount:n.launchCount+1};zL((F0)=>({...F0,launchCount:F0.launchCount+1}));let w0=Z.threadId&&N8(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await yw4({codebaseContextService:D.codebaseContextService,history:new Df0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,threadHistoryService:D.threadHistoryService,threadFuzzyIndexer:t,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:L6,threadPool:k,createSystemPromptDeps:async()=>pC4(D),ideClient:U7,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:W0,updateService:l,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:w0,showJetBrainsInstaller:f,showIdePickerHint:o,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:D0,freeTierStatusPromise:v,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-20T05:02:03.107Z"},(F0)=>new wp0({...F0,threadPool:F0.threadPool},($0)=>new Bl0({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await D.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function D3(J){if(R.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)R2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7663
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;R.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Qf1({get:async(z)=>{if(z!==nx)return;try{let F=await fC4(ci0,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(z,F)=>{if(z!==nx)return;await uC4(_B.dirname(ci0),{recursive:!0}),await p83(ci0,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:hV()});KR1(Y);let X=await sV4({...J,workspaceTrust:{current:!0,changes:uy},getHook:process.env.AMP_URL?(z,F)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let z=await Aq4(J.mcpConfig);X=jq4(X,z)}let K=_B.dirname(X.getSettingsFilePath());n$4(aC,K);let V=await X.get("url","global");if(!V)V=K2;if(R.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!GU(V))R.info("Targeting custom Amp server",{ampURL:V});return X=oj1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:pq4(await _f0(J,X))}}function D93(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,(z,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function U93(){fJ4();let J=D93(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));rX4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?l83: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)d0.level=0;if(n83(R),R.info("Starting Amp CLI.",{version:"0.0.1773982701-g41d390",buildTimestamp:"2026-03-20T05:02:03.107Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new j1(V3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await z93().parseAsync(process.argv)}l$4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await U93().catch(mC)});async function W93(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"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7620
+ `),await kG(),process.exit(1);let v=(async()=>{if(G){R.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await D.configService.getLatest(),$0=$v(F0),G0=await L6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(G0.ok)return R.info("User free tier status:",G0),G0.result;return}catch(F0){R.error("Failed to fetch free tier status:",F0);return}})(),b=!J.executeMode?new Zh0:null,k,u=null;if(b)k=b,u=(async()=>{let F0=G?await D.serverStatusPromise:D.serverStatus;await li0(Q,Z,F0);let $0=process.hrtime.bigint(),G0=ni0(E,F0),i=M6(F0)?ii0({userEmail:F0.user.email,features:F0.features}):!1;TC4({dtwEnabled:G0,hasV2TUIAccess:i});let a=await S(G0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),b.attach(a),K){let s=await O1(a.threadHandles$);if(!s)throw new j1("No active thread is available yet.",1);await s.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));b.setInitError($0),await mC(F0,Z.threadId)});else F=process.hrtime.bigint(),TC4({dtwEnabled:O,hasV2TUIAccess:w}),k=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let c=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),$93({configService:D.configService,threadService:D.threadService,config:c,useNotificationsForService:p,threadViewStates$:()=>k.threadHandles$.pipe(Z4((F0)=>{if(!F0)return k0.of({});return c6(F0.thread$,F0.threadViewState$).pipe(F1(([$0,G0])=>({[$0.id]:G0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){Rq4(D.mcpService,J.settings);let F0={userInput:K,stdinInput:V,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await oK4({threadPool:k,...F0});if(await Wc($0,"execute"),Z.archive)await L6.archiveThread({thread:$0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let f=!1,o=!1;if(Z.jetbrains||Z.ide){await oR1();let F0=await Bw({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)f=!await D.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)U7.selectConfig($0)}else o=!0}F=process.hrtime.bigint();let l=rf0("0.0.1773994045-ge5da52",D.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let t=new vj0(D.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let W0=new Cb0(D.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let F0=await O1(k.threadHandles$);if(!F0)throw new j1("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let n=await A20();X("runMainThread:loadSessionState",F),R.info("Loaded session state:",n);let D0={...n,launchCount:n.launchCount+1};zL((F0)=>({...F0,launchCount:F0.launchCount+1}));let w0=Z.threadId&&N8(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await yw4({codebaseContextService:D.codebaseContextService,history:new Df0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,threadHistoryService:D.threadHistoryService,threadFuzzyIndexer:t,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:L6,threadPool:k,createSystemPromptDeps:async()=>pC4(D),ideClient:U7,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:W0,updateService:l,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:w0,showJetBrainsInstaller:f,showIdePickerHint:o,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:D0,freeTierStatusPromise:v,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-20T08:11:11.923Z"},(F0)=>new wp0({...F0,threadPool:F0.threadPool},($0)=>new Bl0({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await D.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function D3(J){if(R.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)R2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7621
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;R.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Qf1({get:async(z)=>{if(z!==nx)return;try{let F=await fC4(ci0,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(z,F)=>{if(z!==nx)return;await uC4(_B.dirname(ci0),{recursive:!0}),await p83(ci0,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:hV()});KR1(Y);let X=await sV4({...J,workspaceTrust:{current:!0,changes:uy},getHook:process.env.AMP_URL?(z,F)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let z=await Aq4(J.mcpConfig);X=jq4(X,z)}let K=_B.dirname(X.getSettingsFilePath());n$4(aC,K);let V=await X.get("url","global");if(!V)V=K2;if(R.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!GU(V))R.info("Targeting custom Amp server",{ampURL:V});return X=oj1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:pq4(await _f0(J,X))}}function D93(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,(z,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function U93(){fJ4();let J=D93(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));rX4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?l83: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)d0.level=0;if(n83(R),R.info("Starting Amp CLI.",{version:"0.0.1773994045-ge5da52",buildTimestamp:"2026-03-20T08:11:11.923Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new j1(V3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await z93().parseAsync(process.argv)}l$4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await U93().catch(mC)});async function W93(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"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7664
7622
  `);else if(!GU(J.ampURL))p6.write(`Logging in to ${new URL(J.ampURL).hostname}
7665
7623
  `);let Y=process.env.AMP_API_KEY;if(Y)p6.write(`API key found in environment variable, storing...
7666
7624
  `),await Z.set("apiKey",Y,J.ampURL),p6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1773982701-g41d390",
3
+ "version": "0.0.1773994045-ge5da52",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {