@sourcegraph/amp 0.0.1775019248-g482f31 → 0.0.1775031755-gf66c2b
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 +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -731,7 +731,7 @@ Start by using the walkthrough tool to explore a starting point, then iterativel
|
|
|
731
731
|
- "Create a diagram showing the data flow from API request to database"
|
|
732
732
|
- "Explore the relationship between the Router and Controller components"
|
|
733
733
|
- "Show me how the event system connects publishers and subscribers"
|
|
734
|
-
`,ir1;var nr1=Q0(()=>{ir1={name:"walkthrough",description:'Explore and visualize codebase architecture.
|
|
734
|
+
`,ir1;var nr1=Q0(()=>{ir1={name:"walkthrough",description:'Explore and visualize codebase architecture. Only use it when the user asked to visualize or diagram an architecture or when asked to "walk me through", "show how X works", "explain the flow", "diagram the architecture", or understand how components connect and interact.',frontmatter:{name:"walkthrough",description:'Explore and visualize codebase architecture. Only use it when the user asked to visualize or diagram an architecture or when asked to "walk me through", "show how X works", "explain the flow", "diagram the architecture", or understand how components connect and interact.'},content:l75,baseDir:c75,builtinTools:["walkthrough","walkthrough_diagram"]}});function ar1(J){return[br1,cr1,ir1,pr1,gr1]}var or1;var n_0=Q0(()=>{hr1();mr1();dr1();lr1();nr1();or1={code_tour:"code-tour",code_review:"code-review",walkthrough:"walkthrough",walkthrough_diagram:"walkthrough"}});function i75(J){if(!J)throw new kB("Invalid skill name","Skill name is required");if(J.length>eF)throw new kB("Invalid skill name",`Frontmatter name "${J}" must be ${eF} characters or less`);if(!$M.test(J))throw new kB("Invalid skill name",`Frontmatter name "${J}" is invalid. Skill name must be lowercase alphanumeric with hyphens, no trailing hyphen (e.g., "my-skill")`)}function a_0(J){let Q=J.replace(/^\uFEFF/,"").match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/);if(!Q||!Q[1])throw new kB("Missing YAML frontmatter",`Add frontmatter at the top of SKILL.md:
|
|
735
735
|
---
|
|
736
736
|
name: my-skill
|
|
737
737
|
description: Your skill description
|
|
@@ -6223,11 +6223,11 @@ ${U}`))}},error:(D)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${D.message}`))}
|
|
|
6223
6223
|
${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))H+=`
|
|
6224
6224
|
|
|
6225
6225
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6226
|
-
npm install -g @sourcegraph/amp`;G(Error(H))}},error:(D)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!q)q=!0,V()}})})}d0();d0();pM();async function LY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=BI4(J,z),W=q<0,D,U;if(F.time){let H=F.time[J],B=F.time[z],N=Date.now();if(H)D=Math.floor((N-new Date(H).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return T.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:D,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:D,latestVersionAge:U,source:"npm"}}catch(G){return T.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var XJ3="https://static.ampcode.com/cli/cli-version.txt";async function OY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${XJ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=BI4(J,X),V=K<0;return T.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return T.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var KJ3=604800000;function HI4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>KJ3)return{ageMs:Q};return null}function BI4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Ua0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?Mz(Q):void 0;return{sha:Y,age:X}}catch{return null}}L1();function Ha0(J,Z,Q={}){let Y=new K4,X=Y.pipe(h6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new PF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await Ez(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await Ez(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await wY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let D=W?await OY0(J):await LY0(J,Mj());if(!(D.latestVersion&&D.hasUpdate)){K.debug("no update available");return}let U=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!U())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ga0()){if(K.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!U())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await Ui(D.latestVersion,q);let H=await ww(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await Ez(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}pM();import{stderr as TG}from"node:process";function NI4(J){let Z=new bN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Ya0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6226
|
+
npm install -g @sourcegraph/amp`;G(Error(H))}},error:(D)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!q)q=!0,V()}})})}d0();d0();pM();async function LY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=BI4(J,z),W=q<0,D,U;if(F.time){let H=F.time[J],B=F.time[z],N=Date.now();if(H)D=Math.floor((N-new Date(H).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return T.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:D,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:D,latestVersionAge:U,source:"npm"}}catch(G){return T.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var XJ3="https://static.ampcode.com/cli/cli-version.txt";async function OY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${XJ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=BI4(J,X),V=K<0;return T.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return T.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var KJ3=604800000;function HI4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>KJ3)return{ageMs:Q};return null}function BI4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Ua0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?Mz(Q):void 0;return{sha:Y,age:X}}catch{return null}}L1();function Ha0(J,Z,Q={}){let Y=new K4,X=Y.pipe(h6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new PF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await Ez(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await Ez(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await wY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let D=W?await OY0(J):await LY0(J,Mj());if(!(D.latestVersion&&D.hasUpdate)){K.debug("no update available");return}let U=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!U())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ga0()){if(K.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!U())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await Ui(D.latestVersion,q);let H=await ww(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await Ez(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}pM();import{stderr as TG}from"node:process";function NI4(J){let Z=new bN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Ya0(Y.force||!1,Y.verbose||!1,"0.0.1775031755-gf66c2b"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new bN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await VJ3(Y.targetVersion)});J.addCommand(Q)}async function VJ3(J){let Z=process.platform==="win32"&&NY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")TG.write(p0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6227
6227
|
|
|
6228
6228
|
`));try{if(!J){TG.write(p0.blue(`Checking for updates...
|
|
6229
|
-
`));let{hasUpdate:K,latestVersion:V}=NY0()?await OY0("0.0.
|
|
6230
|
-
`));let z=await ww("0.0.
|
|
6229
|
+
`));let{hasUpdate:K,latestVersion:V}=NY0()?await OY0("0.0.1775031755-gf66c2b"):await LY0("0.0.1775031755-gf66c2b",Mj());if(!K){let G=Ua0("0.0.1775031755-gf66c2b"),F=G?.age?`released ${G.age} ago`:`built ${Mz(new Date("2026-04-01T08:26:12.103Z"))} ago`;TG.write(p0.green(`✓ Amp is already up to date on version ${"0.0.1775031755-gf66c2b"} (${F})
|
|
6230
|
+
`));let z=await ww("0.0.1775031755-gf66c2b",Q);if(z.warning)TG.write(`
|
|
6231
6231
|
`+p0.yellow(z.warning)+`
|
|
6232
6232
|
`);process.exit(0)}if(!V)TG.write(p0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}TG.write(p0.blue(`Updating to version ${J}...
|
|
6233
6233
|
`)),await Ui(J,void 0,(K)=>{TG.write(p0.dim(`Running: ${K}
|
|
@@ -7398,7 +7398,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let f=z.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7398
7398
|
`),K=[];for(let V=0;V<X.length;V++){let z=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new S(q.slice(1,-1),new d({color:Y.app.keybind,bold:!0})));else K.push(new S(q,new d({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new S(`
|
|
7399
7399
|
`))}return new s0({decoration:{color:Q.colorScheme.background,border:D4.all(new B4(Y.app.keybind,1,"rounded"))},child:new l0({padding:T0.symmetric(0,1),child:new Z0({text:new S(void 0,void 0,K)})})})}}class Ce0 extends R${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=QG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Ie0({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function Fb4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?A9:0,F=Y-G;if(F<=0)return null;let z=Z-G;if(z<0||z>=F)return null;let q=Math.max(1,Math.floor(F/K)),W=Math.floor(z/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?A9:0,F=Y-G;if(F<=0)return null;let z=Math.max(0,Math.min(F-1,Z-G));if(K===1)return 0;let q=F/(K-1),W=Math.round(z/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function _A3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=K?A9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let D=Math.max(1,Math.floor(q/X)),U=z+Z*D+Math.floor(D/2),H=G>0?V/G:0,B=Math.round((1-H)*(W-1));return{x:U,y:B}}case"line":case"sparkline":case"stacked-area":{let z=K?A9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let D=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),U=G>0?V/G:0,H=Math.round((1-U)*(W-1));return{x:D,y:H}}default:return null}}function SA3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function kA3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+F.length}let K=J.label.length,V=0;for(let G of Q){let F=G.points[Z];if(!F)continue;V+=F.value;let z=2+G.name.length+2+Y(F.value).length;K=Math.max(K,z)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function vA3(J,Z,Q,Y,X,K,V){let G;try{let H=l1.of(J),B=b0.of(J);G={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new d({color:G.foreground,bold:!0}),z=new d({color:G.foreground}),q=new d({color:G.foreground,dim:!0}),W=[],D=new d({color:G.foreground,underline:!0}),U=(H,B)=>new S(B,D,void 0,TY0(H),()=>{d3(J,H)});if(Y.length<=1){if(W.push(new S(`${Z.label}: `,F)),Z.link)W.push(U(Z.link,K(Z.value)));else W.push(new S(K(Z.value),z));if(Z.meta)W.push(new S(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";W.push(new S(`${Z.label}
|
|
7400
7400
|
`,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new S("● ",new d({color:O}))),W.push(new S(`${w.name}: `,q)),L.link)W.push(U(L.link,K(L.value)));else W.push(new S(K(L.value),z));if(N<Y.length-1||H)W.push(new S(`
|
|
7401
|
-
`))}if(H)W.push(new S(" ",q)),W.push(new S("Total: ",q)),W.push(new S(K(B),z))}return new s0({decoration:{color:G.background,border:D4.all(new B4(G.border,1,"rounded"))},child:new Z0({text:new S(void 0,void 0,W)})})}rO();d0();L7();VE();G$();_3();E2();Qd();RX();dZ();sQ();aZ();OA();g4();Mg();IP();L1();d0();dZ();class Te0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1775019248-g482f31"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await t10(Z,this.configService)}catch(Z){T.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VL extends a0{props;constructor(J){super();this.props=J}createState(){return new zb4}}class zb4 extends n0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class qb4 extends n0{controller=new i2;focusNode=new B6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=b0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=D4.all(new B4(Q.foreground,1,"solid")),F=new aY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let H=U.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new O1({children:[new s0({decoration:{color:Q.background},child:new Z0({text:new S(">",new d({color:Q.foreground}))})}),new a1({child:F})]}),q=new s0({padding:T0.symmetric(1,0),child:new Z0({text:new S("",void 0,[new S("Command: ",new d({color:Q.foreground})),new S(this.widget.props.commandName,new d({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new S("Enter",new d({color:Y.keybind}))),W.push(new S(" to submit, ",new d({color:Q.foreground,dim:!0})));W.push(new S("Esc",new d({color:Y.keybind}))),W.push(new S(" to cancel",new d({color:Q.foreground,dim:!0})));let D=new s0({padding:T0.symmetric(1,0),child:new Z0({text:new S("",void 0,W)})});return new s0({decoration:{border:G,color:Q.background},padding:T0.all(1),child:new g0({children:[q,new P0({height:1}),z,new k3,D]})})}}class Va extends a0{props;constructor(J){super();this.props=J}createState(){return new qb4}}aZ();import{mkdtemp as fA3,readFile as uA3,rmdir as bA3,unlink as hA3,writeFile as gA3}from"node:fs/promises";import{tmpdir as mA3}from"node:os";import Ob4 from"node:path";d0();d0();class Wb4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class UR extends Wb4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Db4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class _e0{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class Se0 extends U8{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new Ub4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ub4 extends x4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(r4(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}class ke0 extends U8{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new Bq(this)}createRenderObject(){return new Hb4(this.link)}updateRenderObject(J){J.link=this.link}}class Hb4 extends x4{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Z=this.offset.y,Q=this.parent;while(Q&&Q instanceof x4)J+=Q.offset.x,Z+=Q.offset.y,Q=Q.parent;return{x:J,y:Z}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(r4(!!J,"performLayout called without constraints"),this.children.length>0){let Z=this.children[0];Z.layout(J);let Q=Z.size;this.setSize(Q.width,Q.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}d0();class ve0{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Z){T.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}d0();var yA3=500;class ye0{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new UR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),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.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let F=G.detect(Z,Y);if(F&&(!X||F.start>X.start))X=F}if(!this.currentState.isActive&&X&&X.query.length>0){let G=O6(Z),F=Y,z=F;while(z<G.length){let q=G[z];if(q&&/[\s)\]}@]/.test(q))break;z++}if(z>F){let W=[...G.slice(0,F),...G.slice(z)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(T.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},yA3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Ga{}class Fa{}class za{}class XG0{}class KG0 extends a0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Bb4(this.props)}}class Bb4 extends n0{props;controller;stateListener=null;overlayEntry=null;layerLink=new ve0;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new B6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new ye0,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Db4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)t6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}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 Ga)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Fa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof za)return this.controller.acceptSelected(),"handled";if(J instanceof XG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new aY({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new iY({shortcuts:new Map([[new u4("ArrowDown"),new Ga],[new u4("ArrowUp"),new Fa],[new u4("n",{ctrl:!0}),new Ga],[new u4("p",{ctrl:!0}),new Fa],[new u4("Enter"),new za],[new u4("Escape"),new XG0],[new u4("Tab"),new za]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new S$({actions:new Map([[Ga,new b6(this.invoke)],[Fa,new b6(this.invoke)],[za,new b6(this.invoke)],[XG0,new b6(this.invoke)]]),child:Q});return new ke0({link:this.layerLink,child:Y})}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 _e0((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{qR.of(this.context).insert(this.overlayEntry)}catch(J){T.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new S(Q,new d({color:b0.of(J).app.command})),new S(" ",new d({color:Z})));return X.push(new S(Y,new d({color:Z}))),[{child:new Z0({text:new S(" ",new d({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=l1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=R4.sizeOf(J).height,G=0;try{let I=this.layerLink.getTargetTransform();if(I)G=I.position.y}catch{}let F=this.props.autoOverlayPosition?G<V/3:!1,z=2,q;if(F){let I=this.props.controller.getCursorVisualRow(),_=G+I+1;q=V-_-z}else q=G-z;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,D=Math.min(Z.options.length,W+K),U=[],H=0;for(let I=W;I<D;I++){let _=Z.options[I];if(!_)continue;let C=I===Z.selectedIndex,h,m;if(this.props.optionViewBuilder){h=this.props.optionViewBuilder(J,_,C);let f=this.props.displayStringForOption?.(_)??String(_),p="",g=f,b=_;if(b&&typeof b==="object"&&"type"in b)switch(b.type){case"file":p="@",g=b.path||f;break;case"artifact":p="",g=b.label||f;break}m=p+g}else{let f=this.props.displayStringForOption?.(_)??String(_),p=Q?.colorScheme.selection??M0.default(),g=Q?.colorScheme.foreground??M0.default();h=new Z0({text:new S(f,new d({color:g,backgroundColor:C?p:void 0}))}),m=f}let x=R4.of(J),k=I5(m,x.supportsEmojiWidth);H=Math.max(H,k),U.push(h)}let B=R4.sizeOf(J).width,N=H+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=U.length+2,A;if(F)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new P0({width:L,child:new s0({height:M,decoration:new K6(Y),child:new W2({decoration:{border:D4.all(new B4(X,1,"rounded"))},padding:T0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new g0({crossAxisAlignment:"start",children:U})})})});return new Se0({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Nb4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function wb4(J){switch(J.type){case"file":return J.path;case"hint":return`${xA3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Lb4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function xA3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=O6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7401
|
+
`))}if(H)W.push(new S(" ",q)),W.push(new S("Total: ",q)),W.push(new S(K(B),z))}return new s0({decoration:{color:G.background,border:D4.all(new B4(G.border,1,"rounded"))},child:new Z0({text:new S(void 0,void 0,W)})})}rO();d0();L7();VE();G$();_3();E2();Qd();RX();dZ();sQ();aZ();OA();g4();Mg();IP();L1();d0();dZ();class Te0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1775031755-gf66c2b"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await t10(Z,this.configService)}catch(Z){T.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VL extends a0{props;constructor(J){super();this.props=J}createState(){return new zb4}}class zb4 extends n0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class qb4 extends n0{controller=new i2;focusNode=new B6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=b0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=D4.all(new B4(Q.foreground,1,"solid")),F=new aY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let H=U.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new O1({children:[new s0({decoration:{color:Q.background},child:new Z0({text:new S(">",new d({color:Q.foreground}))})}),new a1({child:F})]}),q=new s0({padding:T0.symmetric(1,0),child:new Z0({text:new S("",void 0,[new S("Command: ",new d({color:Q.foreground})),new S(this.widget.props.commandName,new d({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new S("Enter",new d({color:Y.keybind}))),W.push(new S(" to submit, ",new d({color:Q.foreground,dim:!0})));W.push(new S("Esc",new d({color:Y.keybind}))),W.push(new S(" to cancel",new d({color:Q.foreground,dim:!0})));let D=new s0({padding:T0.symmetric(1,0),child:new Z0({text:new S("",void 0,W)})});return new s0({decoration:{border:G,color:Q.background},padding:T0.all(1),child:new g0({children:[q,new P0({height:1}),z,new k3,D]})})}}class Va extends a0{props;constructor(J){super();this.props=J}createState(){return new qb4}}aZ();import{mkdtemp as fA3,readFile as uA3,rmdir as bA3,unlink as hA3,writeFile as gA3}from"node:fs/promises";import{tmpdir as mA3}from"node:os";import Ob4 from"node:path";d0();d0();class Wb4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class UR extends Wb4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Db4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class _e0{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class Se0 extends U8{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new Ub4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ub4 extends x4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(r4(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}class ke0 extends U8{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new Bq(this)}createRenderObject(){return new Hb4(this.link)}updateRenderObject(J){J.link=this.link}}class Hb4 extends x4{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Z=this.offset.y,Q=this.parent;while(Q&&Q instanceof x4)J+=Q.offset.x,Z+=Q.offset.y,Q=Q.parent;return{x:J,y:Z}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(r4(!!J,"performLayout called without constraints"),this.children.length>0){let Z=this.children[0];Z.layout(J);let Q=Z.size;this.setSize(Q.width,Q.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}d0();class ve0{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Z){T.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}d0();var yA3=500;class ye0{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new UR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),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.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let F=G.detect(Z,Y);if(F&&(!X||F.start>X.start))X=F}if(!this.currentState.isActive&&X&&X.query.length>0){let G=O6(Z),F=Y,z=F;while(z<G.length){let q=G[z];if(q&&/[\s)\]}@]/.test(q))break;z++}if(z>F){let W=[...G.slice(0,F),...G.slice(z)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(T.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},yA3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Ga{}class Fa{}class za{}class XG0{}class KG0 extends a0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Bb4(this.props)}}class Bb4 extends n0{props;controller;stateListener=null;overlayEntry=null;layerLink=new ve0;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new B6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new ye0,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Db4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)t6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}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 Ga)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Fa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof za)return this.controller.acceptSelected(),"handled";if(J instanceof XG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new aY({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new iY({shortcuts:new Map([[new u4("ArrowDown"),new Ga],[new u4("ArrowUp"),new Fa],[new u4("n",{ctrl:!0}),new Ga],[new u4("p",{ctrl:!0}),new Fa],[new u4("Enter"),new za],[new u4("Escape"),new XG0],[new u4("Tab"),new za]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new S$({actions:new Map([[Ga,new b6(this.invoke)],[Fa,new b6(this.invoke)],[za,new b6(this.invoke)],[XG0,new b6(this.invoke)]]),child:Q});return new ke0({link:this.layerLink,child:Y})}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 _e0((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{qR.of(this.context).insert(this.overlayEntry)}catch(J){T.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new S(Q,new d({color:b0.of(J).app.command})),new S(" ",new d({color:Z})));return X.push(new S(Y,new d({color:Z}))),[{child:new Z0({text:new S(" ",new d({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=l1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=R4.sizeOf(J).height,G=0;try{let I=this.layerLink.getTargetTransform();if(I)G=I.position.y}catch{}let F=this.props.autoOverlayPosition?G<V/3:!1,z=2,q;if(F){let I=this.props.controller.getCursorVisualRow(),_=G+I+1;q=V-_-z}else q=G-z;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,D=Math.min(Z.options.length,W+K),U=[],H=0;for(let I=W;I<D;I++){let _=Z.options[I];if(!_)continue;let C=I===Z.selectedIndex,h,m;if(this.props.optionViewBuilder){h=this.props.optionViewBuilder(J,_,C);let f=this.props.displayStringForOption?.(_)??String(_),p="",g=f,b=_;if(b&&typeof b==="object"&&"type"in b)switch(b.type){case"file":p="@",g=b.path||f;break;case"artifact":p="",g=b.label||f;break}m=p+g}else{let f=this.props.displayStringForOption?.(_)??String(_),p=Q?.colorScheme.selection??M0.default(),g=Q?.colorScheme.foreground??M0.default();h=new Z0({text:new S(f,new d({color:g,backgroundColor:C?p:void 0}))}),m=f}let x=R4.of(J),k=I5(m,x.supportsEmojiWidth);H=Math.max(H,k),U.push(h)}let B=R4.sizeOf(J).width,N=H+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=U.length+2,A;if(F)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new P0({width:L,child:new s0({height:M,decoration:new K6(Y),child:new W2({decoration:{border:D4.all(new B4(X,1,"rounded"))},padding:T0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new g0({crossAxisAlignment:"start",children:U})})})});return new Se0({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Nb4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function wb4(J){switch(J.type){case"file":return J.path;case"hint":return`${xA3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Lb4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function xA3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=O6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7402
7402
|
`))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class HR extends a0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Eb4(this.props)}}var pA3=":";class Eb4 extends n0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new e5;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new vq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let G=X.query.toLowerCase().startsWith(pA3);if(G!==this._isCommitMode)this._isCommitMode=G,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=J.kind==="commit"?"@:":"@@",F=K+G+V;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=X+G.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=`git-commit(${J.hash})`,F=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new B6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Uu4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await fA3(Ob4.join(mA3(),"amp-edit-")),Q=Ob4.join(Z,"message.amp.md");await gA3(Q,J,"utf-8"),await xK(Q);try{let Y=await uA3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")T.error("Failed to read temporary file",Y)}try{await hA3(Q),await bA3(Z)}catch(Y){T.warn("Failed to clean up temporary file",Y)}}catch(Z){T.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new O1({mainAxisSize:"min",children:[new Z0({text:new S("Skills: ",new d({color:Z.foreground,dim:!0}))}),...Q.flatMap((F,z)=>{let q=new q4({onClick:()=>{this.props.onSkillClick?.(z)},cursor:"pointer",child:new Z0({text:new S(F.name,new d({color:Z.success,underline:!0}))})});if(z<Q.length-1)return[q,new Z0({text:new S(" ")})];return[q]})]}):null,K=Y?new O1({mainAxisSize:"min",children:[new Z0({text:new S("Images: ",new d({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((F,z)=>{let q=this.props.onImageClick!==void 0,W=new q4({onClick:q?()=>{this.props.onImageClick?.(z)}:void 0,cursor:q?"pointer":void 0,child:new Z0({text:new S(`[Image ${z+1}]`,new d({color:Z.success,underline:!0}))})});if(z<this.props.imageAttachments.length-1)return[W,new Z0({text:new S(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new Z0({text:new S(" ")}),new Z0({text:new S(this._imageUploadSpinner.toBraille(),new d({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new KG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(F)=>wb4(F),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:T0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(F,z,q)=>{let W=q?Z.selection:void 0,D=Z.secondary,U=Z.foreground,H=Z.foreground,B=Z.warning;if(z.type==="commit")return new s0({decoration:new K6(W),child:new O1({children:[new a1({child:new Z0({text:new S("",void 0,[new S(z.shortHash,new d({color:Z.secondary})),new S(" ",new d({})),new S(z.message,new d({color:U}))]),maxLines:1,overflow:"ellipsis"})}),new Z0({text:new S(` ${z.relativeDate}`,new d({color:H,dim:!0}))})]})});let N=[];switch(z.type){case"file":N.push(new S("@",new d({color:D}))),N.push(new S(z.path,new d({color:U})));break;case"hint":N.push(new S(z.kind==="commit"?"@:":"@@",new d({color:B}))),N.push(new S(" ",new d({}))),N.push(new S(z.message,new d({color:B})));break}let w=Lb4(z);if(w)N.push(new S(" - ",new d({color:H,dim:!0}))),N.push(new S(w,new d({color:H,dim:!0})));return new s0({decoration:new K6(W),child:new Z0({text:new S("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let F=[];if(X)F.push(X);if(X&&K)F.push(new Z0({text:new S(" ")}));if(K)F.push(K);let z=new s0({padding:T0.only({bottom:1}),child:new O1({mainAxisSize:"min",children:F})});G.push(z)}if(G.push(new a1({child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new g0({crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class Mb4 extends n0{controller=new i2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new B6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=RV)return!1;let Z=await ZL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=b0.of(J),{colors:Q,app:Y}=Z,K=R4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new HR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:F6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new D6({focusNode:this.focusNode,child:G}),z=new s0({constraints:new v1({maxHeight:V}),padding:T0.symmetric(1,0),child:F}),q=new s0({padding:T0.symmetric(1,0),child:new Z0({text:new S("",void 0,[new S("Command: ",new d({color:Q.foreground})),new S(this.widget.props.commandName,new d({color:Y.command,bold:!0}))])})}),W=new s0({padding:T0.symmetric(1,0),child:new Z0({text:this.isConfirmingClearInput?new S("",void 0,[new S("Esc",new d({color:Y.keybind})),new S(" again to clear input",new d({color:Q.foreground,dim:!0}))]):new S("",void 0,[new S("Press ",new d({color:Q.foreground,dim:!0})),new S("Enter",new d({color:Y.keybind})),new S(" to submit, ",new d({color:Q.foreground,dim:!0})),new S("Esc",new d({color:Y.keybind})),new S(" to clear",new d({color:Q.foreground,dim:!0}))])})}),D=[q,new P0({height:1}),new a1({child:z}),new P0({height:1}),W];return new s0({decoration:{border:D4.all(new B4(Q.foreground,1,"solid")),color:Q.background},padding:T0.all(1),child:new g0({children:D})})}}class xe0 extends a0{props;constructor(J){super();this.props=J}createState(){return new Mb4}}import{isDeepStrictEqual as fe0}from"node:util";var dA3=/[\\/_ +.#"@[({&]/,cA3=/[\\/_ +.#"@[({&]/g,lA3=/[\s-]/,Ab4=/[\s-]/g;function GG0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let F=Y.charAt(K),z=Q.indexOf(F,X),q=0,W,D,U,H;while(z>=0){if(W=GG0(J,Z,Q,Y,z+1,K+1,V),W>q){if(z===X)W*=1;else if(lA3.test(J.charAt(z-1))){if(W*=0.9,H=J.slice(X,z-1).match(Ab4),H&&X>0)W*=0.999**H.length}else if(dA3.test(J.charAt(z-1))){if(W*=0.8,U=J.slice(X,z-1).match(cA3),U&&X>0)W*=0.999**U.length}else if(W*=0.3,X>0)W*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(z-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(z-1)!==Y.charAt(K))){if(D=GG0(J,Z,Q,Y,z+1,K+2,V),D*0.1>W)W=D*0.1}if(W>q)q=W;z=Q.indexOf(F,z+1)}return V[G]=q,q}function VG0(J){return J.toLowerCase().replace(Ab4," ")}function jb4(J,Z){let Q=GG0(J,Z,VG0(J),VG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let F=GG0(J,G,VG0(J),VG0(G),0,0,{});if(F===0)return Q;X+=F,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Vy{}class Gy{}class FG0{}class zG0{}class Rb4 extends a0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Ib4}}class Ib4 extends n0{build(J){return this.widget.onContext(J),this.widget.child}}function iA3(J,Z){if(J==="")return{matches:!0,score:1};let Q=jb4(Z,J);return{matches:Q>0.15,score:Q}}class d9 extends a0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Pb4}}class Pb4 extends n0{textController;focusNode;scrollController=new d5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i2(this.widget.props.controller?.query??""),this.focusNode=new B6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),t6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>fe0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!fe0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>fe0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Vy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),t6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Gy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),t6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof FG0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof zG0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...iA3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;hV0(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),t6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=b0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=D4.all(new B4(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new aY({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),F=new iY({shortcuts:new Map([[new u4("ArrowDown"),new Vy],[new u4("ArrowUp"),new Gy],[new u4("Tab"),new Vy],[new u4("Tab",{shift:!0}),new Gy],[new u4("n",{ctrl:!0}),new Vy],[new u4("p",{ctrl:!0}),new Gy],[new u4("Enter"),new FG0],[new u4("Escape"),new zG0]]),focusNode:this.focusNode,child:G}),z=new S$({actions:new Map([[Vy,new b6(this.invoke)],[Gy,new b6(this.invoke)],[FG0,new b6(this.invoke)],[zG0,new b6(this.invoke)]]),child:F}),q=new O1({children:[new s0({decoration:{color:Q.background},child:new Z0({text:new S(">",new d({color:Q.foreground}))})}),new a1({child:z})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new P0({height:10,child:new V4({child:new Z0({text:new S(N,new d({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new a1({child:new V4({child:new Z0({text:new S(this.widget.props.emptyStateText,new d({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new s0({decoration:A?{color:A}:void 0,padding:T0.symmetric(2,0),child:new Z0({text:new S(this.widget.props.getLabel(w),new d({color:j,dim:E}))})})}return new Rb4(new q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new g0({children:N,crossAxisAlignment:"start"})}let D=new q4({onScroll:this.handleScroll,opaque:!1,child:new n6({controller:this.scrollController,autofocus:!1,child:W})}),U=[];if(this.widget.props.title){let N=new s0({padding:T0.symmetric(1,0),child:new Z0({text:new S(this.widget.props.title,new d({color:Z.app.command,bold:!0}))})});U.push(N)}if(!K)U.push(q,new P0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);U.push(new a1({child:new g0({mainAxisAlignment:"spaceBetween",children:[new a1({child:D}),new s0({padding:T0.only({top:1}),child:new V4({child:w??new P0({height:1})})})]})}))}else U.push(new a1({child:D}));if(this.widget.props.footer)U.push(this.widget.props.footer);return new s0({decoration:{border:X,color:Q.background},padding:T0.symmetric(1,0),child:new g0({children:U})})}}function Cb4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class ue0 extends Q4{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Cb4(X.pubDate).length));return new d9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=b0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,D=K?q.selectionForeground:z.foreground,U=z.mutedForeground,H=(B,N)=>new P0({width:N,child:O1.end([new Z0({text:new S(B,new d({color:U}))})])});return new s0({decoration:W?{color:W}:void 0,padding:T0.symmetric(2,0),child:new O1({children:[new a1({child:new Z0({text:new S(X.title,new d({color:D})),overflow:"ellipsis",maxLines:1})}),new P0({width:2}),H(Cb4(X.pubDate),Q)]})})}})}}ZE();class be0 extends a0{createState(){return new Tb4}}class Tb4 extends n0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=b0.of(J).colors;return new Z0({text:new S("●",new d({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function nA3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return xK0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function he0(J,Z,Q){return new Z0({text:new S(`${J}${Z}`,new d({color:Q})),maxLines:1})}function aA3(J,Z,Q,Y){return[he0("+",J,Y.success),k3.horizontal(1),he0("~",Z,Y.warning),k3.horizontal(1),he0("-",Q,Y.destructive)]}function oA3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class qG0 extends a0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new _b4}}class _b4 extends n0{spinner=new e5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=nA3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),D=b0.of(J),U=new l0({padding:T0.symmetric(0,1),child:new V4({child:new Z0({text:new S("",new d({color:D.colors.foreground,dim:!0}),[new S("Alt+W/Ctrl+T",new d({color:D.colors.primary,dim:!0})),new S(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new d({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(L)=>{if(L!==H)H=L,B=E7(L);return B};return new d9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!oA3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:U,renderItem:(L,O,E,M)=>{let A=b0.of(M),{app:j,colors:I}=A,_=O?j.selectionBackground:void 0,C=O?j.selectionForeground:I.foreground,h=I.mutedForeground,m=(s,U0)=>new P0({width:U0,child:O1.end([new Z0({text:new S(s,new d({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",p=new xn({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],U0=L.ancestorsAreLast.slice(1);for(let L0 of U0)s.push(new S(p.getAncestorPrefix(L0),new d({color:p.connectorColor,dim:p.connectorDim})));let r=L.isLast?p.elbow:p.tee,D0=p.getConnectorText(r);s.push(new S(D0,new d({color:p.connectorColor,dim:p.connectorDim}))),k.push(new Z0({text:new S("",void 0,s)}))}let g=[],b=F===L.id?new S("(current) ",new d({color:I.success})):G.has(L.id)?new S("(visited) ",new d({color:I.foreground,dim:!0})):null;if(b)g.push(new Z0({text:b}));if(mM(x))g.push(new be0),g.push(new P0({width:1}));let i=L.title;if(L.relationshipType==="fork"){let s=i.match(/^Forked\((\d+)\): /);if(s)i=i.slice(s[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);g.push(new Z0({text:new S("[fork] ",new d({color:I.primary}))}))}else if(f)g.push(new Z0({text:new S("[handoff] ",new d({color:I.accent}))}));if(g.push(new a1({child:new Z0({text:new S(i,new d({color:C})),overflow:"ellipsis",maxLines:1})})),g.push(new P0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;g.push(...aA3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),g.push(new P0({width:2}))}return g.push(m(L.description.timeAgo,W)),new s0({decoration:_?{color:_}:void 0,padding:T0.symmetric(2,0),child:new O1({children:[...k,...g]})})}})}}d0();class mK{message;constructor(J){this.message=J}}class D7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function WG0(J){if(J instanceof mK)return{title:"Info",description:J.message,type:"info"};return T.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"}}d0();jX();pM();RX();dZ();g4();U4();IP();var me0=W4($D(),1);import{execSync as BR}from"node:child_process";import{writeFile as Fy}from"node:fs/promises";import rA3 from"node:os";import yq from"node:path";var Sb4="c446b2e9b16cdc06df2ec285894d6421",sA3="5ea19563777f4ade8707fc56f7e7a388",tA3="amp-thread-worker",kb4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function eA3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function FL(J){if(!J||!eA3(J.meta))return!1;return J.meta.usesDtw===!0}function pe0(J){let Z=new URL(`https://dash.cloudflare.com/${Sb4}/workers/durable-objects/view/${sA3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function de0(J){let Z=new URL(`https://dash.cloudflare.com/${Sb4}/workers/services/view/${tA3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function $j3(J,Z){if(jW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function ce0(J,Z){let Q=$j3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function qa(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Wa(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Wa(J){return J.path??C9(J.uri)}function vb4(J,Z,Q){let Y=qa("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function yb4(J,Z){return ce0(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7403
7403
|
${Y}`).join(`
|
|
7404
7404
|
|
|
@@ -7620,7 +7620,7 @@ ${t.content||""}`:t.content||"",C0=[],o0=t.baseDir.startsWith("file://")?aG0(t.b
|
|
|
7620
7620
|
`),process.exit(1)}process.stdout.write(await fC3(F.result.displayText)+`
|
|
7621
7621
|
`),process.exit(0)})}pM();import{stdout as uC3}from"node:process";function bC3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${Mz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function qp4(J){uC3.write(`${bC3(J)}
|
|
7622
7622
|
`)}function Wp4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{qp4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{qp4(Z),process.exit(0)})}var Yv3=rU.join(MX,"logs","headless.log"),q61=rU.join(sk,"device-id.json"),yl4=`cli-tui-${dl4(16).toString("hex")}`;async function Xv3(){for(let J of FE)try{if((await J.listConfigs()).length>0)return J}catch(Z){T.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => W4(by(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){u$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7623
|
-
`)}function Kv3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function H7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")bJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")bJ("experimental.agentMode",Z.mode)}function nl4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Vv3(J){try{return await ll4(J,"utf-8")}catch{return J}}async function W61(J,Z,Q){let Y=nl4(J,Z);if(!Y)return;let X=x6(Q)?Q.features:[],K=x6(Q)?Q.user.email:void 0;if(!B61(X,M2.HARNESS_SYSTEM_PROMPT)&&!al4(K))throw new T1("You are not allowed to do this.",1);bJ("systemPrompt",await Vv3(Y))}function al4(J){return!!(J&&D00(J))}function B61(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function D61(J){return(J.userEmail?xJ(J.userEmail):!1)||B61(J.features,M2.DTW_TUI)}function xl4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function U61(J,Z){if(typeof J==="boolean")return J;if(!x6(Z))return!1;return D61({userEmail:Z.user.email,features:Z.features})}function Gv3(J){return J!=="pending"}function hy(J){if(!x6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Fv3(J){let Z=hy(J);if(Z)return Z.id;if(cF(J))throw Error(J.error.message);throw Error("unreachable")}function zv3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function uF0(J){let Y=zv3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function fl4(J){if(!a6.write(J))await $v3(a6,"drain")}var ul4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??_K,description:`Custom settings file path (overrides the default location ${_K})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Jn0})`},{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:m7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:xF.SMART.key,description:`Set the agent mode (${fF().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fF().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],bl4=(J)=>("deprecated"in J)&&J.deprecated===!0,qv3=(J)=>("hidden"in J)&&J.hidden===!0,Wv3=(J)=>("default"in J),Dv3=(J)=>("default"in J)?J.default:void 0,ol4=[{name:"toggle-skills-count",entryPoint:sa0}];function Uv3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(N3.unknownCommand(Q),1,V)}}async function N61(J){return{...J,getThreadEnvironment:XZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new uV(J.fileSystem),generateThreadTitle:M80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>cZ(J.configService),pluginService:J.pluginService}}function rl4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:XZ,filesystem:J.fileSystem,threadService:J.threadService}}var bF0=G1.file(il4.homedir()),H61=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(bF0,".config");function Hv3(J){return Dz4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Wz4(Z);let Q=YX0(),Y=zo0();if((!Q||Y||RC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(YX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function I9(J,Z,Q){let Y=Q?.deferAuth??!1;Hx1("0.0.
|
|
7623
|
+
`)}function Kv3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function H7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")bJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")bJ("experimental.agentMode",Z.mode)}function nl4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function Vv3(J){try{return await ll4(J,"utf-8")}catch{return J}}async function W61(J,Z,Q){let Y=nl4(J,Z);if(!Y)return;let X=x6(Q)?Q.features:[],K=x6(Q)?Q.user.email:void 0;if(!B61(X,M2.HARNESS_SYSTEM_PROMPT)&&!al4(K))throw new T1("You are not allowed to do this.",1);bJ("systemPrompt",await Vv3(Y))}function al4(J){return!!(J&&D00(J))}function B61(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function D61(J){return(J.userEmail?xJ(J.userEmail):!1)||B61(J.features,M2.DTW_TUI)}function xl4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function U61(J,Z){if(typeof J==="boolean")return J;if(!x6(Z))return!1;return D61({userEmail:Z.user.email,features:Z.features})}function Gv3(J){return J!=="pending"}function hy(J){if(!x6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Fv3(J){let Z=hy(J);if(Z)return Z.id;if(cF(J))throw Error(J.error.message);throw Error("unreachable")}function zv3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function uF0(J){let Y=zv3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function fl4(J){if(!a6.write(J))await $v3(a6,"drain")}var ul4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??_K,description:`Custom settings file path (overrides the default location ${_K})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Jn0})`},{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:m7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:xF.SMART.key,description:`Set the agent mode (${fF().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fF().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],bl4=(J)=>("deprecated"in J)&&J.deprecated===!0,qv3=(J)=>("hidden"in J)&&J.hidden===!0,Wv3=(J)=>("default"in J),Dv3=(J)=>("default"in J)?J.default:void 0,ol4=[{name:"toggle-skills-count",entryPoint:sa0}];function Uv3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(N3.unknownCommand(Q),1,V)}}async function N61(J){return{...J,getThreadEnvironment:XZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new uV(J.fileSystem),generateThreadTitle:M80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>cZ(J.configService),pluginService:J.pluginService}}function rl4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:XZ,filesystem:J.fileSystem,threadService:J.threadService}}var bF0=G1.file(il4.homedir()),H61=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(bF0,".config");function Hv3(J){return Dz4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Wz4(Z);let Q=YX0(),Y=zo0();if((!Q||Y||RC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(YX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function I9(J,Z,Q){let Y=Q?.deferAuth??!1;Hx1("0.0.1775031755-gf66c2b");let X=Y10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(G1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:bF0,userConfigDir:H61});jC4(X);let K=await X.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let g=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(g),T.info("API key lookup before login",{found:Boolean(g),ampURL:J.ampURL,deferAuth:Y}),!g)if(Y)T.info("No API key found, continuing startup with deferred auth");else{a6.write(`No API key found. Starting login flow...
|
|
7624
7624
|
`);let b=await Bv3(J),i=await J.secrets.get("apiKey",J.ampURL);if(T.info("Login flow completed",{success:b,storedKeyPresent:Boolean(i),ampURL:J.ampURL}),!b)await FU(),process.exit(1);V=!0}}{let g=await X.getLatest(),b=g.settings.url,i=g.secrets.isSet?.[b];T.info("Config secrets state after login",{configURL:b,apiKeySet:i?.apiKey??!1})}let G=I1(cZ(X).pipe(o5(Gv3))),F=Y?"pending":await G;if(!Y)T.info("Server status resolved",{status:"ready",isAuthenticated:x6(F),isError:cF(F),errorMessage:cF(F)?F.error.message:void 0});let z=G.then((g)=>Fv3(g)),{toolService:q,dispose:W}=Vz4({configService:X}),D=new Map,U=()=>D.clear(),H=new FT0(X,J.settings.getWorkspaceRootPath()),B=ws1({configService:X,filesystem:t8}),N=Wn1({configService:X,trustStore:H,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(g,b,i)=>{let c=`${g}:${b}`,s=D.get(c);if(s)return T.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:b}),s;T.debug("Creating OAuth provider for server",{serverName:g,serverUrl:b});let U0=(async()=>{let r=new NE(J.secrets),D0=await r.getClientInfo(g,b),L0=i?.scopes??D0?.scopes,F0=XR4();T.info("OAuth headless mode check",{useHeadless:F0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:a6.isTTY});let $0;if(F0)$0=J.executeMode?YR4():QR4(g);let z0=new dj0({storage:r,serverName:g,serverUrl:b,clientId:i?.clientId??D0?.clientId,clientSecret:i?.clientSecret??D0?.clientSecret,authUrl:i?.authUrl??D0?.authUrl,tokenUrl:i?.tokenUrl??D0?.tokenUrl,scopes:L0,headlessAuthHandler:$0});return T.debug("OAuth provider created",{serverName:g,serverUrl:b,hasManualClientId:!!(i?.clientId??D0?.clientId),willUseDCR:!(i?.clientId??D0?.clientId),scopes:L0,headlessMode:F0,executeMode:J.executeMode}),z0})();return D.set(c,U0),U0}}),w=qg0({configService:X,filesystem:t8,spawn:F$0}),L;if(J.executeMode){let g=await qV4({toolService:q,providers:[N,w],initialTimeout:15000});L=g.registrations;for(let[b,i]of g.initErrors)T.warn(`${b} provider initialization slow or failed:`,i)}else L=Wg0({toolService:q,providers:[N,w]});if(Z.jetbrains)YE("JetBrains");else if(Z.ide&&dR4())YE("VS Code");else if(Z.ide&&cR4())YE("Neovim");else if(Z.ide){let g=await Xv3();if(g){let b=U10(g.ideName);if(b)YE(b)}}if(J.executeMode)Bx1(!0);let O,E=a$.status.pipe(B1((g)=>Boolean(g.connected&&g.authenticated&&g.ideName&&Qf1(g.ideName))),h4()).subscribe((g)=>{if(g){if(!O)O=q.registerTool(zV4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let g=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new rQ0(process.cwd(),{alwaysIncludePaths:g},!0)}else M=new class extends rQ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new qS0(vs1(X),{maxThreads:200});T.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=U61(j,F),_=new Do0,C=process.env.PLUGINS??"off",h=Z.headless?VC4():void 0,m=h??new eY0({configService:X}),x=m instanceof eY0?m:void 0;if(x)x.pluginExecutorKind=I?"local":"unknown";let k=RT0({configService:X,fileSystem:t8,platform:m,internalPlugins:ol4,pluginFilter:C}),f=Va1({pluginService:k,toolService:q}),p={configService:X,toolService:q,mcpService:N,skillService:B,toolboxService:w,trustStore:H,threadService:A,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,fileSystem:t8,terminal:_,pluginService:k,pluginPlatform:x,headlessPluginPlatform:h,serverStatus:F,serverStatusPromise:G,viewerUserIDPromise:z,hasAPIKeyAtStartup:V};return{...p,async asyncDispose(){if(p.mcpService.hasAuthenticatingClients())T.info("Waiting for OAuth authentication to complete before exit..."),await p.mcpService.waitForAuthentication();for(let g of L.values())g.dispose();await p.mcpService.dispose(),U(),await p.threadService.asyncDispose(),p.configService.unsubscribe(),W(),p.fuzzyServer.dispose(),p.settingsStorage[Symbol.dispose](),E.unsubscribe(),O?.dispose(),f.dispose(),await p.pluginService.dispose()}}}async function Bv3(J){if(!J.executeMode){if(!await rY0("Would you like to log in to Amp? [(y)es, (n)o]: "))return a6.write(`Login cancelled. Run the command again to retry.
|
|
7625
7625
|
`),!1}return await sl4(J)}async function sl4(J){let Z=dl4(32).toString("hex"),Q=await Xv(J.ampURL,Z),Y=new AbortController;try{await NV(Q,Y.signal)}catch(K){T.error("Error opening browser",{error:K})}let X=await Xv(J.ampURL,Z,!1);a6.write(`If your browser does not open automatically, visit:
|
|
7626
7626
|
|
|
@@ -7628,7 +7628,7 @@ ${p0.blue.bold(X)}
|
|
|
7628
7628
|
|
|
7629
7629
|
`);try{return await gP4(J.ampURL,Z,J.secrets,Y),a6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return T.error("Login failed",{error:K}),u$.write(`
|
|
7630
7630
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7631
|
-
`),!1}}function hl4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Nv3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!M7(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function wv3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Lv3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!wv3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Ov3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Ev3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Mv3(J){let Z=new bN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Bj(),process.exit(0);let N=B.originalError??B;Yj4(N)}),Wp4(Z,{version:"0.0.
|
|
7631
|
+
`),!1}}function hl4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Nv3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!M7(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function wv3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Lv3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!wv3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Ov3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Ev3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Mv3(J){let Z=new bN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Bj(),process.exit(0);let N=B.originalError??B;Yj4(N)}),Wp4(Z,{version:"0.0.1775031755-gf66c2b",buildTimestamp:"2026-04-01T08:26:12.103Z",buildType:"'release'"}),Z.addHelpText("after",gR4()),Z.configureHelp({formatHelp:mR4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await I3(w);await _v3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await I3(w);await Tv3(L,await rn0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await I3(L);await kj4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await I3(w);await vj4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7632
7632
|
Actions:
|
|
7633
7633
|
create Create a new DTW thread and print its ID
|
|
7634
7634
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7692,8 +7692,8 @@ ${M}
|
|
|
7692
7692
|
|
|
7693
7693
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function Av3(J){T.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new fn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:XZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new uV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw T.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function jv3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await qv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await qv()).trimEnd(),stdinInput:null}}function Rv3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("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"
|
|
7694
7694
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function hF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(F0,$0)=>{let z0=Number(process.hrtime.bigint()-$0)/1e6,n=KL4();T.info("Startup phase",{phase:F0,phaseMs:Math.round(z0),sinceMainMs:n===null?void 0:Math.round(n)})},{userInput:V,stdinInput:G}=await jv3(Z),F=!!Z.streamJson||!!Z.streamJsonThinking;Rv3({...Z,streamJson:F},J.executeMode,V),H7(Q,Z);let z=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;T.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await I9(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",z),z=process.hrtime.bigint();let U=await N61(D);K("runMainThread:createWorkerDeps",z);let{serverStatus:H}=D;if(!W&&cF(H)){let F0=pk(Error(H.error.message));if(F0.message===N3.networkOffline||F0.message===N3.networkTimeout)throw uF0(J.ampURL);throw new T1(N3.invalidAPIKey,1)}let B=x6(H)?H:null,N=B?.user.email,w=al4(N),L=D61({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&U61(O,B);if(!W)await W61(Q,Z,H);let M=hy(H),A=M?.features??[],j=M?.team??null,I=sY0(Z,M);if(I instanceof Error)P3(I.message);if((J.executeMode||F)&&h8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!KE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await zC4(V,G,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!xJ(N))throw new T1("Headless DTW mode is only available for Amp employees",1);let F0=await D.secretStorage.get("apiKey",J.ampURL);if(!F0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!M7($0))throw new T1(`Invalid thread ID: ${$0}`,1);let z0=$0?void 0:await hv3({dependencies:D,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),n=$0??z0?.threadId;if(!n)throw new T1("Failed to resolve headless thread ID",1);let a=await FR4(n);if(a.status==="already-running")await D.asyncDispose(),await FU(),process.exit(0);try{await JR4({ampURL:J.ampURL,apiKey:F0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:n,ownerUserId:z0?.ownerUserId,threadVersion:z0?.threadVersion,agentMode:z0?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await a.release(),await D.asyncDispose()}await FU(),process.exit(0)}let _=J.executeMode?void 0:async(F0)=>Jo(F0,"interactive"),C={threadService:D.threadService,workerDeps:U,createThread:async()=>{let F0=W?await D.serverStatusPromise:H,$0=await xQ0(J.settings,process.cwd(),hy(F0),I);if($0 instanceof Error)P3($0.message);return Tt0(U,{threadMeta:$0?kG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(F0,$0)=>{if($0?.nonBlockingOwnershipCheck){gl4(F0,D.configService,D.viewerUserIDPromise).catch((z0)=>{if(z0 instanceof T1){if($0.onOwnershipError){$0.onOwnershipError(z0,F0);return}zU(z0,F0);return}T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})});return}try{await gl4(F0,D.configService,D.viewerUserIDPromise)}catch(z0){if(z0 instanceof T1)throw z0;T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:zU},h=async(F0)=>{try{if(F0==="dtw")return Av3({ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,clientID:yl4,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Hx4(C,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof T1)throw $0;throw await zU($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")u$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7695
|
-
`),await FU(),process.exit(1);let m=(async()=>{if(W){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await D.configService.getLatest(),$0=yu(F0),z0=await b5.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(z0.ok)return T.info("User free tier status:",z0),z0.result;return}catch(F0){T.error("Failed to fetch free tier status:",F0);return}})(),k=!J.executeMode?new Rt0:null,f,p=null;if(k)f=k,p=(async()=>{let F0=W?await D.serverStatusPromise:D.serverStatus;await W61(Q,Z,F0);let $0=process.hrtime.bigint(),z0=U61(O,F0),n=x6(F0)?D61({userEmail:F0.user.email,features:F0.features}):!1;xl4({dtwEnabled:z0,hasV2TUIAccess:n});let a=await h(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await I1(a.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),p.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));k.setInitError($0),await zU(F0,Z.threadId)});else z=process.hrtime.bigint(),xl4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let g=Z.notifications!==void 0?Z.notifications:!J.executeMode;z=process.hrtime.bigint();let b=await D.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),Hv3({configService:D.configService,threadService:D.threadService,config:b,useNotificationsForService:g,threadViewStates$:()=>f.threadHandles$.pipe(I4((F0)=>{if(!F0)return k0.of({});return G5(F0.thread$,F0.threadViewState$).pipe(B1(([$0,z0])=>({[$0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){tP4(D.mcpService,J.settings);let F0={userInput:V,stdinInput:G,dependencies:D,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},$0=await Hj4({threadPool:f,...F0});if(await Jo($0,"execute"),Z.archive)await D.threadService.archive($0,!0),await Zo(D.threadService,$0);await D.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await Ff1();let F0=await zE({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)i=!await D.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)a$.selectConfig($0)}else c=!0}z=process.hrtime.bigint();let s=Ha0("0.0.
|
|
7696
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Nn1({get:async(G)=>{if(G!==xh)return;try{let F=await ll4(q61,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==xh)return;await cl4(rU.dirname(q61),{recursive:!0}),await Jv3(q61,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:vF()});Nx1(Y);let X=await MR4({...J,workspaceTrust:{current:!0,changes:HA0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await rP4(J.mcpConfig);X=sP4(X,G)}let K=rU.dirname(X.getSettingsFilePath());qz4(sk,K);let V=await X.get("url","global");if(!V)V=i7;if(T.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jW(V))T.info("Targeting custom Amp server",{ampURL:V});return X=zy1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:HC4(await rn0(J,X))}}function Iv3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Pv3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=rU.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Yv3:Jn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Cv3(){XL4();let J=Iv3(process.argv),Z=Pv3(process.argv,J),Q=HA4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)p0.level=0;if(Kv3(T),T.info("Starting Amp CLI.",{version:"0.0.
|
|
7695
|
+
`),await FU(),process.exit(1);let m=(async()=>{if(W){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await D.configService.getLatest(),$0=yu(F0),z0=await b5.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(z0.ok)return T.info("User free tier status:",z0),z0.result;return}catch(F0){T.error("Failed to fetch free tier status:",F0);return}})(),k=!J.executeMode?new Rt0:null,f,p=null;if(k)f=k,p=(async()=>{let F0=W?await D.serverStatusPromise:D.serverStatus;await W61(Q,Z,F0);let $0=process.hrtime.bigint(),z0=U61(O,F0),n=x6(F0)?D61({userEmail:F0.user.email,features:F0.features}):!1;xl4({dtwEnabled:z0,hasV2TUIAccess:n});let a=await h(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await I1(a.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),p.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));k.setInitError($0),await zU(F0,Z.threadId)});else z=process.hrtime.bigint(),xl4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let g=Z.notifications!==void 0?Z.notifications:!J.executeMode;z=process.hrtime.bigint();let b=await D.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),Hv3({configService:D.configService,threadService:D.threadService,config:b,useNotificationsForService:g,threadViewStates$:()=>f.threadHandles$.pipe(I4((F0)=>{if(!F0)return k0.of({});return G5(F0.thread$,F0.threadViewState$).pipe(B1(([$0,z0])=>({[$0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){tP4(D.mcpService,J.settings);let F0={userInput:V,stdinInput:G,dependencies:D,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},$0=await Hj4({threadPool:f,...F0});if(await Jo($0,"execute"),Z.archive)await D.threadService.archive($0,!0),await Zo(D.threadService,$0);await D.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await Ff1();let F0=await zE({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)i=!await D.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)a$.selectConfig($0)}else c=!0}z=process.hrtime.bigint();let s=Ha0("0.0.1775031755-gf66c2b",D.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let U0=new ra0(D.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let F0=await I1(f.threadHandles$);if(!F0)throw new T1("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let r=await $X0();K("runMainThread:loadSessionState",z),T.info("Loaded session state:",r);let D0={...r,launchCount:r.launchCount+1};Fv((F0)=>({...F0,launchCount:F0.launchCount+1}));let L0=Z.threadId&&M7(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await Yf4({history:new kn0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:b5,threadPool:f,createSystemPromptDeps:async()=>rl4(D),ideClient:a$,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:U0,updateService:s,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:i,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:yl4,logFile:{path:Y},sessionState:D0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-01T08:26:12.103Z"},(F0)=>new pt0({...F0,threadPool:F0.threadPool},($0)=>new f11({...$0,threadState:$0.threadState}))),K("runMainThread:mountApp-returned",z),p)await p}finally{}await D.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function I3(J){if(T.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)u$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7696
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Nn1({get:async(G)=>{if(G!==xh)return;try{let F=await ll4(q61,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==xh)return;await cl4(rU.dirname(q61),{recursive:!0}),await Jv3(q61,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:vF()});Nx1(Y);let X=await MR4({...J,workspaceTrust:{current:!0,changes:HA0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await rP4(J.mcpConfig);X=sP4(X,G)}let K=rU.dirname(X.getSettingsFilePath());qz4(sk,K);let V=await X.get("url","global");if(!V)V=i7;if(T.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jW(V))T.info("Targeting custom Amp server",{ampURL:V});return X=zy1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:HC4(await rn0(J,X))}}function Iv3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Pv3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=rU.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Yv3:Jn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Cv3(){XL4();let J=Iv3(process.argv),Z=Pv3(process.argv,J),Q=HA4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)p0.level=0;if(Kv3(T),T.info("Starting Amp CLI.",{version:"0.0.1775031755-gf66c2b",buildTimestamp:"2026-04-01T08:26:12.103Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(N3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Mv3(Q).parseAsync(process.argv)}Fz4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Cv3().catch(zU)});async function Tv3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),a6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7697
7697
|
`);else if(!jW(J.ampURL))a6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7698
7698
|
`);let Y=process.env.AMP_API_KEY;if(Y)a6.write(`API key found in environment variable, storing...
|
|
7699
7699
|
`),await Z.set("apiKey",Y,J.ampURL),a6.write(`API key successfully stored.
|