@sourcegraph/amp 0.0.1761720604-gb6da12 → 0.0.1761724890-gadc2fc
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.
- package/dist/main.js +11 -11
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6046,11 +6046,11 @@ Actual: ${Y}`)}async function UJ9(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
6046
6046
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
6047
6047
|
|
|
6048
6048
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6049
|
-
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function KJ1(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=DJ9(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function DJ9(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}v0();function of1(J,Q){let Z=new f8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new Zz().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await c_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await KJ1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await YJ1();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await wp(z.latestVersion,U);let W=await qN(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await c_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as GW}from"node:process";function lX6(J){let Q=new DR().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(X)=>{await af1(X.force||!1,X.verbose||!1,"0.0.
|
|
6049
|
+
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function KJ1(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=DJ9(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function DJ9(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}v0();function of1(J,Q){let Z=new f8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new Zz().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await c_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await KJ1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await YJ1();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await wp(z.latestVersion,U);let W=await qN(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await c_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as GW}from"node:process";function lX6(J){let Q=new DR().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(X)=>{await af1(X.force||!1,X.verbose||!1,"0.0.1761724890-gadc2fc"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new DR("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await MJ9(X.version)});J.addCommand(Z)}async function MJ9(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")GW.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6050
6050
|
|
|
6051
6051
|
`));try{if(!J){GW.write(W8.blue(`Checking for updates...
|
|
6052
|
-
`));let{hasUpdate:Z,latestVersion:X}=await KJ1("0.0.
|
|
6053
|
-
`));let Y=await qN("0.0.
|
|
6052
|
+
`));let{hasUpdate:Z,latestVersion:X}=await KJ1("0.0.1761724890-gadc2fc");if(!Z){GW.write(W8.green(`✓ Amp CLI is already up to date.
|
|
6053
|
+
`));let Y=await qN("0.0.1761724890-gadc2fc");if(Y.warning)GW.write(`
|
|
6054
6054
|
`+W8.yellow(Y.warning)+`
|
|
6055
6055
|
`);process.exit(0)}if(!X)GW.write(W8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}GW.write(W8.blue(`Updating to version ${J}...
|
|
6056
6056
|
`)),await wp(J,void 0,(Z)=>{GW.write(W8.dim(`Running: ${Z}
|
|
@@ -6470,7 +6470,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||MO}function vY6(J,Q){let
|
|
|
6470
6470
|
`);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let G=K.optsWithGlobals(),q=await Q(K,G),z=0;await q.mcpService.initialized;let U=K.args.slice(1),W;if(CY6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await PY6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:q,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await q.asyncDispose(),q.cleanupTerminal(),process.exit(z)})}import{randomBytes as _B9}from"node:crypto";import{homedir as xB9}from"node:os";import _d from"node:path";v0();G0();var kY6=120000,_Y6=180000;function Yh1(J,Q=Date.now()){return Q-J<_Y6}function Kh1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return uN(t1.of(void 0),Zc(kY6).pipe(C7(()=>Z()))).pipe(q8(()=>c6(async(q)=>{let z=await X?.getContext();u.debug("[Ads] Fetching ad from server",{hasContext:!!z});let U=await J.getCurrentAd({context:z,excludeAdIds:K},{config:Q,signal:q});if(!U.ok)throw u.error("[Ads] Failed to fetch ad",{error:U.error.message}),Error(U.error.message);if(U.result){if(Y=U.result,K.length>=G)K.shift();K.push(Y.id),u.debug("[Ads] Received ad from server",{adTitle:Y.title,matchType:Y.matchType,matchedPatterns:Y.matchedPatterns,candidateAdPoolCount:Y.candidateAdPoolCount,recentlyShownCount:K.length})}else u.debug("[Ads] No ad available from server");return Y})),J8((q,z)=>q?.id===z?.id))}G0();G$();U2();YD();e9();_L();z8();k6();function xY6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function bY6(J,Q,Z){if(J.agentMode)return J.agentMode;if(Q?.agentMode){let X=Q.agentMode;if(X==="free"){if(Z?.canUseAmpFree??!1)return"free";return"smart"}return X}return"smart"}G0();YD();import gQ9 from"node:fs";import yY6 from"node:path";function fY6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!yY6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function hY6(J){try{let Q=yY6.extname(J).toLowerCase(),Z=R00(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=gQ9.readFileSync(J);return mQ9(X,Z)}catch(X){u.error(`Failed to read image file ${J}:`,X)}}catch(Q){u.error("Error handling image file path",{imagePath:J,error:Q})}return null}function mQ9(J,Q){if(J.length===0)return u.warn("Image file is empty (0 bytes)"),null;if(J.length>gW)return u.warn(`Image file too large: ${J.length} bytes (max: ${gW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as xG9}from"node:child_process";Ej();G0();import{spawn as uQ9}from"node:child_process";import{promises as pQ9}from"node:fs";function gY6(J){return J.kind==="executable"}function mY6(J){return J.kind==="markdown"}var ZB=50000,uY6=300000;async function jp(J,Q,Z,X={}){let{timeoutMs:Y=uY6,signal:K}=X;try{let G=await Z.getCommand(J);if(!G)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(u.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),mY6(G))return await dQ9(G,Q);else if(gY6(G))return await cQ9(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return u.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function dQ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await pQ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>ZB?Z.slice(0,ZB)+`
|
|
6471
6471
|
... (output truncated at ${ZB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function cQ9(J,Q,Z=uY6,X){return new Promise((Y)=>{let[K,G]=lQ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=D00(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=uQ9(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=ZB)F.push(V);else{let N=ZB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=ZB)H.push(V);else{let N=ZB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(q.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
|
6472
6472
|
${L}`:L;if(B>ZB)A+=`
|
|
6473
|
-
... (output truncated at ${ZB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function lQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return nQ9(Z,X?[...X]:null,Y,Q);else return iQ9(Z,X?[...X]:null,Y,Q)}function iQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function nQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();G$();U2();EW();iX();Pz();k6();v0();var HJ1={};j6(HJ1,{scrollUp:()=>BZ9,scrollDown:()=>DZ9,link:()=>wZ9,image:()=>RZ9,iTerm:()=>OZ9,exitAlternativeScreen:()=>LZ9,eraseUp:()=>HZ9,eraseStartLine:()=>WZ9,eraseScreen:()=>Gh1,eraseLines:()=>zZ9,eraseLine:()=>lY6,eraseEndLine:()=>UZ9,eraseDown:()=>FZ9,enterAlternativeScreen:()=>NZ9,cursorUp:()=>dY6,cursorTo:()=>sQ9,cursorShow:()=>qZ9,cursorSavePosition:()=>QZ9,cursorRestorePosition:()=>ZZ9,cursorPrevLine:()=>KZ9,cursorNextLine:()=>YZ9,cursorMove:()=>oQ9,cursorLeft:()=>cY6,cursorHide:()=>GZ9,cursorGetPosition:()=>XZ9,cursorForward:()=>eQ9,cursorDown:()=>tQ9,cursorBackward:()=>JZ9,clearTerminal:()=>VZ9,clearScreen:()=>MZ9,beep:()=>AZ9});import qh1 from"node:process";var FJ1=globalThis.window?.document!==void 0,Rj2=globalThis.process?.versions?.node!==void 0,Oj2=globalThis.process?.versions?.bun!==void 0,jj2=globalThis.Deno?.version?.deno!==void 0,$j2=globalThis.process?.versions?.electron!==void 0,Ej2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,Ij2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Pj2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Tj2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,Cj2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,$p=globalThis.navigator?.userAgentData?.platform,Sj2=$p==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",vj2=$p==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",kj2=$p==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",_j2=$p==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),xj2=$p==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Ip="\x1B]",hC="\x07",Ep=";",pY6=!FJ1&&qh1.env.TERM_PROGRAM==="Apple_Terminal",aQ9=!FJ1&&qh1.platform==="win32",rQ9=FJ1?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:qh1.cwd,sQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return O2+(J+1)+"G";return O2+(Q+1)+Ep+(J+1)+"H"},oQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=O2+-J+"D";else if(J>0)Z+=O2+J+"C";if(Q<0)Z+=O2+-Q+"A";else if(Q>0)Z+=O2+Q+"B";return Z},dY6=(J=1)=>O2+J+"A",tQ9=(J=1)=>O2+J+"B",eQ9=(J=1)=>O2+J+"C",JZ9=(J=1)=>O2+J+"D",cY6=O2+"G",QZ9=pY6?"\x1B7":O2+"s",ZZ9=pY6?"\x1B8":O2+"u",XZ9=O2+"6n",YZ9=O2+"E",KZ9=O2+"F",GZ9=O2+"?25l",qZ9=O2+"?25h",zZ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lY6+(Z<J-1?dY6():"");if(J)Q+=cY6;return Q},UZ9=O2+"K",WZ9=O2+"1K",lY6=O2+"2K",FZ9=O2+"J",HZ9=O2+"1J",Gh1=O2+"2J",BZ9=O2+"S",DZ9=O2+"T",MZ9="\x1Bc",VZ9=aQ9?`${Gh1}${O2}0f`:`${Gh1}${O2}3J${O2}H`,NZ9=O2+"?1049h",LZ9=O2+"?1049l",AZ9=hC,wZ9=(J,Q)=>[Ip,"8",Ep,Ep,Q,hC,J,Ip,"8",Ep,Ep,hC].join(""),RZ9=(J,Q={})=>{let Z=`${Ip}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+hC},OZ9={setCwd:(J=rQ9())=>`${Ip}50;CurrentDir=${J}${hC}`,annotation(J,Q={}){let Z=`${Ip}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+hC}};var BJ1=v6(tY6(),1);function WN(J,Q,{target:Z="stdout",...X}={}){if(!BJ1.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return HJ1.link(J,Q)}WN.isSupported=BJ1.default.stdout;WN.stderr=(J,Q,Z={})=>WN(J,Q,{target:"stderr",...Z});WN.stderr.isSupported=BJ1.default.stderr;G0();iX();class Pp{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761720604-gb6da12"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ca(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as MJ1}from"node:child_process";import{platform as Hh1}from"node:os";import{promisify as IZ9}from"node:util";var DJ1=IZ9(MJ1),PZ9=(J)=>`\x1B]52;c;${J}\x1B\\`,TZ9="\x1B]52;c;?\x1B\\",CZ9="\x1B]52;p;?\x1B\\";class eY6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await DJ1("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=MJ1("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=MJ1("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=MJ1("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(TZ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await DJ1("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await DJ1("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await DJ1("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(CZ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Hh1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(Hh1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=PZ9(Z);process.stdout.write(X);return}if(Hh1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var jY=new eY6;G0();class t9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function VJ1(J){if(J instanceof t9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var NN=null,bG9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(NN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (g51(),Tf1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{NN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});NN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{NN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => v6(hp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new t9(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!NN)return new t9("Not connected to Amp web interface");try{NN.disconnect();let Z=NN.clientID;return NN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new t9(`Disconnected from Amp web interface
|
|
6473
|
+
... (output truncated at ${ZB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function lQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return nQ9(Z,X?[...X]:null,Y,Q);else return iQ9(Z,X?[...X]:null,Y,Q)}function iQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function nQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();G$();U2();EW();iX();Pz();k6();v0();var HJ1={};j6(HJ1,{scrollUp:()=>BZ9,scrollDown:()=>DZ9,link:()=>wZ9,image:()=>RZ9,iTerm:()=>OZ9,exitAlternativeScreen:()=>LZ9,eraseUp:()=>HZ9,eraseStartLine:()=>WZ9,eraseScreen:()=>Gh1,eraseLines:()=>zZ9,eraseLine:()=>lY6,eraseEndLine:()=>UZ9,eraseDown:()=>FZ9,enterAlternativeScreen:()=>NZ9,cursorUp:()=>dY6,cursorTo:()=>sQ9,cursorShow:()=>qZ9,cursorSavePosition:()=>QZ9,cursorRestorePosition:()=>ZZ9,cursorPrevLine:()=>KZ9,cursorNextLine:()=>YZ9,cursorMove:()=>oQ9,cursorLeft:()=>cY6,cursorHide:()=>GZ9,cursorGetPosition:()=>XZ9,cursorForward:()=>eQ9,cursorDown:()=>tQ9,cursorBackward:()=>JZ9,clearTerminal:()=>VZ9,clearScreen:()=>MZ9,beep:()=>AZ9});import qh1 from"node:process";var FJ1=globalThis.window?.document!==void 0,Rj2=globalThis.process?.versions?.node!==void 0,Oj2=globalThis.process?.versions?.bun!==void 0,jj2=globalThis.Deno?.version?.deno!==void 0,$j2=globalThis.process?.versions?.electron!==void 0,Ej2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,Ij2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Pj2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Tj2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,Cj2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,$p=globalThis.navigator?.userAgentData?.platform,Sj2=$p==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",vj2=$p==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",kj2=$p==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",_j2=$p==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),xj2=$p==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Ip="\x1B]",hC="\x07",Ep=";",pY6=!FJ1&&qh1.env.TERM_PROGRAM==="Apple_Terminal",aQ9=!FJ1&&qh1.platform==="win32",rQ9=FJ1?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:qh1.cwd,sQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return O2+(J+1)+"G";return O2+(Q+1)+Ep+(J+1)+"H"},oQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=O2+-J+"D";else if(J>0)Z+=O2+J+"C";if(Q<0)Z+=O2+-Q+"A";else if(Q>0)Z+=O2+Q+"B";return Z},dY6=(J=1)=>O2+J+"A",tQ9=(J=1)=>O2+J+"B",eQ9=(J=1)=>O2+J+"C",JZ9=(J=1)=>O2+J+"D",cY6=O2+"G",QZ9=pY6?"\x1B7":O2+"s",ZZ9=pY6?"\x1B8":O2+"u",XZ9=O2+"6n",YZ9=O2+"E",KZ9=O2+"F",GZ9=O2+"?25l",qZ9=O2+"?25h",zZ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lY6+(Z<J-1?dY6():"");if(J)Q+=cY6;return Q},UZ9=O2+"K",WZ9=O2+"1K",lY6=O2+"2K",FZ9=O2+"J",HZ9=O2+"1J",Gh1=O2+"2J",BZ9=O2+"S",DZ9=O2+"T",MZ9="\x1Bc",VZ9=aQ9?`${Gh1}${O2}0f`:`${Gh1}${O2}3J${O2}H`,NZ9=O2+"?1049h",LZ9=O2+"?1049l",AZ9=hC,wZ9=(J,Q)=>[Ip,"8",Ep,Ep,Q,hC,J,Ip,"8",Ep,Ep,hC].join(""),RZ9=(J,Q={})=>{let Z=`${Ip}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+hC},OZ9={setCwd:(J=rQ9())=>`${Ip}50;CurrentDir=${J}${hC}`,annotation(J,Q={}){let Z=`${Ip}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+hC}};var BJ1=v6(tY6(),1);function WN(J,Q,{target:Z="stdout",...X}={}){if(!BJ1.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return HJ1.link(J,Q)}WN.isSupported=BJ1.default.stdout;WN.stderr=(J,Q,Z={})=>WN(J,Q,{target:"stderr",...Z});WN.stderr.isSupported=BJ1.default.stderr;G0();iX();class Pp{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761724890-gadc2fc"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ca(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as MJ1}from"node:child_process";import{platform as Hh1}from"node:os";import{promisify as IZ9}from"node:util";var DJ1=IZ9(MJ1),PZ9=(J)=>`\x1B]52;c;${J}\x1B\\`,TZ9="\x1B]52;c;?\x1B\\",CZ9="\x1B]52;p;?\x1B\\";class eY6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await DJ1("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=MJ1("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=MJ1("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=MJ1("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(TZ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await DJ1("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await DJ1("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await DJ1("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(CZ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Hh1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(Hh1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=PZ9(Z);process.stdout.write(X);return}if(Hh1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var jY=new eY6;G0();class t9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function VJ1(J){if(J instanceof t9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var NN=null,bG9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(NN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (g51(),Tf1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{NN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});NN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{NN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => v6(hp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new t9(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!NN)return new t9("Not connected to Amp web interface");try{NN.disconnect();let Z=NN.clientID;return NN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new t9(`Disconnected from Amp web interface
|
|
6474
6474
|
Client ID: ${Z}
|
|
6475
6475
|
Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Gg1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=SS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Pp(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(b0((Z)=>wZ(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...yG9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,bG9);if(J)Object.assign(this.commands,fG9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((q)=>{u.debug("Failed to submit command telemetry",q)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((q)=>q.name===J),G=await jp(J,Z,this.customRegistry,{signal:X});if(G.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:G.output});return}else{Q.submitMessage(G.output);return}return Error(G.error??`Command '${J}' failed`)}query(J,Q,Z){let X=Object.values(this.commands).filter((K)=>{if(!Q||!K.isVisible)return!0;return K.isVisible(Q,Z)}),Y=this.latestCustom.filter((K)=>K.available).map((K)=>({name:K.name,description:"Custom command",requiresArgs:K.kind==="executable",execute:(G,q)=>this.execute(K.name,G,q??[])}));return[...X,...Y]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}getCustomCommand(J){return this.latestCustom.find((Q)=>Q.name===J)}}var yG9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${x5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=mZ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:ia}],agentMode:K}});return}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{return J.openInEditor("")}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return RZ("dangerouslyAllowAll",!1),new t9("Amp is now following permissions rules for this session")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return RZ("dangerouslyAllowAll",!0),new t9("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await qW();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw u.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:qW};await yC(Y);return}catch(Y){u.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return u.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},handoff:{name:"handoff",description:"Draft a new thread with relevant context from current thread: /handoff <your goal>",requiresArgs:!0,execute:async()=>{return},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new t9(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return u.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((q)=>q.type==="text").map((q)=>q.text).join("").trim()}).filter(Boolean).join(`
|
|
6476
6476
|
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=tW(new URL(Y),Z.id).toString(),q=`Thread URL: ${WN(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public_unlisted"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new t9(`${q}
|
|
@@ -6542,7 +6542,7 @@ The context used was: `+J.widget.constructor.name);return Q}updateShouldNotify(J
|
|
|
6542
6542
|
`)continue;let A=i4(L,q);if(W+A<=Y+G){let R=V&&N>=V.start&&N<V.end?this._style.selectionBackgroundColor??I1.blue:X;J.setChar(W,K,L,{fg:Z,bg:R,dim:z},A),W+=A}else break}}_paintMultilineText(J,Q,Z,X,Y,K,G,q,z,U=!1){if(!Q)return;let W=this._controller.text,F,H,B;if(W)F=this._controller.getLayoutLines(),H=this._controller.getScrollOffset(),B=this._controller.graphemes;else F=new qd(Q,{maxWidth:G,wrapMode:this._wrap?"word":"none",emojiSupported:z}).lines,H=0,B=j2(Q);let M=Math.min(H+q,F.length),V=this._controller.selectionRange;for(let N=H;N<M;N++){let L=K+(N-H),A=F[N];if(A){let w=B.slice(A.startOffset,A.endOffset),R=Y,O=N===0,$=this._controller.text,j=O?this._prompts.find((I)=>I.match($)):void 0;if(j){let I=j2(j.display),T=j.style?.color??Z;for(let _ of I){let h=i4(_,z);if(R+h<=Y+G)J.setChar(R,L,_,{fg:T,bg:X},h),R+=h}let S=j.spacing??0;for(let _=0;_<S;_++)if(R<Y+G)J.setChar(R,L," ",{fg:Z,bg:X},1),R+=1}let E=j?.concealPrefix?j2(j.display).length:0;for(let I=E;I<w.length&&R<Y+G;I++){let T=w[I],S=i4(T,z);if(R+S<=Y+G){let _=A.startOffset+I,v=V&&_>=V.start&&_<V.end?this._style.selectionBackgroundColor??I1.blue:X;J.setChar(R,L,T,{fg:Z,bg:v,dim:U},S),R+=S}else break}}}}_paintCursor(J,Q,Z,X,Y,K){if(this.isMultiline){let q=this._controller.cursorPosition,z=this._controller.getLayoutLines(),U=-1,W=0;for(let H=0;H<z.length;H++){let B=z[H];if(q>=B.startOffset&&q<=B.endOffset){U=H,W=q-B.startOffset;break}}let F=this._controller.getScrollOffset();if(U>=F&&U<F+Y){let H=Z+(U-F),B=z[U],M=this._controller.graphemes,V=Q,N=U===0,L=this._controller.text,A=N?this._prompts.find((O)=>O.match(L)):void 0;if(A){let O=j2(A.display);for(let $ of O)V+=i4($,K);V+=A.spacing??0}let w=A?.concealPrefix?j2(A.display).length:0,R=Math.max(0,W-w);for(let O=0;O<R;O++){let $=B.startOffset+w+O;if($<M.length){let j=M[$],E=i4(j,K);V+=E}}if(V>=Q&&V<=Q+X)J.setCursor(V,H);else J.clearCursor()}else J.clearCursor()}else{let q=this._controller.cursorPosition,z=this._controller.graphemes,U=this._controller.text,W=this._prompts.find((V)=>V.match(U)),F=Q;if(W){let V=j2(W.display);for(let N of V)F+=i4(N,K);F+=W.spacing??0}let H=W?.concealPrefix?j2(W.display).length:0,B=Math.max(this._hScrollOffset,H),M=Math.max(q,H);for(let V=B;V<M&&V<z.length;V++){let N=z[V];if(N!==`
|
|
6543
6543
|
`)F+=i4(N,K)}if(F>=Q&&F<=Q+X)J.setCursor(F,Z);else J.clearCursor()}}_updateScrollOffsetFromLayout(J,Q){let Z=this._controller;if(!(Q>=J.maxHeight)){Z.setScrollOffset(0);return}let Y=Z.getLayoutLines(),K=Z.cursorPosition,G=-1;for(let L=0;L<Y.length;L++){let A=Y[L];if(K>=A.startOffset&&K<=A.endOffset){G=L;break}}if(G===-1)return;let q=this._style.padding||N0.all(0),U=this._style.border?1:0,W=Q-q.top-q.bottom-U*2,F=Z.getScrollOffset(),H=F,B=F+W-1;if(G<H)Z.setScrollOffset(G);else if(G>B){let L=G-W+1;Z.setScrollOffset(L)}let M=Math.max(0,Y.length-W),V=Z.getScrollOffset(),N=Math.max(0,Math.min(V,M));Z.setScrollOffset(N)}}var Jz9=new Set([" ","\t",`
|
|
6544
6544
|
`,"\r","\v","\f"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," ","\uFEFF"]),Qz9=new Set(["/","\\",".",",",";",":","!","?","(",")","[","]","{","}","<",">","'",'"',"=","+","-","*","&","|","^","%","$","#","@","~","`","_"]);G0();class sg1{_state;_textController=null;_triggers=[];_optionsBuilder=null;_onSelected=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new hR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Q,optionsBuilder:Z,onSelected:X}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._triggers=Q,this._optionsBuilder=Z,this._onSelected=X||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Q=J.options[J.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this._textController.text,Q=this._textController.cursorPosition,Z=null;for(let Y of this._triggers){let K=Y.detect(J,Q);if(K&&(!Z||K.start>Z.start))Z=K}if(!Z){if(this.currentState.isActive)this.dismiss();return}let X=this.currentState.generationId+1;this._updateState({trigger:Z,generationId:X,isActive:!0,selectedIndex:-1}),this._buildOptions(Z.query,X)};async _buildOptions(J,Q){if(!this._optionsBuilder)return;try{let Z=await this._optionsBuilder(J);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:Z,selectedIndex:Z.length>0?0:-1,isActive:Z.length>0})}catch(Z){if(u.error("Error building autocomplete options:",Z),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._textController)this._textController.removeListener(this._handleTextChange)}}class zd{}class Ud{}class Wd{}class iJ1{}class nJ1 extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Nz6(this.props)}}class Nz6 extends d0{props;controller;stateListener=null;overlayEntry=null;layerLink=new rg1;scrollOffset=0;_effectiveFocusNode;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new Q9({debugLabel:"AutocompleteFocusOwned"}),this.controller=new sg1,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Fz6(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.canStealFocus)c9.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Q=J.props,Z=this.widget.props;if(this.props=Z,Q.controller!==Z.controller||Q.triggers!==Z.triggers||Q.optionsBuilder!==Z.optionsBuilder||Q.textFieldProps!==Z.textFieldProps||Q.onSelected!==Z.onSelected)this.controller.initialize({textController:Z.controller,triggers:Z.triggers,optionsBuilder:Z.optionsBuilder,onSelected:Z.onSelected});this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof zd)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Ud)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Wd)return this.controller.acceptSelected(),"handled";if(J instanceof iJ1)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Q=J.selectedIndex,Z=J.options.length,X=Z;try{let z=this.layerLink.getTargetTransform();if(z){let U=z.position.y,W=2,F=U-2;X=Math.min(Z,Math.max(1,F))}}catch{}if(X>=Z){this.scrollOffset=0;return}let Y=Q-this.scrollOffset,K=1,G=this.scrollOffset;if(Y>=X-K)G=Math.max(0,Q-(X-K-1));if(Y<K)G=Math.max(0,Q-K);let q=Math.max(0,Z-X);G=Math.min(G,q),this.scrollOffset=G}build(J){let Q=new rq({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Z=new aq({shortcuts:new Map([[new y6("ArrowDown"),new zd],[new y6("ArrowUp"),new Ud],[new y6("n",{ctrl:!0}),new zd],[new y6("p",{ctrl:!0}),new Ud],[new y6("Enter"),new Wd],[new y6("Escape"),new iJ1],[new y6("Tab"),new Wd]]),focusNode:this._effectiveFocusNode,child:Q}),X=new NZ({actions:new Map([[zd,new S9(this.invoke)],[Ud,new S9(this.invoke)],[Wd,new S9(this.invoke)],[iJ1,new S9(this.invoke)]]),child:Z});return new ag1({link:this.layerLink,child:X})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new ig1((J)=>{let Q=this.controller.currentState;return this.buildOverlayContent(J,Q)});try{ON.of(this.context).insert(this.overlayEntry)}catch(J){u.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayContent(J,Q){let Z=e6.maybeOf(J),X=Z?.colorScheme.background??I1.black,Y=this.props.overlayBorderColor??Z?.colorScheme.border??I1.white,K=Q.options.length;try{let w=this.layerLink.getTargetTransform();if(w){let R=w.position.y,O=2,$=R-2;K=Math.min(K,Math.max(1,$))}}catch{}this.updateScrollPosition();let G=this.scrollOffset,q=Math.min(Q.options.length,G+K),z=[],U=0;for(let w=G;w<q;w++){let R=Q.options[w];if(!R)continue;let O=w===Q.selectedIndex,$,j;if(this.props.optionViewBuilder){$=this.props.optionViewBuilder(J,R,O);let T=this.props.displayStringForOption?.(R)??String(R),S="",_=T,h="",v=R;if(v&&typeof v==="object"&&"type"in v)switch(v.type){case"command":S="/",_=v.name||T,h=v.description||"";break;case"file":S="@",_=v.path||T;break;case"thread":_=v.title||T,h=v.description||"";break;case"argument":_=v.value||T,h=v.description||"";break}j=S+_+(h?" - "+h:"")}else{let T=this.props.displayStringForOption?.(R)??String(R),S=Z?.colorScheme.selection??I1.index(8),_=Z?.colorScheme.foreground??I1.white;$=new n1({text:new V1(T,new $1({color:_,backgroundColor:O?S:void 0}))}),j=T}let E=_8.of(J),I=$Y(j,E.supportsEmojiWidth);U=Math.max(U,I),z.push($)}let W=_8.sizeOf(J).width,F=U+4,H=Math.floor(W*0.9),B=Math.max(Math.min(F,H),Math.min(30,H)),N=z.length+2,L=-N,A=new U0({width:B,child:new f0({height:N,padding:N0.symmetric(1,0),decoration:new i8(X,x8.all(new w8(Y,1,"rounded"))),child:new i0({crossAxisAlignment:"start",children:z})})});return new ng1({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:L},child:A})}}G9();var Ym1=v6(Sz6(),1);l8();f2();var vz6=20,kz6=" .:-=+*#%@",wz9=" ",Rz9=[0,55,0],Oz9=[0,255,136],jz9=[128,51,0],$z9=[255,215,0],Ez9=[0,26,51],Iz9=[0,184,255],_z6=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],QQ1=0.5,Xm1=(J,Q,Z)=>J+(Q-J)*Z;function Pz9(J,Q){let Z=Math.max(0,Math.min(1,J));if(Q==="low"){let Y=Math.floor(Z*(_z6.length-1));return I1.index(_z6[Y])}if(Q==="fast"){let Y=jz9.map((K,G)=>Math.round(Xm1(K,$z9[G],Z)));return I1.rgb(Y[0],Y[1],Y[2])}if(Q==="free"){let Y=Ez9.map((K,G)=>Math.round(Xm1(K,Iz9[G],Z)));return I1.rgb(Y[0],Y[1],Y[2])}let X=Rz9.map((Y,K)=>Math.round(Xm1(Y,Oz9[K],Z)));return I1.rgb(X[0],X[1],X[2])}var Km1=1,Tz9=30,xz6=3;class Gm1 extends c0{width;height;minWidth;minHeight;maxWidth;maxHeight;colorMode;t;onFrame;fps;seed;constructor({key:J,width:Q=40,height:Z=40,minWidth:X,minHeight:Y,maxWidth:K,maxHeight:G,colorMode:q="high",t:z,onFrame:U,fps:W=60,seed:F}){super(J?{key:J}:{});this.width=Q,this.height=Z,this.minWidth=X??8,this.minHeight=Y??8,this.maxWidth=K??40,this.maxHeight=G??40,this.colorMode=q,this.t=z,this.onFrame=U,this.fps=W,this.seed=F}createState(){return new bz6}}class bz6 extends d0{_t=0;_timer=null;_shockwaves=[];initState(){if(super.initState(),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}if(this.widget.fps==0)return;this._timer=setInterval(()=>{if(this._t+=1/this.widget.fps,this.widget.onFrame){let J=this._t;setImmediate(()=>this.widget.onFrame?.(J))}this._shockwaves=this._shockwaves.filter((J)=>this._t-J.startTime<Km1),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.t!==void 0&&this.widget.t!==J.t)this._t=this.widget.t,this.setState(()=>{})}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}handleClick=(J)=>{this._shockwaves.push({x:J.localPosition.x,y:J.localPosition.y,startTime:this._t}),this.setState(()=>{})};build(J){let Q=new yz6({width:this.widget.width,height:this.widget.height,minWidth:this.widget.minWidth,minHeight:this.widget.minHeight,maxWidth:this.widget.maxWidth,maxHeight:this.widget.maxHeight,time:this._t,colorMode:this.widget.colorMode,seed:this.widget.seed,shockwaves:this._shockwaves});return new x9({onClick:this.handleClick,child:Q})}}class yz6 extends KB{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new wN(this)}createRenderObject(){return new fz6(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.colorMode,this.props.seed,this.props.shockwaves)}updateRenderObject(J){J.update(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.colorMode,this.props.seed,this.props.shockwaves)}}class fz6 extends Z8{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_colorMode;_seed;_shockwaves;_noise2D;constructor(J,Q,Z,X,Y,K,G,q,z,U=[]){super();this._width=J;this._height=Q;this._minWidth=Z;this._minHeight=X;this._maxWidth=Y;this._maxHeight=K;this._time=G;this._colorMode=q;this._seed=z;this._shockwaves=U;this._noise2D=Ym1.makeNoise2D(this._seed??Date.now())}getMinIntrinsicWidth(J){return this._minWidth}getMaxIntrinsicWidth(J){return this._maxWidth}getMinIntrinsicHeight(J){return this._minHeight}getMaxIntrinsicHeight(J){return this._maxHeight}update(J,Q,Z,X,Y,K,G,q,z,U=[]){let W=!1;if(J!==this._width||Q!==this._height||Z!==this._minWidth||X!==this._minHeight||Y!==this._maxWidth||K!==this._maxHeight)this._width=J,this._height=Q,this._minWidth=Z,this._minHeight=X,this._maxWidth=Y,this._maxHeight=K,W=!0;if(z!==this._seed)this._seed=z,this._noise2D=Ym1.makeNoise2D(this._seed??Date.now());if(this._time=G,this._colorMode=q,this._shockwaves=U,W)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;u6(!!J,"performLayout called without constraints");let Q=J.constrain(this._width,this._height);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Q+this.offset.x,Y=Z+this.offset.y,K=Math.floor(this.size.width),G=Math.floor(this.size.height),q=K/2,z=G/2,U=Math.max(1,K/2-1),W=Math.max(1,G/(2*QQ1)-1),F=Math.min(U,W);for(let H=0;H<G;H++){let B=Y+H,M=!0;if(H>0){M=!0;for(let N=0;N<K;N++){let L=N-q,A=(H-1-z)/QQ1;if(Math.sqrt(L*L+A*A)/F<1){M=!1;break}}}let V=!0;for(let N=0;N<K;N++){let L=N-q,A=(H-z)/QQ1,w=Math.sqrt(L*L+A*A),R=w/F;if(R>=1)continue;let O=1-R*R,$=this._colorMode==="fast"?2.5:1,E=(this._noise2D(N/vz6,H/vz6+this._time*$)+1)*0.5*O;for(let _ of this._shockwaves){let h=this._time-_.startTime;if(h<0||h>Km1)continue;let v=N-_.x,x=(H-_.y)/QQ1,y=Math.sqrt(v*v+x*x),g=h*Tz9,k=Math.abs(y-g);if(k<xz6){let f=w/F;if(f<0.95){let b=1-h/Km1,m=(1-k/xz6)*b,n=1-Math.pow(f,3);E=Math.min(1,E+m*0.8*n)}}}let I=kz6[Math.floor(E*kz6.length)]||wz9,T=Pz9(E,this._colorMode),S=X+N;if(S<0||S>=J.getSize().width)continue;J.setCell(S,B,{char:I,width:1,style:{fg:T}}),V=!1}if(V&&M)continue}}}class ZQ1{toolRunning;toolSuccess;toolError;toolCancelled;toolName;userMessage;assistantMessage;systemMessage;codeBlock;inlineCode;syntaxHighlight;fileReference;processing;waiting;completed;cancelled;recommendation;suggestion;command;filename;keybind;button;shellMode;shellModeHidden;diffAdded;diffRemoved;diffChanged;diffContext;ideConnected;ideDisconnected;ideWarning;scrollbarThumb;scrollbarTrack;tableBorder;constructor({toolRunning:J,toolSuccess:Q,toolError:Z,toolCancelled:X,toolName:Y,userMessage:K,assistantMessage:G,systemMessage:q,codeBlock:z,inlineCode:U,syntaxHighlight:W,fileReference:F,processing:H,waiting:B,completed:M,cancelled:V,suggestion:N,command:L,filename:A,keybind:w,button:R,shellMode:O,shellModeHidden:$,diffAdded:j,diffRemoved:E,diffChanged:I,diffContext:T,ideConnected:S,ideDisconnected:_,ideWarning:h,scrollbarThumb:v,scrollbarTrack:x,tableBorder:y,recommendation:g}){this.toolRunning=J,this.toolSuccess=Q,this.toolError=Z,this.toolCancelled=X,this.toolName=Y,this.userMessage=K,this.assistantMessage=G,this.systemMessage=q,this.codeBlock=z,this.inlineCode=U,this.syntaxHighlight=W,this.fileReference=F,this.processing=H,this.waiting=B,this.completed=M,this.cancelled=V,this.suggestion=N,this.command=L,this.filename=A,this.keybind=w,this.button=R,this.shellMode=O,this.shellModeHidden=$,this.diffAdded=j,this.diffRemoved=E,this.diffChanged=I,this.diffContext=T,this.ideConnected=S,this.ideDisconnected=_,this.ideWarning=h,this.scrollbarThumb=v,this.scrollbarTrack=x,this.tableBorder=y,this.recommendation=g}static default(){return new ZQ1({toolRunning:I1.blue,toolSuccess:I1.green,toolError:I1.red,toolCancelled:I1.yellow,toolName:I1.default(),userMessage:I1.cyan,assistantMessage:I1.white,systemMessage:I1.index(8),codeBlock:I1.default(),inlineCode:I1.yellow,syntaxHighlight:{keyword:I1.blue,string:I1.green,number:I1.yellow,comment:I1.index(8),function:I1.cyan,variable:I1.default(),type:I1.magenta,operator:I1.white},fileReference:I1.cyan,processing:I1.blue,waiting:I1.yellow,completed:I1.green,cancelled:I1.index(8),recommendation:I1.blue,suggestion:I1.magenta,command:I1.yellow,filename:I1.cyan,keybind:I1.blue,button:I1.cyan,shellMode:I1.blue,shellModeHidden:I1.index(8),diffAdded:I1.green,diffRemoved:I1.red,diffChanged:I1.yellow,diffContext:I1.index(8),ideConnected:I1.green,ideDisconnected:I1.red,ideWarning:I1.yellow,scrollbarThumb:I1.index(7),scrollbarTrack:I1.index(8),tableBorder:I1.index(8)})}}class ZS{base;app;constructor({base:J,app:Q}){this.base=J,this.app=Q}get colors(){return this.base.colorScheme}static default(){return new ZS({base:QG.default(),app:ZQ1.default()})}static fromBaseTheme(J){return new ZS({base:J,app:ZQ1.default()})}}class O6 extends VZ{data;constructor({key:J,data:Q,child:Z}){super({key:J,child:Z});this.data=Q}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(O6);if(Q)return Q.widget.data;return ZS.default()}static maybeOf(J){let Q=J.dependOnInheritedWidgetOfExactType(O6);if(Q)return Q.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}G9();class hz6{vertical="│";tee="├";elbow="╰";horizontal="─";indent=4;connectorColor=I1.white;connectorDim=!0}class Dd extends EY{style;showTreeCharacters;constructor({key:J,children:Q,style:Z,showTreeCharacters:X=!0}){super({key:J,children:Q});this.style=Z??new hz6,this.showTreeCharacters=X}createRenderObject(){return new gz6({style:this.style,showTreeCharacters:this.showTreeCharacters})}updateRenderObject(J){J.updateTreeView({style:this.style,showTreeCharacters:this.showTreeCharacters})}}class gz6 extends Z8{style;showTreeCharacters;constructor({style:J,showTreeCharacters:Q}){super();this.style=J,this.showTreeCharacters=Q}updateTreeView({style:J,showTreeCharacters:Q}){this.style=J,this.showTreeCharacters=Q,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;if(!J)return;let Z=(this.style.tee+this.style.horizontal+" ").length,X=Math.max(0,J.maxWidth-Z),Y=0;for(let G of this.children){let q=G,z=new R6(X,X,0,1/0);q.layout(z),q.setOffset(Z,Y),Y+=q.size.height}let K=J.constrain(J.maxWidth,Y);this.setSize(K.width,K.height)}paint(J,Q,Z){if(this.showTreeCharacters){let X=Z+this.offset.y;for(let Y=0;Y<this.children.length;Y++){let G=this.children[Y],q=Y===this.children.length-1,z=G.size.height,W=(q?this.style.elbow:this.style.tee)+this.style.horizontal+" ",F=Q+this.offset.x;for(let H of W){let B=D9(H,{fg:this.style.connectorColor,dim:this.style.connectorDim});J.setCell(F,X,B),F++}if(F=Q+this.offset.x,!q){let H=D9(this.style.vertical,{fg:this.style.connectorColor,dim:this.style.connectorDim});for(let B=1;B<z;B++)J.setCell(F,X+B,H)}X+=G.size.height}}super.paint(J,Q,Z)}}class XQ1 extends P6{bashInvocations;constructor({bashInvocations:J,key:Q}){super(Q?{key:Q}:{});this.bashInvocations=J}build(J){if(this.bashInvocations.length===0)return new i0({children:[]});let Q=O6.of(J),Z=Q.colors,X=this.bashInvocations.map((K)=>{let G=K.hidden,q=G?Q.app.shellModeHidden:Q.app.shellMode,U=[new n1({text:new V1("",void 0,[new V1(`${G?"$$":"$"} `,new $1({color:q,bold:!0})),new V1(K.args.cmd,new $1({color:I1.green}))]),selectable:!0})];if(K.toolRun.status==="in-progress"||K.toolRun.status==="done"){let W=K.toolRun.progress;if(W?.output){let F=this.getLastOutputLines(W.output);U.push(...F.map((H)=>new n1({text:new V1(H,new $1({color:I1.white,dim:!0})),selectable:!0})))}}if(K.toolRun.status==="blocked-on-user"){let W=K.toolRun.reason?` (${K.toolRun.reason})`:"";U.push(new n1({text:new V1(`Waiting for confirmation${W}`,new $1({color:I1.white,italic:!0})),selectable:!0}))}return new i0({crossAxisAlignment:"start",children:U})}),Y=[new U0({height:1}),new n1({text:new V1("Shell Mode:",new $1({color:I1.blue,bold:!0})),selectable:!0}),new Dd({children:X})];return new i0({crossAxisAlignment:"start",children:Y})}getLastOutputLines(J){if(!J)return[];return J.split(`
|
|
6545
|
-
`).filter((Z)=>Z.trim()!=="").slice(-3)}}G9();f2();class qm1 extends P6{leftChild;rightChild1;rightChild2;maxHeight;borderColor;borderStyle;overlayTexts;hasBanner;constructor({key:J,leftChild:Q,rightChild1:Z,rightChild2:X,maxHeight:Y,borderColor:K=I1.index(7),borderStyle:G="rounded",overlayTexts:q=[],hasBanner:z=!1}){super({key:J});this.leftChild=Q,this.rightChild1=Z,this.rightChild2=X,this.maxHeight=Y,this.borderColor=K,this.borderStyle=G,this.overlayTexts=q,this.hasBanner=z}build(J){let Q=[];for(let Z of this.overlayTexts){let X=0,Y,K=0,G;switch(Z.position){case"top-left":X=2+(Z.offsetX??0),K=0+(Z.offsetY??0);break;case"top-right":Y=2+(Z.offsetX??0),K=0+(Z.offsetY??0);break;case"bottom-left":X=2+(Z.offsetX??0),G=0+(Z.offsetY??0);break;case"bottom-right":Y=2+(Z.offsetX??0),G=0+(Z.offsetY??0);break}let q=new n1({text:Z.text}),z=Z.onClick?new x9({child:q,onClick:Z.onClick,cursor:"pointer"}):q;Q.push(new $X({left:X!==0?X:void 0,right:Y!==void 0?Y:void 0,top:K!==0?K:void 0,bottom:G!==void 0?G:void 0,child:z}))}return new oC({child:new kJ({children:[new mz6({children:[this.leftChild,...this.rightChild1?[this.rightChild1]:[],...this.rightChild2?[this.rightChild2]:[]],maxHeight:this.maxHeight,borderColor:this.borderColor,borderStyle:this.borderStyle,hasBanner:this.hasBanner}),...Q]})})}}class mz6 extends EY{maxHeight;borderColor;borderStyle;hasBanner;constructor({children:J,maxHeight:Q,borderColor:Z,borderStyle:X,hasBanner:Y}){super({children:J});this.maxHeight=Q,this.borderColor=Z,this.borderStyle=X,this.hasBanner=Y}createRenderObject(){return new uz6(this.maxHeight,this.borderColor,this.borderStyle,this.hasBanner)}updateRenderObject(J){J.maxHeight=this.maxHeight,J.borderColor=this.borderColor,J.borderStyle=this.borderStyle,J.hasBanner=this.hasBanner}}class uz6 extends Z8{maxHeight;borderColor;borderStyle;hasBanner;constructor(J,Q=I1.index(7),Z="rounded",X=!1){super();this.maxHeight=J,this.borderColor=Q,this.borderStyle=Z,this.hasBanner=X}performLayout(){let J=this._lastConstraints;u6(!!J,"performLayout called without constraints");let Q=this.children;if(Q.length===0){this.setSize(J.minWidth,2),super.performLayout();return}let Z=Q[0];if(!Z){this.setSize(J.minWidth,2),super.performLayout();return}let X=Q.length>1?Q[1]:void 0,Y=Q.length>2?Q[2]:void 0,K=J.maxWidth,G=Math.floor(K/2),q=this.getMinIntrinsicHeight(K),z=Math.min(q,J.maxHeight);if(this.maxHeight)z=Math.min(z,this.maxHeight);this.setSize(K,z);let U=z-2,F=X||Y?G-2:K-2,H=new R6(0,F,0,Math.max(0,U));if(Z.layout(H),Z.setOffset(1,1),X||Y){let B=K-G-2,M=Math.max(0,Math.floor(U)),V=(w)=>new R6(0,B,0,Math.max(0,Math.floor(w))),N=M,L=0;if(X){let w=X.getMinIntrinsicHeight(B),R=Math.min(w,N);X.layout(V(R)),L=X.size.height,X.setOffset(G+1,1),N=Math.max(0,N-L)}if(!!(X&&Y&&L>0))N=Math.max(0,N-1);if(Y){let w=Y.getMinIntrinsicHeight(B),R=Math.min(w,N);Y.layout(V(R));let O=L>0?L+2:1;Y.setOffset(G+1,O)}}super.performLayout()}getMinIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 2;let Z=Q[0];if(!Z)return 2;let X=Q.length>1?Q[1]:void 0,Y=Q.length>2?Q[2]:void 0,K=Math.floor(J/2),q=X||Y?K:J,z=Z.getMinIntrinsicHeight(q-2),U=Math.min(z,50),W=0;if(X||Y){let B=J-K-2,M=X?X.getMinIntrinsicHeight(B):0,V=Y?Y.getMinIntrinsicHeight(B):0;W=M+V+(M>0&&V>0?1:0)}return Math.max(U,W)+2}getMaxIntrinsicHeight(J){return this.getMinIntrinsicHeight(J)}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y);super.paint(J,Q,Z),this._paintGridBorders(J,X,Y)}_paintGridBorders(J,Q,Z){let X=this.size.width,Y=this.size.height,K=this.children,G=K.length>1,q=K.length>1?K[1]:void 0,z=K.length>2?K[2]:void 0,U={fg:this.borderColor},W=Math.floor(X/2),H=(()=>{return this.borderStyle==="rounded"?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"}})();for(let B=0;B<X;B++)J.setChar(Q+B,Z,"─",U,1);for(let B=0;B<X;B++)J.setChar(Q+B,Z+Y-1,"─",U,1);for(let B=0;B<Y;B++)J.setChar(Q,Z+B,"│",U,1);for(let B=0;B<Y;B++)J.setChar(Q+X-1,Z+B,"│",U,1);if(this.hasBanner)J.setChar(Q,Z,"├",U,1),J.setChar(Q+X-1,Z,"┤",U,1);else J.setChar(Q,Z,H.tl,U,1),J.setChar(Q+X-1,Z,H.tr,U,1);if(J.setChar(Q,Z+Y-1,H.bl,U,1),J.setChar(Q+X-1,Z+Y-1,H.br,U,1),G){for(let B=1;B<Y-1;B++)J.setChar(Q+W,Z+B,"│",U,1);J.setChar(Q+W,Z,"┬",U,1),J.setChar(Q+W,Z+Y-1,"┴",U,1)}if(q&&z&&q.size.height>0){let B=q.offset.y+q.size.height;for(let M=W+1;M<X-1;M++)J.setChar(Q+M,Z+B,"─",U,1);J.setChar(Q+W,Z+B,"├",U,1),J.setChar(Q+X-1,Z+B,"┤",U,1)}}}e9();oy();class zm1 extends P6{status;constructor({status:J,key:Q}){super(Q?{key:Q}:{});this.status=J}build(J){if(this.status===null||!this.status.enabled)return new U0({width:0,height:0});let Q=this.status,Z=Q.connected===!0,X=!!Q.errorMessage,Y=Q.clientID||"unknown",K,G;if(X)K="×",G=I1.red;else if(Z)K="✓",G=I1.green;else K="○",G=I1.yellow;let q=`${K} Client: ${Y}`;return new X8({mainAxisSize:"min",children:[new n1({text:new V1(q,new $1({color:G}))})]})}}G0();v0();function Md(J,Q){if(J===Q)return!0;if(J==null||Q==null||typeof J!=="object"||typeof Q!=="object")return!1;let Z=Array.isArray(J),X=Array.isArray(Q);if(Z!==X)return!1;if(Z&&X)return J.length===Q.length&&J.every((K,G)=>Md(K,Q[G]));let Y=new Set([...Object.keys(J),...Object.keys(Q)]);for(let K of Y)if(!Md(J[K],Q[K]))return!1;return!0}G0();$D();function pz6(J){return Zc(600000).pipe(d2(void 0),q8(()=>J.config.pipe(b0(({settings:Q,secrets:Z})=>({settings:{url:Q.url,proxy:Q.proxy},secrets:Z})),J8((Q,Z)=>Md(Q.settings,Z.settings)&&Q.secrets===Z.secrets),cN(()=>c6(async(Q)=>{let Z=await UJ.getUserInfo({},{signal:Q,config:J});if(Z.ok)return Z.result;if(Z.error&&Z.error.code==="auth-required")return null;throw u.error("getUserInfo failed",{error:Z.error}),Error(`getUserInfo error: ${Z.error.code}`)})))),b0((Q)=>{return Q instanceof Error?{error:{message:String(Q)}}:Q===QJ?"pending":Q?{user:Q,workspace:Q?.team}:{error:{message:"User not found"}}}),J8((Q,Z)=>Md(Q,Z)),M9({shouldCountRefs:!0}))}function dz6(J){return Boolean(typeof J==="object"&&"user"in J&&J.user)}v0();l8();var Um1=!1;class Wm1 extends c0{props;constructor(J){super();this.props=J}createState(){return new cz6}}class cz6 extends d0{showCost=Um1;subscription=null;initState(){super.initState(),this.subscription=b9(pz6(this.widget.props.configService).pipe(C7((J)=>J!=="pending")),this.widget.props.configService.config).pipe(b0(([J,Q])=>{let Z=dz6(J)?J.user.email:"",X=Z.toLowerCase().endsWith("@sourcegraph.com"),Y=Um1||X,K=Q.settings["internal.showCost"]??!0,G=Y&&K;return u.debug("CostDisplayProvider computed showCost",{email:Z,isTeammate:X,isEligible:Y,setting:K,computedShowCost:G,currentShowCost:this.showCost}),G}),J8()).subscribe((J)=>{u.debug("CostDisplayProvider setState called",{previousShowCost:this.showCost,newShowCost:J}),this.setState(()=>{this.showCost=J})})}dispose(){this.subscription?.unsubscribe(),this.subscription=null,super.dispose()}build(J){return new Fm1({showCost:this.showCost,child:this.widget.props.child})}}class Fm1 extends VZ{showCost;constructor({showCost:J,child:Q}){super({child:Q});this.showCost=J}updateShouldNotify(J){return this.showCost!==J.showCost}}function qB(J){let Q=J.dependOnInheritedWidgetOfExactType(Fm1);if(Q)return Q.widget.showCost;return Um1}class Hm1 extends P6{totalCredits;onClick;constructor({totalCredits:J,onClick:Q,key:Z}){super(Z?{key:Z}:{});this.totalCredits=J,this.onClick=Q}build(J){if(!qB(J))return new U0({width:0,height:0});if(!this.totalCredits)return new U0({width:0,height:0});let Z=e6.of(J).colorScheme,X=GB(this.totalCredits),Y=new n1({text:new V1(X,new $1({color:Z.foreground,dim:!0}))});if(this.onClick)return new x9({onClick:this.onClick,child:Y});return Y}}G0();EW();_L();ac();k6();l8();G0();f2();class jN extends VZ{onError;constructor({onError:J,child:Q}){super({child:Q});this.onError=J}updateShouldNotify(J){return!1}static of(J){return J.dependOnInheritedWidgetOfExactType(jN)?.widget?.onError}}class RQ extends P6{uri;text;style;maxLines;overflow;onError;constructor({uri:J,text:Q,style:Z,maxLines:X,overflow:Y,onError:K,key:G}){super({key:G});this.uri=J,this.text=Q,this.style=Z,this.maxLines=X,this.overflow=Y,this.onError=K}build(J){let Q=jN.of(J),Z=this.onError??Q;return u6(Z!==void 0,"Link widget requires either onError prop or ErrorHandlerProvider in context"),RQ.createWidget(this.uri,this.text,Z,this.style,this.maxLines,this.overflow)}static createWidget(J,Q,Z,X,Y,K){let G=new n1({text:RQ.createSpan(J,Q,X),selectable:!0,maxLines:Y,overflow:K});return new x9({onClick:async()=>{try{await PQ(J)}catch(q){u.error("[Link] Error opening link",{uri:J,error:q});let z=q instanceof Error?q:Error(String(q));z.uri=J,u.error("[Link] Calling error handler"),Z(z)}},cursor:"pointer",child:G})}static createSpan(J,Q,Z){let X=LQ(),Y=X?J:Q,K=X?new $1({color:Z?.color,dim:!0}):Z||new $1({underline:!0}),G=X?void 0:Fq6(J);return new V1(Y,K,void 0,G)}}EW();k6();l8();class Bm1 extends c0{props;constructor(J){super();this.props=J}createState(){return new lz6}}class lz6 extends d0{displayPathEnvInfo=null;subscription=null;constructor(){super()}initState(){super.initState(),this.subscription=this.widget.props.configService.displayPathEnvInfo.subscribe((J)=>{fc(J),this.setState(()=>{this.displayPathEnvInfo=J})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}build(J){return new Dm1({displayPathEnvInfo:this.displayPathEnvInfo,child:this.widget.props.child})}}class Dm1 extends VZ{displayPathEnvInfo;constructor({displayPathEnvInfo:J,child:Q}){super({child:Q});this.displayPathEnvInfo=J}updateShouldNotify(J){return this.displayPathEnvInfo!==J.displayPathEnvInfo}}function gR(J){let Q=J.dependOnInheritedWidgetOfExactType(Dm1);if(!Q)return null;return Q.widget.displayPathEnvInfo}function XS(J,Q){if(J.startsWith("/")||/^[A-Za-z]:[\\/]/.test(J)){let X=gR(Q),Y=$0.file(J);return GJ(Y,X??void 0)}return J}f51();function Mm1(J,Q,Z){return new n1({text:new V1(`${J}${Q}`,new $1({color:Z})),maxLines:1})}function iz6(J,Q,Z,X){return[Mm1("+",J,X.success),r7.horizontal(1),Mm1("~",Q,X.warning),r7.horizontal(1),Mm1("-",Z,X.destructive)]}class Vm1 extends c0{threadViewState;threadID;onFileChangesClick;constructor({threadViewState:J,threadID:Q,onFileChangesClick:Z,key:X}){super(X?{key:X}:{});this.threadViewState=J,this.threadID=Q,this.onFileChangesClick=Z}createState(){return new nz6}}class nz6 extends d0{build(J){let Z=O6.of(J).colors;if(this.widget.threadViewState.state!=="active")return new U0({width:0,height:0});let{fileChanges:X}=this.widget.threadViewState,Y=WY1(X);if(Y.totalFiles===0)return new U0({width:0,height:0});let K=Y.totalFiles-Y.revertedFiles,G=`${K} ${K===1?"file":"files"} changed`,q=new n1({text:new V1(G,new $1({color:Z.foreground,dim:!0})),maxLines:1}),z;if(Y.totalAdded>0||Y.totalModified>0||Y.totalRemoved>0){let U=iz6(Y.totalAdded,Y.totalModified,Y.totalRemoved,Z);z=new X8({children:[q,r7.horizontal(1),...U],mainAxisSize:"min"})}else z=q;return new x9({onClick:()=>{if(this.widget.onFileChangesClick)this.widget.onFileChangesClick()},cursor:"pointer",child:z})}}class Nm1 extends c0{createState(){return new az6}}class az6 extends d0{build(J){let Z=e6.of(J).colorScheme,Y=O6.of(J).app,K=_8.of(J),G=y51();if(!G)return new U0({width:0,height:0});let q=G.getThreadData(),z=q.viewState,U=q.mainThread?.id;if(z.state!=="active"||!U)return new U0({width:0,height:0});let{fileChanges:W}=z,F=WY1(W);if(F.totalFiles===0)return new U0({width:0,height:0});let H=F.totalFiles-F.revertedFiles,B=F.allReverted?`${F.revertedFiles} ${F.revertedFiles===1?"change":"changes"} reverted`:`${H} ${H===1?"file":"files"} changed`,M=new C9({child:new n1({text:new V1(B,new $1({color:Z.primary,bold:!0}))})}),V=gR(J),N=[];for(let v of W.files){let x=$0.parse(v.uri),y=GJ(x,V??void 0),g=v.reverted,k=[];if(k.push(new R8({child:new RQ({uri:v.uri,text:y,style:new $1({color:I1.cyan,dim:g,underline:!g}),maxLines:1,overflow:"ellipsis"})})),k.push(r7.horizontal(1)),g)k.push(new n1({text:new V1("Reverted",new $1({color:Z.foreground,dim:!0,italic:!0}))}));else{let b=iz6(v.diffStat.added,v.diffStat.modified,v.diffStat.removed,Z);k.push(...b),k.push(r7.horizontal(1)),k.push(new x9({onClick:async(m)=>{try{await VJ.revertFileChanges(U,v.uri),this.setState(()=>{})}catch(n){u.error(`Error reverting file ${v.uri} (thread id: ${U}):`,n)}},cursor:"pointer",child:new n1({text:new V1("↶",new $1({color:Y.button}))})}))}let f=new X8({mainAxisSize:"max",crossAxisAlignment:"center",children:k});N.push(new b6({padding:N0.only({left:2,right:2,top:0,bottom:0}),child:f}))}let L=[];L.push(M),L.push(new U0({height:1}));for(let v of N)L.push(v);if(!F.allReverted&&H>0){let v=new b6({padding:N0.only({top:1,left:2,right:2}),child:new X8({mainAxisSize:"max",crossAxisAlignment:"center",children:[new R8({child:new n1({text:new V1(`${H} ${H===1?"file":"files"} changed`,new $1({color:Z.foreground}))})}),r7.horizontal(1),new x9({onClick:async(x)=>{try{await VJ.revertFileChanges(U),this.setState(()=>{})}catch(y){u.error(`Error reverting all files (thread id: ${U}):`,y)}},cursor:"pointer",child:new n1({text:new V1("Revert All",new $1({color:Y.button}))})})]})});L.push(v)}let A=K.size.width,w=K.size.height,R=A-4,O=w-4,$=Math.min(60,R),j=new C9({child:new n1({text:new V1("",new $1({color:Z.foreground}),[new V1("Press ",new $1({color:Z.foreground})),new V1("Escape",new $1({color:Y.keybind})),new V1(" to close",new $1({color:Z.foreground}))])})}),E=[...L,new U0({height:1}),j],I=2+N.length+(H>0?2:0)+1+1+4+2,T=Math.min(I,O),S=new b6({padding:N0.all(1),child:new i0({crossAxisAlignment:"stretch",children:E})}),h=I>O?new PY({autofocus:!0,child:S}):S;return new C9({child:new f0({constraints:new R6($,$,T,T),decoration:new i8(Z.background,x8.all(new w8(Z.primary,1,"rounded"))),child:h})})}}ev();import rz6 from"node:path";l8();function Cz9(J,Q){try{return decodeURIComponent(J)}catch(Z){if(Q!==void 0)return Q;throw Z}}class Lm1 extends c0{ideStatus;onShowIdePicker;constructor({ideStatus:J,onShowIdePicker:Q,key:Z}){super(Z?{key:Z}:{});this.ideStatus=J,this.onShowIdePicker=Q}createState(){return new sz6}}class sz6 extends d0{ideCount=0;intervalId;initState(){this.loadConfigs(),this.intervalId=setInterval(()=>{this.loadConfigs()},5000)}dispose(){if(this.intervalId)clearInterval(this.intervalId)}loadConfigs(){this.ideCount=cB({includeAll:!0}).length,this.setState()}build(J){if(this.widget.ideStatus===null||!this.widget.ideStatus.enabled)return this.statusIdle();let Q=this.widget.ideStatus,Z=Q.connectionState;if(!Z||Z==="never-connected")return this.statusIdle();if(Z==="reconnecting")return this.statusReconnecting(Q);if(Z==="disconnected")return this.statusDisconnected(Q);let X=Q.authenticated,Y=Q.selections?.[0],K=!q11(Y)&&Y?Y.range.endLine-Y.range.startLine+1:0,G=[];if(!X)if(Q.errorMessage)G.push(Q.errorMessage);else if(Q.connected===!1)G.push("IDE Not Connected");else G.push("IDE Error");else if(!Q.openFile&&!Y)G.push(`${Q.ideName?Q.ideName:"Unknown IDE"}`);if(Q.openFile)G.push(rz6.basename(Cz9(Q.openFile,Q.openFile)));if(Y&&K>0)G.push(`${K} selected ${yJ(K,"line")}`);let q=G.join(" • "),z=X?"✓":"×",U=X?I1.index(10):I1.index(9),F=`${z} ${q}${!X?" • Use /ide to connect":""}`;return this.idePickerText(F,U)}statusIdle(){if(this.ideCount===0)return new U0({width:0,height:0});else{let J=`${this.ideCount} ${yJ(this.ideCount,"IDE")} available`;return this.idePickerText(J)}}statusDisconnected(J){if((J.reconnectElapsedMs??0)>=60000)return this.statusIdle();let Z="IDE disconnected. Use /ide to connect";return this.idePickerText(Z)}statusReconnecting(J){let Q=J.ideName||"IDE",Z=J.workspace?` in ${rz6.basename(J.workspace)}`:"",X=`Reconnecting to ${Q}${Z}...`,Y=J.reconnectElapsedMs??0;return this.idePickerText(X,Y<5000?I1.yellow:I1.index(8))}idePickerText(J,Q=I1.index(8)){let Z=new n1({text:new V1(J,new $1({color:Q})),maxLines:1}),X=this.widget.onShowIdePicker?new x9({onClick:this.widget.onShowIdePicker,cursor:"pointer",child:Z}):Z;return new X8({children:[X],mainAxisSize:"min"})}}l8();function Sz9(J){return J.toLowerCase().includes("sonnet")}function vz9(J){return{recommendation:Sz9(J)?0.2:0.6,warning:0.8,danger:0.9}}function kz9(J,Q){let Z=vz9(Q);if(J>=Z.danger)return"danger";else if(J>=Z.warning)return"warning";else if(J>=Z.recommendation)return"recommendation";return!1}function Am1(J){let Q=J.totalInputTokens/J.maxInputTokens;return kz9(Q,J.model||"")}class wm1 extends c0{threadViewState;tokenUsage;thread;waitingForConfirmation;showingEphemeralError;executingCommand;executingCommandMessage;runningBashInvocations;constructor({threadViewState:J,tokenUsage:Q,thread:Z,waitingForConfirmation:X=!1,showingEphemeralError:Y=!1,executingCommand:K=null,executingCommandMessage:G=null,runningBashInvocations:q=!1,key:z}={}){super(z?{key:z}:{});this.threadViewState=J,this.tokenUsage=Q,this.thread=Z,this.waitingForConfirmation=X,this.showingEphemeralError=Y,this.executingCommand=K,this.executingCommandMessage=G,this.runningBashInvocations=q}createState(){return new oz6}}class oz6 extends d0{animationFrame=0;animationTimer=null;animationFrames=["∿","∾","∽","≋","≈","∼"];initState(){this.startAnimationIfNeeded()}didUpdateWidget(J){this.startAnimationIfNeeded()}dispose(){this.stopAnimation()}startAnimationIfNeeded(){let J=this.shouldShowSpinner();if(J&&!this.animationTimer)this.startAnimation();else if(!J&&this.animationTimer)this.stopAnimation()}startAnimation(){if(this.animationTimer)return;this.animationTimer=setInterval(()=>{this.setState(()=>{this.animationFrame=(this.animationFrame+1)%this.animationFrames.length})},200)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}shouldShowSpinner(){let{threadViewState:J,waitingForConfirmation:Q,runningBashInvocations:Z}=this.widget;return Boolean(Z||J&&J.state==="active"&&(J.inferenceState==="running"||J.interactionState==="tool-running")&&!this.isShowingTokenUsageNote()&&!Q)}isShowingTokenUsageNote(){let{tokenUsage:J,showingEphemeralError:Q}=this.widget;if(!J||Q)return!1;let Z=Am1(J);return Z==="recommendation"||Z==="warning"||Z==="danger"}getSpinnerColor(){let{threadViewState:J}=this.widget;if(!J)return I1.index(8);if(J.state==="active"){if(J.inferenceState==="running")return I1.index(12)}return I1.index(8)}getStatusMessageColor(J,Q){let{threadViewState:Z,tokenUsage:X,showingEphemeralError:Y,executingCommand:K,runningBashInvocations:G}=this.widget;if(K)return Q.command;if(G)return J.foreground;if(X&&!Y){let q=Am1(X);if(q==="recommendation")return Q.recommendation;if(q==="warning")return J.warning;if(q==="danger")return J.destructive}if(Z?.state==="active"&&Z.inferenceState==="cancelled")return I1.index(8);return J.foreground}build(J){let Q=O6.of(J),Z=Q.colors,X=Q.app,Y=Rm1(this.widget);if(!Y)return new U0({width:0,height:0});let K=[];if(this.shouldShowSpinner()){let q=this.animationFrames[this.animationFrame];K.push(new n1({text:new V1(q,new $1({color:this.getSpinnerColor()})),maxLines:1})),K.push(r7.horizontal(1))}return K.push(new n1({text:new V1(Y,new $1({color:this.getStatusMessageColor(Z,X),italic:this.widget.threadViewState?.state==="active"&&this.widget.threadViewState.inferenceState==="cancelled"})),textAlign:"left",maxLines:1,overflow:"clip"})),new X8({children:K,mainAxisSize:"min"})}}function Rm1(J){let{threadViewState:Q,tokenUsage:Z,showingEphemeralError:X,executingCommand:Y,executingCommandMessage:K,runningBashInvocations:G}=J;if(Y)return K??`Executing /${Y}...`;if(G)return"Running shell command...";if(!Q||Q.state!=="active")return null;if(Q.interactionState==="tool-running"){let q=Q.toolState.running;if(q>1)return`Running ${q} tools...`;return"Running tools..."}if(Q.inferenceState==="running"){let q=J.thread?.messages.at(-1);if(!(q?.role==="assistant"&&q.state.type==="streaming"))return"Waiting for response...";if(J.runningBashInvocations)return"Running tools...";return"Streaming response..."}if(Z&&!X&&J.thread?.agentMode!=="free"){let q=Am1(Z);if(q==="recommendation")return"Optimize context: /handoff to focus on specific tasks or /new for a fresh start";if(q==="warning")return"High context usage. Use /handoff to focus on specific tasks or /new to restart";if(q==="danger")return"Context window is close to full. Use /handoff to focus on specific tasks or /new to restart"}return null}function _z9(J){if(J>=900000)return{recommendation:0.2,warning:0.8,danger:0.9};else if(J>=400000)return{recommendation:0.7,warning:0.8,danger:0.9};else return{recommendation:0.8,warning:0.9,danger:0.95}}function xz9(J){if(J>=1e6)return`${Math.round(J/1e6)}M`;else if(J>=1000)return`${Math.round(J/1000)}k`;return J.toString()}function bz9(J,Q){let Z=_z9(Q);if(J>=Z.danger)return"danger";else if(J>=Z.warning)return"warning";else if(J>=Z.recommendation)return"recommendation";return!1}class Om1 extends P6{tokenUsage;isNarrow;constructor({tokenUsage:J,isNarrow:Q=!1,key:Z}){super(Z?{key:Z}:{});this.tokenUsage=J,this.isNarrow=Q}build(J){let Z=O6.of(J).colors,X=this.tokenUsage.totalInputTokens/this.tokenUsage.maxInputTokens,Y=Math.round(X*100),K=Math.max(0,Math.min(Y,100)),G=this.isNarrow?`${K}%`:`${K}% of ${xz9(this.tokenUsage.maxInputTokens)}`,q=new $1({color:Z.foreground,dim:!0}),z=bz9(X,this.tokenUsage.maxInputTokens);if(z==="danger")q=new $1({color:Z.destructive});else if(z==="warning")q=new $1({color:Z.warning});else if(z==="recommendation")q=new $1({color:Z.info});return new n1({text:new V1(G,q),textAlign:"left",maxLines:1,overflow:"clip"})}}class jm1 extends P6{hint;constructor({hint:J,key:Q}={}){super(Q?{key:Q}:{});this.hint=J}build(J){if(!this.hint)return new U0({width:0,height:0});return new n1({text:this.hint,textAlign:"left",maxLines:1,overflow:"clip"})}}class YQ1 extends P6{statusText;isAnimated;statusType;threadViewState;threadTokenUsage;threadID;thread;onFileChangesClick;onCostBreakdownClick;onShowIdePicker;ideStatus;connectedClientsStatus;isNarrow;uiHint;waitingForConfirmation;showingEphemeralError;executingCommand;executingCommandMessage;runningBashInvocations;constructor({statusText:J,isAnimated:Q=!1,statusType:Z="idle",threadViewState:X,threadTokenUsage:Y,threadID:K,thread:G,onFileChangesClick:q,onCostBreakdownClick:z,onShowIdePicker:U,ideStatus:W=null,connectedClientsStatus:F=null,isNarrow:H=!1,uiHint:B,waitingForConfirmation:M=!1,showingEphemeralError:V=!1,executingCommand:N=null,executingCommandMessage:L=null,runningBashInvocations:A=!1,key:w}={}){super(w?{key:w}:{});this.statusText=J,this.isAnimated=Q,this.statusType=Z,this.threadViewState=X,this.threadTokenUsage=Y,this.threadID=K,this.thread=G,this.onFileChangesClick=q,this.onCostBreakdownClick=z,this.onShowIdePicker=U,this.ideStatus=W,this.connectedClientsStatus=F,this.isNarrow=H,this.uiHint=B,this.waitingForConfirmation=M,this.showingEphemeralError=V,this.executingCommand=N,this.executingCommandMessage=L,this.runningBashInvocations=A}build(J){let Q=[],Z=!1;if(this.threadViewState){let X=new wm1({threadViewState:this.threadViewState,tokenUsage:this.threadTokenUsage,thread:this.thread,waitingForConfirmation:this.waitingForConfirmation,showingEphemeralError:this.showingEphemeralError,executingCommand:this.executingCommand,executingCommandMessage:this.executingCommandMessage,runningBashInvocations:this.runningBashInvocations});if(Rm1(X))Z=!0;Q.push(X)}if(this.uiHint){if(Z)Q.push(r7.horizontal(2));Q.push(new jm1({hint:this.uiHint}))}if(Q.push(r7.flexible()),this.ideStatus)Q.push(new Lm1({ideStatus:this.ideStatus,onShowIdePicker:this.onShowIdePicker})),Q.push(r7.horizontal(1));if(this.connectedClientsStatus)Q.push(new zm1({status:this.connectedClientsStatus})),Q.push(r7.horizontal(1));if(this.threadViewState&&!this.isNarrow&&this.threadID&&MG(this.threadID))Q.push(new Vm1({threadViewState:this.threadViewState,threadID:this.threadID,onFileChangesClick:this.onFileChangesClick})),Q.push(r7.horizontal(1));if(this.threadTokenUsage){if(Q.push(new Om1({tokenUsage:this.threadTokenUsage,isNarrow:this.isNarrow})),this.thread&&qB(J)){let X=I30(this.thread);if(X>0)Q.push(r7.horizontal(2)),Q.push(new Hm1({totalCredits:X,onClick:this.onCostBreakdownClick}))}}return new X8({children:Q,mainAxisSize:"min",mainAxisAlignment:"start"})}}var yz9={};function mR(J,Q){let Z=Q||yz9,X=typeof Z.includeImageAlt==="boolean"?Z.includeImageAlt:!0,Y=typeof Z.includeHtml==="boolean"?Z.includeHtml:!0;return ez6(J,X,Y)}function ez6(J,Q,Z){if(fz9(J)){if("value"in J)return J.type==="html"&&!Z?"":J.value;if(Q&&"alt"in J&&J.alt)return J.alt;if("children"in J)return tz6(J.children,Q,Z)}if(Array.isArray(J))return tz6(J,Q,Z);return""}function tz6(J,Q,Z){let X=[],Y=-1;while(++Y<J.length)X[Y]=ez6(J[Y],Q,Z);return X.join("")}function fz9(J){return Boolean(J&&typeof J==="object")}var $m1={AElig:"Æ",AMP:"&",Aacute:"Á",Abreve:"Ă",Acirc:"Â",Acy:"А",Afr:"\uD835\uDD04",Agrave:"À",Alpha:"Α",Amacr:"Ā",And:"⩓",Aogon:"Ą",Aopf:"\uD835\uDD38",ApplyFunction:"",Aring:"Å",Ascr:"\uD835\uDC9C",Assign:"≔",Atilde:"Ã",Auml:"Ä",Backslash:"∖",Barv:"⫧",Barwed:"⌆",Bcy:"Б",Because:"∵",Bernoullis:"ℬ",Beta:"Β",Bfr:"\uD835\uDD05",Bopf:"\uD835\uDD39",Breve:"˘",Bscr:"ℬ",Bumpeq:"≎",CHcy:"Ч",COPY:"©",Cacute:"Ć",Cap:"⋒",CapitalDifferentialD:"ⅅ",Cayleys:"ℭ",Ccaron:"Č",Ccedil:"Ç",Ccirc:"Ĉ",Cconint:"∰",Cdot:"Ċ",Cedilla:"¸",CenterDot:"·",Cfr:"ℭ",Chi:"Χ",CircleDot:"⊙",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",Colon:"∷",Colone:"⩴",Congruent:"≡",Conint:"∯",ContourIntegral:"∮",Copf:"ℂ",Coproduct:"∐",CounterClockwiseContourIntegral:"∳",Cross:"⨯",Cscr:"\uD835\uDC9E",Cup:"⋓",CupCap:"≍",DD:"ⅅ",DDotrahd:"⤑",DJcy:"Ђ",DScy:"Ѕ",DZcy:"Џ",Dagger:"‡",Darr:"↡",Dashv:"⫤",Dcaron:"Ď",Dcy:"Д",Del:"∇",Delta:"Δ",Dfr:"\uD835\uDD07",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",Diamond:"⋄",DifferentialD:"ⅆ",Dopf:"\uD835\uDD3B",Dot:"¨",DotDot:"⃜",DotEqual:"≐",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",Downarrow:"⇓",Dscr:"\uD835\uDC9F",Dstrok:"Đ",ENG:"Ŋ",ETH:"Ð",Eacute:"É",Ecaron:"Ě",Ecirc:"Ê",Ecy:"Э",Edot:"Ė",Efr:"\uD835\uDD08",Egrave:"È",Element:"∈",Emacr:"Ē",EmptySmallSquare:"◻",EmptyVerySmallSquare:"▫",Eogon:"Ę",Eopf:"\uD835\uDD3C",Epsilon:"Ε",Equal:"⩵",EqualTilde:"≂",Equilibrium:"⇌",Escr:"ℰ",Esim:"⩳",Eta:"Η",Euml:"Ë",Exists:"∃",ExponentialE:"ⅇ",Fcy:"Ф",Ffr:"\uD835\uDD09",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",Fopf:"\uD835\uDD3D",ForAll:"∀",Fouriertrf:"ℱ",Fscr:"ℱ",GJcy:"Ѓ",GT:">",Gamma:"Γ",Gammad:"Ϝ",Gbreve:"Ğ",Gcedil:"Ģ",Gcirc:"Ĝ",Gcy:"Г",Gdot:"Ġ",Gfr:"\uD835\uDD0A",Gg:"⋙",Gopf:"\uD835\uDD3E",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"\uD835\uDCA2",Gt:"≫",HARDcy:"Ъ",Hacek:"ˇ",Hat:"^",Hcirc:"Ĥ",Hfr:"ℌ",HilbertSpace:"ℋ",Hopf:"ℍ",HorizontalLine:"─",Hscr:"ℋ",Hstrok:"Ħ",HumpDownHump:"≎",HumpEqual:"≏",IEcy:"Е",IJlig:"IJ",IOcy:"Ё",Iacute:"Í",Icirc:"Î",Icy:"И",Idot:"İ",Ifr:"ℑ",Igrave:"Ì",Im:"ℑ",Imacr:"Ī",ImaginaryI:"ⅈ",Implies:"⇒",Int:"∬",Integral:"∫",Intersection:"⋂",InvisibleComma:"",InvisibleTimes:"",Iogon:"Į",Iopf:"\uD835\uDD40",Iota:"Ι",Iscr:"ℐ",Itilde:"Ĩ",Iukcy:"І",Iuml:"Ï",Jcirc:"Ĵ",Jcy:"Й",Jfr:"\uD835\uDD0D",Jopf:"\uD835\uDD41",Jscr:"\uD835\uDCA5",Jsercy:"Ј",Jukcy:"Є",KHcy:"Х",KJcy:"Ќ",Kappa:"Κ",Kcedil:"Ķ",Kcy:"К",Kfr:"\uD835\uDD0E",Kopf:"\uD835\uDD42",Kscr:"\uD835\uDCA6",LJcy:"Љ",LT:"<",Lacute:"Ĺ",Lambda:"Λ",Lang:"⟪",Laplacetrf:"ℒ",Larr:"↞",Lcaron:"Ľ",Lcedil:"Ļ",Lcy:"Л",LeftAngleBracket:"⟨",LeftArrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",LeftRightArrow:"↔",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",Leftarrow:"⇐",Leftrightarrow:"⇔",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",LessLess:"⪡",LessSlantEqual:"⩽",LessTilde:"≲",Lfr:"\uD835\uDD0F",Ll:"⋘",Lleftarrow:"⇚",Lmidot:"Ŀ",LongLeftArrow:"⟵",LongLeftRightArrow:"⟷",LongRightArrow:"⟶",Longleftarrow:"⟸",Longleftrightarrow:"⟺",Longrightarrow:"⟹",Lopf:"\uD835\uDD43",LowerLeftArrow:"↙",LowerRightArrow:"↘",Lscr:"ℒ",Lsh:"↰",Lstrok:"Ł",Lt:"≪",Map:"⤅",Mcy:"М",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"\uD835\uDD10",MinusPlus:"∓",Mopf:"\uD835\uDD44",Mscr:"ℳ",Mu:"Μ",NJcy:"Њ",Nacute:"Ń",Ncaron:"Ň",Ncedil:"Ņ",Ncy:"Н",NegativeMediumSpace:"",NegativeThickSpace:"",NegativeThinSpace:"",NegativeVeryThinSpace:"",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:`
|
|
6545
|
+
`).filter((Z)=>Z.trim()!=="").slice(-3)}}G9();f2();class qm1 extends P6{leftChild;rightChild1;rightChild2;maxHeight;borderColor;borderStyle;overlayTexts;hasBanner;constructor({key:J,leftChild:Q,rightChild1:Z,rightChild2:X,maxHeight:Y,borderColor:K=I1.index(7),borderStyle:G="rounded",overlayTexts:q=[],hasBanner:z=!1}){super({key:J});this.leftChild=Q,this.rightChild1=Z,this.rightChild2=X,this.maxHeight=Y,this.borderColor=K,this.borderStyle=G,this.overlayTexts=q,this.hasBanner=z}build(J){let Q=[];for(let Z of this.overlayTexts){let X=0,Y,K=0,G;switch(Z.position){case"top-left":X=2+(Z.offsetX??0),K=0+(Z.offsetY??0);break;case"top-right":Y=2+(Z.offsetX??0),K=0+(Z.offsetY??0);break;case"bottom-left":X=2+(Z.offsetX??0),G=0+(Z.offsetY??0);break;case"bottom-right":Y=2+(Z.offsetX??0),G=0+(Z.offsetY??0);break}let q=new n1({text:Z.text}),z=Z.onClick?new x9({child:q,onClick:Z.onClick,cursor:"pointer"}):q;Q.push(new $X({left:X!==0?X:void 0,right:Y!==void 0?Y:void 0,top:K!==0?K:void 0,bottom:G!==void 0?G:void 0,child:z}))}return new oC({child:new kJ({children:[new mz6({children:[this.leftChild,...this.rightChild1?[this.rightChild1]:[],...this.rightChild2?[this.rightChild2]:[]],maxHeight:this.maxHeight,borderColor:this.borderColor,borderStyle:this.borderStyle,hasBanner:this.hasBanner}),...Q]})})}}class mz6 extends EY{maxHeight;borderColor;borderStyle;hasBanner;constructor({children:J,maxHeight:Q,borderColor:Z,borderStyle:X,hasBanner:Y}){super({children:J});this.maxHeight=Q,this.borderColor=Z,this.borderStyle=X,this.hasBanner=Y}createRenderObject(){return new uz6(this.maxHeight,this.borderColor,this.borderStyle,this.hasBanner)}updateRenderObject(J){J.maxHeight=this.maxHeight,J.borderColor=this.borderColor,J.borderStyle=this.borderStyle,J.hasBanner=this.hasBanner}}class uz6 extends Z8{maxHeight;borderColor;borderStyle;hasBanner;constructor(J,Q=I1.index(7),Z="rounded",X=!1){super();this.maxHeight=J,this.borderColor=Q,this.borderStyle=Z,this.hasBanner=X}performLayout(){let J=this._lastConstraints;u6(!!J,"performLayout called without constraints");let Q=this.children;if(Q.length===0){this.setSize(J.minWidth,2),super.performLayout();return}let Z=Q[0];if(!Z){this.setSize(J.minWidth,2),super.performLayout();return}let X=Q.length>1?Q[1]:void 0,Y=Q.length>2?Q[2]:void 0,K=J.maxWidth,G=Math.floor(K/2),q=this.getMinIntrinsicHeight(K),z=Math.min(q,J.maxHeight);if(this.maxHeight)z=Math.min(z,this.maxHeight);this.setSize(K,z);let U=z-2,F=X||Y?G-2:K-2,H=new R6(0,F,0,Math.max(0,U));if(Z.layout(H),Z.setOffset(1,1),X||Y){let B=K-G-2,M=Math.max(0,Math.floor(U)),V=(w)=>new R6(0,B,0,Math.max(0,Math.floor(w))),N=M,L=0;if(X){let w=X.getMinIntrinsicHeight(B),R=Math.min(w,N);X.layout(V(R)),L=X.size.height,X.setOffset(G+1,1),N=Math.max(0,N-L)}if(!!(X&&Y&&L>0))N=Math.max(0,N-1);if(Y){let w=Y.getMinIntrinsicHeight(B),R=Math.min(w,N);Y.layout(V(R));let O=L>0?L+2:1;Y.setOffset(G+1,O)}}super.performLayout()}getMinIntrinsicHeight(J){let Q=this.children;if(Q.length===0)return 2;let Z=Q[0];if(!Z)return 2;let X=Q.length>1?Q[1]:void 0,Y=Q.length>2?Q[2]:void 0,K=Math.floor(J/2),q=X||Y?K:J,z=Z.getMinIntrinsicHeight(q-2),U=Math.min(z,50),W=0;if(X||Y){let B=J-K-2,M=X?X.getMinIntrinsicHeight(B):0,V=Y?Y.getMinIntrinsicHeight(B):0;W=M+V+(M>0&&V>0?1:0)}return Math.max(U,W)+2}getMaxIntrinsicHeight(J){return this.getMinIntrinsicHeight(J)}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y);super.paint(J,Q,Z),this._paintGridBorders(J,X,Y)}_paintGridBorders(J,Q,Z){let X=this.size.width,Y=this.size.height,K=this.children,G=K.length>1,q=K.length>1?K[1]:void 0,z=K.length>2?K[2]:void 0,U={fg:this.borderColor},W=Math.floor(X/2),H=(()=>{return this.borderStyle==="rounded"?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"}})();for(let B=0;B<X;B++)J.setChar(Q+B,Z,"─",U,1);for(let B=0;B<X;B++)J.setChar(Q+B,Z+Y-1,"─",U,1);for(let B=0;B<Y;B++)J.setChar(Q,Z+B,"│",U,1);for(let B=0;B<Y;B++)J.setChar(Q+X-1,Z+B,"│",U,1);if(this.hasBanner)J.setChar(Q,Z,"├",U,1),J.setChar(Q+X-1,Z,"┤",U,1);else J.setChar(Q,Z,H.tl,U,1),J.setChar(Q+X-1,Z,H.tr,U,1);if(J.setChar(Q,Z+Y-1,H.bl,U,1),J.setChar(Q+X-1,Z+Y-1,H.br,U,1),G){for(let B=1;B<Y-1;B++)J.setChar(Q+W,Z+B,"│",U,1);J.setChar(Q+W,Z,"┬",U,1),J.setChar(Q+W,Z+Y-1,"┴",U,1)}if(q&&z&&q.size.height>0){let B=q.offset.y+q.size.height;for(let M=W+1;M<X-1;M++)J.setChar(Q+M,Z+B,"─",U,1);J.setChar(Q+W,Z+B,"├",U,1),J.setChar(Q+X-1,Z+B,"┤",U,1)}}}e9();oy();class zm1 extends P6{status;constructor({status:J,key:Q}){super(Q?{key:Q}:{});this.status=J}build(J){if(this.status===null||!this.status.enabled)return new U0({width:0,height:0});let Q=this.status,Z=Q.connected===!0,X=!!Q.errorMessage,Y=Q.clientID||"unknown",K,G;if(X)K="×",G=I1.red;else if(Z)K="✓",G=I1.green;else K="○",G=I1.yellow;let q=`${K} Client: ${Y}`;return new X8({mainAxisSize:"min",children:[new n1({text:new V1(q,new $1({color:G}))})]})}}G0();v0();function Md(J,Q){if(J===Q)return!0;if(J==null||Q==null||typeof J!=="object"||typeof Q!=="object")return!1;let Z=Array.isArray(J),X=Array.isArray(Q);if(Z!==X)return!1;if(Z&&X)return J.length===Q.length&&J.every((K,G)=>Md(K,Q[G]));let Y=new Set([...Object.keys(J),...Object.keys(Q)]);for(let K of Y)if(!Md(J[K],Q[K]))return!1;return!0}G0();$D();function pz6(J){return Zc(600000).pipe(d2(void 0),q8(()=>J.config.pipe(b0(({settings:Q,secrets:Z})=>({settings:{url:Q.url,proxy:Q.proxy},secrets:Z})),J8((Q,Z)=>Md(Q.settings,Z.settings)&&Q.secrets===Z.secrets),cN(()=>c6(async(Q)=>{let Z=await UJ.getUserInfo({},{signal:Q,config:J});if(Z.ok)return Z.result;if(Z.error&&Z.error.code==="auth-required")return null;throw u.error("getUserInfo failed",{error:Z.error}),Error(`getUserInfo error: ${Z.error.code}`)})))),b0((Q)=>{return Q instanceof Error?{error:{message:String(Q)}}:Q===QJ?"pending":Q?{user:Q,workspace:Q?.team}:{error:{message:"User not found"}}}),J8((Q,Z)=>Md(Q,Z)),M9({shouldCountRefs:!0}))}function dz6(J){return Boolean(typeof J==="object"&&"user"in J&&J.user)}v0();l8();var Um1=!1;class Wm1 extends c0{props;constructor(J){super();this.props=J}createState(){return new cz6}}class cz6 extends d0{showCost=Um1;subscription=null;initState(){super.initState(),this.subscription=b9(pz6(this.widget.props.configService).pipe(C7((J)=>J!=="pending")),this.widget.props.configService.config).pipe(b0(([J,Q])=>{let Z=dz6(J)?J.user.email:"",X=Z.toLowerCase().endsWith("@sourcegraph.com"),Y=Um1||X,K=Q.settings["internal.showCost"]??!0,G=Y&&K;return u.debug("CostDisplayProvider computed showCost",{email:Z,isTeammate:X,isEligible:Y,setting:K,computedShowCost:G,currentShowCost:this.showCost}),G}),J8()).subscribe((J)=>{u.debug("CostDisplayProvider setState called",{previousShowCost:this.showCost,newShowCost:J}),this.setState(()=>{this.showCost=J})})}dispose(){this.subscription?.unsubscribe(),this.subscription=null,super.dispose()}build(J){return new Fm1({showCost:this.showCost,child:this.widget.props.child})}}class Fm1 extends VZ{showCost;constructor({showCost:J,child:Q}){super({child:Q});this.showCost=J}updateShouldNotify(J){return this.showCost!==J.showCost}}function qB(J){let Q=J.dependOnInheritedWidgetOfExactType(Fm1);if(Q)return Q.widget.showCost;return Um1}class Hm1 extends P6{totalCredits;onClick;constructor({totalCredits:J,onClick:Q,key:Z}){super(Z?{key:Z}:{});this.totalCredits=J,this.onClick=Q}build(J){if(!qB(J))return new U0({width:0,height:0});if(!this.totalCredits)return new U0({width:0,height:0});let Z=e6.of(J).colorScheme,X=GB(this.totalCredits),Y=new n1({text:new V1(X,new $1({color:Z.foreground,dim:!0}))});if(this.onClick)return new x9({onClick:this.onClick,child:Y});return Y}}G0();EW();_L();ac();k6();l8();G0();f2();class jN extends VZ{onError;constructor({onError:J,child:Q}){super({child:Q});this.onError=J}updateShouldNotify(J){return!1}static of(J){return J.dependOnInheritedWidgetOfExactType(jN)?.widget?.onError}}class RQ extends P6{uri;text;style;maxLines;overflow;onError;constructor({uri:J,text:Q,style:Z,maxLines:X,overflow:Y,onError:K,key:G}){super({key:G});this.uri=J,this.text=Q,this.style=Z,this.maxLines=X,this.overflow=Y,this.onError=K}build(J){let Q=jN.of(J),Z=this.onError??Q;return u6(Z!==void 0,"Link widget requires either onError prop or ErrorHandlerProvider in context"),RQ.createWidget(this.uri,this.text,Z,this.style,this.maxLines,this.overflow)}static createWidget(J,Q,Z,X,Y,K){let G=new n1({text:RQ.createSpan(J,Q,X),selectable:!0,maxLines:Y,overflow:K});return new x9({onClick:async()=>{try{await PQ(J)}catch(q){u.error("[Link] Error opening link",{uri:J,error:q});let z=q instanceof Error?q:Error(String(q));z.uri=J,u.error("[Link] Calling error handler"),Z(z)}},cursor:"pointer",child:G})}static createSpan(J,Q,Z){let X=LQ(),Y=X?J:Q,K=X?new $1({color:Z?.color,dim:!0}):Z||new $1({underline:!0}),G=X?void 0:Fq6(J);return new V1(Y,K,void 0,G)}}EW();k6();l8();class Bm1 extends c0{props;constructor(J){super();this.props=J}createState(){return new lz6}}class lz6 extends d0{displayPathEnvInfo=null;subscription=null;constructor(){super()}initState(){super.initState(),this.subscription=this.widget.props.configService.displayPathEnvInfo.subscribe((J)=>{fc(J),this.setState(()=>{this.displayPathEnvInfo=J})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}build(J){return new Dm1({displayPathEnvInfo:this.displayPathEnvInfo,child:this.widget.props.child})}}class Dm1 extends VZ{displayPathEnvInfo;constructor({displayPathEnvInfo:J,child:Q}){super({child:Q});this.displayPathEnvInfo=J}updateShouldNotify(J){return this.displayPathEnvInfo!==J.displayPathEnvInfo}}function gR(J){let Q=J.dependOnInheritedWidgetOfExactType(Dm1);if(!Q)return null;return Q.widget.displayPathEnvInfo}function XS(J,Q){if(J.startsWith("/")||/^[A-Za-z]:[\\/]/.test(J)){let X=gR(Q),Y=$0.file(J);return GJ(Y,X??void 0)}return J}f51();function Mm1(J,Q,Z){return new n1({text:new V1(`${J}${Q}`,new $1({color:Z})),maxLines:1})}function iz6(J,Q,Z,X){return[Mm1("+",J,X.success),r7.horizontal(1),Mm1("~",Q,X.warning),r7.horizontal(1),Mm1("-",Z,X.destructive)]}class Vm1 extends c0{threadViewState;threadID;onFileChangesClick;constructor({threadViewState:J,threadID:Q,onFileChangesClick:Z,key:X}){super(X?{key:X}:{});this.threadViewState=J,this.threadID=Q,this.onFileChangesClick=Z}createState(){return new nz6}}class nz6 extends d0{build(J){let Z=O6.of(J).colors;if(this.widget.threadViewState.state!=="active")return new U0({width:0,height:0});let{fileChanges:X}=this.widget.threadViewState,Y=WY1(X);if(Y.totalFiles===0)return new U0({width:0,height:0});let K=Y.totalFiles-Y.revertedFiles,G=`${K} ${K===1?"file":"files"} changed`,q=new n1({text:new V1(G,new $1({color:Z.foreground,dim:!0})),maxLines:1}),z;if(Y.totalAdded>0||Y.totalModified>0||Y.totalRemoved>0){let U=iz6(Y.totalAdded,Y.totalModified,Y.totalRemoved,Z);z=new X8({children:[q,r7.horizontal(1),...U],mainAxisSize:"min"})}else z=q;return new x9({onClick:()=>{if(this.widget.onFileChangesClick)this.widget.onFileChangesClick()},cursor:"pointer",child:z})}}class Nm1 extends c0{createState(){return new az6}}class az6 extends d0{build(J){let Z=e6.of(J).colorScheme,Y=O6.of(J).app,K=_8.of(J),G=y51();if(!G)return new U0({width:0,height:0});let q=G.getThreadData(),z=q.viewState,U=q.mainThread?.id;if(z.state!=="active"||!U)return new U0({width:0,height:0});let{fileChanges:W}=z,F=WY1(W);if(F.totalFiles===0)return new U0({width:0,height:0});let H=F.totalFiles-F.revertedFiles,B=F.allReverted?`${F.revertedFiles} ${F.revertedFiles===1?"change":"changes"} reverted`:`${H} ${H===1?"file":"files"} changed`,M=new C9({child:new n1({text:new V1(B,new $1({color:Z.primary,bold:!0}))})}),V=gR(J),N=[];for(let v of W.files){let x=$0.parse(v.uri),y=GJ(x,V??void 0),g=v.reverted,k=[];if(k.push(new R8({child:new RQ({uri:v.uri,text:y,style:new $1({color:I1.cyan,dim:g,underline:!g}),maxLines:1,overflow:"ellipsis"})})),k.push(r7.horizontal(1)),g)k.push(new n1({text:new V1("Reverted",new $1({color:Z.foreground,dim:!0,italic:!0}))}));else{let b=iz6(v.diffStat.added,v.diffStat.modified,v.diffStat.removed,Z);k.push(...b),k.push(r7.horizontal(1)),k.push(new x9({onClick:async(m)=>{try{await VJ.revertFileChanges(U,v.uri),this.setState(()=>{})}catch(n){u.error(`Error reverting file ${v.uri} (thread id: ${U}):`,n)}},cursor:"pointer",child:new n1({text:new V1("↶",new $1({color:Y.button}))})}))}let f=new X8({mainAxisSize:"max",crossAxisAlignment:"center",children:k});N.push(new b6({padding:N0.only({left:2,right:2,top:0,bottom:0}),child:f}))}let L=[];L.push(M),L.push(new U0({height:1}));for(let v of N)L.push(v);if(!F.allReverted&&H>0){let v=new b6({padding:N0.only({top:1,left:2,right:2}),child:new X8({mainAxisSize:"max",crossAxisAlignment:"center",children:[new R8({child:new n1({text:new V1(`${H} ${H===1?"file":"files"} changed`,new $1({color:Z.foreground}))})}),r7.horizontal(1),new x9({onClick:async(x)=>{try{await VJ.revertFileChanges(U),this.setState(()=>{})}catch(y){u.error(`Error reverting all files (thread id: ${U}):`,y)}},cursor:"pointer",child:new n1({text:new V1("Revert All",new $1({color:Y.button}))})})]})});L.push(v)}let A=K.size.width,w=K.size.height,R=A-4,O=w-4,$=Math.min(60,R),j=new C9({child:new n1({text:new V1("",new $1({color:Z.foreground}),[new V1("Press ",new $1({color:Z.foreground})),new V1("Escape",new $1({color:Y.keybind})),new V1(" to close",new $1({color:Z.foreground}))])})}),E=[...L,new U0({height:1}),j],I=2+N.length+(H>0?2:0)+1+1+4+2,T=Math.min(I,O),S=new b6({padding:N0.all(1),child:new i0({crossAxisAlignment:"stretch",children:E})}),h=I>O?new PY({autofocus:!0,child:S}):S;return new C9({child:new f0({constraints:new R6($,$,T,T),decoration:new i8(Z.background,x8.all(new w8(Z.primary,1,"rounded"))),child:h})})}}ev();import rz6 from"node:path";l8();function Cz9(J,Q){try{return decodeURIComponent(J)}catch(Z){if(Q!==void 0)return Q;throw Z}}class Lm1 extends c0{ideStatus;onShowIdePicker;constructor({ideStatus:J,onShowIdePicker:Q,key:Z}){super(Z?{key:Z}:{});this.ideStatus=J,this.onShowIdePicker=Q}createState(){return new sz6}}class sz6 extends d0{ideCount=0;intervalId;initState(){this.loadConfigs(),this.intervalId=setInterval(()=>{this.loadConfigs()},5000)}dispose(){if(this.intervalId)clearInterval(this.intervalId)}loadConfigs(){this.ideCount=cB({includeAll:!0}).length,this.setState()}build(J){if(this.widget.ideStatus===null||!this.widget.ideStatus.enabled)return this.statusIdle();let Q=this.widget.ideStatus,Z=Q.connectionState;if(!Z||Z==="never-connected")return this.statusIdle();if(Z==="reconnecting")return this.statusReconnecting(Q);if(Z==="disconnected")return this.statusDisconnected(Q);let X=Q.authenticated,Y=Q.selections?.[0],K=!q11(Y)&&Y?Y.range.endLine-Y.range.startLine+1:0,G=[];if(!X)if(Q.errorMessage)G.push(Q.errorMessage);else if(Q.connected===!1)G.push("IDE Not Connected");else G.push("IDE Error");else if(!Q.openFile&&!Y)G.push(`${Q.ideName?Q.ideName:"Unknown IDE"}`);if(Q.openFile)G.push(rz6.basename(Cz9(Q.openFile,Q.openFile)));if(Y&&K>0)G.push(`${K} selected ${yJ(K,"line")}`);let q=G.join(" • "),z=X?"✓":"×",U=X?I1.index(10):I1.index(9),F=`${z} ${q}${!X?" • Use /ide to connect":""}`;return this.idePickerText(F,U)}statusIdle(){if(this.ideCount===0)return new U0({width:0,height:0});else{let J=`${this.ideCount} ${yJ(this.ideCount,"IDE")} available`;return this.idePickerText(J)}}statusDisconnected(J){if((J.reconnectElapsedMs??0)>=60000)return this.statusIdle();let Z="IDE disconnected. Use /ide to connect";return this.idePickerText(Z)}statusReconnecting(J){let Q=J.ideName||"IDE",Z=J.workspace?` in ${rz6.basename(J.workspace)}`:"",X=`Reconnecting to ${Q}${Z}...`,Y=J.reconnectElapsedMs??0;return this.idePickerText(X,Y<5000?I1.yellow:I1.index(8))}idePickerText(J,Q=I1.index(8)){let Z=new n1({text:new V1(J,new $1({color:Q})),maxLines:1}),X=this.widget.onShowIdePicker?new x9({onClick:this.widget.onShowIdePicker,cursor:"pointer",child:Z}):Z;return new X8({children:[X],mainAxisSize:"min"})}}l8();function Sz9(J){return J.toLowerCase().includes("sonnet")}function vz9(J){return{recommendation:Sz9(J)?0.2:0.6,warning:0.8,danger:0.9}}function kz9(J,Q){let Z=vz9(Q);if(J>=Z.danger)return"danger";else if(J>=Z.warning)return"warning";else if(J>=Z.recommendation)return"recommendation";return!1}function Am1(J){let Q=J.totalInputTokens/J.maxInputTokens;return kz9(Q,J.model||"")}class wm1 extends c0{threadViewState;tokenUsage;thread;waitingForConfirmation;showingEphemeralError;executingCommand;executingCommandMessage;runningBashInvocations;constructor({threadViewState:J,tokenUsage:Q,thread:Z,waitingForConfirmation:X=!1,showingEphemeralError:Y=!1,executingCommand:K=null,executingCommandMessage:G=null,runningBashInvocations:q=!1,key:z}={}){super(z?{key:z}:{});this.threadViewState=J,this.tokenUsage=Q,this.thread=Z,this.waitingForConfirmation=X,this.showingEphemeralError=Y,this.executingCommand=K,this.executingCommandMessage=G,this.runningBashInvocations=q}createState(){return new oz6}}class oz6 extends d0{animationFrame=0;animationTimer=null;animationFrames=["∿","∾","∽","≋","≈","∼"];initState(){this.startAnimationIfNeeded()}didUpdateWidget(J){this.startAnimationIfNeeded()}dispose(){this.stopAnimation()}startAnimationIfNeeded(){let J=this.shouldShowSpinner();if(J&&!this.animationTimer)this.startAnimation();else if(!J&&this.animationTimer)this.stopAnimation()}startAnimation(){if(this.animationTimer)return;this.animationTimer=setInterval(()=>{this.setState(()=>{this.animationFrame=(this.animationFrame+1)%this.animationFrames.length})},200)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}shouldShowSpinner(){let{threadViewState:J,waitingForConfirmation:Q,runningBashInvocations:Z}=this.widget;return Boolean(Z||J&&J.state==="active"&&(J.inferenceState==="running"||J.interactionState==="tool-running")&&!this.isShowingTokenUsageNote()&&!Q)}isShowingTokenUsageNote(){let{tokenUsage:J,showingEphemeralError:Q}=this.widget;if(!J||Q)return!1;let Z=Am1(J);return Z==="recommendation"||Z==="warning"||Z==="danger"}getSpinnerColor(){let{threadViewState:J}=this.widget;if(!J)return I1.index(8);if(J.state==="active"){if(J.inferenceState==="running")return I1.index(12)}return I1.index(8)}getStatusMessageColor(J,Q){let{threadViewState:Z,tokenUsage:X,showingEphemeralError:Y,executingCommand:K,runningBashInvocations:G}=this.widget;if(K)return Q.command;if(G)return J.foreground;if(X&&!Y){let q=Am1(X);if(q==="recommendation")return Q.recommendation;if(q==="warning")return J.warning;if(q==="danger")return J.destructive}if(Z?.state==="active"&&Z.inferenceState==="cancelled")return I1.index(8);return J.foreground}build(J){let Q=O6.of(J),Z=Q.colors,X=Q.app,Y=Rm1(this.widget);if(!Y)return new U0({width:0,height:0});let K=[];if(this.shouldShowSpinner()){let q=this.animationFrames[this.animationFrame];K.push(new n1({text:new V1(q,new $1({color:this.getSpinnerColor()})),maxLines:1})),K.push(r7.horizontal(1))}return K.push(new n1({text:new V1(Y,new $1({color:this.getStatusMessageColor(Z,X),italic:this.widget.threadViewState?.state==="active"&&this.widget.threadViewState.inferenceState==="cancelled"})),textAlign:"left",maxLines:1,overflow:"clip"})),new X8({children:K,mainAxisSize:"min"})}}function Rm1(J){let{threadViewState:Q,tokenUsage:Z,showingEphemeralError:X,executingCommand:Y,executingCommandMessage:K,runningBashInvocations:G}=J;if(Y)return K??`Executing /${Y}...`;if(G)return"Running shell command...";if(!Q||Q.state!=="active")return null;if(Q.interactionState==="tool-running"){let q=Q.toolState.running;if(q>1)return`Running ${q} tools...`;return"Running tools..."}if(Q.inferenceState==="running"){let q=J.thread?.messages.at(-1);if(!(q?.role==="assistant"&&q.state.type==="streaming"))return"Waiting for response...";if(J.runningBashInvocations)return"Running tools...";return"Streaming response..."}if(Z&&!X&&J.thread?.agentMode!=="free"){let q=Am1(Z);if(q==="recommendation")return"Optimize context: Use Ctrl+O to handoff or start a new thread";if(q==="warning")return"High context usage. Use Ctrl+O to handoff or start a new thread";if(q==="danger")return"Context window is close to full. Use Ctrl+O to handoff or start a new thread"}return null}function _z9(J){if(J>=900000)return{recommendation:0.2,warning:0.8,danger:0.9};else if(J>=400000)return{recommendation:0.7,warning:0.8,danger:0.9};else return{recommendation:0.8,warning:0.9,danger:0.95}}function xz9(J){if(J>=1e6)return`${Math.round(J/1e6)}M`;else if(J>=1000)return`${Math.round(J/1000)}k`;return J.toString()}function bz9(J,Q){let Z=_z9(Q);if(J>=Z.danger)return"danger";else if(J>=Z.warning)return"warning";else if(J>=Z.recommendation)return"recommendation";return!1}class Om1 extends P6{tokenUsage;isNarrow;constructor({tokenUsage:J,isNarrow:Q=!1,key:Z}){super(Z?{key:Z}:{});this.tokenUsage=J,this.isNarrow=Q}build(J){let Z=O6.of(J).colors,X=this.tokenUsage.totalInputTokens/this.tokenUsage.maxInputTokens,Y=Math.round(X*100),K=Math.max(0,Math.min(Y,100)),G=this.isNarrow?`${K}%`:`${K}% of ${xz9(this.tokenUsage.maxInputTokens)}`,q=new $1({color:Z.foreground,dim:!0}),z=bz9(X,this.tokenUsage.maxInputTokens);if(z==="danger")q=new $1({color:Z.destructive});else if(z==="warning")q=new $1({color:Z.warning});else if(z==="recommendation")q=new $1({color:Z.info});return new n1({text:new V1(G,q),textAlign:"left",maxLines:1,overflow:"clip"})}}class jm1 extends P6{hint;constructor({hint:J,key:Q}={}){super(Q?{key:Q}:{});this.hint=J}build(J){if(!this.hint)return new U0({width:0,height:0});return new n1({text:this.hint,textAlign:"left",maxLines:1,overflow:"clip"})}}class YQ1 extends P6{statusText;isAnimated;statusType;threadViewState;threadTokenUsage;threadID;thread;onFileChangesClick;onCostBreakdownClick;onShowIdePicker;ideStatus;connectedClientsStatus;isNarrow;uiHint;waitingForConfirmation;showingEphemeralError;executingCommand;executingCommandMessage;runningBashInvocations;constructor({statusText:J,isAnimated:Q=!1,statusType:Z="idle",threadViewState:X,threadTokenUsage:Y,threadID:K,thread:G,onFileChangesClick:q,onCostBreakdownClick:z,onShowIdePicker:U,ideStatus:W=null,connectedClientsStatus:F=null,isNarrow:H=!1,uiHint:B,waitingForConfirmation:M=!1,showingEphemeralError:V=!1,executingCommand:N=null,executingCommandMessage:L=null,runningBashInvocations:A=!1,key:w}={}){super(w?{key:w}:{});this.statusText=J,this.isAnimated=Q,this.statusType=Z,this.threadViewState=X,this.threadTokenUsage=Y,this.threadID=K,this.thread=G,this.onFileChangesClick=q,this.onCostBreakdownClick=z,this.onShowIdePicker=U,this.ideStatus=W,this.connectedClientsStatus=F,this.isNarrow=H,this.uiHint=B,this.waitingForConfirmation=M,this.showingEphemeralError=V,this.executingCommand=N,this.executingCommandMessage=L,this.runningBashInvocations=A}build(J){let Q=[],Z=!1;if(this.threadViewState){let X=new wm1({threadViewState:this.threadViewState,tokenUsage:this.threadTokenUsage,thread:this.thread,waitingForConfirmation:this.waitingForConfirmation,showingEphemeralError:this.showingEphemeralError,executingCommand:this.executingCommand,executingCommandMessage:this.executingCommandMessage,runningBashInvocations:this.runningBashInvocations});if(Rm1(X))Z=!0;Q.push(X)}if(this.uiHint){if(Z)Q.push(r7.horizontal(2));Q.push(new jm1({hint:this.uiHint}))}if(Q.push(r7.flexible()),this.ideStatus)Q.push(new Lm1({ideStatus:this.ideStatus,onShowIdePicker:this.onShowIdePicker})),Q.push(r7.horizontal(1));if(this.connectedClientsStatus)Q.push(new zm1({status:this.connectedClientsStatus})),Q.push(r7.horizontal(1));if(this.threadViewState&&!this.isNarrow&&this.threadID&&MG(this.threadID))Q.push(new Vm1({threadViewState:this.threadViewState,threadID:this.threadID,onFileChangesClick:this.onFileChangesClick})),Q.push(r7.horizontal(1));if(this.threadTokenUsage){if(Q.push(new Om1({tokenUsage:this.threadTokenUsage,isNarrow:this.isNarrow})),this.thread&&qB(J)){let X=I30(this.thread);if(X>0)Q.push(r7.horizontal(2)),Q.push(new Hm1({totalCredits:X,onClick:this.onCostBreakdownClick}))}}return new X8({children:Q,mainAxisSize:"min",mainAxisAlignment:"start"})}}var yz9={};function mR(J,Q){let Z=Q||yz9,X=typeof Z.includeImageAlt==="boolean"?Z.includeImageAlt:!0,Y=typeof Z.includeHtml==="boolean"?Z.includeHtml:!0;return ez6(J,X,Y)}function ez6(J,Q,Z){if(fz9(J)){if("value"in J)return J.type==="html"&&!Z?"":J.value;if(Q&&"alt"in J&&J.alt)return J.alt;if("children"in J)return tz6(J.children,Q,Z)}if(Array.isArray(J))return tz6(J,Q,Z);return""}function tz6(J,Q,Z){let X=[],Y=-1;while(++Y<J.length)X[Y]=ez6(J[Y],Q,Z);return X.join("")}function fz9(J){return Boolean(J&&typeof J==="object")}var $m1={AElig:"Æ",AMP:"&",Aacute:"Á",Abreve:"Ă",Acirc:"Â",Acy:"А",Afr:"\uD835\uDD04",Agrave:"À",Alpha:"Α",Amacr:"Ā",And:"⩓",Aogon:"Ą",Aopf:"\uD835\uDD38",ApplyFunction:"",Aring:"Å",Ascr:"\uD835\uDC9C",Assign:"≔",Atilde:"Ã",Auml:"Ä",Backslash:"∖",Barv:"⫧",Barwed:"⌆",Bcy:"Б",Because:"∵",Bernoullis:"ℬ",Beta:"Β",Bfr:"\uD835\uDD05",Bopf:"\uD835\uDD39",Breve:"˘",Bscr:"ℬ",Bumpeq:"≎",CHcy:"Ч",COPY:"©",Cacute:"Ć",Cap:"⋒",CapitalDifferentialD:"ⅅ",Cayleys:"ℭ",Ccaron:"Č",Ccedil:"Ç",Ccirc:"Ĉ",Cconint:"∰",Cdot:"Ċ",Cedilla:"¸",CenterDot:"·",Cfr:"ℭ",Chi:"Χ",CircleDot:"⊙",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",Colon:"∷",Colone:"⩴",Congruent:"≡",Conint:"∯",ContourIntegral:"∮",Copf:"ℂ",Coproduct:"∐",CounterClockwiseContourIntegral:"∳",Cross:"⨯",Cscr:"\uD835\uDC9E",Cup:"⋓",CupCap:"≍",DD:"ⅅ",DDotrahd:"⤑",DJcy:"Ђ",DScy:"Ѕ",DZcy:"Џ",Dagger:"‡",Darr:"↡",Dashv:"⫤",Dcaron:"Ď",Dcy:"Д",Del:"∇",Delta:"Δ",Dfr:"\uD835\uDD07",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",Diamond:"⋄",DifferentialD:"ⅆ",Dopf:"\uD835\uDD3B",Dot:"¨",DotDot:"⃜",DotEqual:"≐",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",Downarrow:"⇓",Dscr:"\uD835\uDC9F",Dstrok:"Đ",ENG:"Ŋ",ETH:"Ð",Eacute:"É",Ecaron:"Ě",Ecirc:"Ê",Ecy:"Э",Edot:"Ė",Efr:"\uD835\uDD08",Egrave:"È",Element:"∈",Emacr:"Ē",EmptySmallSquare:"◻",EmptyVerySmallSquare:"▫",Eogon:"Ę",Eopf:"\uD835\uDD3C",Epsilon:"Ε",Equal:"⩵",EqualTilde:"≂",Equilibrium:"⇌",Escr:"ℰ",Esim:"⩳",Eta:"Η",Euml:"Ë",Exists:"∃",ExponentialE:"ⅇ",Fcy:"Ф",Ffr:"\uD835\uDD09",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",Fopf:"\uD835\uDD3D",ForAll:"∀",Fouriertrf:"ℱ",Fscr:"ℱ",GJcy:"Ѓ",GT:">",Gamma:"Γ",Gammad:"Ϝ",Gbreve:"Ğ",Gcedil:"Ģ",Gcirc:"Ĝ",Gcy:"Г",Gdot:"Ġ",Gfr:"\uD835\uDD0A",Gg:"⋙",Gopf:"\uD835\uDD3E",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"\uD835\uDCA2",Gt:"≫",HARDcy:"Ъ",Hacek:"ˇ",Hat:"^",Hcirc:"Ĥ",Hfr:"ℌ",HilbertSpace:"ℋ",Hopf:"ℍ",HorizontalLine:"─",Hscr:"ℋ",Hstrok:"Ħ",HumpDownHump:"≎",HumpEqual:"≏",IEcy:"Е",IJlig:"IJ",IOcy:"Ё",Iacute:"Í",Icirc:"Î",Icy:"И",Idot:"İ",Ifr:"ℑ",Igrave:"Ì",Im:"ℑ",Imacr:"Ī",ImaginaryI:"ⅈ",Implies:"⇒",Int:"∬",Integral:"∫",Intersection:"⋂",InvisibleComma:"",InvisibleTimes:"",Iogon:"Į",Iopf:"\uD835\uDD40",Iota:"Ι",Iscr:"ℐ",Itilde:"Ĩ",Iukcy:"І",Iuml:"Ï",Jcirc:"Ĵ",Jcy:"Й",Jfr:"\uD835\uDD0D",Jopf:"\uD835\uDD41",Jscr:"\uD835\uDCA5",Jsercy:"Ј",Jukcy:"Є",KHcy:"Х",KJcy:"Ќ",Kappa:"Κ",Kcedil:"Ķ",Kcy:"К",Kfr:"\uD835\uDD0E",Kopf:"\uD835\uDD42",Kscr:"\uD835\uDCA6",LJcy:"Љ",LT:"<",Lacute:"Ĺ",Lambda:"Λ",Lang:"⟪",Laplacetrf:"ℒ",Larr:"↞",Lcaron:"Ľ",Lcedil:"Ļ",Lcy:"Л",LeftAngleBracket:"⟨",LeftArrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",LeftRightArrow:"↔",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",Leftarrow:"⇐",Leftrightarrow:"⇔",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",LessLess:"⪡",LessSlantEqual:"⩽",LessTilde:"≲",Lfr:"\uD835\uDD0F",Ll:"⋘",Lleftarrow:"⇚",Lmidot:"Ŀ",LongLeftArrow:"⟵",LongLeftRightArrow:"⟷",LongRightArrow:"⟶",Longleftarrow:"⟸",Longleftrightarrow:"⟺",Longrightarrow:"⟹",Lopf:"\uD835\uDD43",LowerLeftArrow:"↙",LowerRightArrow:"↘",Lscr:"ℒ",Lsh:"↰",Lstrok:"Ł",Lt:"≪",Map:"⤅",Mcy:"М",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"\uD835\uDD10",MinusPlus:"∓",Mopf:"\uD835\uDD44",Mscr:"ℳ",Mu:"Μ",NJcy:"Њ",Nacute:"Ń",Ncaron:"Ň",Ncedil:"Ņ",Ncy:"Н",NegativeMediumSpace:"",NegativeThickSpace:"",NegativeThinSpace:"",NegativeVeryThinSpace:"",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:`
|
|
6546
6546
|
`,Nfr:"\uD835\uDD11",NoBreak:"",NonBreakingSpace:" ",Nopf:"ℕ",Not:"⫬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",Nscr:"\uD835\uDCA9",Ntilde:"Ñ",Nu:"Ν",OElig:"Œ",Oacute:"Ó",Ocirc:"Ô",Ocy:"О",Odblac:"Ő",Ofr:"\uD835\uDD12",Ograve:"Ò",Omacr:"Ō",Omega:"Ω",Omicron:"Ο",Oopf:"\uD835\uDD46",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",Or:"⩔",Oscr:"\uD835\uDCAA",Oslash:"Ø",Otilde:"Õ",Otimes:"⨷",Ouml:"Ö",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",PartialD:"∂",Pcy:"П",Pfr:"\uD835\uDD13",Phi:"Φ",Pi:"Π",PlusMinus:"±",Poincareplane:"ℌ",Popf:"ℙ",Pr:"⪻",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",Prime:"″",Product:"∏",Proportion:"∷",Proportional:"∝",Pscr:"\uD835\uDCAB",Psi:"Ψ",QUOT:'"',Qfr:"\uD835\uDD14",Qopf:"ℚ",Qscr:"\uD835\uDCAC",RBarr:"⤐",REG:"®",Racute:"Ŕ",Rang:"⟫",Rarr:"↠",Rarrtl:"⤖",Rcaron:"Ř",Rcedil:"Ŗ",Rcy:"Р",Re:"ℜ",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",Rfr:"ℜ",Rho:"Ρ",RightAngleBracket:"⟩",RightArrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",Rightarrow:"⇒",Ropf:"ℝ",RoundImplies:"⥰",Rrightarrow:"⇛",Rscr:"ℛ",Rsh:"↱",RuleDelayed:"⧴",SHCHcy:"Щ",SHcy:"Ш",SOFTcy:"Ь",Sacute:"Ś",Sc:"⪼",Scaron:"Š",Scedil:"Ş",Scirc:"Ŝ",Scy:"С",Sfr:"\uD835\uDD16",ShortDownArrow:"↓",ShortLeftArrow:"←",ShortRightArrow:"→",ShortUpArrow:"↑",Sigma:"Σ",SmallCircle:"∘",Sopf:"\uD835\uDD4A",Sqrt:"√",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",Sscr:"\uD835\uDCAE",Star:"⋆",Sub:"⋐",Subset:"⋐",SubsetEqual:"⊆",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",SuchThat:"∋",Sum:"∑",Sup:"⋑",Superset:"⊃",SupersetEqual:"⊇",Supset:"⋑",THORN:"Þ",TRADE:"™",TSHcy:"Ћ",TScy:"Ц",Tab:"\t",Tau:"Τ",Tcaron:"Ť",Tcedil:"Ţ",Tcy:"Т",Tfr:"\uD835\uDD17",Therefore:"∴",Theta:"Θ",ThickSpace:" ",ThinSpace:" ",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",Topf:"\uD835\uDD4B",TripleDot:"⃛",Tscr:"\uD835\uDCAF",Tstrok:"Ŧ",Uacute:"Ú",Uarr:"↟",Uarrocir:"⥉",Ubrcy:"Ў",Ubreve:"Ŭ",Ucirc:"Û",Ucy:"У",Udblac:"Ű",Ufr:"\uD835\uDD18",Ugrave:"Ù",Umacr:"Ū",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",Uopf:"\uD835\uDD4C",UpArrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",UpEquilibrium:"⥮",UpTee:"⊥",UpTeeArrow:"↥",Uparrow:"⇑",Updownarrow:"⇕",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",Upsilon:"Υ",Uring:"Ů",Uscr:"\uD835\uDCB0",Utilde:"Ũ",Uuml:"Ü",VDash:"⊫",Vbar:"⫫",Vcy:"В",Vdash:"⊩",Vdashl:"⫦",Vee:"⋁",Verbar:"‖",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"\uD835\uDD19",Vopf:"\uD835\uDD4D",Vscr:"\uD835\uDCB1",Vvdash:"⊪",Wcirc:"Ŵ",Wedge:"⋀",Wfr:"\uD835\uDD1A",Wopf:"\uD835\uDD4E",Wscr:"\uD835\uDCB2",Xfr:"\uD835\uDD1B",Xi:"Ξ",Xopf:"\uD835\uDD4F",Xscr:"\uD835\uDCB3",YAcy:"Я",YIcy:"Ї",YUcy:"Ю",Yacute:"Ý",Ycirc:"Ŷ",Ycy:"Ы",Yfr:"\uD835\uDD1C",Yopf:"\uD835\uDD50",Yscr:"\uD835\uDCB4",Yuml:"Ÿ",ZHcy:"Ж",Zacute:"Ź",Zcaron:"Ž",Zcy:"З",Zdot:"Ż",ZeroWidthSpace:"",Zeta:"Ζ",Zfr:"ℨ",Zopf:"ℤ",Zscr:"\uD835\uDCB5",aacute:"á",abreve:"ă",ac:"∾",acE:"∾̳",acd:"∿",acirc:"â",acute:"´",acy:"а",aelig:"æ",af:"",afr:"\uD835\uDD1E",agrave:"à",alefsym:"ℵ",aleph:"ℵ",alpha:"α",amacr:"ā",amalg:"⨿",amp:"&",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",aogon:"ą",aopf:"\uD835\uDD52",ap:"≈",apE:"⩰",apacir:"⩯",ape:"≊",apid:"≋",apos:"'",approx:"≈",approxeq:"≊",aring:"å",ascr:"\uD835\uDCB6",ast:"*",asymp:"≈",asympeq:"≍",atilde:"ã",auml:"ä",awconint:"∳",awint:"⨑",bNot:"⫭",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",barvee:"⊽",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",beta:"β",beth:"ℶ",between:"≬",bfr:"\uD835\uDD1F",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bnot:"⌐",bopf:"\uD835\uDD53",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxDL:"╗",boxDR:"╔",boxDl:"╖",boxDr:"╓",boxH:"═",boxHD:"╦",boxHU:"╩",boxHd:"╤",boxHu:"╧",boxUL:"╝",boxUR:"╚",boxUl:"╜",boxUr:"╙",boxV:"║",boxVH:"╬",boxVL:"╣",boxVR:"╠",boxVh:"╫",boxVl:"╢",boxVr:"╟",boxbox:"⧉",boxdL:"╕",boxdR:"╒",boxdl:"┐",boxdr:"┌",boxh:"─",boxhD:"╥",boxhU:"╨",boxhd:"┬",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxuL:"╛",boxuR:"╘",boxul:"┘",boxur:"└",boxv:"│",boxvH:"╪",boxvL:"╡",boxvR:"╞",boxvh:"┼",boxvl:"┤",boxvr:"├",bprime:"‵",breve:"˘",brvbar:"¦",bscr:"\uD835\uDCB7",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",bumpeq:"≏",cacute:"ć",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",caps:"∩︀",caret:"⁁",caron:"ˇ",ccaps:"⩍",ccaron:"č",ccedil:"ç",ccirc:"ĉ",ccups:"⩌",ccupssm:"⩐",cdot:"ċ",cedil:"¸",cemptyv:"⦲",cent:"¢",centerdot:"·",cfr:"\uD835\uDD20",chcy:"ч",check:"✓",checkmark:"✓",chi:"χ",cir:"○",cirE:"⧃",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledR:"®",circledS:"Ⓢ",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",clubs:"♣",clubsuit:"♣",colon:":",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",conint:"∮",copf:"\uD835\uDD54",coprod:"∐",copy:"©",copysr:"℗",crarr:"↵",cross:"✗",cscr:"\uD835\uDCB8",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cup:"∪",cupbrcap:"⩈",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dArr:"⇓",dHar:"⥥",dagger:"†",daleth:"ℸ",darr:"↓",dash:"‐",dashv:"⊣",dbkarow:"⤏",dblac:"˝",dcaron:"ď",dcy:"д",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",ddotseq:"⩷",deg:"°",delta:"δ",demptyv:"⦱",dfisht:"⥿",dfr:"\uD835\uDD21",dharl:"⇃",dharr:"⇂",diam:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",dopf:"\uD835\uDD55",dot:"˙",doteq:"≐",doteqdot:"≑",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",downarrow:"↓",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",dscr:"\uD835\uDCB9",dscy:"ѕ",dsol:"⧶",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",dzcy:"џ",dzigrarr:"⟿",eDDot:"⩷",eDot:"≑",eacute:"é",easter:"⩮",ecaron:"ě",ecir:"≖",ecirc:"ê",ecolon:"≕",ecy:"э",edot:"ė",ee:"ⅇ",efDot:"≒",efr:"\uD835\uDD22",eg:"⪚",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",emacr:"ē",empty:"∅",emptyset:"∅",emptyv:"∅",emsp13:" ",emsp14:" ",emsp:" ",eng:"ŋ",ensp:" ",eogon:"ę",eopf:"\uD835\uDD56",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",equals:"=",equest:"≟",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erDot:"≓",erarr:"⥱",escr:"ℯ",esdot:"≐",esim:"≂",eta:"η",eth:"ð",euml:"ë",euro:"€",excl:"!",exist:"∃",expectation:"ℰ",exponentiale:"ⅇ",fallingdotseq:"≒",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",ffr:"\uD835\uDD23",filig:"fi",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",fopf:"\uD835\uDD57",forall:"∀",fork:"⋔",forkv:"⫙",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"\uD835\uDCBB",gE:"≧",gEl:"⪌",gacute:"ǵ",gamma:"γ",gammad:"ϝ",gap:"⪆",gbreve:"ğ",gcirc:"ĝ",gcy:"г",gdot:"ġ",ge:"≥",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",gfr:"\uD835\uDD24",gg:"≫",ggg:"⋙",gimel:"ℷ",gjcy:"ѓ",gl:"≷",glE:"⪒",gla:"⪥",glj:"⪤",gnE:"≩",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",gopf:"\uD835\uDD58",grave:"`",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",hArr:"⇔",hairsp:" ",half:"½",hamilt:"ℋ",hardcy:"ъ",harr:"↔",harrcir:"⥈",harrw:"↭",hbar:"ℏ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"\uD835\uDD25",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"\uD835\uDD59",horbar:"―",hscr:"\uD835\uDCBD",hslash:"ℏ",hstrok:"ħ",hybull:"⁃",hyphen:"‐",iacute:"í",ic:"",icirc:"î",icy:"и",iecy:"е",iexcl:"¡",iff:"⇔",ifr:"\uD835\uDD26",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",ijlig:"ij",imacr:"ī",image:"ℑ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",int:"∫",intcal:"⊺",integers:"ℤ",intercal:"⊺",intlarhk:"⨗",intprod:"⨼",iocy:"ё",iogon:"į",iopf:"\uD835\uDD5A",iota:"ι",iprod:"⨼",iquest:"¿",iscr:"\uD835\uDCBE",isin:"∈",isinE:"⋹",isindot:"⋵",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"",itilde:"ĩ",iukcy:"і",iuml:"ï",jcirc:"ĵ",jcy:"й",jfr:"\uD835\uDD27",jmath:"ȷ",jopf:"\uD835\uDD5B",jscr:"\uD835\uDCBF",jsercy:"ј",jukcy:"є",kappa:"κ",kappav:"ϰ",kcedil:"ķ",kcy:"к",kfr:"\uD835\uDD28",kgreen:"ĸ",khcy:"х",kjcy:"ќ",kopf:"\uD835\uDD5C",kscr:"\uD835\uDCC0",lAarr:"⇚",lArr:"⇐",lAtail:"⤛",lBarr:"⤎",lE:"≦",lEg:"⪋",lHar:"⥢",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",lambda:"λ",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",laquo:"«",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",latail:"⤙",late:"⪭",lates:"⪭︀",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",lcaron:"ľ",lcedil:"ļ",lceil:"⌈",lcub:"{",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",leftarrow:"←",leftarrowtail:"↢",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",leftthreetimes:"⋋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",lessgtr:"≶",lesssim:"≲",lfisht:"⥼",lfloor:"⌊",lfr:"\uD835\uDD29",lg:"≶",lgE:"⪑",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",ljcy:"љ",ll:"≪",llarr:"⇇",llcorner:"⌞",llhard:"⥫",lltri:"◺",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnE:"≨",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",longleftrightarrow:"⟷",longmapsto:"⟼",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",lopf:"\uD835\uDD5D",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"",lrtri:"⊿",lsaquo:"‹",lscr:"\uD835\uDCC1",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",lstrok:"ł",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltrPar:"⦖",ltri:"◃",ltrie:"⊴",ltrif:"◂",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",mDDot:"∺",macr:"¯",male:"♂",malt:"✠",maltese:"✠",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",mcy:"м",mdash:"—",measuredangle:"∡",mfr:"\uD835\uDD2A",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",mopf:"\uD835\uDD5E",mp:"∓",mscr:"\uD835\uDCC2",mstpos:"∾",mu:"μ",multimap:"⊸",mumap:"⊸",nGg:"⋙̸",nGt:"≫⃒",nGtv:"≫̸",nLeftarrow:"⇍",nLeftrightarrow:"⇎",nLl:"⋘̸",nLt:"≪⃒",nLtv:"≪̸",nRightarrow:"⇏",nVDash:"⊯",nVdash:"⊮",nabla:"∇",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",ncaron:"ň",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",ncy:"н",ndash:"–",ne:"≠",neArr:"⇗",nearhk:"⤤",nearr:"↗",nearrow:"↗",nedot:"≐̸",nequiv:"≢",nesear:"⤨",nesim:"≂̸",nexist:"∄",nexists:"∄",nfr:"\uD835\uDD2B",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",ngsim:"≵",ngt:"≯",ngtr:"≯",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",njcy:"њ",nlArr:"⇍",nlE:"≦̸",nlarr:"↚",nldr:"‥",nle:"≰",nleftarrow:"↚",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nlsim:"≴",nlt:"≮",nltri:"⋪",nltrie:"⋬",nmid:"∤",nopf:"\uD835\uDD5F",not:"¬",notin:"∉",notinE:"⋹̸",notindot:"⋵̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",nscr:"\uD835\uDCC3",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",nu:"ν",num:"#",numero:"№",numsp:" ",nvDash:"⊭",nvHarr:"⤄",nvap:"≍⃒",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwArr:"⇖",nwarhk:"⤣",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",oS:"Ⓢ",oacute:"ó",oast:"⊛",ocir:"⊚",ocirc:"ô",ocy:"о",odash:"⊝",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",oelig:"œ",ofcir:"⦿",ofr:"\uD835\uDD2C",ogon:"˛",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",omacr:"ō",omega:"ω",omicron:"ο",omid:"⦶",ominus:"⊖",oopf:"\uD835\uDD60",opar:"⦷",operp:"⦹",oplus:"⊕",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oscr:"ℴ",oslash:"ø",osol:"⊘",otilde:"õ",otimes:"⊗",otimesas:"⨶",ouml:"ö",ovbar:"⌽",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",pfr:"\uD835\uDD2D",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",pointint:"⨕",popf:"\uD835\uDD61",pound:"£",pr:"≺",prE:"⪳",prap:"⪷",prcue:"≼",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",prime:"′",primes:"ℙ",prnE:"⪵",prnap:"⪹",prnsim:"⋨",prod:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",propto:"∝",prsim:"≾",prurel:"⊰",pscr:"\uD835\uDCC5",psi:"ψ",puncsp:" ",qfr:"\uD835\uDD2E",qint:"⨌",qopf:"\uD835\uDD62",qprime:"⁗",qscr:"\uD835\uDCC6",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quot:'"',rAarr:"⇛",rArr:"⇒",rAtail:"⤜",rBarr:"⤏",rHar:"⥤",race:"∽̱",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",rarrtl:"↣",rarrw:"↝",ratail:"⤚",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",rcaron:"ř",rcedil:"ŗ",rceil:"⌉",rcub:"}",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",reg:"®",rfisht:"⥽",rfloor:"⌋",rfr:"\uD835\uDD2F",rhard:"⇁",rharu:"⇀",rharul:"⥬",rho:"ρ",rhov:"ϱ",rightarrow:"→",rightarrowtail:"↣",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",rightthreetimes:"⋌",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"\uD835\uDD63",roplus:"⨮",rotimes:"⨵",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",rsaquo:"›",rscr:"\uD835\uDCC7",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",ruluhar:"⥨",rx:"℞",sacute:"ś",sbquo:"‚",sc:"≻",scE:"⪴",scap:"⪸",scaron:"š",sccue:"≽",sce:"⪰",scedil:"ş",scirc:"ŝ",scnE:"⪶",scnap:"⪺",scnsim:"⋩",scpolint:"⨓",scsim:"≿",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",seArr:"⇘",searhk:"⤥",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",sfr:"\uD835\uDD30",sfrown:"⌢",sharp:"♯",shchcy:"щ",shcy:"ш",shortmid:"∣",shortparallel:"∥",shy:"",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",sopf:"\uD835\uDD64",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",square:"□",squarf:"▪",squf:"▪",srarr:"→",sscr:"\uD835\uDCC8",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",subE:"⫅",subdot:"⪽",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",sum:"∑",sung:"♪",sup1:"¹",sup2:"²",sup3:"³",sup:"⊃",supE:"⫆",supdot:"⪾",supdsub:"⫘",supe:"⊇",supedot:"⫄",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swArr:"⇙",swarhk:"⤦",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",target:"⌖",tau:"τ",tbrk:"⎴",tcaron:"ť",tcedil:"ţ",tcy:"т",tdot:"⃛",telrec:"⌕",tfr:"\uD835\uDD31",there4:"∴",therefore:"∴",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",thinsp:" ",thkap:"≈",thksim:"∼",thorn:"þ",tilde:"˜",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",topf:"\uD835\uDD65",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",tscr:"\uD835\uDCC9",tscy:"ц",tshcy:"ћ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",uArr:"⇑",uHar:"⥣",uacute:"ú",uarr:"↑",ubrcy:"ў",ubreve:"ŭ",ucirc:"û",ucy:"у",udarr:"⇅",udblac:"ű",udhar:"⥮",ufisht:"⥾",ufr:"\uD835\uDD32",ugrave:"ù",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",umacr:"ū",uml:"¨",uogon:"ų",uopf:"\uD835\uDD66",uparrow:"↑",updownarrow:"↕",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",upsi:"υ",upsih:"ϒ",upsilon:"υ",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",uring:"ů",urtri:"◹",uscr:"\uD835\uDCCA",utdot:"⋰",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",uuml:"ü",uwangle:"⦧",vArr:"⇕",vBar:"⫨",vBarv:"⫩",vDash:"⊨",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vcy:"в",vdash:"⊢",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",verbar:"|",vert:"|",vfr:"\uD835\uDD33",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",vopf:"\uD835\uDD67",vprop:"∝",vrtri:"⊳",vscr:"\uD835\uDCCB",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",vzigzag:"⦚",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",wedgeq:"≙",weierp:"℘",wfr:"\uD835\uDD34",wopf:"\uD835\uDD68",wp:"℘",wr:"≀",wreath:"≀",wscr:"\uD835\uDCCC",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",xfr:"\uD835\uDD35",xhArr:"⟺",xharr:"⟷",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",xopf:"\uD835\uDD69",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",xscr:"\uD835\uDCCD",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",yacute:"ý",yacy:"я",ycirc:"ŷ",ycy:"ы",yen:"¥",yfr:"\uD835\uDD36",yicy:"ї",yopf:"\uD835\uDD6A",yscr:"\uD835\uDCCE",yucy:"ю",yuml:"ÿ",zacute:"ź",zcaron:"ž",zcy:"з",zdot:"ż",zeetrf:"ℨ",zeta:"ζ",zfr:"\uD835\uDD37",zhcy:"ж",zigrarr:"⇝",zopf:"\uD835\uDD6B",zscr:"\uD835\uDCCF",zwj:"",zwnj:""};var hz9={}.hasOwnProperty;function YS(J){return hz9.call($m1,J)?$m1[J]:!1}function P7(J,Q,Z,X){let Y=J.length,K=0,G;if(Q<0)Q=-Q>Y?0:Y+Q;else Q=Q>Y?Y:Q;if(Z=Z>0?Z:0,X.length<1e4)G=Array.from(X),G.unshift(Q,Z),J.splice(...G);else{if(Z)J.splice(Q,Z);while(K<X.length)G=X.slice(K,K+1e4),G.unshift(Q,0),J.splice(...G),K+=1e4,Q+=1e4}}function LZ(J,Q){if(J.length>0)return P7(J,J.length,0,Q),J;return Q}var JU6={}.hasOwnProperty;function KQ1(J){let Q={},Z=-1;while(++Z<J.length)gz9(Q,J[Z]);return Q}function gz9(J,Q){let Z;for(Z in Q){let Y=(JU6.call(J,Z)?J[Z]:void 0)||(J[Z]={}),K=Q[Z],G;if(K)for(G in K){if(!JU6.call(Y,G))Y[G]=[];let q=K[G];mz9(Y[G],Array.isArray(q)?q:q?[q]:[])}}}function mz9(J,Q){let Z=-1,X=[];while(++Z<Q.length)(Q[Z].add==="after"?J:X).push(Q[Z]);P7(J,0,0,X)}function GQ1(J,Q){let Z=Number.parseInt(J,Q);if(Z<9||Z===11||Z>13&&Z<32||Z>126&&Z<160||Z>55295&&Z<57344||Z>64975&&Z<65008||(Z&65535)===65535||(Z&65535)===65534||Z>1114111)return"�";return String.fromCodePoint(Z)}function OQ(J){return J.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var T5=$N(/[A-Za-z]/),C5=$N(/[\dA-Za-z]/),QU6=$N(/[#-'*+\--9=?A-Z^-~]/);function uR(J){return J!==null&&(J<32||J===127)}var Vd=$N(/\d/),ZU6=$N(/[\dA-Fa-f]/),XU6=$N(/[!-/:-@[-`{-~]/);function D6(J){return J!==null&&J<-2}function R9(J){return J!==null&&(J<0||J===32)}function F8(J){return J===-2||J===-1||J===32}var pR=$N(/\p{P}|\p{S}/u),FW=$N(/\s/);function $N(J){return Q;function Q(Z){return Z!==null&&Z>-1&&J.test(String.fromCharCode(Z))}}function G8(J,Q,Z,X){let Y=X?X-1:Number.POSITIVE_INFINITY,K=0;return G;function G(z){if(F8(z))return J.enter(Z),q(z);return Q(z)}function q(z){if(F8(z)&&K++<Y)return J.consume(z),q;return J.exit(Z),Q(z)}}var YU6={tokenize:uz9};function uz9(J){let Q=J.attempt(this.parser.constructs.contentInitial,X,Y),Z;return Q;function X(q){if(q===null){J.consume(q);return}return J.enter("lineEnding"),J.consume(q),J.exit("lineEnding"),G8(J,Q,"linePrefix")}function Y(q){return J.enter("paragraph"),K(q)}function K(q){let z=J.enter("chunkText",{contentType:"text",previous:Z});if(Z)Z.next=z;return Z=z,G(q)}function G(q){if(q===null){J.exit("chunkText"),J.exit("paragraph"),J.consume(q);return}if(D6(q))return J.consume(q),J.exit("chunkText"),K;return J.consume(q),G}}var GU6={tokenize:pz9},KU6={tokenize:dz9};function pz9(J){let Q=this,Z=[],X=0,Y,K,G;return q;function q(w){if(X<Z.length){let R=Z[X];return Q.containerState=R[1],J.attempt(R[0].continuation,z,U)(w)}return U(w)}function z(w){if(X++,Q.containerState._closeFlow){if(Q.containerState._closeFlow=void 0,Y)A();let R=Q.events.length,O=R,$;while(O--)if(Q.events[O][0]==="exit"&&Q.events[O][1].type==="chunkFlow"){$=Q.events[O][1].end;break}L(X);let j=R;while(j<Q.events.length)Q.events[j][1].end={...$},j++;return P7(Q.events,O+1,0,Q.events.slice(R)),Q.events.length=j,U(w)}return q(w)}function U(w){if(X===Z.length){if(!Y)return H(w);if(Y.currentConstruct&&Y.currentConstruct.concrete)return M(w);Q.interrupt=Boolean(Y.currentConstruct&&!Y._gfmTableDynamicInterruptHack)}return Q.containerState={},J.check(KU6,W,F)(w)}function W(w){if(Y)A();return L(X),H(w)}function F(w){return Q.parser.lazy[Q.now().line]=X!==Z.length,G=Q.now().offset,M(w)}function H(w){return Q.containerState={},J.attempt(KU6,B,M)(w)}function B(w){return X++,Z.push([Q.currentConstruct,Q.containerState]),H(w)}function M(w){if(w===null){if(Y)A();L(0),J.consume(w);return}return Y=Y||Q.parser.flow(Q.now()),J.enter("chunkFlow",{_tokenizer:Y,contentType:"flow",previous:K}),V(w)}function V(w){if(w===null){N(J.exit("chunkFlow"),!0),L(0),J.consume(w);return}if(D6(w))return J.consume(w),N(J.exit("chunkFlow")),X=0,Q.interrupt=void 0,q;return J.consume(w),V}function N(w,R){let O=Q.sliceStream(w);if(R)O.push(null);if(w.previous=K,K)K.next=w;if(K=w,Y.defineSkip(w.start),Y.write(O),Q.parser.lazy[w.start.line]){let $=Y.events.length;while($--)if(Y.events[$][1].start.offset<G&&(!Y.events[$][1].end||Y.events[$][1].end.offset>G))return;let j=Q.events.length,E=j,I,T;while(E--)if(Q.events[E][0]==="exit"&&Q.events[E][1].type==="chunkFlow"){if(I){T=Q.events[E][1].end;break}I=!0}L(X),$=j;while($<Q.events.length)Q.events[$][1].end={...T},$++;P7(Q.events,E+1,0,Q.events.slice(j)),Q.events.length=$}}function L(w){let R=Z.length;while(R-- >w){let O=Z[R];Q.containerState=O[1],O[0].exit.call(Q,J)}Z.length=w}function A(){Y.write([null]),K=void 0,Y=void 0,Q.containerState._closeFlow=void 0}}function dz9(J,Q,Z){return G8(J,J.attempt(this.parser.constructs.document,Q,Z),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function zB(J){if(J===null||R9(J)||FW(J))return 1;if(pR(J))return 2}function EN(J,Q,Z){let X=[],Y=-1;while(++Y<J.length){let K=J[Y].resolveAll;if(K&&!X.includes(K))Q=K(Q,Z),X.push(K)}return Q}var Nd={name:"attention",resolveAll:cz9,tokenize:lz9};function cz9(J,Q){let Z=-1,X,Y,K,G,q,z,U,W;while(++Z<J.length)if(J[Z][0]==="enter"&&J[Z][1].type==="attentionSequence"&&J[Z][1]._close){X=Z;while(X--)if(J[X][0]==="exit"&&J[X][1].type==="attentionSequence"&&J[X][1]._open&&Q.sliceSerialize(J[X][1]).charCodeAt(0)===Q.sliceSerialize(J[Z][1]).charCodeAt(0)){if((J[X][1]._close||J[Z][1]._open)&&(J[Z][1].end.offset-J[Z][1].start.offset)%3&&!((J[X][1].end.offset-J[X][1].start.offset+J[Z][1].end.offset-J[Z][1].start.offset)%3))continue;z=J[X][1].end.offset-J[X][1].start.offset>1&&J[Z][1].end.offset-J[Z][1].start.offset>1?2:1;let F={...J[X][1].end},H={...J[Z][1].start};if(qU6(F,-z),qU6(H,z),G={type:z>1?"strongSequence":"emphasisSequence",start:F,end:{...J[X][1].end}},q={type:z>1?"strongSequence":"emphasisSequence",start:{...J[Z][1].start},end:H},K={type:z>1?"strongText":"emphasisText",start:{...J[X][1].end},end:{...J[Z][1].start}},Y={type:z>1?"strong":"emphasis",start:{...G.start},end:{...q.end}},J[X][1].end={...G.start},J[Z][1].start={...q.end},U=[],J[X][1].end.offset-J[X][1].start.offset)U=LZ(U,[["enter",J[X][1],Q],["exit",J[X][1],Q]]);if(U=LZ(U,[["enter",Y,Q],["enter",G,Q],["exit",G,Q],["enter",K,Q]]),U=LZ(U,EN(Q.parser.constructs.insideSpan.null,J.slice(X+1,Z),Q)),U=LZ(U,[["exit",K,Q],["enter",q,Q],["exit",q,Q],["exit",Y,Q]]),J[Z][1].end.offset-J[Z][1].start.offset)W=2,U=LZ(U,[["enter",J[Z][1],Q],["exit",J[Z][1],Q]]);else W=0;P7(J,X-1,Z-X+3,U),Z=X+U.length-W-2;break}}Z=-1;while(++Z<J.length)if(J[Z][1].type==="attentionSequence")J[Z][1].type="data";return J}function lz9(J,Q){let Z=this.parser.constructs.attentionMarkers.null,X=this.previous,Y=zB(X),K;return G;function G(z){return K=z,J.enter("attentionSequence"),q(z)}function q(z){if(z===K)return J.consume(z),q;let U=J.exit("attentionSequence"),W=zB(z),F=!W||W===2&&Y||Z.includes(z),H=!Y||Y===2&&W||Z.includes(X);return U._open=Boolean(K===42?F:F&&(Y||!H)),U._close=Boolean(K===42?H:H&&(W||!F)),Q(z)}}function qU6(J,Q){J.column+=Q,J.offset+=Q,J._bufferIndex+=Q}var Em1={name:"autolink",tokenize:iz9};function iz9(J,Q,Z){let X=0;return Y;function Y(B){return J.enter("autolink"),J.enter("autolinkMarker"),J.consume(B),J.exit("autolinkMarker"),J.enter("autolinkProtocol"),K}function K(B){if(T5(B))return J.consume(B),G;if(B===64)return Z(B);return U(B)}function G(B){if(B===43||B===45||B===46||C5(B))return X=1,q(B);return U(B)}function q(B){if(B===58)return J.consume(B),X=0,z;if((B===43||B===45||B===46||C5(B))&&X++<32)return J.consume(B),q;return X=0,U(B)}function z(B){if(B===62)return J.exit("autolinkProtocol"),J.enter("autolinkMarker"),J.consume(B),J.exit("autolinkMarker"),J.exit("autolink"),Q;if(B===null||B===32||B===60||uR(B))return Z(B);return J.consume(B),z}function U(B){if(B===64)return J.consume(B),W;if(QU6(B))return J.consume(B),U;return Z(B)}function W(B){return C5(B)?F(B):Z(B)}function F(B){if(B===46)return J.consume(B),X=0,W;if(B===62)return J.exit("autolinkProtocol").type="autolinkEmail",J.enter("autolinkMarker"),J.consume(B),J.exit("autolinkMarker"),J.exit("autolink"),Q;return H(B)}function H(B){if((B===45||C5(B))&&X++<63){let M=B===45?H:F;return J.consume(B),M}return Z(B)}}var HW={partial:!0,tokenize:nz9};function nz9(J,Q,Z){return X;function X(K){return F8(K)?G8(J,Y,"linePrefix")(K):Y(K)}function Y(K){return K===null||D6(K)?Q(K):Z(K)}}var qQ1={continuation:{tokenize:rz9},exit:sz9,name:"blockQuote",tokenize:az9};function az9(J,Q,Z){let X=this;return Y;function Y(G){if(G===62){let q=X.containerState;if(!q.open)J.enter("blockQuote",{_container:!0}),q.open=!0;return J.enter("blockQuotePrefix"),J.enter("blockQuoteMarker"),J.consume(G),J.exit("blockQuoteMarker"),K}return Z(G)}function K(G){if(F8(G))return J.enter("blockQuotePrefixWhitespace"),J.consume(G),J.exit("blockQuotePrefixWhitespace"),J.exit("blockQuotePrefix"),Q;return J.exit("blockQuotePrefix"),Q(G)}}function rz9(J,Q,Z){let X=this;return Y;function Y(G){if(F8(G))return G8(J,K,"linePrefix",X.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(G);return K(G)}function K(G){return J.attempt(qQ1,Q,Z)(G)}}function sz9(J){J.exit("blockQuote")}var zQ1={name:"characterEscape",tokenize:oz9};function oz9(J,Q,Z){return X;function X(K){return J.enter("characterEscape"),J.enter("escapeMarker"),J.consume(K),J.exit("escapeMarker"),Y}function Y(K){if(XU6(K))return J.enter("characterEscapeValue"),J.consume(K),J.exit("characterEscapeValue"),J.exit("characterEscape"),Q;return Z(K)}}var UQ1={name:"characterReference",tokenize:tz9};function tz9(J,Q,Z){let X=this,Y=0,K,G;return q;function q(F){return J.enter("characterReference"),J.enter("characterReferenceMarker"),J.consume(F),J.exit("characterReferenceMarker"),z}function z(F){if(F===35)return J.enter("characterReferenceMarkerNumeric"),J.consume(F),J.exit("characterReferenceMarkerNumeric"),U;return J.enter("characterReferenceValue"),K=31,G=C5,W(F)}function U(F){if(F===88||F===120)return J.enter("characterReferenceMarkerHexadecimal"),J.consume(F),J.exit("characterReferenceMarkerHexadecimal"),J.enter("characterReferenceValue"),K=6,G=ZU6,W;return J.enter("characterReferenceValue"),K=7,G=Vd,W(F)}function W(F){if(F===59&&Y){let H=J.exit("characterReferenceValue");if(G===C5&&!YS(X.sliceSerialize(H)))return Z(F);return J.enter("characterReferenceMarker"),J.consume(F),J.exit("characterReferenceMarker"),J.exit("characterReference"),Q}if(G(F)&&Y++<K)return J.consume(F),W;return Z(F)}}var zU6={partial:!0,tokenize:JU9},WQ1={concrete:!0,name:"codeFenced",tokenize:ez9};function ez9(J,Q,Z){let X=this,Y={partial:!0,tokenize:O},K=0,G=0,q;return z;function z($){return U($)}function U($){let j=X.events[X.events.length-1];return K=j&&j[1].type==="linePrefix"?j[2].sliceSerialize(j[1],!0).length:0,q=$,J.enter("codeFenced"),J.enter("codeFencedFence"),J.enter("codeFencedFenceSequence"),W($)}function W($){if($===q)return G++,J.consume($),W;if(G<3)return Z($);return J.exit("codeFencedFenceSequence"),F8($)?G8(J,F,"whitespace")($):F($)}function F($){if($===null||D6($))return J.exit("codeFencedFence"),X.interrupt?Q($):J.check(zU6,V,R)($);return J.enter("codeFencedFenceInfo"),J.enter("chunkString",{contentType:"string"}),H($)}function H($){if($===null||D6($))return J.exit("chunkString"),J.exit("codeFencedFenceInfo"),F($);if(F8($))return J.exit("chunkString"),J.exit("codeFencedFenceInfo"),G8(J,B,"whitespace")($);if($===96&&$===q)return Z($);return J.consume($),H}function B($){if($===null||D6($))return F($);return J.enter("codeFencedFenceMeta"),J.enter("chunkString",{contentType:"string"}),M($)}function M($){if($===null||D6($))return J.exit("chunkString"),J.exit("codeFencedFenceMeta"),F($);if($===96&&$===q)return Z($);return J.consume($),M}function V($){return J.attempt(Y,R,N)($)}function N($){return J.enter("lineEnding"),J.consume($),J.exit("lineEnding"),L}function L($){return K>0&&F8($)?G8(J,A,"linePrefix",K+1)($):A($)}function A($){if($===null||D6($))return J.check(zU6,V,R)($);return J.enter("codeFlowValue"),w($)}function w($){if($===null||D6($))return J.exit("codeFlowValue"),A($);return J.consume($),w}function R($){return J.exit("codeFenced"),Q($)}function O($,j,E){let I=0;return T;function T(x){return $.enter("lineEnding"),$.consume(x),$.exit("lineEnding"),S}function S(x){return $.enter("codeFencedFence"),F8(x)?G8($,_,"linePrefix",X.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):_(x)}function _(x){if(x===q)return $.enter("codeFencedFenceSequence"),h(x);return E(x)}function h(x){if(x===q)return I++,$.consume(x),h;if(I>=G)return $.exit("codeFencedFenceSequence"),F8(x)?G8($,v,"whitespace")(x):v(x);return E(x)}function v(x){if(x===null||D6(x))return $.exit("codeFencedFence"),j(x);return E(x)}}}function JU9(J,Q,Z){let X=this;return Y;function Y(G){if(G===null)return Z(G);return J.enter("lineEnding"),J.consume(G),J.exit("lineEnding"),K}function K(G){return X.parser.lazy[X.now().line]?Z(G):Q(G)}}var Ld={name:"codeIndented",tokenize:ZU9},QU9={partial:!0,tokenize:XU9};function ZU9(J,Q,Z){let X=this;return Y;function Y(U){return J.enter("codeIndented"),G8(J,K,"linePrefix",5)(U)}function K(U){let W=X.events[X.events.length-1];return W&&W[1].type==="linePrefix"&&W[2].sliceSerialize(W[1],!0).length>=4?G(U):Z(U)}function G(U){if(U===null)return z(U);if(D6(U))return J.attempt(QU9,G,z)(U);return J.enter("codeFlowValue"),q(U)}function q(U){if(U===null||D6(U))return J.exit("codeFlowValue"),G(U);return J.consume(U),q}function z(U){return J.exit("codeIndented"),Q(U)}}function XU9(J,Q,Z){let X=this;return Y;function Y(G){if(X.parser.lazy[X.now().line])return Z(G);if(D6(G))return J.enter("lineEnding"),J.consume(G),J.exit("lineEnding"),Y;return G8(J,K,"linePrefix",5)(G)}function K(G){let q=X.events[X.events.length-1];return q&&q[1].type==="linePrefix"&&q[2].sliceSerialize(q[1],!0).length>=4?Q(G):D6(G)?Y(G):Z(G)}}var Im1={name:"codeText",previous:KU9,resolve:YU9,tokenize:GU9};function YU9(J){let Q=J.length-4,Z=3,X,Y;if((J[Z][1].type==="lineEnding"||J[Z][1].type==="space")&&(J[Q][1].type==="lineEnding"||J[Q][1].type==="space")){X=Z;while(++X<Q)if(J[X][1].type==="codeTextData"){J[Z][1].type="codeTextPadding",J[Q][1].type="codeTextPadding",Z+=2,Q-=2;break}}X=Z-1,Q++;while(++X<=Q)if(Y===void 0){if(X!==Q&&J[X][1].type!=="lineEnding")Y=X}else if(X===Q||J[X][1].type==="lineEnding"){if(J[Y][1].type="codeTextData",X!==Y+2)J[Y][1].end=J[X-1][1].end,J.splice(Y+2,X-Y-2),Q-=X-Y-2,X=Y+2;Y=void 0}return J}function KU9(J){return J!==96||this.events[this.events.length-1][1].type==="characterEscape"}function GU9(J,Q,Z){let X=this,Y=0,K,G;return q;function q(H){return J.enter("codeText"),J.enter("codeTextSequence"),z(H)}function z(H){if(H===96)return J.consume(H),Y++,z;return J.exit("codeTextSequence"),U(H)}function U(H){if(H===null)return Z(H);if(H===32)return J.enter("space"),J.consume(H),J.exit("space"),U;if(H===96)return G=J.enter("codeTextSequence"),K=0,F(H);if(D6(H))return J.enter("lineEnding"),J.consume(H),J.exit("lineEnding"),U;return J.enter("codeTextData"),W(H)}function W(H){if(H===null||H===32||H===96||D6(H))return J.exit("codeTextData"),U(H);return J.consume(H),W}function F(H){if(H===96)return J.consume(H),K++,F;if(K===Y)return J.exit("codeTextSequence"),J.exit("codeText"),Q(H);return G.type="codeTextData",W(H)}}class Pm1{constructor(J){this.left=J?[...J]:[],this.right=[]}get(J){if(J<0||J>=this.left.length+this.right.length)throw RangeError("Cannot access index `"+J+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");if(J<this.left.length)return this.left[J];return this.right[this.right.length-J+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(J,Q){let Z=Q===null||Q===void 0?Number.POSITIVE_INFINITY:Q;if(Z<this.left.length)return this.left.slice(J,Z);if(J>this.left.length)return this.right.slice(this.right.length-Z+this.left.length,this.right.length-J+this.left.length).reverse();return this.left.slice(J).concat(this.right.slice(this.right.length-Z+this.left.length).reverse())}splice(J,Q,Z){let X=Q||0;this.setCursor(Math.trunc(J));let Y=this.right.splice(this.right.length-X,Number.POSITIVE_INFINITY);if(Z)Ad(this.left,Z);return Y.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(J){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(J)}pushMany(J){this.setCursor(Number.POSITIVE_INFINITY),Ad(this.left,J)}unshift(J){this.setCursor(0),this.right.push(J)}unshiftMany(J){this.setCursor(0),Ad(this.right,J.reverse())}setCursor(J){if(J===this.left.length||J>this.left.length&&this.right.length===0||J<0&&this.left.length===0)return;if(J<this.left.length){let Q=this.left.splice(J,Number.POSITIVE_INFINITY);Ad(this.right,Q.reverse())}else{let Q=this.right.splice(this.left.length+this.right.length-J,Number.POSITIVE_INFINITY);Ad(this.left,Q.reverse())}}}function Ad(J,Q){let Z=0;if(Q.length<1e4)J.push(...Q);else while(Z<Q.length)J.push(...Q.slice(Z,Z+1e4)),Z+=1e4}function FQ1(J){let Q={},Z=-1,X,Y,K,G,q,z,U,W=new Pm1(J);while(++Z<W.length){while(Z in Q)Z=Q[Z];if(X=W.get(Z),Z&&X[1].type==="chunkFlow"&&W.get(Z-1)[1].type==="listItemPrefix"){if(z=X[1]._tokenizer.events,K=0,K<z.length&&z[K][1].type==="lineEndingBlank")K+=2;if(K<z.length&&z[K][1].type==="content")while(++K<z.length){if(z[K][1].type==="content")break;if(z[K][1].type==="chunkText")z[K][1]._isInFirstContentOfListItem=!0,K++}}if(X[0]==="enter"){if(X[1].contentType)Object.assign(Q,qU9(W,Z)),Z=Q[Z],U=!0}else if(X[1]._container){K=Z,Y=void 0;while(K--)if(G=W.get(K),G[1].type==="lineEnding"||G[1].type==="lineEndingBlank"){if(G[0]==="enter"){if(Y)W.get(Y)[1].type="lineEndingBlank";G[1].type="lineEnding",Y=K}}else if(G[1].type==="linePrefix"||G[1].type==="listItemIndent");else break;if(Y)X[1].end={...W.get(Y)[1].start},q=W.slice(Y,Z),q.unshift(X),W.splice(Y,Z-Y+1,q)}}return P7(J,0,Number.POSITIVE_INFINITY,W.slice(0)),!U}function qU9(J,Q){let Z=J.get(Q)[1],X=J.get(Q)[2],Y=Q-1,K=[],G=Z._tokenizer;if(!G){if(G=X.parser[Z.contentType](Z.start),Z._contentTypeTextTrailing)G._contentTypeTextTrailing=!0}let q=G.events,z=[],U={},W,F,H=-1,B=Z,M=0,V=0,N=[V];while(B){while(J.get(++Y)[1]!==B);if(K.push(Y),!B._tokenizer){if(W=X.sliceStream(B),!B.next)W.push(null);if(F)G.defineSkip(B.start);if(B._isInFirstContentOfListItem)G._gfmTasklistFirstContentOfListItem=!0;if(G.write(W),B._isInFirstContentOfListItem)G._gfmTasklistFirstContentOfListItem=void 0}F=B,B=B.next}B=Z;while(++H<q.length)if(q[H][0]==="exit"&&q[H-1][0]==="enter"&&q[H][1].type===q[H-1][1].type&&q[H][1].start.line!==q[H][1].end.line)V=H+1,N.push(V),B._tokenizer=void 0,B.previous=void 0,B=B.next;if(G.events=[],B)B._tokenizer=void 0,B.previous=void 0;else N.pop();H=N.length;while(H--){let L=q.slice(N[H],N[H+1]),A=K.pop();z.push([A,A+L.length-1]),J.splice(A,2,L)}z.reverse(),H=-1;while(++H<z.length)U[M+z[H][0]]=M+z[H][1],M+=z[H][1]-z[H][0]-1;return U}var Tm1={resolve:UU9,tokenize:WU9},zU9={partial:!0,tokenize:FU9};function UU9(J){return FQ1(J),J}function WU9(J,Q){let Z;return X;function X(q){return J.enter("content"),Z=J.enter("chunkContent",{contentType:"content"}),Y(q)}function Y(q){if(q===null)return K(q);if(D6(q))return J.check(zU9,G,K)(q);return J.consume(q),Y}function K(q){return J.exit("chunkContent"),J.exit("content"),Q(q)}function G(q){return J.consume(q),J.exit("chunkContent"),Z.next=J.enter("chunkContent",{contentType:"content",previous:Z}),Z=Z.next,Y}}function FU9(J,Q,Z){let X=this;return Y;function Y(G){return J.exit("chunkContent"),J.enter("lineEnding"),J.consume(G),J.exit("lineEnding"),G8(J,K,"linePrefix")}function K(G){if(G===null||D6(G))return Z(G);let q=X.events[X.events.length-1];if(!X.parser.constructs.disable.null.includes("codeIndented")&&q&&q[1].type==="linePrefix"&&q[2].sliceSerialize(q[1],!0).length>=4)return Q(G);return J.interrupt(X.parser.constructs.flow,Z,Q)(G)}}function HQ1(J,Q,Z,X,Y,K,G,q,z){let U=z||Number.POSITIVE_INFINITY,W=0;return F;function F(L){if(L===60)return J.enter(X),J.enter(Y),J.enter(K),J.consume(L),J.exit(K),H;if(L===null||L===32||L===41||uR(L))return Z(L);return J.enter(X),J.enter(G),J.enter(q),J.enter("chunkString",{contentType:"string"}),V(L)}function H(L){if(L===62)return J.enter(K),J.consume(L),J.exit(K),J.exit(Y),J.exit(X),Q;return J.enter(q),J.enter("chunkString",{contentType:"string"}),B(L)}function B(L){if(L===62)return J.exit("chunkString"),J.exit(q),H(L);if(L===null||L===60||D6(L))return Z(L);return J.consume(L),L===92?M:B}function M(L){if(L===60||L===62||L===92)return J.consume(L),B;return B(L)}function V(L){if(!W&&(L===null||L===41||R9(L)))return J.exit("chunkString"),J.exit(q),J.exit(G),J.exit(X),Q(L);if(W<U&&L===40)return J.consume(L),W++,V;if(L===41)return J.consume(L),W--,V;if(L===null||L===32||L===40||uR(L))return Z(L);return J.consume(L),L===92?N:V}function N(L){if(L===40||L===41||L===92)return J.consume(L),V;return V(L)}}function BQ1(J,Q,Z,X,Y,K){let G=this,q=0,z;return U;function U(B){return J.enter(X),J.enter(Y),J.consume(B),J.exit(Y),J.enter(K),W}function W(B){if(q>999||B===null||B===91||B===93&&!z||B===94&&!q&&"_hiddenFootnoteSupport"in G.parser.constructs)return Z(B);if(B===93)return J.exit(K),J.enter(Y),J.consume(B),J.exit(Y),J.exit(X),Q;if(D6(B))return J.enter("lineEnding"),J.consume(B),J.exit("lineEnding"),W;return J.enter("chunkString",{contentType:"string"}),F(B)}function F(B){if(B===null||B===91||B===93||D6(B)||q++>999)return J.exit("chunkString"),W(B);if(J.consume(B),!z)z=!F8(B);return B===92?H:F}function H(B){if(B===91||B===92||B===93)return J.consume(B),q++,F;return F(B)}}function DQ1(J,Q,Z,X,Y,K){let G;return q;function q(H){if(H===34||H===39||H===40)return J.enter(X),J.enter(Y),J.consume(H),J.exit(Y),G=H===40?41:H,z;return Z(H)}function z(H){if(H===G)return J.enter(Y),J.consume(H),J.exit(Y),J.exit(X),Q;return J.enter(K),U(H)}function U(H){if(H===G)return J.exit(K),z(G);if(H===null)return Z(H);if(D6(H))return J.enter("lineEnding"),J.consume(H),J.exit("lineEnding"),G8(J,U,"linePrefix");return J.enter("chunkString",{contentType:"string"}),W(H)}function W(H){if(H===G||H===null||D6(H))return J.exit("chunkString"),U(H);return J.consume(H),H===92?F:W}function F(H){if(H===G||H===92)return J.consume(H),W;return W(H)}}function dR(J,Q){let Z;return X;function X(Y){if(D6(Y))return J.enter("lineEnding"),J.consume(Y),J.exit("lineEnding"),Z=!0,X;if(F8(Y))return G8(J,X,Z?"linePrefix":"lineSuffix")(Y);return Q(Y)}}var Cm1={name:"definition",tokenize:BU9},HU9={partial:!0,tokenize:DU9};function BU9(J,Q,Z){let X=this,Y;return K;function K(B){return J.enter("definition"),G(B)}function G(B){return BQ1.call(X,J,q,Z,"definitionLabel","definitionLabelMarker","definitionLabelString")(B)}function q(B){if(Y=OQ(X.sliceSerialize(X.events[X.events.length-1][1]).slice(1,-1)),B===58)return J.enter("definitionMarker"),J.consume(B),J.exit("definitionMarker"),z;return Z(B)}function z(B){return R9(B)?dR(J,U)(B):U(B)}function U(B){return HQ1(J,W,Z,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(B)}function W(B){return J.attempt(HU9,F,F)(B)}function F(B){return F8(B)?G8(J,H,"whitespace")(B):H(B)}function H(B){if(B===null||D6(B))return J.exit("definition"),X.parser.defined.push(Y),Q(B);return Z(B)}}function DU9(J,Q,Z){return X;function X(q){return R9(q)?dR(J,Y)(q):Z(q)}function Y(q){return DQ1(J,K,Z,"definitionTitle","definitionTitleMarker","definitionTitleString")(q)}function K(q){return F8(q)?G8(J,G,"whitespace")(q):G(q)}function G(q){return q===null||D6(q)?Q(q):Z(q)}}var Sm1={name:"hardBreakEscape",tokenize:MU9};function MU9(J,Q,Z){return X;function X(K){return J.enter("hardBreakEscape"),J.consume(K),Y}function Y(K){if(D6(K))return J.exit("hardBreakEscape"),Q(K);return Z(K)}}var vm1={name:"headingAtx",resolve:VU9,tokenize:NU9};function VU9(J,Q){let Z=J.length-2,X=3,Y,K;if(J[X][1].type==="whitespace")X+=2;if(Z-2>X&&J[Z][1].type==="whitespace")Z-=2;if(J[Z][1].type==="atxHeadingSequence"&&(X===Z-1||Z-4>X&&J[Z-2][1].type==="whitespace"))Z-=X+1===Z?2:4;if(Z>X)Y={type:"atxHeadingText",start:J[X][1].start,end:J[Z][1].end},K={type:"chunkText",start:J[X][1].start,end:J[Z][1].end,contentType:"text"},P7(J,X,Z-X+1,[["enter",Y,Q],["enter",K,Q],["exit",K,Q],["exit",Y,Q]]);return J}function NU9(J,Q,Z){let X=0;return Y;function Y(W){return J.enter("atxHeading"),K(W)}function K(W){return J.enter("atxHeadingSequence"),G(W)}function G(W){if(W===35&&X++<6)return J.consume(W),G;if(W===null||R9(W))return J.exit("atxHeadingSequence"),q(W);return Z(W)}function q(W){if(W===35)return J.enter("atxHeadingSequence"),z(W);if(W===null||D6(W))return J.exit("atxHeading"),Q(W);if(F8(W))return G8(J,q,"whitespace")(W);return J.enter("atxHeadingText"),U(W)}function z(W){if(W===35)return J.consume(W),z;return J.exit("atxHeadingSequence"),q(W)}function U(W){if(W===null||W===35||R9(W))return J.exit("atxHeadingText"),q(W);return J.consume(W),U}}var UU6=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],km1=["pre","script","style","textarea"];var _m1={concrete:!0,name:"htmlFlow",resolveTo:wU9,tokenize:RU9},LU9={partial:!0,tokenize:jU9},AU9={partial:!0,tokenize:OU9};function wU9(J){let Q=J.length;while(Q--)if(J[Q][0]==="enter"&&J[Q][1].type==="htmlFlow")break;if(Q>1&&J[Q-2][1].type==="linePrefix")J[Q][1].start=J[Q-2][1].start,J[Q+1][1].start=J[Q-2][1].start,J.splice(Q-2,2);return J}function RU9(J,Q,Z){let X=this,Y,K,G,q,z;return U;function U(p){return W(p)}function W(p){return J.enter("htmlFlow"),J.enter("htmlFlowData"),J.consume(p),F}function F(p){if(p===33)return J.consume(p),H;if(p===47)return J.consume(p),K=!0,V;if(p===63)return J.consume(p),Y=3,X.interrupt?Q:b;if(T5(p))return J.consume(p),G=String.fromCharCode(p),N;return Z(p)}function H(p){if(p===45)return J.consume(p),Y=2,B;if(p===91)return J.consume(p),Y=5,q=0,M;if(T5(p))return J.consume(p),Y=4,X.interrupt?Q:b;return Z(p)}function B(p){if(p===45)return J.consume(p),X.interrupt?Q:b;return Z(p)}function M(p){if(p==="CDATA[".charCodeAt(q++)){if(J.consume(p),q===6)return X.interrupt?Q:_;return M}return Z(p)}function V(p){if(T5(p))return J.consume(p),G=String.fromCharCode(p),N;return Z(p)}function N(p){if(p===null||p===47||p===62||R9(p)){let e=p===47,G1=G.toLowerCase();if(!e&&!K&&km1.includes(G1))return Y=1,X.interrupt?Q(p):_(p);if(UU6.includes(G.toLowerCase())){if(Y=6,e)return J.consume(p),L;return X.interrupt?Q(p):_(p)}return Y=7,X.interrupt&&!X.parser.lazy[X.now().line]?Z(p):K?A(p):w(p)}if(p===45||C5(p))return J.consume(p),G+=String.fromCharCode(p),N;return Z(p)}function L(p){if(p===62)return J.consume(p),X.interrupt?Q:_;return Z(p)}function A(p){if(F8(p))return J.consume(p),A;return T(p)}function w(p){if(p===47)return J.consume(p),T;if(p===58||p===95||T5(p))return J.consume(p),R;if(F8(p))return J.consume(p),w;return T(p)}function R(p){if(p===45||p===46||p===58||p===95||C5(p))return J.consume(p),R;return O(p)}function O(p){if(p===61)return J.consume(p),$;if(F8(p))return J.consume(p),O;return w(p)}function $(p){if(p===null||p===60||p===61||p===62||p===96)return Z(p);if(p===34||p===39)return J.consume(p),z=p,j;if(F8(p))return J.consume(p),$;return E(p)}function j(p){if(p===z)return J.consume(p),z=null,I;if(p===null||D6(p))return Z(p);return J.consume(p),j}function E(p){if(p===null||p===34||p===39||p===47||p===60||p===61||p===62||p===96||R9(p))return O(p);return J.consume(p),E}function I(p){if(p===47||p===62||F8(p))return w(p);return Z(p)}function T(p){if(p===62)return J.consume(p),S;return Z(p)}function S(p){if(p===null||D6(p))return _(p);if(F8(p))return J.consume(p),S;return Z(p)}function _(p){if(p===45&&Y===2)return J.consume(p),y;if(p===60&&Y===1)return J.consume(p),g;if(p===62&&Y===4)return J.consume(p),m;if(p===63&&Y===3)return J.consume(p),b;if(p===93&&Y===5)return J.consume(p),f;if(D6(p)&&(Y===6||Y===7))return J.exit("htmlFlowData"),J.check(LU9,n,h)(p);if(p===null||D6(p))return J.exit("htmlFlowData"),h(p);return J.consume(p),_}function h(p){return J.check(AU9,v,n)(p)}function v(p){return J.enter("lineEnding"),J.consume(p),J.exit("lineEnding"),x}function x(p){if(p===null||D6(p))return h(p);return J.enter("htmlFlowData"),_(p)}function y(p){if(p===45)return J.consume(p),b;return _(p)}function g(p){if(p===47)return J.consume(p),G="",k;return _(p)}function k(p){if(p===62){let e=G.toLowerCase();if(km1.includes(e))return J.consume(p),m;return _(p)}if(T5(p)&&G.length<8)return J.consume(p),G+=String.fromCharCode(p),k;return _(p)}function f(p){if(p===93)return J.consume(p),b;return _(p)}function b(p){if(p===62)return J.consume(p),m;if(p===45&&Y===2)return J.consume(p),b;return _(p)}function m(p){if(p===null||D6(p))return J.exit("htmlFlowData"),n(p);return J.consume(p),m}function n(p){return J.exit("htmlFlow"),Q(p)}}function OU9(J,Q,Z){let X=this;return Y;function Y(G){if(D6(G))return J.enter("lineEnding"),J.consume(G),J.exit("lineEnding"),K;return Z(G)}function K(G){return X.parser.lazy[X.now().line]?Z(G):Q(G)}}function jU9(J,Q,Z){return X;function X(Y){return J.enter("lineEnding"),J.consume(Y),J.exit("lineEnding"),J.attempt(HW,Q,Z)}}var xm1={name:"htmlText",tokenize:$U9};function $U9(J,Q,Z){let X=this,Y,K,G;return q;function q(b){return J.enter("htmlText"),J.enter("htmlTextData"),J.consume(b),z}function z(b){if(b===33)return J.consume(b),U;if(b===47)return J.consume(b),O;if(b===63)return J.consume(b),w;if(T5(b))return J.consume(b),E;return Z(b)}function U(b){if(b===45)return J.consume(b),W;if(b===91)return J.consume(b),K=0,M;if(T5(b))return J.consume(b),A;return Z(b)}function W(b){if(b===45)return J.consume(b),B;return Z(b)}function F(b){if(b===null)return Z(b);if(b===45)return J.consume(b),H;if(D6(b))return G=F,g(b);return J.consume(b),F}function H(b){if(b===45)return J.consume(b),B;return F(b)}function B(b){return b===62?y(b):b===45?H(b):F(b)}function M(b){if(b==="CDATA[".charCodeAt(K++))return J.consume(b),K===6?V:M;return Z(b)}function V(b){if(b===null)return Z(b);if(b===93)return J.consume(b),N;if(D6(b))return G=V,g(b);return J.consume(b),V}function N(b){if(b===93)return J.consume(b),L;return V(b)}function L(b){if(b===62)return y(b);if(b===93)return J.consume(b),L;return V(b)}function A(b){if(b===null||b===62)return y(b);if(D6(b))return G=A,g(b);return J.consume(b),A}function w(b){if(b===null)return Z(b);if(b===63)return J.consume(b),R;if(D6(b))return G=w,g(b);return J.consume(b),w}function R(b){return b===62?y(b):w(b)}function O(b){if(T5(b))return J.consume(b),$;return Z(b)}function $(b){if(b===45||C5(b))return J.consume(b),$;return j(b)}function j(b){if(D6(b))return G=j,g(b);if(F8(b))return J.consume(b),j;return y(b)}function E(b){if(b===45||C5(b))return J.consume(b),E;if(b===47||b===62||R9(b))return I(b);return Z(b)}function I(b){if(b===47)return J.consume(b),y;if(b===58||b===95||T5(b))return J.consume(b),T;if(D6(b))return G=I,g(b);if(F8(b))return J.consume(b),I;return y(b)}function T(b){if(b===45||b===46||b===58||b===95||C5(b))return J.consume(b),T;return S(b)}function S(b){if(b===61)return J.consume(b),_;if(D6(b))return G=S,g(b);if(F8(b))return J.consume(b),S;return I(b)}function _(b){if(b===null||b===60||b===61||b===62||b===96)return Z(b);if(b===34||b===39)return J.consume(b),Y=b,h;if(D6(b))return G=_,g(b);if(F8(b))return J.consume(b),_;return J.consume(b),v}function h(b){if(b===Y)return J.consume(b),Y=void 0,x;if(b===null)return Z(b);if(D6(b))return G=h,g(b);return J.consume(b),h}function v(b){if(b===null||b===34||b===39||b===60||b===61||b===96)return Z(b);if(b===47||b===62||R9(b))return I(b);return J.consume(b),v}function x(b){if(b===47||b===62||R9(b))return I(b);return Z(b)}function y(b){if(b===62)return J.consume(b),J.exit("htmlTextData"),J.exit("htmlText"),Q;return Z(b)}function g(b){return J.exit("htmlTextData"),J.enter("lineEnding"),J.consume(b),J.exit("lineEnding"),k}function k(b){return F8(b)?G8(J,f,"linePrefix",X.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(b):f(b)}function f(b){return J.enter("htmlTextData"),G(b)}}var cR={name:"labelEnd",resolveAll:TU9,resolveTo:CU9,tokenize:SU9},EU9={tokenize:vU9},IU9={tokenize:kU9},PU9={tokenize:_U9};function TU9(J){let Q=-1,Z=[];while(++Q<J.length){let X=J[Q][1];if(Z.push(J[Q]),X.type==="labelImage"||X.type==="labelLink"||X.type==="labelEnd"){let Y=X.type==="labelImage"?4:2;X.type="data",Q+=Y}}if(J.length!==Z.length)P7(J,0,J.length,Z);return J}function CU9(J,Q){let Z=J.length,X=0,Y,K,G,q;while(Z--)if(Y=J[Z][1],K){if(Y.type==="link"||Y.type==="labelLink"&&Y._inactive)break;if(J[Z][0]==="enter"&&Y.type==="labelLink")Y._inactive=!0}else if(G){if(J[Z][0]==="enter"&&(Y.type==="labelImage"||Y.type==="labelLink")&&!Y._balanced){if(K=Z,Y.type!=="labelLink"){X=2;break}}}else if(Y.type==="labelEnd")G=Z;let z={type:J[K][1].type==="labelLink"?"link":"image",start:{...J[K][1].start},end:{...J[J.length-1][1].end}},U={type:"label",start:{...J[K][1].start},end:{...J[G][1].end}},W={type:"labelText",start:{...J[K+X+2][1].end},end:{...J[G-2][1].start}};return q=[["enter",z,Q],["enter",U,Q]],q=LZ(q,J.slice(K+1,K+X+3)),q=LZ(q,[["enter",W,Q]]),q=LZ(q,EN(Q.parser.constructs.insideSpan.null,J.slice(K+X+4,G-3),Q)),q=LZ(q,[["exit",W,Q],J[G-2],J[G-1],["exit",U,Q]]),q=LZ(q,J.slice(G+1)),q=LZ(q,[["exit",z,Q]]),P7(J,K,J.length,q),J}function SU9(J,Q,Z){let X=this,Y=X.events.length,K,G;while(Y--)if((X.events[Y][1].type==="labelImage"||X.events[Y][1].type==="labelLink")&&!X.events[Y][1]._balanced){K=X.events[Y][1];break}return q;function q(H){if(!K)return Z(H);if(K._inactive)return F(H);return G=X.parser.defined.includes(OQ(X.sliceSerialize({start:K.end,end:X.now()}))),J.enter("labelEnd"),J.enter("labelMarker"),J.consume(H),J.exit("labelMarker"),J.exit("labelEnd"),z}function z(H){if(H===40)return J.attempt(EU9,W,G?W:F)(H);if(H===91)return J.attempt(IU9,W,G?U:F)(H);return G?W(H):F(H)}function U(H){return J.attempt(PU9,W,F)(H)}function W(H){return Q(H)}function F(H){return K._balanced=!0,Z(H)}}function vU9(J,Q,Z){return X;function X(F){return J.enter("resource"),J.enter("resourceMarker"),J.consume(F),J.exit("resourceMarker"),Y}function Y(F){return R9(F)?dR(J,K)(F):K(F)}function K(F){if(F===41)return W(F);return HQ1(J,G,q,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(F)}function G(F){return R9(F)?dR(J,z)(F):W(F)}function q(F){return Z(F)}function z(F){if(F===34||F===39||F===40)return DQ1(J,U,Z,"resourceTitle","resourceTitleMarker","resourceTitleString")(F);return W(F)}function U(F){return R9(F)?dR(J,W)(F):W(F)}function W(F){if(F===41)return J.enter("resourceMarker"),J.consume(F),J.exit("resourceMarker"),J.exit("resource"),Q;return Z(F)}}function kU9(J,Q,Z){let X=this;return Y;function Y(q){return BQ1.call(X,J,K,G,"reference","referenceMarker","referenceString")(q)}function K(q){return X.parser.defined.includes(OQ(X.sliceSerialize(X.events[X.events.length-1][1]).slice(1,-1)))?Q(q):Z(q)}function G(q){return Z(q)}}function _U9(J,Q,Z){return X;function X(K){return J.enter("reference"),J.enter("referenceMarker"),J.consume(K),J.exit("referenceMarker"),Y}function Y(K){if(K===93)return J.enter("referenceMarker"),J.consume(K),J.exit("referenceMarker"),J.exit("reference"),Q;return Z(K)}}var bm1={name:"labelStartImage",resolveAll:cR.resolveAll,tokenize:xU9};function xU9(J,Q,Z){let X=this;return Y;function Y(q){return J.enter("labelImage"),J.enter("labelImageMarker"),J.consume(q),J.exit("labelImageMarker"),K}function K(q){if(q===91)return J.enter("labelMarker"),J.consume(q),J.exit("labelMarker"),J.exit("labelImage"),G;return Z(q)}function G(q){return q===94&&"_hiddenFootnoteSupport"in X.parser.constructs?Z(q):Q(q)}}var ym1={name:"labelStartLink",resolveAll:cR.resolveAll,tokenize:bU9};function bU9(J,Q,Z){let X=this;return Y;function Y(G){return J.enter("labelLink"),J.enter("labelMarker"),J.consume(G),J.exit("labelMarker"),J.exit("labelLink"),K}function K(G){return G===94&&"_hiddenFootnoteSupport"in X.parser.constructs?Z(G):Q(G)}}var wd={name:"lineEnding",tokenize:yU9};function yU9(J,Q){return Z;function Z(X){return J.enter("lineEnding"),J.consume(X),J.exit("lineEnding"),G8(J,Q,"linePrefix")}}var lR={name:"thematicBreak",tokenize:fU9};function fU9(J,Q,Z){let X=0,Y;return K;function K(U){return J.enter("thematicBreak"),G(U)}function G(U){return Y=U,q(U)}function q(U){if(U===Y)return J.enter("thematicBreakSequence"),z(U);if(X>=3&&(U===null||D6(U)))return J.exit("thematicBreak"),Q(U);return Z(U)}function z(U){if(U===Y)return J.consume(U),X++,z;return J.exit("thematicBreakSequence"),F8(U)?G8(J,q,"whitespace")(U):q(U)}}var jQ={continuation:{tokenize:uU9},exit:dU9,name:"list",tokenize:mU9},hU9={partial:!0,tokenize:cU9},gU9={partial:!0,tokenize:pU9};function mU9(J,Q,Z){let X=this,Y=X.events[X.events.length-1],K=Y&&Y[1].type==="linePrefix"?Y[2].sliceSerialize(Y[1],!0).length:0,G=0;return q;function q(B){let M=X.containerState.type||(B===42||B===43||B===45?"listUnordered":"listOrdered");if(M==="listUnordered"?!X.containerState.marker||B===X.containerState.marker:Vd(B)){if(!X.containerState.type)X.containerState.type=M,J.enter(M,{_container:!0});if(M==="listUnordered")return J.enter("listItemPrefix"),B===42||B===45?J.check(lR,Z,U)(B):U(B);if(!X.interrupt||B===49)return J.enter("listItemPrefix"),J.enter("listItemValue"),z(B)}return Z(B)}function z(B){if(Vd(B)&&++G<10)return J.consume(B),z;if((!X.interrupt||G<2)&&(X.containerState.marker?B===X.containerState.marker:B===41||B===46))return J.exit("listItemValue"),U(B);return Z(B)}function U(B){return J.enter("listItemMarker"),J.consume(B),J.exit("listItemMarker"),X.containerState.marker=X.containerState.marker||B,J.check(HW,X.interrupt?Z:W,J.attempt(hU9,H,F))}function W(B){return X.containerState.initialBlankLine=!0,K++,H(B)}function F(B){if(F8(B))return J.enter("listItemPrefixWhitespace"),J.consume(B),J.exit("listItemPrefixWhitespace"),H;return Z(B)}function H(B){return X.containerState.size=K+X.sliceSerialize(J.exit("listItemPrefix"),!0).length,Q(B)}}function uU9(J,Q,Z){let X=this;return X.containerState._closeFlow=void 0,J.check(HW,Y,K);function Y(q){return X.containerState.furtherBlankLines=X.containerState.furtherBlankLines||X.containerState.initialBlankLine,G8(J,Q,"listItemIndent",X.containerState.size+1)(q)}function K(q){if(X.containerState.furtherBlankLines||!F8(q))return X.containerState.furtherBlankLines=void 0,X.containerState.initialBlankLine=void 0,G(q);return X.containerState.furtherBlankLines=void 0,X.containerState.initialBlankLine=void 0,J.attempt(gU9,Q,G)(q)}function G(q){return X.containerState._closeFlow=!0,X.interrupt=void 0,G8(J,J.attempt(jQ,Q,Z),"linePrefix",X.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(q)}}function pU9(J,Q,Z){let X=this;return G8(J,Y,"listItemIndent",X.containerState.size+1);function Y(K){let G=X.events[X.events.length-1];return G&&G[1].type==="listItemIndent"&&G[2].sliceSerialize(G[1],!0).length===X.containerState.size?Q(K):Z(K)}}function dU9(J){J.exit(this.containerState.type)}function cU9(J,Q,Z){let X=this;return G8(J,Y,"listItemPrefixWhitespace",X.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function Y(K){let G=X.events[X.events.length-1];return!F8(K)&&G&&G[1].type==="listItemPrefixWhitespace"?Q(K):Z(K)}}var MQ1={name:"setextUnderline",resolveTo:lU9,tokenize:iU9};function lU9(J,Q){let Z=J.length,X,Y,K;while(Z--)if(J[Z][0]==="enter"){if(J[Z][1].type==="content"){X=Z;break}if(J[Z][1].type==="paragraph")Y=Z}else{if(J[Z][1].type==="content")J.splice(Z,1);if(!K&&J[Z][1].type==="definition")K=Z}let G={type:"setextHeading",start:{...J[X][1].start},end:{...J[J.length-1][1].end}};if(J[Y][1].type="setextHeadingText",K)J.splice(Y,0,["enter",G,Q]),J.splice(K+1,0,["exit",J[X][1],Q]),J[X][1].end={...J[K][1].end};else J[X][1]=G;return J.push(["exit",G,Q]),J}function iU9(J,Q,Z){let X=this,Y;return K;function K(U){let W=X.events.length,F;while(W--)if(X.events[W][1].type!=="lineEnding"&&X.events[W][1].type!=="linePrefix"&&X.events[W][1].type!=="content"){F=X.events[W][1].type==="paragraph";break}if(!X.parser.lazy[X.now().line]&&(X.interrupt||F))return J.enter("setextHeadingLine"),Y=U,G(U);return Z(U)}function G(U){return J.enter("setextHeadingLineSequence"),q(U)}function q(U){if(U===Y)return J.consume(U),q;return J.exit("setextHeadingLineSequence"),F8(U)?G8(J,z,"lineSuffix")(U):z(U)}function z(U){if(U===null||D6(U))return J.exit("setextHeadingLine"),Q(U);return Z(U)}}var WU6={tokenize:nU9};function nU9(J){let Q=this,Z=J.attempt(HW,X,J.attempt(this.parser.constructs.flowInitial,Y,G8(J,J.attempt(this.parser.constructs.flow,Y,J.attempt(Tm1,Y)),"linePrefix")));return Z;function X(K){if(K===null){J.consume(K);return}return J.enter("lineEndingBlank"),J.consume(K),J.exit("lineEndingBlank"),Q.currentConstruct=void 0,Z}function Y(K){if(K===null){J.consume(K);return}return J.enter("lineEnding"),J.consume(K),J.exit("lineEnding"),Q.currentConstruct=void 0,Z}}var FU6={resolveAll:MU6()},HU6=DU6("string"),BU6=DU6("text");function DU6(J){return{resolveAll:MU6(J==="text"?aU9:void 0),tokenize:Q};function Q(Z){let X=this,Y=this.parser.constructs[J],K=Z.attempt(Y,G,q);return G;function G(W){return U(W)?K(W):q(W)}function q(W){if(W===null){Z.consume(W);return}return Z.enter("data"),Z.consume(W),z}function z(W){if(U(W))return Z.exit("data"),K(W);return Z.consume(W),z}function U(W){if(W===null)return!0;let F=Y[W],H=-1;if(F)while(++H<F.length){let B=F[H];if(!B.previous||B.previous.call(X,X.previous))return!0}return!1}}}function MU6(J){return Q;function Q(Z,X){let Y=-1,K;while(++Y<=Z.length)if(K===void 0){if(Z[Y]&&Z[Y][1].type==="data")K=Y,Y++}else if(!Z[Y]||Z[Y][1].type!=="data"){if(Y!==K+2)Z[K][1].end=Z[Y-1][1].end,Z.splice(K+2,Y-K-2),Y=K+2;K=void 0}return J?J(Z,X):Z}}function aU9(J,Q){let Z=0;while(++Z<=J.length)if((Z===J.length||J[Z][1].type==="lineEnding")&&J[Z-1][1].type==="data"){let X=J[Z-1][1],Y=Q.sliceStream(X),K=Y.length,G=-1,q=0,z;while(K--){let U=Y[K];if(typeof U==="string"){G=U.length;while(U.charCodeAt(G-1)===32)q++,G--;if(G)break;G=-1}else if(U===-2)z=!0,q++;else if(U===-1);else{K++;break}}if(Q._contentTypeTextTrailing&&Z===J.length)q=0;if(q){let U={type:Z===J.length||z||q<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:K?G:X.start._bufferIndex+G,_index:X.start._index+K,line:X.end.line,column:X.end.column-q,offset:X.end.offset-q},end:{...X.end}};if(X.end={...U.start},X.start.offset===X.end.offset)Object.assign(X,U);else J.splice(Z,0,["enter",U,Q],["exit",U,Q]),Z+=2}Z++}return J}var fm1={};j6(fm1,{text:()=>JW9,string:()=>eU9,insideSpan:()=>QW9,flowInitial:()=>oU9,flow:()=>tU9,document:()=>rU9,disable:()=>XW9,contentInitial:()=>sU9,attentionMarkers:()=>ZW9});var rU9={[42]:jQ,[43]:jQ,[45]:jQ,[48]:jQ,[49]:jQ,[50]:jQ,[51]:jQ,[52]:jQ,[53]:jQ,[54]:jQ,[55]:jQ,[56]:jQ,[57]:jQ,[62]:qQ1},sU9={[91]:Cm1},oU9={[-2]:Ld,[-1]:Ld,[32]:Ld},tU9={[35]:vm1,[42]:lR,[45]:[MQ1,lR],[60]:_m1,[61]:MQ1,[95]:lR,[96]:WQ1,[126]:WQ1},eU9={[38]:UQ1,[92]:zQ1},JW9={[-5]:wd,[-4]:wd,[-3]:wd,[33]:bm1,[38]:UQ1,[42]:Nd,[60]:[Em1,xm1],[91]:ym1,[92]:[Sm1,zQ1],[93]:cR,[95]:Nd,[96]:Im1},QW9={null:[Nd,FU6]},ZW9={null:[42,95]},XW9={null:[]};function VU6(J,Q,Z){let X={_bufferIndex:-1,_index:0,line:Z&&Z.line||1,column:Z&&Z.column||1,offset:Z&&Z.offset||0},Y={},K=[],G=[],q=[],z=!0,U={attempt:I(j),check:I(E),consume:R,enter:O,exit:$,interrupt:I(E,{interrupt:!0})},W={code:null,containerState:{},defineSkip:L,events:[],now:N,parser:J,previous:null,sliceSerialize:M,sliceStream:V,write:B},F=Q.tokenize.call(W,U),H;if(Q.resolveAll)K.push(Q);return W;function B(h){if(G=LZ(G,h),A(),G[G.length-1]!==null)return[];return T(Q,0),W.events=EN(K,W.events,W),W.events}function M(h,v){return KW9(V(h),v)}function V(h){return YW9(G,h)}function N(){let{_bufferIndex:h,_index:v,line:x,column:y,offset:g}=X;return{_bufferIndex:h,_index:v,line:x,column:y,offset:g}}function L(h){Y[h.line]=h.column,_()}function A(){let h;while(X._index<G.length){let v=G[X._index];if(typeof v==="string"){if(h=X._index,X._bufferIndex<0)X._bufferIndex=0;while(X._index===h&&X._bufferIndex<v.length)w(v.charCodeAt(X._bufferIndex))}else w(v)}}function w(h){z=void 0,H=h,F=F(h)}function R(h){if(D6(h))X.line++,X.column=1,X.offset+=h===-3?2:1,_();else if(h!==-1)X.column++,X.offset++;if(X._bufferIndex<0)X._index++;else if(X._bufferIndex++,X._bufferIndex===G[X._index].length)X._bufferIndex=-1,X._index++;W.previous=h,z=!0}function O(h,v){let x=v||{};return x.type=h,x.start=N(),W.events.push(["enter",x,W]),q.push(x),x}function $(h){let v=q.pop();return v.end=N(),W.events.push(["exit",v,W]),v}function j(h,v){T(h,v.from)}function E(h,v){v.restore()}function I(h,v){return x;function x(y,g,k){let f,b,m,n;return Array.isArray(y)?e(y):("tokenize"in y)?e([y]):p(y);function p(F1){return l;function l(d){let i=d!==null&&F1[d],r=d!==null&&F1.null,o=[...Array.isArray(i)?i:i?[i]:[],...Array.isArray(r)?r:r?[r]:[]];return e(o)(d)}}function e(F1){if(f=F1,b=0,F1.length===0)return k;return G1(F1[b])}function G1(F1){return l;function l(d){if(n=S(),m=F1,!F1.partial)W.currentConstruct=F1;if(F1.name&&W.parser.constructs.disable.null.includes(F1.name))return Z1(d);return F1.tokenize.call(v?Object.assign(Object.create(W),v):W,U,W1,Z1)(d)}}function W1(F1){return z=!0,h(m,n),g}function Z1(F1){if(z=!0,n.restore(),++b<f.length)return G1(f[b]);return k}}}function T(h,v){if(h.resolveAll&&!K.includes(h))K.push(h);if(h.resolve)P7(W.events,v,W.events.length-v,h.resolve(W.events.slice(v),W));if(h.resolveTo)W.events=h.resolveTo(W.events,W)}function S(){let h=N(),v=W.previous,x=W.currentConstruct,y=W.events.length,g=Array.from(q);return{from:y,restore:k};function k(){X=h,W.previous=v,W.currentConstruct=x,W.events.length=y,q=g,_()}}function _(){if(X.line in Y&&X.column<2)X.column=Y[X.line],X.offset+=Y[X.line]-1}}function YW9(J,Q){let Z=Q.start._index,X=Q.start._bufferIndex,Y=Q.end._index,K=Q.end._bufferIndex,G;if(Z===Y)G=[J[Z].slice(X,K)];else{if(G=J.slice(Z,Y),X>-1){let q=G[0];if(typeof q==="string")G[0]=q.slice(X);else G.shift()}if(K>0)G.push(J[Y].slice(0,K))}return G}function KW9(J,Q){let Z=-1,X=[],Y;while(++Z<J.length){let K=J[Z],G;if(typeof K==="string")G=K;else switch(K){case-5:{G="\r";break}case-4:{G=`
|
|
6547
6547
|
`;break}case-3:{G=`\r
|
|
6548
6548
|
`;break}case-2:{G=Q?" ":"\t";break}case-1:{if(!Q&&Y)continue;G=" ";break}default:G=String.fromCharCode(K)}Y=K===-2,X.push(G)}return X.join("")}function hm1(J){let X={constructs:KQ1([fm1,...(J||{}).extensions||[]]),content:Y(YU6),defined:[],document:Y(GU6),flow:Y(WU6),lazy:{},string:Y(HU6),text:Y(BU6)};return X;function Y(K){return G;function G(q){return VU6(X,K,q)}}}function gm1(J){while(!FQ1(J));return J}var NU6=/[\0\t\n\r]/g;function mm1(){let J=1,Q="",Z=!0,X;return Y;function Y(K,G,q){let z=[],U,W,F,H,B;if(K=Q+(typeof K==="string"?K.toString():new TextDecoder(G||void 0).decode(K)),F=0,Q="",Z){if(K.charCodeAt(0)===65279)F++;Z=void 0}while(F<K.length){if(NU6.lastIndex=F,U=NU6.exec(K),H=U&&U.index!==void 0?U.index:K.length,B=K.charCodeAt(H),!U){Q=K.slice(F);break}if(B===10&&F===H&&X)z.push(-3),X=void 0;else{if(X)z.push(-5),X=void 0;if(F<H)z.push(K.slice(F,H)),J+=H-F;switch(B){case 0:{z.push(65533),J++;break}case 9:{W=Math.ceil(J/4)*4,z.push(-2);while(J++<W)z.push(-1);break}case 10:{z.push(-4),J=1;break}default:X=!0,J=1}}F=H+1}if(q){if(X)z.push(-5);if(Q)z.push(Q);z.push(null)}return z}}var GW9=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function VQ1(J){return J.replace(GW9,qW9)}function qW9(J,Q,Z){if(Q)return Q;if(Z.charCodeAt(0)===35){let Y=Z.charCodeAt(1),K=Y===120||Y===88;return GQ1(Z.slice(K?2:1),K?16:10)}return YS(Z)||J}function IN(J){if(!J||typeof J!=="object")return"";if("position"in J||"type"in J)return LU6(J.position);if("start"in J||"end"in J)return LU6(J);if("line"in J||"column"in J)return um1(J);return""}function um1(J){return AU6(J&&J.line)+":"+AU6(J&&J.column)}function LU6(J){return um1(J&&J.start)+"-"+um1(J&&J.end)}function AU6(J){return J&&typeof J==="number"?J:1}var RU6={}.hasOwnProperty;function pm1(J,Q,Z){if(typeof Q!=="string")Z=Q,Q=void 0;return zW9(Z)(gm1(hm1(Z).document().write(mm1()(J,Q,!0))))}function zW9(J){let Q={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:K(w1),autolinkProtocol:I,autolinkEmail:I,atxHeading:K(J1),blockQuote:K(d),characterEscape:I,characterReference:I,codeFenced:K(i),codeFencedFenceInfo:G,codeFencedFenceMeta:G,codeIndented:K(i,G),codeText:K(r,G),codeTextData:I,data:I,codeFlowValue:I,definition:K(o),definitionDestinationString:G,definitionLabelString:G,definitionTitleString:G,emphasis:K(Y1),hardBreakEscape:K(H1),hardBreakTrailing:K(H1),htmlFlow:K(z1,G),htmlFlowData:I,htmlText:K(z1,G),htmlTextData:I,image:K(U1),label:G,link:K(w1),listItem:K(y1),listItemValue:H,listOrdered:K(D1,F),listUnordered:K(D1),paragraph:K(l1),reference:p,referenceString:G,resourceDestinationString:G,resourceTitleString:G,setextHeading:K(J1),strong:K(s1),thematicBreak:K(r1)},exit:{atxHeading:z(),atxHeadingSequence:O,autolink:z(),autolinkEmail:l,autolinkProtocol:F1,blockQuote:z(),characterEscapeValue:T,characterReferenceMarkerHexadecimal:G1,characterReferenceMarkerNumeric:G1,characterReferenceValue:W1,characterReference:Z1,codeFenced:z(N),codeFencedFence:V,codeFencedFenceInfo:B,codeFencedFenceMeta:M,codeFlowValue:T,codeIndented:z(L),codeText:z(x),codeTextData:T,data:T,definition:z(),definitionDestinationString:R,definitionLabelString:A,definitionTitleString:w,emphasis:z(),hardBreakEscape:z(_),hardBreakTrailing:z(_),htmlFlow:z(h),htmlFlowData:T,htmlText:z(v),htmlTextData:T,image:z(g),label:f,labelText:k,lineEnding:S,link:z(y),listItem:z(),listOrdered:z(),listUnordered:z(),paragraph:z(),referenceString:e,resourceDestinationString:b,resourceTitleString:m,resource:n,setextHeading:z(E),setextHeadingLineSequence:j,setextHeadingText:$,strong:z(),thematicBreak:z()}};OU6(Q,(J||{}).mdastExtensions||[]);let Z={};return X;function X(N1){let t={type:"root",children:[]},O1={stack:[t],tokenStack:[],config:Q,enter:q,exit:U,buffer:G,resume:W,data:Z},M1=[],E1=-1;while(++E1<N1.length)if(N1[E1][1].type==="listOrdered"||N1[E1][1].type==="listUnordered")if(N1[E1][0]==="enter")M1.push(E1);else{let X1=M1.pop();E1=Y(N1,X1,E1)}E1=-1;while(++E1<N1.length){let X1=Q[N1[E1][0]];if(RU6.call(X1,N1[E1][1].type))X1[N1[E1][1].type].call(Object.assign({sliceSerialize:N1[E1][2].sliceSerialize},O1),N1[E1][1])}if(O1.tokenStack.length>0){let X1=O1.tokenStack[O1.tokenStack.length-1];(X1[1]||wU6).call(O1,void 0,X1[0])}t.position={start:PN(N1.length>0?N1[0][1].start:{line:1,column:1,offset:0}),end:PN(N1.length>0?N1[N1.length-2][1].end:{line:1,column:1,offset:0})},E1=-1;while(++E1<Q.transforms.length)t=Q.transforms[E1](t)||t;return t}function Y(N1,t,O1){let M1=t-1,E1=-1,X1=!1,v1,q1,P1,T1;while(++M1<=O1){let b1=N1[M1];switch(b1[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{if(b1[0]==="enter")E1++;else E1--;T1=void 0;break}case"lineEndingBlank":{if(b1[0]==="enter"){if(v1&&!T1&&!E1&&!P1)P1=M1;T1=void 0}break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:T1=void 0}if(!E1&&b1[0]==="enter"&&b1[1].type==="listItemPrefix"||E1===-1&&b1[0]==="exit"&&(b1[1].type==="listUnordered"||b1[1].type==="listOrdered")){if(v1){let h1=M1;q1=void 0;while(h1--){let c1=N1[h1];if(c1[1].type==="lineEnding"||c1[1].type==="lineEndingBlank"){if(c1[0]==="exit")continue;if(q1)N1[q1][1].type="lineEndingBlank",X1=!0;c1[1].type="lineEnding",q1=h1}else if(c1[1].type==="linePrefix"||c1[1].type==="blockQuotePrefix"||c1[1].type==="blockQuotePrefixWhitespace"||c1[1].type==="blockQuoteMarker"||c1[1].type==="listItemIndent");else break}if(P1&&(!q1||P1<q1))v1._spread=!0;v1.end=Object.assign({},q1?N1[q1][1].start:b1[1].end),N1.splice(q1||M1,0,["exit",v1,b1[2]]),M1++,O1++}if(b1[1].type==="listItemPrefix"){let h1={type:"listItem",_spread:!1,start:Object.assign({},b1[1].start),end:void 0};v1=h1,N1.splice(M1,0,["enter",h1,b1[2]]),M1++,O1++,P1=void 0,T1=!0}}}return N1[t][1]._spread=X1,O1}function K(N1,t){return O1;function O1(M1){if(q.call(this,N1(M1),M1),t)t.call(this,M1)}}function G(){this.stack.push({type:"fragment",children:[]})}function q(N1,t,O1){this.stack[this.stack.length-1].children.push(N1),this.stack.push(N1),this.tokenStack.push([t,O1||void 0]),N1.position={start:PN(t.start),end:void 0}}function z(N1){return t;function t(O1){if(N1)N1.call(this,O1);U.call(this,O1)}}function U(N1,t){let O1=this.stack.pop(),M1=this.tokenStack.pop();if(!M1)throw Error("Cannot close `"+N1.type+"` ("+IN({start:N1.start,end:N1.end})+"): it’s not open");else if(M1[0].type!==N1.type)if(t)t.call(this,N1,M1[0]);else(M1[1]||wU6).call(this,N1,M1[0]);O1.position.end=PN(N1.end)}function W(){return mR(this.stack.pop())}function F(){this.data.expectingFirstListItemValue=!0}function H(N1){if(this.data.expectingFirstListItemValue){let t=this.stack[this.stack.length-2];t.start=Number.parseInt(this.sliceSerialize(N1),10),this.data.expectingFirstListItemValue=void 0}}function B(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.lang=N1}function M(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.meta=N1}function V(){if(this.data.flowCodeInside)return;this.buffer(),this.data.flowCodeInside=!0}function N(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.value=N1.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function L(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.value=N1.replace(/(\r?\n|\r)$/g,"")}function A(N1){let t=this.resume(),O1=this.stack[this.stack.length-1];O1.label=t,O1.identifier=OQ(this.sliceSerialize(N1)).toLowerCase()}function w(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.title=N1}function R(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.url=N1}function O(N1){let t=this.stack[this.stack.length-1];if(!t.depth){let O1=this.sliceSerialize(N1).length;t.depth=O1}}function $(){this.data.setextHeadingSlurpLineEnding=!0}function j(N1){let t=this.stack[this.stack.length-1];t.depth=this.sliceSerialize(N1).codePointAt(0)===61?1:2}function E(){this.data.setextHeadingSlurpLineEnding=void 0}function I(N1){let O1=this.stack[this.stack.length-1].children,M1=O1[O1.length-1];if(!M1||M1.type!=="text")M1=d1(),M1.position={start:PN(N1.start),end:void 0},O1.push(M1);this.stack.push(M1)}function T(N1){let t=this.stack.pop();t.value+=this.sliceSerialize(N1),t.position.end=PN(N1.end)}function S(N1){let t=this.stack[this.stack.length-1];if(this.data.atHardBreak){let O1=t.children[t.children.length-1];O1.position.end=PN(N1.end),this.data.atHardBreak=void 0;return}if(!this.data.setextHeadingSlurpLineEnding&&Q.canContainEols.includes(t.type))I.call(this,N1),T.call(this,N1)}function _(){this.data.atHardBreak=!0}function h(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.value=N1}function v(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.value=N1}function x(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.value=N1}function y(){let N1=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||"shortcut";N1.type+="Reference",N1.referenceType=t,delete N1.url,delete N1.title}else delete N1.identifier,delete N1.label;this.data.referenceType=void 0}function g(){let N1=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||"shortcut";N1.type+="Reference",N1.referenceType=t,delete N1.url,delete N1.title}else delete N1.identifier,delete N1.label;this.data.referenceType=void 0}function k(N1){let t=this.sliceSerialize(N1),O1=this.stack[this.stack.length-2];O1.label=VQ1(t),O1.identifier=OQ(t).toLowerCase()}function f(){let N1=this.stack[this.stack.length-1],t=this.resume(),O1=this.stack[this.stack.length-1];if(this.data.inReference=!0,O1.type==="link"){let M1=N1.children;O1.children=M1}else O1.alt=t}function b(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.url=N1}function m(){let N1=this.resume(),t=this.stack[this.stack.length-1];t.title=N1}function n(){this.data.inReference=void 0}function p(){this.data.referenceType="collapsed"}function e(N1){let t=this.resume(),O1=this.stack[this.stack.length-1];O1.label=t,O1.identifier=OQ(this.sliceSerialize(N1)).toLowerCase(),this.data.referenceType="full"}function G1(N1){this.data.characterReferenceType=N1.type}function W1(N1){let t=this.sliceSerialize(N1),O1=this.data.characterReferenceType,M1;if(O1)M1=GQ1(t,O1==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0;else M1=YS(t);let E1=this.stack[this.stack.length-1];E1.value+=M1}function Z1(N1){let t=this.stack.pop();t.position.end=PN(N1.end)}function F1(N1){T.call(this,N1);let t=this.stack[this.stack.length-1];t.url=this.sliceSerialize(N1)}function l(N1){T.call(this,N1);let t=this.stack[this.stack.length-1];t.url="mailto:"+this.sliceSerialize(N1)}function d(){return{type:"blockquote",children:[]}}function i(){return{type:"code",lang:null,meta:null,value:""}}function r(){return{type:"inlineCode",value:""}}function o(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Y1(){return{type:"emphasis",children:[]}}function J1(){return{type:"heading",depth:0,children:[]}}function H1(){return{type:"break"}}function z1(){return{type:"html",value:""}}function U1(){return{type:"image",title:null,url:"",alt:null}}function w1(){return{type:"link",title:null,url:"",children:[]}}function D1(N1){return{type:"list",ordered:N1.type==="listOrdered",start:null,spread:N1._spread,children:[]}}function y1(N1){return{type:"listItem",spread:N1._spread,checked:null,children:[]}}function l1(){return{type:"paragraph",children:[]}}function s1(){return{type:"strong",children:[]}}function d1(){return{type:"text",value:""}}function r1(){return{type:"thematicBreak"}}}function PN(J){return{line:J.line,column:J.column,offset:J.offset}}function OU6(J,Q){let Z=-1;while(++Z<Q.length){let X=Q[Z];if(Array.isArray(X))OU6(J,X);else UW9(J,X)}}function UW9(J,Q){let Z;for(Z in Q)if(RU6.call(Q,Z))switch(Z){case"canContainEols":{let X=Q[Z];if(X)J[Z].push(...X);break}case"transforms":{let X=Q[Z];if(X)J[Z].push(...X);break}case"enter":case"exit":{let X=Q[Z];if(X)Object.assign(J[Z],X);break}}}function wU6(J,Q){if(J)throw Error("Cannot close `"+J.type+"` ("+IN({start:J.start,end:J.end})+"): a different token (`"+Q.type+"`, "+IN({start:Q.start,end:Q.end})+") is open");else throw Error("Cannot close document, a token (`"+Q.type+"`, "+IN({start:Q.start,end:Q.end})+") is still open")}function NQ1(J){let Q=this;Q.parser=Z;function Z(X){return pm1(X,{...Q.data("settings"),...J,extensions:Q.data("micromarkExtensions")||[],mdastExtensions:Q.data("fromMarkdownExtensions")||[]})}}var jU6={}.hasOwnProperty;function $U6(J,Q){let Z=Q||{};function X(Y,...K){let{invalid:G,handlers:q}=X;if(Y&&jU6.call(Y,J)){let z=String(Y[J]);G=jU6.call(q,z)?q[z]:X.unknown}if(G)return G.call(this,Y,...K)}return X.handlers=Z.handlers||{},X.invalid=Z.invalid,X.unknown=Z.unknown,X}var WW9={}.hasOwnProperty;function dm1(J,Q){let Z=-1,X;if(Q.extensions)while(++Z<Q.extensions.length)dm1(J,Q.extensions[Z]);for(X in Q)if(WW9.call(Q,X))switch(X){case"extensions":break;case"unsafe":{EU6(J[X],Q[X]);break}case"join":{EU6(J[X],Q[X]);break}case"handlers":{FW9(J[X],Q[X]);break}default:J.options[X]=Q[X]}return J}function EU6(J,Q){if(Q)J.push(...Q)}function FW9(J,Q){if(Q)Object.assign(J,Q)}function IU6(J,Q,Z,X){let Y=Z.enter("blockquote"),K=Z.createTracker(X);K.move("> "),K.shift(2);let G=Z.indentLines(Z.containerFlow(J,K.current()),HW9);return Y(),G}function HW9(J,Q,Z){return">"+(Z?"":" ")+J}function LQ1(J,Q){return PU6(J,Q.inConstruct,!0)&&!PU6(J,Q.notInConstruct,!1)}function PU6(J,Q,Z){if(typeof Q==="string")Q=[Q];if(!Q||Q.length===0)return Z;let X=-1;while(++X<Q.length)if(J.includes(Q[X]))return!0;return!1}function cm1(J,Q,Z,X){let Y=-1;while(++Y<Z.unsafe.length)if(Z.unsafe[Y].character===`
|
|
@@ -6612,7 +6612,7 @@ exit code: ${q}`,new $1({color:X.foreground,dim:!0,italic:!0})));if(z)U.push(new
|
|
|
6612
6612
|
|
|
6613
6613
|
(${z}, command and output not shown to agent)`,new $1({color:X.foreground,dim:!0,italic:!0})));else if(Y)U.push(new V1(`
|
|
6614
6614
|
|
|
6615
|
-
(Command and output not shown to agent)`,new $1({color:X.foreground,dim:!0,italic:!0})));return new n1({text:new V1("",void 0,U)})}class fQ1 extends c0{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onMessageRestoreSubmit;onMessageForkSubmit;thread;focusNode;onDismissFocus;isInSelectionMode=!1;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Z=this.items[Q];if(Z?.type==="message"&&Z.message.role==="user")J.push(Q)}return J}constructor({key:J,items:Q,subagentToolsByParentID:Z={},controller:X,autofocus:Y=!1,onNewMessage:K,showScrollbar:G=!0,onCopy:q,onMessageEditSubmit:z,onMessageRestoreSubmit:U,onMessageForkSubmit:W,thread:F,focusNode:H,onDismissFocus:B,isInSelectionMode:M=!1}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Z,this.controller=X,this.autofocus=Y,this.onNewMessage=K,this.showScrollbar=G,this.onCopy=q,this.onMessageEditSubmit=z,this.onMessageRestoreSubmit=U,this.onMessageForkSubmit=W,this.thread=F,this.focusNode=H,this.onDismissFocus=B,this.isInSelectionMode=M}createState(){return new XF6}}class XF6 extends d0{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;get controller(){return this._controller}dismiss(){c9.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=this.getUserMessageIndexFromOrdinal(Z);if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);if(this.setState(()=>{this._selectedUserMessageOrdinal=Z}),Y!==null)c9.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y,{animated:!0,offset:0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null;if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);this.setState(()=>{this._editingMessageOrdinal=Z})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Z=this.widget.userMessageIndices.indexOf(J);return Z>=0?Z:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Z=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Z===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Z!==null)this._selectUserMessageByOrdinal(Z)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!0}),c9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"}return"ignored"};handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._isShowingRestoreConfirmation=!1}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null)this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!1}),c9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user"){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Z=o7(Q.content),X=Q.content.filter((Y)=>Y.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${X}|${Z}`}else if(Q.role==="assistant"){let Z=o7(Q.content),X=Q.state.type==="complete",Y=Q.content.filter((G)=>G.type==="thinking"),K=Q.content.filter((G)=>G.type==="tool_use");return`${J.id}|assistant|${X?1:0}|${Y.length}|${K.length}|${Z}`}else{let X=Q.content.map((Y)=>Y.type).join(",");return`${J.id}|info|${X}`}}else{let Z=J.toolResult.run.status;return`${J.id}|tool|${Z}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Z=`${J}-${Q}`;return this._thinkingBlockStates.get(Z)??$Q.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Z)=>{let X=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(X,Z),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Z,X){let Y=Z===X.content.length-1,K=X.state?.type==="streaming"&&Y;return new $d({key:new a7(`thinking-${Q}-${Z}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Z),onToggle:this.toggleThinkingBlock(Q,Z),isStreaming:K})}buildAssistantMessageWidget(J,Q,Z,X){let Y=Q.content.map((H,B)=>({block:H,index:B})).filter((H)=>H.block.type==="thinking"),K=Y.some(({block:H})=>du1(H.thinking).length>0),G=Q.content.filter((H)=>H.type==="text"),q=[];if(q.push(...Y.map(({block:H,index:B})=>this.buildThinkingBlock(H,Z,B,Q))),K&&G.length>0)q.push(new U0({height:1}));let z=o7(G);if(z.trim())q.push(WH9(J,z,X));let U=qB(J),W=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(U&&W){let B=O6.maybeOf(J)?.colors??e6.of(J).colorScheme,M=cq6(Q.usage);q.push(new b6({padding:N0.only({top:1}),child:new n1({text:new V1(M,new $1({color:B.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new f0;else if(q.length===1)F=q[0];else F=new i0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Z){let X=new a7(`thread-item-${Q.id}`);if(Q.type==="message"){let Y=Q.message;if(Y.role==="user"){if(!this.widget.isInSelectionMode)return new Ed({message:Y});let K=this.getOrdinalFromUserMessageIndex(Z);if(K===null)return new Ed({message:Y});if(this._editingMessageOrdinal===K)return new eu1({initialText:o7(Y.content),onSubmitted:(q)=>{if(q.trim()==="")return;this.widget.onMessageEditSubmit?.(Y,q),this._selectEditingUserMessageByOrdinal(null),this._clearSelectedUserMessage(),this.dismiss(),this.controller.animateToBottom(100)}});if(this._selectedUserMessageOrdinal===K)return new tu1({message:Y,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()}});else return new Ed({message:Y})}else if(Y.role==="assistant"){let K=this.buildAssistantMessageWidget(J,Y,Z,Q.id);return new f0({key:X,child:K})}else{let K=Y,G=[];for(let q of K.content)if(q.type==="manual_bash_invocation")G.push(HH9(J,q));else if(q.type==="summary"&&q.summary.type==="message")G.push(FH9(J,q));if(G.length===0)return new f0;if(G.length===1)return G[0];return new i0({crossAxisAlignment:"stretch",children:G})}}else{let Y=new tR({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new f0({key:X,child:Y})}return new f0}initState(){if(super.initState(),this._controller=this.widget.controller||new IY,this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},$Q.instance.addListener(this._globalToggleListener),this.widget.items.length>0)c9.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Z=this.getLatestUserMessageOrdinal();if(Z!==null)this._selectUserMessageByOrdinal(Z)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Z=0;Z<Q;Z++){let X=J.items[Z],Y=this.widget.items[Z];if(X&&Y){if(X.type!==Y.type){this._widgetCache.delete(Z);continue}if(X.type==="toolResult"&&Y.type==="toolResult"){let K=X.toolResult.run,G=Y.toolResult.run;if(K.status!==G.status||"result"in K!=="result"in G||"error"in K!=="error"in G)this._widgetCache.delete(Z)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Z of this._streamingIndexes)if(Z>=this.widget.items.length)this._streamingIndexes.delete(Z)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Z=this._isMessageStreaming(Q);if(Z&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Z&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._globalToggleListener)$Q.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=O6.of(J),Z=qB(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Z)this._widgetCache.clear();this._lastCostDisplayState=Z;let X=this._getTotalItemCount(J),Y=[];for(let H=0;H<X;H++)if(Y.push(this._buildItemAtIndex(J,H)),H<X-1)Y.push(new U0({height:1}));let K=new PY({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new i0({key:new a7("message-list-column"),crossAxisAlignment:"start",children:Y})}),q=[new b6({padding:N0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:K})];if(this.widget.showScrollbar&&this._controller){let H=new oR({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});q.push(new $X({right:1,top:0,bottom:0,child:new U0({width:1,child:H})}))}let z=new kJ({children:q}),U=new yR({key:new a7("message-view-selection-area"),child:z,onCopy:this.widget.onCopy}),W=new Map([[bQ1,new S9(this.handleNavigateUserMessageUp)],[yQ1,new S9(this.handleNavigateUserMessageDown)],[Jp1,new S9(this.handleEscape)],[Qp1,new S9(this.handleScrollDown)],[Zp1,new S9(this.handleScrollUp)],[Xp1,new S9(this.handleEditMessage)],[Yp1,new S9(this.handleRestoreMessage)],[Kp1,new S9(this.handleForkMessage)]]),F=new Map([[y6.key("Tab"),new bQ1],[y6.shift("Tab"),new yQ1],[y6.key("Escape"),new Jp1],[y6.key("j"),new Qp1],[y6.key("k"),new Zp1],[y6.key("e"),new Xp1],[y6.key("r"),new Yp1],[y6.key("f"),new Kp1]]);if(!LQ())F.set(y6.key("ArrowUp"),new bQ1),F.set(y6.key("ArrowDown"),new yQ1);if(this.widget.focusNode)return new q9({focusNode:this.widget.focusNode,child:new NZ({actions:W,child:new aq({shortcuts:F,focusNode:this.widget.focusNode,child:U})})});return U}_getTotalItemCount(J){return this.widget.items.length}_buildItemAtIndex(J,Q){let Z=this.widget.items[Q];if(!Z)return new f0;let X=Z.type==="message"&&this._isMessageStreaming(Z),Y=Z.type==="toolResult"&&(Z.toolResult.run.status==="queued"||Z.toolResult.run.status==="in-progress")&&!("result"in Z.toolResult.run)&&!("error"in Z.toolResult.run);if(!X&&!Y){let q=this._signatureFor(Z),z=this._widgetCache.get(Q);if(z&&z.sig===q)return z.widget;let U=this.buildThreadItemWidget(J,Z,Q);return this._widgetCache.set(Q,{sig:q,widget:U}),U}return this.buildThreadItemWidget(J,Z,Q)}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offset:Z=0,edge:X="top",duration:Y}={}){if(this._isDisposed||!this._controller)return!1;let K=this._getMessageRelativeOffset(J,X);if(K===null)return!1;let G=K-Z;if(Q)this._controller.animateTo(G,Y);else this._controller.jumpTo(G);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new a7("message-list-column"),Z=(X)=>{if(X.widget.key?.equals(Q))return X;for(let Y of X.children){let K=Z(Y);if(K)return K}return null};return Z(J)}_getMessageRelativeOffset(J,Q){let Z=this._getColumnElement();if(!Z)return null;let X=J*2,Y=Z.children[X];if(!Y?.renderObject)return null;let K=Y.renderObject,G=Z.renderObject;if(!G)return null;let q=K.localToGlobal({x:0,y:0}),z=G.localToGlobal({x:0,y:0}),U=0;if(Q==="bottom")U=K.size.height;return q.y+U-z.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Z=this._controller?.offset??0,X=J+Q;return{totalContentHeight:Math.max(X,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Z,0)}}}G9();var YF6=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use /queue to enqueue messages without interrupting the agent"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Generate an AGENTS.md file with the /generate-agent-file command"},{type:"hint",text:"Open your thread in the browser with /browser"},{type:"hint",text:"Create a new thread with /new"},{type:"hint",text:"Change the visiblity settings of your thread with /visibility"},{type:"hint",text:"Open the settings with the /settings command"},{type:"hint",text:"Draft a new thread based on the current thread with /handoff"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`}];class hQ1 extends P6{agentMode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode}build(J){let Z=e6.of(J).colorScheme,Y=O6.of(J).app,G=_8.of(J).capabilities.animationSupport,q=process.pid%YF6.length,z=YF6[q],U=z.type==="quote"?new $1({color:Z.foreground,dim:!0}):z.type==="hint"?new $1({color:Z.secondary}):new $1({color:z.type==="prompt"?Z.primary:Z.warning}),W=new $1({color:Y.keybind}),F=new $1({color:Y.command}),H=new $1({color:Z.secondary}),B=new $1({color:Z.foreground,dim:!0}),M=[];if(z.type==="hint"){let A=z.text.split(/(\s\/[\w-]+)/g);for(let w of A)if(w.match(/^\s\/[\w-]+$/)){let R=w.trim(),O=w.slice(0,w.length-R.length),$=R.slice(1);M.push(new V1(O,U)),M.push(new V1($,F))}else M.push(new V1(w,U))}else M.push(new V1(z.text,U));let V=[new V1("Welcome to Amp",new $1({color:Z.foreground})),new V1(`
|
|
6615
|
+
(Command and output not shown to agent)`,new $1({color:X.foreground,dim:!0,italic:!0})));return new n1({text:new V1("",void 0,U)})}class fQ1 extends c0{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onMessageRestoreSubmit;onMessageForkSubmit;thread;focusNode;onDismissFocus;isInSelectionMode=!1;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Z=this.items[Q];if(Z?.type==="message"&&Z.message.role==="user")J.push(Q)}return J}constructor({key:J,items:Q,subagentToolsByParentID:Z={},controller:X,autofocus:Y=!1,onNewMessage:K,showScrollbar:G=!0,onCopy:q,onMessageEditSubmit:z,onMessageRestoreSubmit:U,onMessageForkSubmit:W,thread:F,focusNode:H,onDismissFocus:B,isInSelectionMode:M=!1}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Z,this.controller=X,this.autofocus=Y,this.onNewMessage=K,this.showScrollbar=G,this.onCopy=q,this.onMessageEditSubmit=z,this.onMessageRestoreSubmit=U,this.onMessageForkSubmit=W,this.thread=F,this.focusNode=H,this.onDismissFocus=B,this.isInSelectionMode=M}createState(){return new XF6}}class XF6 extends d0{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;get controller(){return this._controller}dismiss(){c9.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=this.getUserMessageIndexFromOrdinal(Z);if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);if(this.setState(()=>{this._selectedUserMessageOrdinal=Z}),Y!==null)c9.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y,{animated:!0,offset:0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null;if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);this.setState(()=>{this._editingMessageOrdinal=Z})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Z=this.widget.userMessageIndices.indexOf(J);return Z>=0?Z:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Z=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Z===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Z!==null)this._selectUserMessageByOrdinal(Z)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!0}),c9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"}return"ignored"};handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._isShowingRestoreConfirmation=!1}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null)this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!1}),c9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user"){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Z=o7(Q.content),X=Q.content.filter((Y)=>Y.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${X}|${Z}`}else if(Q.role==="assistant"){let Z=o7(Q.content),X=Q.state.type==="complete",Y=Q.content.filter((G)=>G.type==="thinking"),K=Q.content.filter((G)=>G.type==="tool_use");return`${J.id}|assistant|${X?1:0}|${Y.length}|${K.length}|${Z}`}else{let X=Q.content.map((Y)=>Y.type).join(",");return`${J.id}|info|${X}`}}else{let Z=J.toolResult.run.status;return`${J.id}|tool|${Z}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Z=`${J}-${Q}`;return this._thinkingBlockStates.get(Z)??$Q.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Z)=>{let X=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(X,Z),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Z,X){let Y=Z===X.content.length-1,K=X.state?.type==="streaming"&&Y;return new $d({key:new a7(`thinking-${Q}-${Z}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Z),onToggle:this.toggleThinkingBlock(Q,Z),isStreaming:K})}buildAssistantMessageWidget(J,Q,Z,X){let Y=Q.content.map((H,B)=>({block:H,index:B})).filter((H)=>H.block.type==="thinking"),K=Y.some(({block:H})=>du1(H.thinking).length>0),G=Q.content.filter((H)=>H.type==="text"),q=[];if(q.push(...Y.map(({block:H,index:B})=>this.buildThinkingBlock(H,Z,B,Q))),K&&G.length>0)q.push(new U0({height:1}));let z=o7(G);if(z.trim())q.push(WH9(J,z,X));let U=qB(J),W=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(U&&W){let B=O6.maybeOf(J)?.colors??e6.of(J).colorScheme,M=cq6(Q.usage);q.push(new b6({padding:N0.only({top:1}),child:new n1({text:new V1(M,new $1({color:B.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new f0;else if(q.length===1)F=q[0];else F=new i0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Z){let X=new a7(`thread-item-${Q.id}`);if(Q.type==="message"){let Y=Q.message;if(Y.role==="user"){if(!this.widget.isInSelectionMode)return new Ed({message:Y});let K=this.getOrdinalFromUserMessageIndex(Z);if(K===null)return new Ed({message:Y});if(this._editingMessageOrdinal===K)return new eu1({initialText:o7(Y.content),onSubmitted:(q)=>{if(q.trim()==="")return;this.widget.onMessageEditSubmit?.(Y,q),this._selectEditingUserMessageByOrdinal(null),this._clearSelectedUserMessage(),this.dismiss(),this.controller.animateToBottom(100)}});if(this._selectedUserMessageOrdinal===K)return new tu1({message:Y,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()}});else return new Ed({message:Y})}else if(Y.role==="assistant"){let K=this.buildAssistantMessageWidget(J,Y,Z,Q.id);return new f0({key:X,child:K})}else{let K=Y,G=[];for(let q of K.content)if(q.type==="manual_bash_invocation")G.push(HH9(J,q));else if(q.type==="summary"&&q.summary.type==="message")G.push(FH9(J,q));if(G.length===0)return new f0;if(G.length===1)return G[0];return new i0({crossAxisAlignment:"stretch",children:G})}}else{let Y=new tR({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new f0({key:X,child:Y})}return new f0}initState(){if(super.initState(),this._controller=this.widget.controller||new IY,this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},$Q.instance.addListener(this._globalToggleListener),this.widget.items.length>0)c9.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Z=this.getLatestUserMessageOrdinal();if(Z!==null)this._selectUserMessageByOrdinal(Z)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Z=0;Z<Q;Z++){let X=J.items[Z],Y=this.widget.items[Z];if(X&&Y){if(X.type!==Y.type){this._widgetCache.delete(Z);continue}if(X.type==="toolResult"&&Y.type==="toolResult"){let K=X.toolResult.run,G=Y.toolResult.run;if(K.status!==G.status||"result"in K!=="result"in G||"error"in K!=="error"in G)this._widgetCache.delete(Z)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Z of this._streamingIndexes)if(Z>=this.widget.items.length)this._streamingIndexes.delete(Z)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Z=this._isMessageStreaming(Q);if(Z&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Z&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._globalToggleListener)$Q.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=O6.of(J),Z=qB(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Z)this._widgetCache.clear();this._lastCostDisplayState=Z;let X=this._getTotalItemCount(J),Y=[];for(let H=0;H<X;H++)if(Y.push(this._buildItemAtIndex(J,H)),H<X-1)Y.push(new U0({height:1}));let K=new PY({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new i0({key:new a7("message-list-column"),crossAxisAlignment:"start",children:Y})}),q=[new b6({padding:N0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:K})];if(this.widget.showScrollbar&&this._controller){let H=new oR({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});q.push(new $X({right:1,top:0,bottom:0,child:new U0({width:1,child:H})}))}let z=new kJ({children:q}),U=new yR({key:new a7("message-view-selection-area"),child:z,onCopy:this.widget.onCopy}),W=new Map([[bQ1,new S9(this.handleNavigateUserMessageUp)],[yQ1,new S9(this.handleNavigateUserMessageDown)],[Jp1,new S9(this.handleEscape)],[Qp1,new S9(this.handleScrollDown)],[Zp1,new S9(this.handleScrollUp)],[Xp1,new S9(this.handleEditMessage)],[Yp1,new S9(this.handleRestoreMessage)],[Kp1,new S9(this.handleForkMessage)]]),F=new Map([[y6.key("Tab"),new bQ1],[y6.shift("Tab"),new yQ1],[y6.key("Escape"),new Jp1],[y6.key("j"),new Qp1],[y6.key("k"),new Zp1],[y6.key("e"),new Xp1],[y6.key("r"),new Yp1],[y6.key("f"),new Kp1]]);if(!LQ())F.set(y6.key("ArrowUp"),new bQ1),F.set(y6.key("ArrowDown"),new yQ1);if(this.widget.focusNode)return new q9({focusNode:this.widget.focusNode,child:new NZ({actions:W,child:new aq({shortcuts:F,focusNode:this.widget.focusNode,child:U})})});return U}_getTotalItemCount(J){return this.widget.items.length}_buildItemAtIndex(J,Q){let Z=this.widget.items[Q];if(!Z)return new f0;let X=Z.type==="message"&&this._isMessageStreaming(Z),Y=Z.type==="toolResult"&&(Z.toolResult.run.status==="queued"||Z.toolResult.run.status==="in-progress")&&!("result"in Z.toolResult.run)&&!("error"in Z.toolResult.run);if(!X&&!Y){let q=this._signatureFor(Z),z=this._widgetCache.get(Q);if(z&&z.sig===q)return z.widget;let U=this.buildThreadItemWidget(J,Z,Q);return this._widgetCache.set(Q,{sig:q,widget:U}),U}return this.buildThreadItemWidget(J,Z,Q)}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offset:Z=0,edge:X="top",duration:Y}={}){if(this._isDisposed||!this._controller)return!1;let K=this._getMessageRelativeOffset(J,X);if(K===null)return!1;let G=K-Z;if(Q)this._controller.animateTo(G,Y);else this._controller.jumpTo(G);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new a7("message-list-column"),Z=(X)=>{if(X.widget.key?.equals(Q))return X;for(let Y of X.children){let K=Z(Y);if(K)return K}return null};return Z(J)}_getMessageRelativeOffset(J,Q){let Z=this._getColumnElement();if(!Z)return null;let X=J*2,Y=Z.children[X];if(!Y?.renderObject)return null;let K=Y.renderObject,G=Z.renderObject;if(!G)return null;let q=K.localToGlobal({x:0,y:0}),z=G.localToGlobal({x:0,y:0}),U=0;if(Q==="bottom")U=K.size.height;return q.y+U-z.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Z=this._controller?.offset??0,X=J+Q;return{totalContentHeight:Math.max(X,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Z,0)}}}G9();var YF6=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+O to open the command palette"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use Ctrl+O → Queue to enqueue messages without interrupting the agent"},{type:"hint",text:"Use Ctrl+O → Browser to open your thread in the browser"},{type:"hint",text:"Use Ctrl+O → New to start a fresh thread"},{type:"hint",text:"Use Ctrl+O → Handoff to draft a new thread with relevant context"},{type:"hint",text:"Use Ctrl+O → Visibility to change thread visibility settings"},{type:"hint",text:"Use Ctrl+O → Settings to configure Amp"},{type:"hint",text:"Use Ctrl+O → Generate Agent File to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`}];class hQ1 extends P6{agentMode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode}build(J){let Z=e6.of(J).colorScheme,Y=O6.of(J).app,G=_8.of(J).capabilities.animationSupport,q=process.pid%YF6.length,z=YF6[q],U=z.type==="quote"?new $1({color:Z.foreground,dim:!0}):z.type==="hint"?new $1({color:Z.secondary}):new $1({color:z.type==="prompt"?Z.primary:Z.warning}),W=new $1({color:Y.keybind}),F=new $1({color:Y.command}),H=new $1({color:Z.secondary}),B=new $1({color:Z.foreground,dim:!0}),M=[];if(z.type==="hint"){let A=z.text.split(/(\s\/[\w-]+)/g);for(let w of A)if(w.match(/^\s\/[\w-]+$/)){let R=w.trim(),O=w.slice(0,w.length-R.length),$=R.slice(1);M.push(new V1(O,U)),M.push(new V1($,F))}else M.push(new V1(w,U))}else M.push(new V1(z.text,U));let V=[new V1("Welcome to Amp",new $1({color:Z.foreground})),new V1(`
|
|
6616
6616
|
|
|
6617
6617
|
|
|
6618
6618
|
`),new V1("Ctrl+O",W),new V1(" to execute ",B),new V1("commands",F),new V1(`
|
|
@@ -6682,11 +6682,11 @@ ${this.stateNotifier.value.getDownloadPath()}.`,new $1({color:Q.colorScheme.fore
|
|
|
6682
6682
|
https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_disk`,new $1({color:Q.colorScheme.foreground}))}),new U0({height:1}),new n1({text:new V1(`Finally restart your JetBrains IDE${!LQ()&&" and Amp"}.`,new $1({color:Q.colorScheme.foreground}))}),new U0({height:1}),new n1({text:new V1("Press any key to exit...",new $1({color:Q.colorScheme.foreground,dim:!0}))})]})})});return new q9({autofocus:!0,onKey:(U)=>{return this.widget.onExit(),"handled"},child:z})}return new f0({decoration:new i8(Q.colorScheme.background),child:new b6({padding:N0.all(2),child:new n1({text:new V1("Discovering JetBrains IDEs...",new $1({color:Q.colorScheme.foreground}))})})})}}function IB9(J){let Q=J.reduce((Z,X)=>{return(Z[X.name]??=[]).push(X),Z},{});return Object.entries(Q).map(([Z,X])=>({name:Z,versions:X.map((Y)=>Y.version).sort()}))}function PB9(J){if(J.length<=1)return"";if(J.length>=3)return` (${J[0]}-${J.at(-1)})`;return` (${J.join(", ")})`}G9();l8();class gp1 extends c0{color;trigger;trail;fps;speed;leftOffset;constructor({key:J,color:Q,trigger:Z,trail:X=5,fps:Y=60,speed:K=1,leftOffset:G=0}){super(J?{key:J}:{});this.color=Q,this.trigger=Z,this.trail=X,this.fps=Y,this.speed=K,this.leftOffset=G}createState(){return new KH6}}class KH6 extends d0{progress=0;timer=null;initState(){this.restart()}didUpdateWidget(J){if(J.trigger!==this.widget.trigger)this.restart()}dispose(){this.stop()}restart(){this.stop(),this.progress=-this.widget.trail,this.start()}start(){if(this.timer)return;let J=Math.max(16,Math.round(1000/Math.max(1,this.widget.fps)));this.timer=setInterval(()=>{this.setState(()=>{this.progress+=this.widget.speed})},J)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}build(J){return new GH6({color:this.widget.color,trail:this.widget.trail,head:this.progress,leftOffset:this.widget.leftOffset},this.widget.key)}}class GH6 extends KB{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new wN(this)}createRenderObject(){return new qH6(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}updateRenderObject(J){J.update(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}}class qH6 extends Z8{_color;_trail;_head;_leftOffset;constructor(J,Q,Z,X){super();this._color=J;this._trail=Q;this._head=Z;this._leftOffset=X}update(J,Q,Z,X){let Y=!1;if(Q!==this._trail)this._trail=Q,Y=!0;if(this._color=J,this._head=Z,this._leftOffset=X,Y)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Q=J.constrain(J.biggest.width,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y),K=Math.floor(this.size.width),G=[1,0.7,0.5,0.35,0.25,0.15];for(let q=0;q<=this._trail&&q<G.length;q++){let z=Math.floor(this._head)-q+this._leftOffset;if(z<this._leftOffset||z>=K)continue;let U=TB9(this._color,G[q]);J.setChar(X+z,Y,"━",{fg:U},1)}super.paint(J,Q,Z)}}function TB9(J,Q){if(J.type==="rgb")return I1.rgb(J.value.r,J.value.g,J.value.b,Q);if(J.type==="index")return I1.index(J.value,Q);return I1.default(Q)}class mp1 extends P6{message;onDismiss;constructor({key:J,message:Q,onDismiss:Z}){super({key:J});this.message=Q,this.onDismiss=Z}build(J){let Z=e6.of(J).colorScheme,X=VJ1(this.message),Y=[{value:"dismiss",label:"Dismiss"}],K=X.type==="error"?Z.destructive:Z.primary,G=new yR({child:new n1({text:new V1(X.description),selectable:!0})});return new FB({title:X.title,body:G,options:Y,onSelect:(q)=>{this.onDismiss()},borderColor:K,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})}}G9();class up1 extends P6{url;qrCode;constructor({key:J,url:Q,qrCode:Z}){super(J?{key:J}:{});this.url=Q,this.qrCode=Z}build(J){let Z=e6.of(J).colorScheme,X=_8.of(J),Y=new $1({color:I1.rgb(0,0,0)}),K=new $1({color:Z.foreground}),G=new $1({color:Z.foreground}),q=new $1({color:Z.secondary,bold:!0}),z=X.size.width,U=X.size.height,W=z-4,F=Math.min(U-4,Math.floor(U*0.8)),H=Math.min(60,W),B=new PY({autofocus:!0,child:new b6({padding:N0.only({left:2,right:2}),child:new i0({crossAxisAlignment:"center",children:[new C9({child:new f0({decoration:new i8(I1.rgb(255,255,255)),padding:N0.all(2),child:new n1({text:new V1(this.qrCode,Y),textAlign:"left"})})}),new U0({height:1}),new C9({child:new n1({text:new V1(`Continue at ${this.url}`,K)})}),new U0({height:1})]})})}),M=new C9({child:new n1({text:new V1("",G,[new V1("Press ",G),new V1("Escape",q),new V1(" to close",G)])})}),V=new i0({crossAxisAlignment:"stretch",children:[new R8({child:B}),M]});return new C9({child:new f0({constraints:new R6(H,H,0,F),decoration:new i8(Z.background,x8.all(new w8(Z.primary,1,"rounded"))),child:V})})}}l8();class pp1 extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new zH6}}class zH6 extends d0{build(J){let{queuedMessages:Q,title:Z="Queue"}=this.widget.props;if(!Array.isArray(Q)||Q.length===0)return new U0({width:0,height:0});let X=Q.map((Y)=>this.buildQueueItem(Y));return new f0({child:new b6({padding:N0.symmetric(1,0),child:new i0({crossAxisAlignment:"stretch",children:[new n1({text:new V1(Z,new $1({bold:!0}))}),...X]})})})}buildQueueItem(J){let Z=J.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join(" ").trim(),X=Z.split(`
|
|
6683
6683
|
`)[0],Y=Z.includes(`
|
|
6684
6684
|
`)?`${X}...`:Z,K=new $1({color:I1.index(8)});return new b6({padding:N0.only({bottom:0}),child:new X8({crossAxisAlignment:"start",children:[new b6({padding:N0.only({right:1}),child:new n1({text:new V1("•",new $1({color:I1.index(8)}))})}),new R8({child:new n1({text:new V1(Y,K)})})]})})}}$W();var CB9=Q1.string(),UH6=Q1.object({id:CB9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","public_unlisted","public_discoverable","thread_workspace_shared"]),sharedGroupIDs:Q1.array(Q1.string())})});G0();iX();$W();var SB9=Q1.object({id:Q1.string()});function vB9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/3600000),Y=Math.floor(X/24),K=Math.floor(Y/7),G=Math.floor(Y/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Y<7)return`${Y}d ago`;if(K<=4)return`${K}w ago`;return`${G}mo ago`}class vd{configService;constructor(J){this.configService=J}async fetchThreadSummaries(J="",Q=0,Z=20){try{let X=await cJ("/api/user",void 0,this.configService);if(!X.ok)return{ok:!1,errorMsg:`Failed to get user info (${X.status})`};let Y;try{Y=SB9.parse(await X.json())}catch(W){return{ok:!1,errorMsg:"Invalid user data format from server"}}let K=new URLSearchParams({createdByUserID:Y.id,limit:String(Z),offset:String(Q*Z)}),G=await cJ(`/api/threads?${K}`,void 0,this.configService);if(!G.ok)return{ok:!1,errorMsg:`Failed to fetch threads (${G.status})`};let q;try{q=Q1.array(UH6).parse(await G.json())}catch(W){return u.error("failed to parse thread data from server",{error:W}),{ok:!1,errorMsg:"Invalid thread data format from server"}}return{ok:!0,threads:q.filter((W)=>W.messageCount>0).filter((W)=>{if(!J.trim())return!0;let F=W.title?.toLowerCase()||"untitled",H=W.id.toLowerCase(),B=J.toLowerCase();return F.includes(B)||H.includes(B)}).slice(0,Z).map((W)=>{let F=W.title||"Untitled",H=new Date(W.updatedAt),B=vB9(H),M=W.id.slice(-8);return{id:W.id,title:F,messageCount:W.messageCount,updatedAt:W.updatedAt,description:{timeAgo:B,title:F,shortThreadID:M}}})}}catch(X){return{ok:!1,errorMsg:X instanceof Error?X.message:"An unexpected error occurred"}}}}l8();class dp1 extends c0{props;constructor(J){super();this.props=J}createState(){return new WH6(this.props.pageSize,this.props.loadBuffer,this.props.autofocus??!0)}}class WH6 extends d0{pageSize;loadBuffer;autofocus;allThreads=[];isLoading=!1;currentPage=0;hasMoreToLoad=!0;error=null;constructor(J=20,Q=J*2,Z){super();this.pageSize=J;this.loadBuffer=Q;this.autofocus=Z}async initState(){await this.loadThreads()}async loadThreads(){if(this.isLoading||!this.hasMoreToLoad)return;this.isLoading=!0,this.error=null;try{let J=await this.widget.props.threadFetcher.fetchThreadSummaries("",this.currentPage,this.pageSize);if(!this.mounted)return;if(!J.ok){this.error=J.errorMsg,this.hasMoreToLoad=!1,this.setState();return}let Q=J.threads;if(Q.length===0)this.hasMoreToLoad=!1;else{let Z=new Set(this.allThreads.map((Y)=>Y.id)),X=Q.filter((Y)=>!Z.has(Y.id));this.allThreads=[...this.allThreads,...X],this.currentPage++}this.setState()}finally{this.isLoading=!1}}onChange=async(J)=>{if(this.allThreads.length-J<=this.loadBuffer&&this.hasMoreToLoad&&!this.isLoading)await this.loadThreads()};formatThreadDescription(J){let Z=`${String(J.messageCount)} msgs`.padEnd(8),X=J.description.timeAgo.padEnd(9);return`${Z} │ ${X}│ ${J.description.shortThreadID}`}build(J){let Q=(G)=>{if(G.ctrlKey&&G.key==="c"||G.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"};if(this.error)return new q9({autofocus:this.autofocus,onKey:Q,child:new n1({text:new V1(this.error)})});if(this.isLoading&&this.allThreads.length===0)return new q9({autofocus:this.autofocus,onKey:Q,child:new n1({text:new V1("Loading threads...")})});let Z=_8.sizeOf(J);if(this.allThreads.length===0&&!this.isLoading)return new q9({autofocus:this.autofocus,onKey:Q,child:new n1({text:new V1("No threads found.")})});let X=this.allThreads.map((G)=>({value:G.id,label:G.title,description:this.formatThreadDescription(G)})),Y=Math.max(5,Z.height);Y-=6;let K=Math.floor(Math.max(1,Y/2));return new q9({autofocus:this.autofocus,onKey:Q,child:new Id({title:"Select a thread to continue:",options:X,onSelect:(G)=>{this.widget.props.onSelect(G)},onChange:this.onChange,maxVisibleItems:K,autofocus:this.autofocus})})}}f51();class kd{detect(J,Q){if(!J||Q<1)return null;let Z=j2(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
|
|
6685
|
-
`))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}function FH6(J,Q){switch(J){case"update-available":return[new V1("A newer Amp is available. Run ",new $1({color:Q.foreground,dim:!0})),new V1("amp update",new $1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new V1("Update complete, run ",new $1({color:Q.foreground,dim:!0})),new V1("amp update",new $1({color:Q.warning})),new V1(" to see warnings",new $1({color:Q.foreground,dim:!0}))];case"update-error":return[new V1("Update failed, run ",new $1({color:Q.foreground,dim:!0})),new V1("amp update",new $1({color:Q.warning})),new V1(" to see warnings",new $1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function bB9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new $1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new $1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class MH6 extends c0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new VH6}}class VH6 extends d0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;threadsForPicker=[];isLoadingThreads=!1;previewThread=null;previewCache=new Map;previewScrollController=new IY;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new Q9({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new Q9({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=wZ();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new V1(this.submitDisabledHint,new $1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new V1("",void 0,[new V1("Ctrl+C",new $1({color:Q.keybind})),new V1(" again to exit",new $1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new V1("",void 0,[new V1("Esc",new $1({color:Q.keybind})),new V1(" again to clear input",new $1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new V1("",void 0,[new V1("Escape",new $1({color:Q.keybind})),new V1(" to close help",new $1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=np1(X);return new V1("",void 0,[new V1("Images aren't supported in ",new $1({color:J.warning,dim:!1})),new V1(X,new $1({color:Y})),new V1(" mode.",new $1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new V1("",void 0,[new V1("Esc",new $1({color:Q.keybind})),new V1(" to cancel",new $1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new V1("Selection copied to clipboard",new $1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new V1(this.showingCannotToggleMessage,new $1({color:J.warning,dim:!1}));let Z=FH6(this.updateState,J);if(Z)return new V1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let Y=Q.mainThread?.messages.findIndex((K)=>K===J);if(Y===void 0||Y===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:Y}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){u.error("Failed to edit message:",K)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;let G=Q.mainThread?.messages.findIndex((q)=>q===J);if(G===void 0||G<=0)return;try{let q=await VJ.getOrCreateForThread(Z,K),z=await bs(q,X,G),U=await Y(z);KN(U),this.widget.dependencies.worker=U,this.widget.dependencies.threadID=U.thread.id;let W=U.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=W})}catch(q){u.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;let K=Y.messages.findIndex((G)=>G===J);if(K===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let G=[{type:"text",text:Q}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);let q={content:G,agentMode:Y.agentMode},z=K===0;if(Y.agentMode&&!z&&q.agentMode!==Y.agentMode){u.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:q,index:K}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){u.error("Failed to edit message:",G)}};textController=new ZG;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new IY);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(Bg1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new a7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;commands=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new Gg1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Lp1(this.getCommands(),this.widget.dependencies.fuzzyServer,new vd(this.widget.dependencies.configService),this.widget.dependencies.configService,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.setState(()=>{this.isShowingIdePicker=!1});return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}showCommandPalette(){if(!this.isShowingPalette)this.loadThreadsForPicker();this.setState(()=>{this.isShowingPalette=!this.isShowingPalette})}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new Up1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})});return this.paletteCommands}dismissPalette=()=>{this.isShowingPalette=!1,this.setState(()=>{this.previewThread=null})};handleThreadPreview=async(J)=>{if(J===null){this.setState(()=>{this.previewThread=null});return}if(this.previewCache.has(J)){this.setState(()=>{this.previewThread=this.previewCache.get(J)??null});return}let Q=await this.widget.dependencies.threadService.get(J);if(Q)this.previewCache.set(J,Q),this.setState(()=>{this.previewThread=Q})};getCommandPaletteContext=(J)=>{let{threadState:Q}=this.widget.dependencies;if(!Q.mainThread)return null;return{worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.onOpenInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},editorDispatch:(Z)=>{if(Z.type==="set-input")this.textController.clear(),this.textController.insertText(Z.input);else if(Z.type==="clear")this.textController.clear()},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{let Z=await this.widget.dependencies.startNewThread();KN(Z)},switchToThread:async(Z)=>{await this.switchToExistingThread(Z)},handleHandoff:async(Z)=>{let X=Z.trim();if(!X){this.setState(()=>{this.displayMessage=Error("Cannot handoff with empty prompt text")});return}try{let Y=this.widget.dependencies.threadState.mainThread?.id;if(!Y){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let K=new AbortController,G=setTimeout(()=>K.abort(),60000);try{let q=await this.widget.dependencies.threadService.createHandoffThread(Y,X,this.widget.dependencies.configService,K.signal);clearTimeout(G),await this.switchToExistingThread(q)}catch(q){if(clearTimeout(G),q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")))throw Error("Handoff took too long and was aborted (timeout: 60s)");throw q}}catch(Y){u.error("Failed to create handoff thread",Y),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${Y instanceof Error?Y.message:String(Y)}`)})}},getGuidanceFiles:async()=>{if(!Q.mainThread)return[];return(await p_({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,J.signal)).map((X)=>({uri:X.uri,type:X.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode}};getThreadsForPicker(){return this.threadsForPicker}async loadThreadsForPicker(){if(this.isLoadingThreads)return;this.isLoadingThreads=!0;try{let Q=await new vd(this.widget.dependencies.configService).fetchThreadSummaries("",0,50);if(Q.ok){let Z=this.widget.dependencies.threadID;this.setState(()=>{this.threadsForPicker=Q.threads.filter((X)=>X.id!==Z).map((X)=>({id:X.id,title:X.title,messageCount:X.messageCount,timeAgo:X.description.timeAgo,shortThreadID:X.description.shortThreadID}))})}}finally{this.isLoadingThreads=!1}}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(G)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:G}:z);else{let z={id:X,args:Y,toolRun:G,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleAgentMode=()=>{if((nK()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=Tc(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=Tc(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:G}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{M2.instance.tuiInstance.suspend();let W=await Z(z.join(q(),"amp-edit-")),F=z.join(W,"message.amp.md");await G(F,J,"utf-8"),Q(`${U} "${F}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(F,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")u.error("Failed to read temporary file",H)}try{await Y(F),await K(W)}catch(H){u.warn("Failed to clean up temporary file",H)}M2.instance.tuiInstance.resume()}catch(W){try{M2.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=this.parseShellModeInput(J);if(Q){if(Q.cmd&&!this.isProcessing())this.invokeBashCommand(Q.cmd,{hidden:Q.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let Z=xY6(J),{threadState:X}=this.widget.dependencies;if(this.isSlashCommand(Z)&&X.mainThread){let Y=Z.slice(1).split(" "),K=Y[0],G=Y.slice(1).filter((q)=>q.trim()!=="");if(K){let q=X.viewState,z=this.getCommands().query(K,X.mainThread,q).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&G.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,G)}else if(K==="compact")this.setState(()=>{this.displayMessage=Error("The /compact command has been removed. Use /handoff to draft a new thread with relevant context instead.")}),this.textController.clear();return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(Z)};onOptionSelected=(J)=>{switch(J.type){case"hint":return;case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),G=Q.slice(Z),q=K+`@${J.path} `+G;this.textController.clear(),this.textController.insertText(q),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Q=this.textController.text,Z=this.textController.cursorPosition,X=Q.split(" ");if(X.length>=1&&X[0]==="/continue"){let Y=`/continue ${J.threadId} `;this.onTextSubmitted(Y)}else{let K=Q.slice(0,Z).lastIndexOf("@");if(K!==-1){let G=Q.slice(0,K),q=Q.slice(Z),z=G+`@${J.threadId} `+q;this.textController.clear(),this.textController.insertText(z),this.textController.cursorPosition=K+1+J.threadId.length+1}}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),G={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,statusMessage:J.statusMessage,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=G});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();KN(z);return}if(J.name==="handoff"){let z=Q?.join(" ").trim()||"";if(!z){this.setState(()=>{this.displayMessage=Error("Usage: /handoff <describe your goal>")});return}try{let U=this.widget.dependencies.threadState.mainThread?.id;if(!U){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let W=new AbortController,F=setTimeout(()=>W.abort(),20000),H=await this.widget.dependencies.threadService.createHandoffThread(U,z,this.widget.dependencies.configService,W.signal);clearTimeout(F),await this.switchToExistingThread(H)}catch(U){u.error("Failed to create handoff thread",U),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${U instanceof Error?U.message:String(U)}`)})}return}if(J.launchesWindow)M2.instance.tuiInstance.suspend();let q=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},submitMessage:(z)=>{return this.proceedWithUserMessage(z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},openInEditor:this.onOpenInEditor,getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await p_({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode},Q,X.signal);if(J.launchesWindow)M2.instance.tuiInstance.resume();if(q)this.setState(()=>{this.displayMessage=q})}catch(q){u.error("Error executing command:",q)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=new kd().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(RY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;M2.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),M2.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),M2.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{c9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=bY6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);u.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.adSubscription=Kh1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&Yh1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=_B9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (KZ1(),YZ1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,G=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:G?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}}),KN(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let X=nK();if(!X){u.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),u.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),u.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=wZ(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Z,X)=>{if(Z.length<=3)return!0;let Y=fY6(Z);if(!Y)return!0;let K=this.getEffectiveAgentMode();if(!Pc(K)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=O00)return!1;let G=hY6(Y);if(G)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,G]}),!1;return this.setState(()=>{this.displayMessage=Error("Failed to attach image: file may be empty, too large, or unsupported")}),!1},this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{u.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Bg1("")),this.shouldUseProgressBar())process.stdout.write(Eq6())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((q)=>q.type==="toolResult").map((q)=>({toolUse:q.toolUse,toolRun:q.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],G=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:G}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){u.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){u.error("No tool use block found in confirmation");return}if(J==="allow-all-session")RZ("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else u.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],G=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",G)}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await PQ(Y)}catch(K){u.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(Gz))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,Gz])}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await VJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){u.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null});let X=await this.widget.dependencies.startNewThread();KN(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),Jh1({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();KN(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await VJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J)=>{try{u.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;if(u.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,KN(Q),y51()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{u.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z}),Q.thread.draft)u.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),this.textController.insertText(Q.thread.draft)}catch(Q){throw u.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=nK()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{let J=this.getEffectiveAgentMode();Jh1({agentMode:J}).catch((Q)=>{u.warn("Failed to save session state on exit:",Q)}).finally(()=>{M2.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=xB9();if(J===Q)return"~";if(J.startsWith(Q+_d.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(_d.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(_d.sep),"…",Q.slice(-2).join(_d.sep)].join(_d.sep)}build(J){let Q=_8.of(J),Z=O6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let q=(nK()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new ON({child:new dp1({onSelect:async(w1)=>{if(w1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(w1);else process.exit(0)},pageSize:50,threadFetcher:new vd(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,F=z.mainThread?.id,H=z.mainThread||void 0,B=this.isTranscriptEmpty(),M=(w1)=>new fQ1({key:new a7(`preview-message-view-${w1.id}`),items:Wp(w1).items,controller:this.previewScrollController,autofocus:!1,thread:w1,focusNode:new Q9({debugLabel:"PreviewFocus"})}),V=this.previewThread?M(this.previewThread):B?new hQ1({agentMode:this.getEffectiveAgentMode()}):new fQ1({key:F?new a7(`message-view-${F}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:F?this.getMessageScrollController(F):new IY,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:H,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),N=Math.max(Math.floor(Q.size.height*0.4),12),L=this.getCurrentEphemeralError(),A=this.buildBottomWidget(L,U,Y,Z,z,W,N,q?this.randomAd:null),w=Q.size.width<40,R=z.mainThread?Aa1(z.mainThread):void 0,O=new YQ1({threadViewState:z.viewState,threadTokenUsage:R,threadID:F??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:w,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),$=new XQ1({bashInvocations:this.bashInvocations}),j=[],E=this.getEffectiveAgentMode(),I=this.currentShellModeStatus,T=np1(E),S=!I?E.length+1:0,_=Q.capabilities.animationSupport,h=_==="disabled"?0:_==="slow"?30:60,v=1,x=h>0&&this.agentModePulseSeq>0?new kJ({children:[A,new $X({top:0,left:1,right:1,height:1,child:new gp1({color:T,trigger:this.agentModePulseSeq,fps:h,speed:v,leftOffset:S})})]}):A;if(j.push(new R8({child:V}),$),q)j.push(new qp1({ad:this.randomAd,onButtonClick:async()=>{let w1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (KZ1(),YZ1)).then(({recordAdEvent:D1})=>{let y1=this.widget.dependencies.worker.thread,l1=y1.messages[y1.messages.length-1];D1("clicked",{adId:w1.id,advertiserId:w1.advertiserId,threadId:y1.id,messageId:l1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await PQ(w1.shortDestinationUrl)}catch(D1){let l1=M2.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:l1,url:w1.shortDestinationUrl}})}}}));j.push(new f0({constraints:new R6(0,Q.size.width,0,N),child:x}),new U0({height:1,child:new b6({padding:N0.horizontal(1),child:O})}));let y=new i0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),g=new S9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingQRCodeOverlay)return this.setState(()=>{this.isShowingQRCodeOverlay=!1,this.qrCodeOverlayData=null}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return u.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((D1)=>{u.error("Failed to mark message as interrupted:",D1)}),this.cancelStreamingMessage().catch((D1)=>{u.error("Failed to cancel streaming message:",D1)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),k=new S9(()=>{return this.onExitPressed(),"handled"}),f=new S9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),b=new S9(()=>{return $Q.instance.toggleAll(),"handled"}),m=new S9(()=>{return this.widget.dependencies.configService.getLatest().then((w1)=>{RZ("internal.showCost",!(w1.settings["internal.showCost"]??!0))}),"handled"}),n=new S9(()=>{return M2.instance.toggleFrameStatsOverlay(),"handled"}),p=new S9(()=>{return M2.instance.tuiInstance.getScreen().markForRefresh(),c9.instance.requestFrame(),"handled"}),e=new S9(()=>{return this.toggleAgentMode(),"handled"}),G1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;D1.animatePageUp(l1,100)}return"handled"}),W1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;D1.animatePageDown(l1,100)}return"handled"}),Z1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1)D1.animateTo(0,100);return"handled"}),F1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1)D1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new S9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:w1}=this.widget.dependencies;if(!w1.mainThread?.messages.some((y1)=>y1.role==="user"))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),d=new S9((w1)=>{if(w1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[y6.ctrl("c"),new Jd],[y6.ctrl("l"),new Kd],[y6.ctrl("o"),new pJ1],[y6.alt("s"),new eC],[y6.ctrl("s"),new eC],[y6.alt("p"),new Yd],[y6.ctrl("r"),new Zd],[y6.alt("d"),new Xd],[y6.key("PageUp"),new hJ1],[y6.key("PageDown"),new gJ1],[y6.key("Home"),new mJ1],[y6.key("End"),new uJ1],[y6.key("Escape"),new ep],[y6.ctrl("p"),new JS("previous")],[y6.ctrl("n"),new JS("next")],[y6.key("Tab"),new Gd]]);if(!LQ())i.set(y6.key("ArrowUp"),new Gd);if(!1)i.set(y6.alt("c"),new Qd);let o=new S9(()=>{return this.showCommandPalette(),"handled"}),Y1=new Map([[ep,g],[Kd,p],[eC,e],[pJ1,o],[Qd,f],[Zd,b],[Xd,m],[Yd,n],[Jd,k],[hJ1,G1],[gJ1,W1],[mJ1,Z1],[uJ1,F1],[Gd,l],[JS,d]]),J1=[y];if(this.isShowingConsoleOverlay)J1.push(new Rp1);if(this.isShowingHelp)J1.push(new $p1);if(this.adActionModal)J1.push(new zp1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(w1)=>{let D1=this.adActionModal.url;if(w1==="copy")try{await M2.instance.tuiInstance.clipboard.writeText(D1),this.setState(()=>{this.displayMessage=new t9("Link copied to clipboard")})}catch(y1){u.error("Failed to copy to clipboard",{error:y1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)J1.push(new Nm1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)J1.push(new Op1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)J1.push(new Ap1({details:this.confirmationOverlayContent}));if(this.isShowingQRCodeOverlay&&this.qrCodeOverlayData)J1.push(new up1({url:this.qrCodeOverlayData.url,qrCode:this.qrCodeOverlayData.qrCode}));let H1=this.getCommandPaletteContext(new AbortController);if(H1&&this.isShowingPalette){let w1=this.getThreadsForPicker();J1.push(new C9({child:new f0({constraints:R6.loose(80,20),child:new Mp1({commandContext:H1,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,threads:w1,onThreadPreview:this.handleThreadPreview})})}))}if(this.isShowingIdePicker)J1.push(new Ep1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let z1=new kJ({children:J1});if(this.isShowingJetBrainsInstaller)return new ON({child:new NZ({actions:Y1,child:new aq({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new hp1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let U1=new jN({onError:(w1)=>{this.showErrorMessage(w1.message)},child:z1});return new ON({child:new NZ({actions:Y1,child:new aq({shortcuts:i,debugLabel:"main-app-shortcuts",child:U1})})})}buildBottomWidget(J,Q,Z,X,Y,K,G,q){if(J)return new jp1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new wp1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new mp1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=bB9(X),W=this.isInRestrictedFreeMode(),F=new nJ1({key:this.textFieldKey,controller:this.textController,triggers:[new kd],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(S)=>Np1(S),overlayBorderColor:Z.border,focusNode:this.autocompleteFocusNode,canStealFocus:!this.isMessageViewInSelectionMode,textFieldProps:{placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!1,enabled:this.isTextfieldAndAutocompleteFocused&&!W,onSubmitted:this.onTextSubmitted,onOpenInEditor:this.onOpenInEditor,submitKey:{character:"Enter"},prompts:U,style:{border:null},clipboard:M2.instance.tuiInstance.clipboard},optionViewBuilder:(S,_,h)=>{let v=h?Z.selection:void 0,x=_.type==="command"||_.type==="thread"?Z.warning:Z.secondary,y=Z.foreground,g=Z.foreground,k,f;switch(_.type){case"command":k="/",f=_.name;break;case"file":k="@",f=_.path;break;case"thread":k="@",f=_.title;break;case"hint":k="",f=_.message;break;default:k="",f=Np1(_);break}let b=OF6(_),m=new V1(k,new $1({color:x})),n=new V1(f,new $1({color:y})),p=[m,n];if(b){let e=new V1(" - ",new $1({color:g,dim:!0})),G1=new V1(b,new $1({color:g,dim:!0}));p.push(e,G1)}return new f0({decoration:new i8(v),child:new n1({text:new V1("",void 0,p),maxLines:1,overflow:"ellipsis"})})}}),H=Y.mainThread?.queuedMessages??[],B=this.currentShellModeStatus,M=this.imageAttachments.length>0?new f0({padding:N0.only({bottom:1,left:1}),child:new n1({text:new V1("",void 0,[new V1("Images: ",new $1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((S,_)=>[new V1(`[image ${_+1}]`,new $1({color:Z.success})),..._<this.imageAttachments.length-1?[new V1(" ")]:[]])])})}):null,V=Array.isArray(K)&&K.length>0,N=Array.isArray(H)&&H.length>0,L=[];if(M)L.push(M);L.push(new R8({child:F}));let A=new i0({crossAxisAlignment:"start",children:L}),w=N?new pp1({queuedMessages:H}):void 0,R=V?new Tg1(new Gp1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,O=[];if(B)O.push({text:new V1(B==="hidden"?"shell mode (incognito)":"shell mode",new $1({color:B==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:M?1:0});let $=this.getEffectiveAgentMode();if(!B&&this.cachedVisibleModes.length>1){let S=np1($),h=Tc($,this.cachedVisibleModes)!==$,x=(nK()||this.widget.dependencies.worker).thread.messages.length===0,g=W||!this.hasToggledAgentMode&&h&&x?new V1("",void 0,[new V1($,new $1({color:S})),new V1(" (click or ",new $1({color:Z.foreground,dim:!0})),new V1("Ctrl+S",new $1({color:z.keybind})),new V1(" to switch)",new $1({color:Z.foreground,dim:!0}))]):new V1($,new $1({color:S}));O.push({text:g,position:"top-left",offsetY:0,onClick:x?this.toggleAgentMode:void 0})}let j=Y.mainThread?.metadata?.treeInfo?.uri,E;if(j)E=$0.isUri(j)?j.fsPath:j;else E=process.cwd();let I=this.toHomeRelative(E),T=this.shorten(I);return O.push({text:new V1(T,new $1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new qm1({leftChild:A,rightChild1:w,rightChild2:R,maxHeight:G,overlayTexts:O,borderColor:W||!this.isTextfieldAndAutocompleteFocused?I1.index(8):void 0,hasBanner:q!==null})}}async function NH6(J){let X=new XB(!1,1000,J.inspectorPort),Y=new $f1({threadService:J.threadService,worker:J.worker,builder:(H,B)=>{let M=nK(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new MH6({...N,threadState:B})}}),K=new Bm1({configService:J.configService,child:Y}),G=new Wm1({configService:J.configService,child:K}),q=new mg1(G),z=new O6({data:ZS.fromBaseTheme(QG.default()),child:q});try{await Ig1(z,{onRootElementMounted:void 0})}finally{}let W=nK()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let H=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6685
|
+
`))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}function FH6(J,Q){switch(J){case"update-available":return[new V1("A newer Amp is available. Run ",new $1({color:Q.foreground,dim:!0})),new V1("amp update",new $1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new V1("Update complete, run ",new $1({color:Q.foreground,dim:!0})),new V1("amp update",new $1({color:Q.warning})),new V1(" to see warnings",new $1({color:Q.foreground,dim:!0}))];case"update-error":return[new V1("Update failed, run ",new $1({color:Q.foreground,dim:!0})),new V1("amp update",new $1({color:Q.warning})),new V1(" to see warnings",new $1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function bB9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new $1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new $1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class MH6 extends c0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new VH6}}class VH6 extends d0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;threadsForPicker=[];isLoadingThreads=!1;previewThread=null;previewCache=new Map;previewScrollController=new IY;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new Q9({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new Q9({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=wZ();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new V1(this.submitDisabledHint,new $1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new V1("",void 0,[new V1("Ctrl+C",new $1({color:Q.keybind})),new V1(" again to exit",new $1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new V1("",void 0,[new V1("Esc",new $1({color:Q.keybind})),new V1(" again to clear input",new $1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new V1("",void 0,[new V1("Escape",new $1({color:Q.keybind})),new V1(" to close help",new $1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=np1(X);return new V1("",void 0,[new V1("Images aren't supported in ",new $1({color:J.warning,dim:!1})),new V1(X,new $1({color:Y})),new V1(" mode.",new $1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new V1("",void 0,[new V1("Esc",new $1({color:Q.keybind})),new V1(" to cancel",new $1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new V1("Selection copied to clipboard",new $1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new V1(this.showingCannotToggleMessage,new $1({color:J.warning,dim:!1}));let Z=FH6(this.updateState,J);if(Z)return new V1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let Y=Q.mainThread?.messages.findIndex((K)=>K===J);if(Y===void 0||Y===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:Y}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){u.error("Failed to edit message:",K)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;let G=Q.mainThread?.messages.findIndex((q)=>q===J);if(G===void 0||G<=0)return;try{let q=await VJ.getOrCreateForThread(Z,K),z=await bs(q,X,G),U=await Y(z);KN(U),this.widget.dependencies.worker=U,this.widget.dependencies.threadID=U.thread.id;let W=U.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=W})}catch(q){u.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;let K=Y.messages.findIndex((G)=>G===J);if(K===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let G=[{type:"text",text:Q}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);let q={content:G,agentMode:Y.agentMode},z=K===0;if(Y.agentMode&&!z&&q.agentMode!==Y.agentMode){u.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:q,index:K}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){u.error("Failed to edit message:",G)}};textController=new ZG;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new IY);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(Bg1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new a7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;commands=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new Gg1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Lp1(this.getCommands(),this.widget.dependencies.fuzzyServer,new vd(this.widget.dependencies.configService),this.widget.dependencies.configService,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.setState(()=>{this.isShowingIdePicker=!1});return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}showCommandPalette(){if(!this.isShowingPalette)this.loadThreadsForPicker();this.setState(()=>{this.isShowingPalette=!this.isShowingPalette})}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new Up1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})});return this.paletteCommands}dismissPalette=()=>{this.isShowingPalette=!1,this.setState(()=>{this.previewThread=null})};handleThreadPreview=async(J)=>{if(J===null){this.setState(()=>{this.previewThread=null});return}if(this.previewCache.has(J)){this.setState(()=>{this.previewThread=this.previewCache.get(J)??null});return}let Q=await this.widget.dependencies.threadService.get(J);if(Q)this.previewCache.set(J,Q),this.setState(()=>{this.previewThread=Q})};getCommandPaletteContext=(J)=>{let{threadState:Q}=this.widget.dependencies;if(!Q.mainThread)return null;return{worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.onOpenInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},editorDispatch:(Z)=>{if(Z.type==="set-input")this.textController.clear(),this.textController.insertText(Z.input);else if(Z.type==="clear")this.textController.clear()},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{let Z=await this.widget.dependencies.startNewThread();KN(Z)},switchToThread:async(Z)=>{await this.switchToExistingThread(Z)},handleHandoff:async(Z)=>{let X=Z.trim();if(!X){this.setState(()=>{this.displayMessage=Error("Cannot handoff with empty prompt text")});return}try{let Y=this.widget.dependencies.threadState.mainThread?.id;if(!Y){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let K=new AbortController,G=setTimeout(()=>K.abort(),60000);try{let q=await this.widget.dependencies.threadService.createHandoffThread(Y,X,this.widget.dependencies.configService,K.signal);clearTimeout(G),await this.switchToExistingThread(q)}catch(q){if(clearTimeout(G),q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")))throw Error("Handoff took too long and was aborted (timeout: 60s)");throw q}}catch(Y){u.error("Failed to create handoff thread",Y),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${Y instanceof Error?Y.message:String(Y)}`)})}},getGuidanceFiles:async()=>{if(!Q.mainThread)return[];return(await p_({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,J.signal)).map((X)=>({uri:X.uri,type:X.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode}};getThreadsForPicker(){return this.threadsForPicker}async loadThreadsForPicker(){if(this.isLoadingThreads)return;this.isLoadingThreads=!0;try{let Q=await new vd(this.widget.dependencies.configService).fetchThreadSummaries("",0,50);if(Q.ok){let Z=this.widget.dependencies.threadID;this.setState(()=>{this.threadsForPicker=Q.threads.filter((X)=>X.id!==Z).map((X)=>({id:X.id,title:X.title,messageCount:X.messageCount,timeAgo:X.description.timeAgo,shortThreadID:X.description.shortThreadID}))})}}finally{this.isLoadingThreads=!1}}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(G)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:G}:z);else{let z={id:X,args:Y,toolRun:G,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleAgentMode=()=>{if((nK()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=Tc(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=Tc(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:G}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{M2.instance.tuiInstance.suspend();let W=await Z(z.join(q(),"amp-edit-")),F=z.join(W,"message.amp.md");await G(F,J,"utf-8"),Q(`${U} "${F}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(F,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")u.error("Failed to read temporary file",H)}try{await Y(F),await K(W)}catch(H){u.warn("Failed to clean up temporary file",H)}M2.instance.tuiInstance.resume()}catch(W){try{M2.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=this.parseShellModeInput(J);if(Q){if(Q.cmd&&!this.isProcessing())this.invokeBashCommand(Q.cmd,{hidden:Q.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let Z=xY6(J);this.textController.clear(),this.resetHistory(),await this.sendUserMessage(Z)};onOptionSelected=(J)=>{switch(J.type){case"hint":return;case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),G=Q.slice(Z),q=K+`@${J.path} `+G;this.textController.clear(),this.textController.insertText(q),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Q=this.textController.text,Z=this.textController.cursorPosition,X=Q.split(" ");if(X.length>=1&&X[0]==="/continue"){let Y=`/continue ${J.threadId} `;this.onTextSubmitted(Y)}else{let K=Q.slice(0,Z).lastIndexOf("@");if(K!==-1){let G=Q.slice(0,K),q=Q.slice(Z),z=G+`@${J.threadId} `+q;this.textController.clear(),this.textController.insertText(z),this.textController.cursorPosition=K+1+J.threadId.length+1}}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),G={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,statusMessage:J.statusMessage,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=G});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();KN(z);return}if(J.name==="handoff"){let z=Q?.join(" ").trim()||"";if(!z){this.setState(()=>{this.displayMessage=Error("Usage: /handoff <describe your goal>")});return}try{let U=this.widget.dependencies.threadState.mainThread?.id;if(!U){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let W=new AbortController,F=setTimeout(()=>W.abort(),20000),H=await this.widget.dependencies.threadService.createHandoffThread(U,z,this.widget.dependencies.configService,W.signal);clearTimeout(F),await this.switchToExistingThread(H)}catch(U){u.error("Failed to create handoff thread",U),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${U instanceof Error?U.message:String(U)}`)})}return}if(J.launchesWindow)M2.instance.tuiInstance.suspend();let q=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},submitMessage:(z)=>{return this.proceedWithUserMessage(z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},openInEditor:this.onOpenInEditor,getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await p_({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode},Q,X.signal);if(J.launchesWindow)M2.instance.tuiInstance.resume();if(q)this.setState(()=>{this.displayMessage=q})}catch(q){u.error("Error executing command:",q)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=new kd().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(RY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;M2.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),M2.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),M2.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{c9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=bY6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);u.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.adSubscription=Kh1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&Yh1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=_B9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (KZ1(),YZ1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,G=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:G?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}}),KN(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let X=nK();if(!X){u.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),u.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),u.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=wZ(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Z,X)=>{if(Z.length<=3)return!0;let Y=fY6(Z);if(!Y)return!0;let K=this.getEffectiveAgentMode();if(!Pc(K)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=O00)return!1;let G=hY6(Y);if(G)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,G]}),!1;return this.setState(()=>{this.displayMessage=Error("Failed to attach image: file may be empty, too large, or unsupported")}),!1},this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{u.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Bg1("")),this.shouldUseProgressBar())process.stdout.write(Eq6())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((q)=>q.type==="toolResult").map((q)=>({toolUse:q.toolUse,toolRun:q.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],G=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:G}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){u.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){u.error("No tool use block found in confirmation");return}if(J==="allow-all-session")RZ("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else u.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],G=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",G)}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await PQ(Y)}catch(K){u.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(Gz))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,Gz])}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await VJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){u.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null});let X=await this.widget.dependencies.startNewThread();KN(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),Jh1({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();KN(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await VJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J)=>{try{u.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;if(u.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,KN(Q),y51()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{u.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z}),Q.thread.draft)u.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),this.textController.insertText(Q.thread.draft)}catch(Q){throw u.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=nK()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{let J=this.getEffectiveAgentMode();Jh1({agentMode:J}).catch((Q)=>{u.warn("Failed to save session state on exit:",Q)}).finally(()=>{M2.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=xB9();if(J===Q)return"~";if(J.startsWith(Q+_d.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(_d.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(_d.sep),"…",Q.slice(-2).join(_d.sep)].join(_d.sep)}build(J){let Q=_8.of(J),Z=O6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let q=(nK()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new ON({child:new dp1({onSelect:async(w1)=>{if(w1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(w1);else process.exit(0)},pageSize:50,threadFetcher:new vd(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,F=z.mainThread?.id,H=z.mainThread||void 0,B=this.isTranscriptEmpty(),M=(w1)=>new fQ1({key:new a7(`preview-message-view-${w1.id}`),items:Wp(w1).items,controller:this.previewScrollController,autofocus:!1,thread:w1,focusNode:new Q9({debugLabel:"PreviewFocus"})}),V=this.previewThread?M(this.previewThread):B?new hQ1({agentMode:this.getEffectiveAgentMode()}):new fQ1({key:F?new a7(`message-view-${F}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:F?this.getMessageScrollController(F):new IY,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:H,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),N=Math.max(Math.floor(Q.size.height*0.4),12),L=this.getCurrentEphemeralError(),A=this.buildBottomWidget(L,U,Y,Z,z,W,N,q?this.randomAd:null),w=Q.size.width<40,R=z.mainThread?Aa1(z.mainThread):void 0,O=new YQ1({threadViewState:z.viewState,threadTokenUsage:R,threadID:F??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:w,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),$=new XQ1({bashInvocations:this.bashInvocations}),j=[],E=this.getEffectiveAgentMode(),I=this.currentShellModeStatus,T=np1(E),S=!I?E.length+1:0,_=Q.capabilities.animationSupport,h=_==="disabled"?0:_==="slow"?30:60,v=1,x=h>0&&this.agentModePulseSeq>0?new kJ({children:[A,new $X({top:0,left:1,right:1,height:1,child:new gp1({color:T,trigger:this.agentModePulseSeq,fps:h,speed:v,leftOffset:S})})]}):A;if(j.push(new R8({child:V}),$),q)j.push(new qp1({ad:this.randomAd,onButtonClick:async()=>{let w1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (KZ1(),YZ1)).then(({recordAdEvent:D1})=>{let y1=this.widget.dependencies.worker.thread,l1=y1.messages[y1.messages.length-1];D1("clicked",{adId:w1.id,advertiserId:w1.advertiserId,threadId:y1.id,messageId:l1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await PQ(w1.shortDestinationUrl)}catch(D1){let l1=M2.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:l1,url:w1.shortDestinationUrl}})}}}));j.push(new f0({constraints:new R6(0,Q.size.width,0,N),child:x}),new U0({height:1,child:new b6({padding:N0.horizontal(1),child:O})}));let y=new i0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),g=new S9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingQRCodeOverlay)return this.setState(()=>{this.isShowingQRCodeOverlay=!1,this.qrCodeOverlayData=null}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return u.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((D1)=>{u.error("Failed to mark message as interrupted:",D1)}),this.cancelStreamingMessage().catch((D1)=>{u.error("Failed to cancel streaming message:",D1)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),k=new S9(()=>{return this.onExitPressed(),"handled"}),f=new S9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),b=new S9(()=>{return $Q.instance.toggleAll(),"handled"}),m=new S9(()=>{return this.widget.dependencies.configService.getLatest().then((w1)=>{RZ("internal.showCost",!(w1.settings["internal.showCost"]??!0))}),"handled"}),n=new S9(()=>{return M2.instance.toggleFrameStatsOverlay(),"handled"}),p=new S9(()=>{return M2.instance.tuiInstance.getScreen().markForRefresh(),c9.instance.requestFrame(),"handled"}),e=new S9(()=>{return this.toggleAgentMode(),"handled"}),G1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;D1.animatePageUp(l1,100)}return"handled"}),W1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;D1.animatePageDown(l1,100)}return"handled"}),Z1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1)D1.animateTo(0,100);return"handled"}),F1=new S9(()=>{let D1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(D1)D1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new S9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:w1}=this.widget.dependencies;if(!w1.mainThread?.messages.some((y1)=>y1.role==="user"))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),d=new S9((w1)=>{if(w1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[y6.ctrl("c"),new Jd],[y6.ctrl("l"),new Kd],[y6.ctrl("o"),new pJ1],[y6.alt("s"),new eC],[y6.ctrl("s"),new eC],[y6.alt("p"),new Yd],[y6.ctrl("r"),new Zd],[y6.alt("d"),new Xd],[y6.key("PageUp"),new hJ1],[y6.key("PageDown"),new gJ1],[y6.key("Home"),new mJ1],[y6.key("End"),new uJ1],[y6.key("Escape"),new ep],[y6.ctrl("p"),new JS("previous")],[y6.ctrl("n"),new JS("next")],[y6.key("Tab"),new Gd]]);if(!LQ())i.set(y6.key("ArrowUp"),new Gd);if(!1)i.set(y6.alt("c"),new Qd);let o=new S9(()=>{return this.showCommandPalette(),"handled"}),Y1=new Map([[ep,g],[Kd,p],[eC,e],[pJ1,o],[Qd,f],[Zd,b],[Xd,m],[Yd,n],[Jd,k],[hJ1,G1],[gJ1,W1],[mJ1,Z1],[uJ1,F1],[Gd,l],[JS,d]]),J1=[y];if(this.isShowingConsoleOverlay)J1.push(new Rp1);if(this.isShowingHelp)J1.push(new $p1);if(this.adActionModal)J1.push(new zp1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(w1)=>{let D1=this.adActionModal.url;if(w1==="copy")try{await M2.instance.tuiInstance.clipboard.writeText(D1),this.setState(()=>{this.displayMessage=new t9("Link copied to clipboard")})}catch(y1){u.error("Failed to copy to clipboard",{error:y1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)J1.push(new Nm1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)J1.push(new Op1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)J1.push(new Ap1({details:this.confirmationOverlayContent}));if(this.isShowingQRCodeOverlay&&this.qrCodeOverlayData)J1.push(new up1({url:this.qrCodeOverlayData.url,qrCode:this.qrCodeOverlayData.qrCode}));let H1=this.getCommandPaletteContext(new AbortController);if(H1&&this.isShowingPalette){let w1=this.getThreadsForPicker();J1.push(new C9({child:new f0({constraints:R6.loose(80,20),child:new Mp1({commandContext:H1,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,threads:w1,onThreadPreview:this.handleThreadPreview})})}))}if(this.isShowingIdePicker)J1.push(new Ep1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let z1=new kJ({children:J1});if(this.isShowingJetBrainsInstaller)return new ON({child:new NZ({actions:Y1,child:new aq({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new hp1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let U1=new jN({onError:(w1)=>{this.showErrorMessage(w1.message)},child:z1});return new ON({child:new NZ({actions:Y1,child:new aq({shortcuts:i,debugLabel:"main-app-shortcuts",child:U1})})})}buildBottomWidget(J,Q,Z,X,Y,K,G,q){if(J)return new jp1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new wp1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new mp1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=bB9(X),W=this.isInRestrictedFreeMode(),F=new nJ1({key:this.textFieldKey,controller:this.textController,triggers:[new kd],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(S)=>Np1(S),overlayBorderColor:Z.border,focusNode:this.autocompleteFocusNode,canStealFocus:!this.isMessageViewInSelectionMode,textFieldProps:{placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!1,enabled:this.isTextfieldAndAutocompleteFocused&&!W,onSubmitted:this.onTextSubmitted,onOpenInEditor:this.onOpenInEditor,submitKey:{character:"Enter"},prompts:U,style:{border:null},clipboard:M2.instance.tuiInstance.clipboard},optionViewBuilder:(S,_,h)=>{let v=h?Z.selection:void 0,x=_.type==="command"||_.type==="thread"?Z.warning:Z.secondary,y=Z.foreground,g=Z.foreground,k,f;switch(_.type){case"command":k="/",f=_.name;break;case"file":k="@",f=_.path;break;case"thread":k="@",f=_.title;break;case"hint":k="",f=_.message;break;default:k="",f=Np1(_);break}let b=OF6(_),m=new V1(k,new $1({color:x})),n=new V1(f,new $1({color:y})),p=[m,n];if(b){let e=new V1(" - ",new $1({color:g,dim:!0})),G1=new V1(b,new $1({color:g,dim:!0}));p.push(e,G1)}return new f0({decoration:new i8(v),child:new n1({text:new V1("",void 0,p),maxLines:1,overflow:"ellipsis"})})}}),H=Y.mainThread?.queuedMessages??[],B=this.currentShellModeStatus,M=this.imageAttachments.length>0?new f0({padding:N0.only({bottom:1,left:1}),child:new n1({text:new V1("",void 0,[new V1("Images: ",new $1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((S,_)=>[new V1(`[image ${_+1}]`,new $1({color:Z.success})),..._<this.imageAttachments.length-1?[new V1(" ")]:[]])])})}):null,V=Array.isArray(K)&&K.length>0,N=Array.isArray(H)&&H.length>0,L=[];if(M)L.push(M);L.push(new R8({child:F}));let A=new i0({crossAxisAlignment:"start",children:L}),w=N?new pp1({queuedMessages:H}):void 0,R=V?new Tg1(new Gp1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,O=[];if(B)O.push({text:new V1(B==="hidden"?"shell mode (incognito)":"shell mode",new $1({color:B==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:M?1:0});let $=this.getEffectiveAgentMode();if(!B&&this.cachedVisibleModes.length>1){let S=np1($),h=Tc($,this.cachedVisibleModes)!==$,x=(nK()||this.widget.dependencies.worker).thread.messages.length===0,g=W||!this.hasToggledAgentMode&&h&&x?new V1("",void 0,[new V1($,new $1({color:S})),new V1(" (click or ",new $1({color:Z.foreground,dim:!0})),new V1("Ctrl+S",new $1({color:z.keybind})),new V1(" to switch)",new $1({color:Z.foreground,dim:!0}))]):new V1($,new $1({color:S}));O.push({text:g,position:"top-left",offsetY:0,onClick:x?this.toggleAgentMode:void 0})}let j=Y.mainThread?.metadata?.treeInfo?.uri,E;if(j)E=$0.isUri(j)?j.fsPath:j;else E=process.cwd();let I=this.toHomeRelative(E),T=this.shorten(I);return O.push({text:new V1(T,new $1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new qm1({leftChild:A,rightChild1:w,rightChild2:R,maxHeight:G,overlayTexts:O,borderColor:W||!this.isTextfieldAndAutocompleteFocused?I1.index(8):void 0,hasBanner:q!==null})}}async function NH6(J){let X=new XB(!1,1000,J.inspectorPort),Y=new $f1({threadService:J.threadService,worker:J.worker,builder:(H,B)=>{let M=nK(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new MH6({...N,threadState:B})}}),K=new Bm1({configService:J.configService,child:Y}),G=new Wm1({configService:J.configService,child:K}),q=new mg1(G),z=new O6({data:ZS.fromBaseTheme(QG.default()),child:q});try{await Ig1(z,{onRootElementMounted:void 0})}finally{}let W=nK()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let H=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6686
6686
|
`),J.stdout.write(`Thread: ${H}
|
|
6687
6687
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6688
6688
|
`)}}function np1(J){return J==="smart"?I1.rgb(3,197,97):J==="free"?I1.rgb(0,184,255):yB9(J)}function yB9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return I1.index(Z[X])}Eg1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){YG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6689
|
-
`)}var rp1=ap1.join(ji1||ap1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function uB9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function oq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")RZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new k9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${W8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")RZ("experimental.agentMode",Q.agentMode)}async function op1(J){try{await hB9(ap1.dirname(rp1),{recursive:!0}),await gB9(rp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function pB9(){try{return(await RH6(rp1,"utf-8")).trim()}catch(J){return null}}function dB9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return lS("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var LH6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??DZ,description:`Custom settings file path (overrides the default location ${DZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Lf1})`},{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:LQ(),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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Ic}],AH6=(J)=>("deprecated"in J)&&J.deprecated===!0,cB9=(J)=>("hidden"in J)&&J.hidden===!0,lB9=(J)=>("default"in J),iB9=(J)=>("default"in J)?J.default:void 0;function nB9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new k9(aK.unknownCommand(Z),1,G)}}var OH6=null;function D24(){return OH6}function qZ1(J){return{...J,getThreadEnvironment:_51,vfs:b70({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Zx(J.fileSystem),generateThreadTitle:az0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var tp1=$0.file(mB9.homedir()),jH6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(tp1,".config");async function tq(J,Q){va1("0.0.
|
|
6689
|
+
`)}var rp1=ap1.join(ji1||ap1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function uB9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function oq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")RZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new k9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${W8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")RZ("experimental.agentMode",Q.agentMode)}async function op1(J){try{await hB9(ap1.dirname(rp1),{recursive:!0}),await gB9(rp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function pB9(){try{return(await RH6(rp1,"utf-8")).trim()}catch(J){return null}}function dB9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return lS("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var LH6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??DZ,description:`Custom settings file path (overrides the default location ${DZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Lf1})`},{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:LQ(),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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Ic}],AH6=(J)=>("deprecated"in J)&&J.deprecated===!0,cB9=(J)=>("hidden"in J)&&J.hidden===!0,lB9=(J)=>("default"in J),iB9=(J)=>("default"in J)?J.default:void 0;function nB9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new k9(aK.unknownCommand(Z),1,G)}}var OH6=null;function D24(){return OH6}function qZ1(J){return{...J,getThreadEnvironment:_51,vfs:b70({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Zx(J.fileSystem),generateThreadTitle:az0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var tp1=$0.file(mB9.homedir()),jH6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(tp1,".config");async function tq(J,Q){va1("0.0.1761724890-gadc2fc");let Z=VY1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:tp1,userConfigDir:jH6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (KZ1(),YZ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=qr(mO({configService:Z})),G=new Map,q=()=>G.clear(),z=F70({configService:Z,toolService:K,secretStorage:J.secrets,createOAuthProvider:async(E)=>{let I=G.get(E);if(I)return u.debug("Reusing existing OAuth provider for server",{serverName:E}),I;u.debug("Creating OAuth provider for server",{serverName:E});let T=(async()=>{let S=new P3(J.secrets),_=await S.getClientInfo(E),h=new gW1({storage:S,serverName:E,clientId:_?.clientId,clientSecret:_?.clientSecret,scopes:_?.scopes});return u.debug("OAuth provider created",{serverName:E,hasManualClientId:!!_?.clientId,willUseDCR:!_?.clientId}),h})();return G.set(E,T),T}}),U=wj0(K,E2,d11).catch((E)=>{u.warn("Toolbox registration failed, continuing anyway:",E)}),W=z.initialized.catch((E)=>{u.warn("MCP service initialization failed, continuing anyway:",E)}),F=Promise.all([W,U]).then(()=>{});if(Q.jetbrains)dO("JetBrains");else if(Q.ide&&CX6())dO("VS Code");else if(Q.ide&&SX6())dO("Neovim");if(J.executeMode)ka1(!0);I46(K,{configService:Z});let H,B=v7.status.pipe(b0((E)=>Boolean(E.connected&&E.authenticated)),J8()).subscribe((E)=>{if(E){if(!H)H=K.registerTool(zo)}else H?.dispose(),H=void 0}),M;if(!J.executeMode)M=new r51(process.cwd(),{},!0);else M=new class extends r51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e2.write(`No API key found. Starting login flow...
|
|
6690
6690
|
`),!await aB9(J))await ER(),process.exit(1)}let V=await u70({isDevelopment:!1}),N=new wN1(V),L=new KD1(V,Z,{lazy:!0}),A=Q.notifications!==void 0?Q.notifications:!J.executeMode,w=T46({playNotificationSound:async(E)=>{if(A){P46(E);let I=jg1(),T=$g1();if((!I||T)&&Y.settings["notifications.system.enabled"]!==!1){if(E==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(E==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:N,configService:Z});u.info("Starting Amp background services");let R=nz0({threadService:N,threadHistoryService:L,configService:Z,isExtensionDevelopment:!1}),O;v7.status.subscribe((E)=>{O=E});let j={codebaseContextService:new zX1({workspaceRoots:[$0.file(process.cwd())],getCurrentFile:()=>{if(!O?.openFile)return;try{return $0.parse(O.openFile)}catch(E){u.warn("Failed to parse current file URI",{uri:O.openFile,error:E});return}},getOpenFiles:()=>{if(!O?.visibleFiles?.length)return[];let E=O.openFile;return O.visibleFiles.filter((I)=>I!==E).map((I)=>{try{return $0.parse(I)}catch(T){return u.warn("Failed to parse visible file URI",{uri:I,error:T}),null}}).filter((I)=>I!==null)}}),configService:Z,toolService:K,mcpService:z,threadService:N,threadHistoryService:L,threadSyncService:R,threadStorage:V,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,notificationService:w,backgroundInit:F,fileSystem:Q.jetbrains||Q.ide?k70:E2};return{...j,async asyncDispose(){await j.mcpService.dispose(),q(),await j.threadService.asyncDispose(),j.configService.unsubscribe(),j.toolService.dispose(),j.fuzzyServer.dispose(),j.threadSyncService.dispose(),j.settingsStorage[Symbol.dispose](),B.unsubscribe(),H?.dispose()}}}async function aB9(J){if(!J.executeMode){if(!await ef1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e2.write(`Login cancelled. Run the command again to retry.
|
|
6691
6691
|
`),!1}return await $H6(J)}async function $H6(J){let Q=fB9(32).toString("hex"),Z=await tf1(J.ampURL,Q),X=new AbortController;try{await PQ(Z,X.signal)}catch(K){u.error("Error opening browser",{error:K})}let Y=await tf1(J.ampURL,Q,!1);e2.write(`If your browser does not open automatically, visit:
|
|
6692
6692
|
|
|
@@ -6696,13 +6696,13 @@ ${W8.blue.bold(Y)}
|
|
|
6696
6696
|
Login successful! You can now use the Amp CLI.
|
|
6697
6697
|
`),!0}catch(K){return u.error("Login failed",{error:K}),YG.write(`
|
|
6698
6698
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
6699
|
-
`),!1}}function rB9(){let J=new DR().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)PR(),process.exit(0);let W=U.originalError??U;SZ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.
|
|
6699
|
+
`),!1}}function rB9(){let J=new DR().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)PR(),process.exit(0);let W=U.originalError??U;SZ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761724890-gadc2fc (released 2025-10-29T08:06:45.138Z)
|
|
6700
6700
|
`),process.exit(0)}),J.addHelpText("after",IX6()),J.configureHelp({formatHelp:PX6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);await eB9(H)}),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(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);await tB9(H,await uf1(F,H.settings))});let Q=async(U,W,F)=>{VY1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:tp1,userConfigDir:jH6});let H={...W,executeMode:!1};await sp1(H,{...U,startWithPicker:!0},F)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);await wH6(F,H,W)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);await KD9(F,H,W)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await IX(H);if(W.pick)YG.write(`${W8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6701
6701
|
`);if(W.last||U||B.executeMode)await YD9(H,B,U,F);else await Q(H,B,F)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await IX(H);await XD9(H,B,U,F)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);await wH6(F,H,W)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await IX(H);await ZD9(H,B,U,F,W.support)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(U,W,F,H)=>{let B=H.optsWithGlobals(),M=await IX(B);await JD9(B,M,U,W,H)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await IX(H);await QD9(H,B,U,F)}),vY6(J,async(U,W)=>{let F=await IX(W);oq(U,W);let H=await tq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:PR,asyncDispose:H.asyncDispose.bind(H)}}),GY6(J),tX6(J,async(U)=>{let W=await IX(U);return{settings:W.settings,secretStorage:W.secrets,getThreadDeps:async(F)=>{oq(F,U);let H=await tq(W,U);return{mcpService:H.mcpService,asyncDispose:H.asyncDispose.bind(H)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);oq(W,F);let B=await tq(H,F);try{await Pf1(B,B.configService,{})}finally{await B.asyncDispose(),await PR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new oV(W,B),V=iB9(U);if(V)M.default(V);if(M.hidden=cB9(U)||AH6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of LH6)switch(U.type){case"flag":{J.addOption(X(U,`--${U.long}`)),J.addOption(X(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(X(U,`--${U.long}`,!0));break}default:{J.addOption(X(U,`--${U.long} <value>`));break}}let Y=new oV("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(Y);let K=new oV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let G=new oV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let q=new oV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new oV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let U=new oV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,W)=>{let F=U,H=await IX(F);if(Object.keys(F).forEach((B)=>{let M=LH6.find((V)=>V.name===B);if(M&&AH6(M)&&!lB9(M))YG.write(W8.yellow(`Warning: '--${B}' flag is deprecated
|
|
6702
6702
|
`))}),W.args.length>0)nB9(H,W);await sp1(H,F,W)}),lX6(J),J}async function GZ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Fz(),K=qZ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await VJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,qJ1(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(t7(z,"assistant"))await op1(Y),q.unsubscribe()});return await G.resume(),G}async function sp1(J,Q,Z){let X=GJ1(Q);if(X instanceof Error)XG(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await Qh1()).trimEnd();if(O)K=O}else Y=(await Qh1()).trimEnd();if(Q.remote&&!J.executeMode)throw new k9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new k9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new k9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new k9("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&Q.agentMode&&Q.agentMode!=="smart")throw new k9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new k9("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new k9("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new k9("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"
|
|
6703
6703
|
Or pipe via stdin: echo "your message" | amp --execute`);oq(Z,Q);let G=await tq(J,Q);if(J.executeMode||Q.threadId)await G.backgroundInit;OH6=G;let q=qZ1(G),z=async(O)=>{let $=await RH6(O,"utf-8"),j=JSON.parse($);if(!MG(j.id))throw new k9(aK.invalidThreadId);return GZ1(G,{visibility:X,thread:j})},U=async(O)=>{if(!MG(O))throw new k9(aK.invalidThreadId);let $=await G.threadService.get(O)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${O}, agentMode: ${$?.agentMode??"undefined"}`),$?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${$.agentMode}`),RZ("experimental.agentMode",$.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return GZ1(G,{visibility:X,thread:$})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return GZ1(G,{visibility:X})}catch(O){if(O instanceof k9)throw O;throw await m51(O,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return GZ1(G,{visibility:X})};if(Q.format==="jsonl")YG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6704
|
-
`),await ER(),process.exit(1);if(J.executeMode&&Q.remote)await qY6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await dZ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await ns1();let O=await cB({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)v7.selectConfig($)}else B=!0}let V=of1("0.0.
|
|
6705
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await WX6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await eX6(J.mcpConfig);X=dB9(X,G)}let Y=await X.get("url","global");if(!Y)Y=OZ;if(!TB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=ri1(X),await X.get("debug.httpLogging"))mi1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zY6(await uf1(J,X))}}function sB9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function oB9(){let J=sB9(process.argv);if(HZ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),uB9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6704
|
+
`),await ER(),process.exit(1);if(J.executeMode&&Q.remote)await qY6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await dZ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await ns1();let O=await cB({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)v7.selectConfig($)}else B=!0}let V=of1("0.0.1761724890-gadc2fc",G.settingsStorage),N=new YD1(G.threadStorage),L=t1.of([$0.file(process.cwd())]),A=SS(void 0,L);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await UJ.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await FY6();u.info("Loaded session state:",R),await NH6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new kf1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:UJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v7,connectedClientsService:new ec,commandRegistry:A,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:R,freeTierStatus:w.ok?w.result:void 0}),await G.asyncDispose(),process.exit(0)}async function IX(J){if(J.interactive)YG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6705
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await WX6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await eX6(J.mcpConfig);X=dB9(X,G)}let Y=await X.get("url","global");if(!Y)Y=OZ;if(!TB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=ri1(X),await X.get("debug.httpLogging"))mi1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zY6(await uf1(J,X))}}function sB9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function oB9(){let J=sB9(process.argv);if(HZ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),uB9(u),u.info("Starting Amp CLI.",{version:"0.0.1761724890-gadc2fc",buildTimestamp:"2025-10-29T08:06:45.138Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(aK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await rB9().parseAsync(process.argv)}oB9().catch(m51);async function tB9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6706
6706
|
`);else if(!TB(J.ampURL))e2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6707
6707
|
`);let Z=process.env.AMP_API_KEY;if(Z)e2.write(`API key found in environment variable, storing...
|
|
6708
6708
|
`),await Q.set("apiKey",Z,J.ampURL),e2.write(`API key successfully stored.
|