@sourcegraph/amp 0.0.1774963753-g9f23e6 → 0.0.1774964363-g9f23e6
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 +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6222,11 +6222,11 @@ ${H}`))}},error:(D)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${D.message}`))}
|
|
|
6222
6222
|
${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))U+=`
|
|
6223
6223
|
|
|
6224
6224
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6225
|
-
npm install -g @sourcegraph/amp`;G(Error(U))}},error:(D)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!q)q=!0,V()}})})}d0();d0();cM();async function MY0(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 z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=RI4(J,F),W=q<0,D,H;if(z.time){let U=z.time[J],B=z.time[F],w=Date.now();if(U)D=Math.floor((w-new Date(U).getTime())/3600000);if(B)H=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:D,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:H,source:"npm"}}catch(G){return C.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var jJ3="https://static.ampcode.com/cli/cli-version.txt";async function AY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${jJ3}?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=RI4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var RJ3=604800000;function jI4(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>RJ3)return{ageMs:Q};return null}function RI4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},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,z=X.parts[V]||0;if(G<z)return-1;if(G>z)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 Na0(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?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function La0(J,Z,Q={}){let Y=new z4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Cz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await EF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await EF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await EY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let D=W?await AY0(J):await MY0(J,jj());if(!(D.latestVersion&&D.hasUpdate)){K.debug("no update available");return}let H=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Wa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())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"),!H())Y.next("update-available");return}try{await wi(D.latestVersion,q);let U=await LN(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await EF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}cM();import{stderr as _G}from"node:process";function II4(J){let Z=new hw().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 Ga0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6225
|
+
npm install -g @sourcegraph/amp`;G(Error(U))}},error:(D)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!q)q=!0,V()}})})}d0();d0();cM();async function MY0(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 z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=RI4(J,F),W=q<0,D,H;if(z.time){let U=z.time[J],B=z.time[F],w=Date.now();if(U)D=Math.floor((w-new Date(U).getTime())/3600000);if(B)H=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:D,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:H,source:"npm"}}catch(G){return C.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var jJ3="https://static.ampcode.com/cli/cli-version.txt";async function AY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${jJ3}?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=RI4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var RJ3=604800000;function jI4(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>RJ3)return{ageMs:Q};return null}function RI4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},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,z=X.parts[V]||0;if(G<z)return-1;if(G>z)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 Na0(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?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function La0(J,Z,Q={}){let Y=new z4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Cz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await EF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await EF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await EY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let D=W?await AY0(J):await MY0(J,jj());if(!(D.latestVersion&&D.hasUpdate)){K.debug("no update available");return}let H=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Wa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())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"),!H())Y.next("update-available");return}try{await wi(D.latestVersion,q);let U=await LN(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await EF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}cM();import{stderr as _G}from"node:process";function II4(J){let Z=new hw().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 Ga0(Y.force||!1,Y.verbose||!1,"0.0.1774964363-g9f23e6"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new hw("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 IJ3(Y.targetVersion)});J.addCommand(Q)}async function IJ3(J){let Z=process.platform==="win32"&&OY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")_G.write(p0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6226
6226
|
|
|
6227
6227
|
`));try{if(!J){_G.write(p0.blue(`Checking for updates...
|
|
6228
|
-
`));let{hasUpdate:K,latestVersion:V}=OY0()?await AY0("0.0.
|
|
6229
|
-
`));let F=await LN("0.0.
|
|
6228
|
+
`));let{hasUpdate:K,latestVersion:V}=OY0()?await AY0("0.0.1774964363-g9f23e6"):await MY0("0.0.1774964363-g9f23e6",jj());if(!K){let G=Na0("0.0.1774964363-g9f23e6"),z=G?.age?`released ${G.age} ago`:`built ${MF(new Date("2026-03-31T13:43:09.682Z"))} ago`;_G.write(p0.green(`✓ Amp is already up to date on version ${"0.0.1774964363-g9f23e6"} (${z})
|
|
6229
|
+
`));let F=await LN("0.0.1774964363-g9f23e6",Q);if(F.warning)_G.write(`
|
|
6230
6230
|
`+p0.yellow(F.warning)+`
|
|
6231
6231
|
`);process.exit(0)}if(!V)_G.write(p0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}_G.write(p0.blue(`Updating to version ${J}...
|
|
6232
6232
|
`)),await wi(J,void 0,(K)=>{_G.write(p0.dim(`Running: ${K}
|
|
@@ -7397,7 +7397,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7397
7397
|
`),K=[];for(let V=0;V<X.length;V++){let F=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 F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new _(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new _(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new _(`
|
|
7398
7398
|
`))}return new o0({decoration:{color:Q.colorScheme.background,border:Q4.all(new r1(Y.app.keybind,1,"rounded"))},child:new l0({padding:C0.symmetric(0,1),child:new J0({text:new _(void 0,void 0,K)})})})}}class ue0 extends C${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=VG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new xe0({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 jb4(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?C9:0,z=Y-G;if(z<=0)return null;let F=Z-G;if(F<0||F>=z)return null;let q=Math.max(1,Math.floor(z/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?C9:0,z=Y-G;if(z<=0)return null;let F=Math.max(0,Math.min(z-1,Z-G));if(K===1)return 0;let q=z/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function oA3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let z=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?C9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let D=Math.max(1,Math.floor(q/X)),H=F+Z*D+Math.floor(D/2),U=G>0?V/G:0,B=Math.round((1-U)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?C9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let D=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=G>0?V/G:0,U=Math.round((1-H)*(W-1));return{x:D,y:U}}default:return null}}function rA3(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 sA3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),z=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+z.length}let K=J.label.length,V=0;for(let G of Q){let z=G.points[Z];if(!z)continue;V+=z.value;let F=2+G.name.length+2+Y(z.value).length;K=Math.max(K,F)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function tA3(J,Z,Q,Y,X,K,V){let G;try{let U=m1.of(J),B=u0.of(J);G={foreground:U.colorScheme.foreground,background:U.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let z=new g({color:G.foreground,bold:!0}),F=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],D=new g({color:G.foreground,underline:!0}),H=(U,B)=>new _(B,D,void 0,kY0(U),()=>{f3(J,U)});if(Y.length<=1){if(W.push(new _(`${Z.label}: `,z)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new _(K(Z.value),F));if(Z.meta)W.push(new _(` (${Z.meta})`,q))}else{let U=V==="stacked-bar"||V==="stacked-area";W.push(new _(`${Z.label}
|
|
7399
7399
|
`,z));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],L=N.points[Q];if(!L)continue;B+=L.value;let O=N.color??X[w%X.length]??G.foreground;if(W.push(new _("● ",new g({color:O}))),W.push(new _(`${N.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new _(K(L.value),F));if(w<Y.length-1||U)W.push(new _(`
|
|
7400
|
-
`))}if(U)W.push(new _(" ",q)),W.push(new _("Total: ",q)),W.push(new _(K(B),F))}return new o0({decoration:{color:G.background,border:Q4.all(new r1(G.border,1,"rounded"))},child:new J0({text:new _(void 0,void 0,W)})})}ZE();d0();P7();GE();F$();v3();j2();Kd();PX();lZ();$Y();rZ();MA();d4();Rg();PP();E1();d0();lZ();class be0{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.1774963753-g9f23e6"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await J40(Z,this.configService)}catch(Z){C.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 GL extends n0{props;constructor(J){super();this.props=J}createState(){return new Rb4}}class Rb4 extends i0{_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 Ib4 extends i0{controller=new o2;focusNode=new N6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Q4.all(new r1(Q.foreground,1,"solid")),z=new sY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let U=H.trim();if(X&&U.length===0)return;this.widget.props.onSubmit(U)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new N1({children:[new o0({decoration:{color:Q.background},child:new J0({text:new _(">",new g({color:Q.foreground}))})}),new p1({child:z})]}),q=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,[new _("Command: ",new g({color:Q.foreground})),new _(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new _("Enter",new g({color:Y.keybind}))),W.push(new _(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new _("Esc",new g({color:Y.keybind}))),W.push(new _(" to cancel",new g({color:Q.foreground,dim:!0})));let D=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,W)})});return new o0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new h0({children:[q,new I0({height:1}),F,new x3,D]})})}}class Fa extends n0{props;constructor(J){super();this.props=J}createState(){return new Ib4}}rZ();import{mkdtemp as Jj3,readFile as Zj3,rmdir as Qj3,unlink as Yj3,writeFile as Xj3}from"node:fs/promises";import{tmpdir as Kj3}from"node:os";import xb4 from"node:path";d0();d0();class Pb4{_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 Pb4{_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 Cb4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class he0{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 ge0 extends N8{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 Tb4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Tb4 extends h4{_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($6(!!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 me0 extends N8{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new Bq(this)}createRenderObject(){return new _b4(this.link)}updateRenderObject(J){J.link=this.link}}class _b4 extends h4{_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 h4)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($6(!!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 pe0{_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){C.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}d0();var eA3=500;class de0{_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 z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=M6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].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(C.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)},eA3)}_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 qa{}class Wa{}class Da{}class zG0{}class FG0 extends n0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sb4(this.props)}}class Sb4 extends i0{props;controller;stateListener=null;overlayEntry=null;layerLink=new pe0;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new N6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new de0,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Cb4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)o6.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 qa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Wa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Da)return this.controller.acceptSelected(),"handled";if(J instanceof zG0)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 sY({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new oY({shortcuts:new Map([[new m4("ArrowDown"),new qa],[new m4("ArrowUp"),new Wa],[new m4("n",{ctrl:!0}),new qa],[new m4("p",{ctrl:!0}),new Wa],[new m4("Enter"),new Da],[new m4("Escape"),new zG0],[new m4("Tab"),new Da]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new y$({actions:new Map([[qa,new h6(this.invoke)],[Wa,new h6(this.invoke)],[Da,new h6(this.invoke)],[zG0,new h6(this.invoke)]]),child:Q});return new me0({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 he0((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{WR.of(this.context).insert(this.overlayEntry)}catch(J){C.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 _(Q,new g({color:u0.of(J).app.command})),new _(" ",new g({color:Z})));return X.push(new _(Y,new g({color:Z}))),[{child:new J0({text:new _(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=m1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=O4.sizeOf(J).height,G=0;try{let I=this.layerLink.getTargetTransform();if(I)G=I.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let I=this.props.controller.getCursorVisualRow(),S=G+I+1;q=V-S-F}else q=G-F;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),H=[],U=0;for(let I=W;I<D;I++){let S=Z.options[I];if(!S)continue;let T=I===Z.selectedIndex,b,m;if(this.props.optionViewBuilder){b=this.props.optionViewBuilder(J,S,T);let f=this.props.displayStringForOption?.(S)??String(S),d="",p=f,h=S;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(S)??String(S),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();b=new J0({text:new _(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let x=O4.of(J),k=C5(m,x.supportsEmojiWidth);U=Math.max(U,k),H.push(b)}let B=O4.sizeOf(J).width,w=U+4,N=Math.floor(B*0.9),L=Math.max(Math.min(w,N),Math.min(30,N)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({width:L,child:new o0({height:M,decoration:new t4(Y),child:new U2({decoration:{border:Q4.all(new r1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new h0({crossAxisAlignment:"start",children:H})})})});return new ge0({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function kb4(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 vb4(J){switch(J.type){case"file":return J.path;case"hint":return`${$j3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function yb4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function $j3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=M6(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(`
|
|
7400
|
+
`))}if(U)W.push(new _(" ",q)),W.push(new _("Total: ",q)),W.push(new _(K(B),F))}return new o0({decoration:{color:G.background,border:Q4.all(new r1(G.border,1,"rounded"))},child:new J0({text:new _(void 0,void 0,W)})})}ZE();d0();P7();GE();F$();v3();j2();Kd();PX();lZ();$Y();rZ();MA();d4();Rg();PP();E1();d0();lZ();class be0{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.1774964363-g9f23e6"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await J40(Z,this.configService)}catch(Z){C.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 GL extends n0{props;constructor(J){super();this.props=J}createState(){return new Rb4}}class Rb4 extends i0{_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 Ib4 extends i0{controller=new o2;focusNode=new N6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Q4.all(new r1(Q.foreground,1,"solid")),z=new sY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let U=H.trim();if(X&&U.length===0)return;this.widget.props.onSubmit(U)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new N1({children:[new o0({decoration:{color:Q.background},child:new J0({text:new _(">",new g({color:Q.foreground}))})}),new p1({child:z})]}),q=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,[new _("Command: ",new g({color:Q.foreground})),new _(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new _("Enter",new g({color:Y.keybind}))),W.push(new _(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new _("Esc",new g({color:Y.keybind}))),W.push(new _(" to cancel",new g({color:Q.foreground,dim:!0})));let D=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,W)})});return new o0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new h0({children:[q,new I0({height:1}),F,new x3,D]})})}}class Fa extends n0{props;constructor(J){super();this.props=J}createState(){return new Ib4}}rZ();import{mkdtemp as Jj3,readFile as Zj3,rmdir as Qj3,unlink as Yj3,writeFile as Xj3}from"node:fs/promises";import{tmpdir as Kj3}from"node:os";import xb4 from"node:path";d0();d0();class Pb4{_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 Pb4{_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 Cb4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class he0{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 ge0 extends N8{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 Tb4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Tb4 extends h4{_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($6(!!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 me0 extends N8{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new Bq(this)}createRenderObject(){return new _b4(this.link)}updateRenderObject(J){J.link=this.link}}class _b4 extends h4{_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 h4)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($6(!!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 pe0{_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){C.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}d0();var eA3=500;class de0{_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 z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=M6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].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(C.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)},eA3)}_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 qa{}class Wa{}class Da{}class zG0{}class FG0 extends n0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sb4(this.props)}}class Sb4 extends i0{props;controller;stateListener=null;overlayEntry=null;layerLink=new pe0;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new N6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new de0,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Cb4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)o6.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 qa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Wa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Da)return this.controller.acceptSelected(),"handled";if(J instanceof zG0)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 sY({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new oY({shortcuts:new Map([[new m4("ArrowDown"),new qa],[new m4("ArrowUp"),new Wa],[new m4("n",{ctrl:!0}),new qa],[new m4("p",{ctrl:!0}),new Wa],[new m4("Enter"),new Da],[new m4("Escape"),new zG0],[new m4("Tab"),new Da]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new y$({actions:new Map([[qa,new h6(this.invoke)],[Wa,new h6(this.invoke)],[Da,new h6(this.invoke)],[zG0,new h6(this.invoke)]]),child:Q});return new me0({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 he0((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{WR.of(this.context).insert(this.overlayEntry)}catch(J){C.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 _(Q,new g({color:u0.of(J).app.command})),new _(" ",new g({color:Z})));return X.push(new _(Y,new g({color:Z}))),[{child:new J0({text:new _(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=m1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=O4.sizeOf(J).height,G=0;try{let I=this.layerLink.getTargetTransform();if(I)G=I.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let I=this.props.controller.getCursorVisualRow(),S=G+I+1;q=V-S-F}else q=G-F;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),H=[],U=0;for(let I=W;I<D;I++){let S=Z.options[I];if(!S)continue;let T=I===Z.selectedIndex,b,m;if(this.props.optionViewBuilder){b=this.props.optionViewBuilder(J,S,T);let f=this.props.displayStringForOption?.(S)??String(S),d="",p=f,h=S;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(S)??String(S),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();b=new J0({text:new _(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let x=O4.of(J),k=C5(m,x.supportsEmojiWidth);U=Math.max(U,k),H.push(b)}let B=O4.sizeOf(J).width,w=U+4,N=Math.floor(B*0.9),L=Math.max(Math.min(w,N),Math.min(30,N)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({width:L,child:new o0({height:M,decoration:new t4(Y),child:new U2({decoration:{border:Q4.all(new r1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new h0({crossAxisAlignment:"start",children:H})})})});return new ge0({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function kb4(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 vb4(J){switch(J.type){case"file":return J.path;case"hint":return`${$j3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function yb4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function $j3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=M6(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
7401
|
`))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 BR extends n0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new fb4(this.props)}}var Vj3=":";class fb4 extends i0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new Z3;_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(Vj3);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"?"@:":"@@",z=K+G+V;this.props.controller.clear(),this.props.controller.insertText(z),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})`,z=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new N6({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=Iu4(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 Jj3(xb4.join(Kj3(),"amp-edit-")),Q=xb4.join(Z,"message.amp.md");await Xj3(Q,J,"utf-8"),await uK(Q);try{let Y=await Zj3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")C.error("Failed to read temporary file",Y)}try{await Yj3(Q),await Qj3(Z)}catch(Y){C.warn("Failed to clean up temporary file",Y)}}catch(Z){C.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 N1({mainAxisSize:"min",children:[new J0({text:new _("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((z,F)=>{let q=new K4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new J0({text:new _(z.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new J0({text:new _(" ")})];return[q]})]}):null,K=Y?new N1({mainAxisSize:"min",children:[new J0({text:new _("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((z,F)=>{let q=this.props.onImageClick!==void 0,W=new K4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new J0({text:new _(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new J0({text:new _(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new J0({text:new _(" ")}),new J0({text:new _(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new FG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(z)=>vb4(z),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:C0.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:(z,F,q)=>{let W=q?Z.selection:void 0,D=Z.secondary,H=Z.foreground,U=Z.foreground,B=Z.warning;if(F.type==="commit")return new o0({decoration:new t4(W),child:new N1({children:[new p1({child:new J0({text:new _("",void 0,[new _(F.shortHash,new g({color:Z.secondary})),new _(" ",new g({})),new _(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new J0({text:new _(` ${F.relativeDate}`,new g({color:U,dim:!0}))})]})});let w=[];switch(F.type){case"file":w.push(new _("@",new g({color:D}))),w.push(new _(F.path,new g({color:H})));break;case"hint":w.push(new _(F.kind==="commit"?"@:":"@@",new g({color:B}))),w.push(new _(" ",new g({}))),w.push(new _(F.message,new g({color:B})));break}let N=yb4(F);if(N)w.push(new _(" - ",new g({color:U,dim:!0}))),w.push(new _(N,new g({color:U,dim:!0})));return new o0({decoration:new t4(W),child:new J0({text:new _("",void 0,w),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let z=[];if(X)z.push(X);if(X&&K)z.push(new J0({text:new _(" ")}));if(K)z.push(K);let F=new o0({padding:C0.only({bottom:1}),child:new N1({mainAxisSize:"min",children:z})});G.push(F)}if(G.push(new p1({child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new h0({crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class ub4 extends i0{controller=new o2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new N6({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>=IV)return!1;let Z=await QL(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=u0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new BR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:Z6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new K6({focusNode:this.focusNode,child:G}),F=new o0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,[new _("Command: ",new g({color:Q.foreground})),new _(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new o0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new _("",void 0,[new _("Esc",new g({color:Y.keybind})),new _(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new _("",void 0,[new _("Press ",new g({color:Q.foreground,dim:!0})),new _("Enter",new g({color:Y.keybind})),new _(" to submit, ",new g({color:Q.foreground,dim:!0})),new _("Esc",new g({color:Y.keybind})),new _(" to clear",new g({color:Q.foreground,dim:!0}))])})}),D=[q,new I0({height:1}),new p1({child:F}),new I0({height:1}),W];return new o0({decoration:{border:Q4.all(new r1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new h0({children:D})})}}class ce0 extends n0{props;constructor(J){super();this.props=J}createState(){return new ub4}}import{isDeepStrictEqual as le0}from"node:util";var Gj3=/[\\/_ +.#"@[({&]/,zj3=/[\\/_ +.#"@[({&]/g,Fj3=/[\s-]/,bb4=/[\s-]/g;function WG0(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 z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,D,H,U;while(F>=0){if(W=WG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(Fj3.test(J.charAt(F-1))){if(W*=0.9,U=J.slice(X,F-1).match(bb4),U&&X>0)W*=0.999**U.length}else if(Gj3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(zj3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(D=WG0(J,Z,Q,Y,F+1,K+2,V),D*0.1>W)W=D*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function qG0(J){return J.toLowerCase().replace(bb4," ")}function hb4(J,Z){let Q=WG0(J,Z,qG0(J),qG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=WG0(J,G,qG0(J),qG0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Vy{}class Gy{}class DG0{}class HG0{}class gb4 extends n0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new mb4}}class mb4 extends i0{build(J){return this.widget.onContext(J),this.widget.child}}function qj3(J,Z){if(J==="")return{matches:!0,score:1};let Q=hb4(Z,J);return{matches:Q>0.15,score:Q}}class n9 extends n0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new pb4}}class pb4 extends i0{textController;focusNode;scrollController=new n5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new o2(this.widget.props.controller?.query??""),this.focusNode=new N6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),o6.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)=>le0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!le0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>le0(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(),o6.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(),o6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof DG0){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 HG0)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,...qj3(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;pV0(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(),o6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=Q4.all(new r1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new sY({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}),z=new oY({shortcuts:new Map([[new m4("ArrowDown"),new Vy],[new m4("ArrowUp"),new Gy],[new m4("Tab"),new Vy],[new m4("Tab",{shift:!0}),new Gy],[new m4("n",{ctrl:!0}),new Vy],[new m4("p",{ctrl:!0}),new Gy],[new m4("Enter"),new DG0],[new m4("Escape"),new HG0]]),focusNode:this.focusNode,child:G}),F=new y$({actions:new Map([[Vy,new h6(this.invoke)],[Gy,new h6(this.invoke)],[DG0,new h6(this.invoke)],[HG0,new h6(this.invoke)]]),child:z}),q=new N1({children:[new o0({decoration:{color:Q.background},child:new J0({text:new _(">",new g({color:Q.foreground}))})}),new p1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new Z4({child:new J0({text:new _(w,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new p1({child:new Z4({child:new J0({text:new _(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new o0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new _(this.widget.props.getLabel(N),new g({color:j,dim:E}))})})}return new gb4(new K4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new h0({children:w,crossAxisAlignment:"start"})}let D=new K4({onScroll:this.handleScroll,opaque:!1,child:new r6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let w=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(w)}if(!K)H.push(q,new I0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);H.push(new p1({child:new h0({mainAxisAlignment:"spaceBetween",children:[new p1({child:D}),new o0({padding:C0.only({top:1}),child:new Z4({child:N??new I0({height:1})})})]})}))}else H.push(new p1({child:D}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new o0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new h0({children:H})})}}function db4(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 ie0 extends J4{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)=>db4(X.pubDate).length));return new n9({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 z=u0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,D=K?q.selectionForeground:F.foreground,H=F.mutedForeground,U=(B,w)=>new I0({width:w,child:N1.end([new J0({text:new _(B,new g({color:H}))})])});return new o0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[new p1({child:new J0({text:new _(X.title,new g({color:D})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),U(db4(X.pubDate),Q)]})})}})}}eO();class ne0 extends n0{createState(){return new cb4}}class cb4 extends i0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=u0.of(J).colors;return new J0({text:new _("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function Wj3(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((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return bK0.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 ae0(J,Z,Q){return new J0({text:new _(`${J}${Z}`,new g({color:Q})),maxLines:1})}function Dj3(J,Z,Q,Y){return[ae0("+",J,Y.success),x3.horizontal(1),ae0("~",Z,Y.warning),x3.horizontal(1),ae0("-",Q,Y.destructive)]}function Hj3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class UG0 extends n0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new lb4}}class lb4 extends i0{spinner=new Z3;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),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)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=Wj3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),D=u0.of(J),H=new l0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new _("",new g({color:D.colors.foreground,dim:!0}),[new _("Alt+W/Ctrl+T",new g({color:D.colors.primary,dim:!0})),new _(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:D.colors.foreground,dim:!0}))])})})}),U="",B=null,w=(L)=>{if(L!==U)U=L,B=j7(L);return B};return new n9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=w(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>w(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!Hj3(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:H,renderItem:(L,O,E,M)=>{let A=u0.of(M),{app:j,colors:I}=A,S=O?j.selectionBackground:void 0,T=O?j.selectionForeground:I.foreground,b=I.mutedForeground,m=(o,H0)=>new I0({width:H0,child:N1.end([new J0({text:new _(o,new g({color:b}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new bn({connectorColor:I.mutedForeground});if(L.depth>0){let o=[],H0=L.ancestorsAreLast.slice(1);for(let L0 of H0)o.push(new _(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,D0=d.getConnectorText(r);o.push(new _(D0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new _("",void 0,o)}))}let p=[],h=z===L.id?new _("(current) ",new g({color:I.success})):G.has(L.id)?new _("(visited) ",new g({color:I.foreground,dim:!0})):null;if(h)p.push(new J0({text:h}));if(dM(x))p.push(new ne0),p.push(new I0({width:1}));let i=L.title;if(L.relationshipType==="fork"){let o=i.match(/^Forked\((\d+)\): /);if(o)i=i.slice(o[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);p.push(new J0({text:new _("[fork] ",new g({color:I.primary}))}))}else if(f)p.push(new J0({text:new _("[handoff] ",new g({color:I.accent}))}));if(p.push(new p1({child:new J0({text:new _(i,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let o=O?{success:b,warning:b,destructive:b}:I;p.push(...Dj3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,o)),p.push(new I0({width:2}))}return p.push(m(L.description.timeAgo,W)),new o0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[...k,...p]})})}})}}d0();AX();cM();PX();lZ();d4();U4();PP();var re0=H4($D(),1);import{execSync as wR}from"node:child_process";import{writeFile as zy}from"node:fs/promises";import Uj3 from"node:os";import yq from"node:path";var ib4="c446b2e9b16cdc06df2ec285894d6421",Bj3="5ea19563777f4ade8707fc56f7e7a388",wj3="amp-thread-worker",nb4=[{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 Nj3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function FL(J){if(!J||!Nj3(J.meta))return!1;return J.meta.usesDtw===!0}function se0(J){let Z=new URL(`https://dash.cloudflare.com/${ib4}/workers/durable-objects/view/${Bj3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function te0(J){let Z=new URL(`https://dash.cloudflare.com/${ib4}/workers/services/view/${wj3}/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 Lj3(J,Z){if(jW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function ee0(J,Z){let Q=Lj3(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 Ha(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ua(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ua(J){return J.path??k9(J.uri)}function ab4(J,Z,Q){let Y=Ha("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function ob4(J,Z){return ee0(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7402
7402
|
${Y}`).join(`
|
|
7403
7403
|
|
|
@@ -7619,7 +7619,7 @@ ${t.content||""}`:t.content||"",T0=[],s0=t.baseDir.startsWith("file://")?sG0(t.b
|
|
|
7619
7619
|
`),process.exit(1)}process.stdout.write(await $T3(z.result.displayText)+`
|
|
7620
7620
|
`),process.exit(0)})}cM();import{stdout as JT3}from"node:process";function ZT3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${MF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function Cp4(J){JT3.write(`${ZT3(J)}
|
|
7621
7621
|
`)}function Tp4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{Cp4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{Cp4(Z),process.exit(0)})}var Mv3=sH.join(jX,"logs","headless.log"),L61=sH.join(sk,"device-id.json"),sl4=`cli-tui-${Ki4(16).toString("hex")}`;async function Av3(){for(let J of FE)try{if((await J.listConfigs()).length>0)return J}catch(Z){C.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4(by(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){g$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7622
|
-
`)}function jv3(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 L7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")mJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")mJ("experimental.agentMode",Z.mode)}function Fi4(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 Rv3(J){try{return await Gi4(J,"utf-8")}catch{return J}}async function O61(J,Z,Q){let Y=Fi4(J,Z);if(!Y)return;let X=f6(Q)?Q.features:[],K=f6(Q)?Q.user.email:void 0;if(!j61(X,R2.HARNESS_SYSTEM_PROMPT)&&!qi4(K))throw new C1("You are not allowed to do this.",1);mJ("systemPrompt",await Rv3(Y))}function qi4(J){return!!(J&&m00(J))}function j61(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function E61(J){return(J.userEmail?bJ(J.userEmail):!1)||j61(J.features,R2.DTW_TUI)}function tl4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function M61(J,Z){if(typeof J==="boolean")return J;if(!f6(Z))return!1;return E61({userEmail:Z.user.email,features:Z.features})}function Iv3(J){return J!=="pending"}function hy(J){if(!f6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Pv3(J){let Z=hy(J);if(Z)return Z.id;if(cz(J))throw Error(J.error.message);throw Error("unreachable")}function Cv3(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 mz0(J){let Y=Cv3(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 C1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function el4(J){if(!s6.write(J))await Nv3(s6,"drain")}var $i4=[{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??kK,description:`Custom settings file path (overrides the default location ${kK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xn0})`},{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:l7(),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:xz.SMART.key,description:`Set the agent mode (${fz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fz().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}],Ji4=(J)=>("deprecated"in J)&&J.deprecated===!0,Tv3=(J)=>("hidden"in J)&&J.hidden===!0,_v3=(J)=>("default"in J),Sv3=(J)=>("default"in J)?J.default:void 0,Wi4=[{name:"toggle-skills-count",entryPoint:Jo0}];function kv3(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 C1(E3.unknownCommand(Q),1,V)}}async function R61(J){return{...J,getThreadEnvironment:VZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new bV(J.fileSystem),generateThreadTitle:j80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iZ(J.configService),pluginService:J.pluginService}}function Di4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:VZ,filesystem:J.fileSystem,threadService:J.threadService}}var pz0=z1.file(zi4.homedir()),A61=process.env.XDG_CONFIG_HOME?z1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(pz0,".config");function vv3(J){return AF4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){MF4(Z);let Q=VX0(),Y=Ho0();if((!Q||Y||yC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(VX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function S9(J,Z,Q){let Y=Q?.deferAuth??!1;Rx1("0.0.
|
|
7622
|
+
`)}function jv3(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 L7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")mJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")mJ("experimental.agentMode",Z.mode)}function Fi4(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 Rv3(J){try{return await Gi4(J,"utf-8")}catch{return J}}async function O61(J,Z,Q){let Y=Fi4(J,Z);if(!Y)return;let X=f6(Q)?Q.features:[],K=f6(Q)?Q.user.email:void 0;if(!j61(X,R2.HARNESS_SYSTEM_PROMPT)&&!qi4(K))throw new C1("You are not allowed to do this.",1);mJ("systemPrompt",await Rv3(Y))}function qi4(J){return!!(J&&m00(J))}function j61(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function E61(J){return(J.userEmail?bJ(J.userEmail):!1)||j61(J.features,R2.DTW_TUI)}function tl4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function M61(J,Z){if(typeof J==="boolean")return J;if(!f6(Z))return!1;return E61({userEmail:Z.user.email,features:Z.features})}function Iv3(J){return J!=="pending"}function hy(J){if(!f6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Pv3(J){let Z=hy(J);if(Z)return Z.id;if(cz(J))throw Error(J.error.message);throw Error("unreachable")}function Cv3(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 mz0(J){let Y=Cv3(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 C1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function el4(J){if(!s6.write(J))await Nv3(s6,"drain")}var $i4=[{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??kK,description:`Custom settings file path (overrides the default location ${kK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xn0})`},{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:l7(),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:xz.SMART.key,description:`Set the agent mode (${fz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fz().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}],Ji4=(J)=>("deprecated"in J)&&J.deprecated===!0,Tv3=(J)=>("hidden"in J)&&J.hidden===!0,_v3=(J)=>("default"in J),Sv3=(J)=>("default"in J)?J.default:void 0,Wi4=[{name:"toggle-skills-count",entryPoint:Jo0}];function kv3(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 C1(E3.unknownCommand(Q),1,V)}}async function R61(J){return{...J,getThreadEnvironment:VZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new bV(J.fileSystem),generateThreadTitle:j80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iZ(J.configService),pluginService:J.pluginService}}function Di4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:VZ,filesystem:J.fileSystem,threadService:J.threadService}}var pz0=z1.file(zi4.homedir()),A61=process.env.XDG_CONFIG_HOME?z1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(pz0,".config");function vv3(J){return AF4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){MF4(Z);let Q=VX0(),Y=Ho0();if((!Q||Y||yC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(VX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function S9(J,Z,Q){let Y=Q?.deferAuth??!1;Rx1("0.0.1774964363-g9f23e6");let X=V10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(z1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:pz0,userConfigDir:A61});vC4(X);let K=await X.getLatest();C.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let i=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(i),C.info("API key lookup before login",{found:Boolean(i),ampURL:J.ampURL,deferAuth:Y}),!i)if(Y)C.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
|
|
7623
7623
|
`);let c=await yv3(J),o=await J.secrets.get("apiKey",J.ampURL);if(C.info("Login flow completed",{success:c,storedKeyPresent:Boolean(o),ampURL:J.ampURL}),!c)await zH(),process.exit(1);V=!0}}{let i=await X.getLatest(),c=i.settings.url,o=i.secrets.isSet?.[c];C.info("Config secrets state after login",{configURL:c,apiKeySet:o?.apiKey??!1})}let G=R1(iZ(X).pipe(y5(Iv3))),z=Y?"pending":await G;if(!Y)C.info("Server status resolved",{status:"ready",isAuthenticated:f6(z),isError:cz(z),errorMessage:cz(z)?z.error.message:void 0});let F=G.then((i)=>Pv3(i)),{toolService:q,dispose:W}=wF4({configService:X}),D=new Map,H=()=>D.clear(),U=new DT0(X,J.settings.getWorkspaceRootPath()),B=Cs1({configService:X,filesystem:n8}),w=Mn1({configService:X,trustStore:U,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(i,c,o)=>{let H0=`${i}:${c}`,r=D.get(H0);if(r)return C.debug("Reusing existing OAuth provider for server",{serverName:i,serverUrl:c}),r;C.debug("Creating OAuth provider for server",{serverName:i,serverUrl:c});let D0=(async()=>{let L0=new NE(J.secrets),G0=await L0.getClientInfo(i,c),$0=o?.scopes??G0?.scopes,F0=HR4();C.info("OAuth headless mode check",{useHeadless:F0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let n;if(F0)n=J.executeMode?DR4():WR4(i);let a=new nj0({storage:L0,serverName:i,serverUrl:c,clientId:o?.clientId??G0?.clientId,clientSecret:o?.clientSecret??G0?.clientSecret,authUrl:o?.authUrl??G0?.authUrl,tokenUrl:o?.tokenUrl??G0?.tokenUrl,scopes:$0,headlessAuthHandler:n});return C.debug("OAuth provider created",{serverName:i,serverUrl:c,hasManualClientId:!!(o?.clientId??G0?.clientId),willUseDCR:!(o?.clientId??G0?.clientId),scopes:$0,headlessMode:F0,executeMode:J.executeMode}),a})();return D.set(H0,D0),D0}}),N=Ug0({configService:X,filesystem:n8,spawn:q$0}),L;if(J.executeMode){let i=await EV4({toolService:q,providers:[w,N],initialTimeout:15000});L=i.registrations;for(let[c,o]of i.initErrors)C.warn(`${c} provider initialization slow or failed:`,o)}else L=Bg0({toolService:q,providers:[w,N]});if(Z.jetbrains)XE("JetBrains");else if(Z.ide&&tR4())XE("VS Code");else if(Z.ide&&eR4())XE("Neovim");else if(Z.ide){let i=await Av3();if(i){let c=w10(i.ideName);if(c)XE(c)}}if(J.executeMode)Ix1(!0);let O,E=q$.status.pipe(w1((i)=>Boolean(i.connected&&i.authenticated&&i.ideName&&Df1(i.ideName))),u4()).subscribe((i)=>{if(i){if(!O)O=q.registerTool(OV4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let i=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new tQ0(process.cwd(),{alwaysIncludePaths:i},!0)}else M=new class extends tQ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new US0(ds1(X),{maxThreads:200});C.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=M61(j,z),S;q$.status.subscribe((i)=>{S=i});let T=new MA0({workspaceRoots:[z1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!S?.openFile)return;try{return z1.parse(S.openFile)}catch(i){C.warn("Failed to parse current file URI",{uri:S.openFile,error:i});return}},getOpenFiles:()=>{if(!S?.visibleFiles?.length)return[];let i=S.openFile;return S.visibleFiles.filter((c)=>c!==i).map((c)=>{try{return z1.parse(c)}catch(o){return C.warn("Failed to parse visible file URI",{uri:c,error:o}),null}}).filter((c)=>c!==null)}}),b=new wo0,m=process.env.PLUGINS??"off",x=Z.headless?BC4():void 0,k=x??new ZX0({configService:X}),f=k instanceof ZX0?k:void 0;if(f)f.pluginExecutorKind=I?"local":"unknown";let d=TT0({configService:X,fileSystem:n8,platform:k,internalPlugins:Wi4,pluginFilter:m}),p=wa1({pluginService:d,toolService:q}),h={codebaseContextService:T,configService:X,toolService:q,mcpService:w,skillService:B,toolboxService:N,trustStore:U,threadService:A,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,fileSystem:n8,terminal:b,pluginService:d,pluginPlatform:f,headlessPluginPlatform:x,serverStatus:z,serverStatusPromise:G,viewerUserIDPromise:F,hasAPIKeyAtStartup:V};return{...h,async asyncDispose(){if(h.mcpService.hasAuthenticatingClients())C.info("Waiting for OAuth authentication to complete before exit..."),await h.mcpService.waitForAuthentication();for(let i of L.values())i.dispose();await h.mcpService.dispose(),H(),await h.threadService.asyncDispose(),h.configService.unsubscribe(),W(),h.fuzzyServer.dispose(),h.settingsStorage[Symbol.dispose](),E.unsubscribe(),O?.dispose(),p.dispose(),await h.pluginService.dispose()}}}async function yv3(J){if(!J.executeMode){if(!await eY0("Would you like to log in to Amp? [(y)es, (n)o]: "))return s6.write(`Login cancelled. Run the command again to retry.
|
|
7624
7624
|
`),!1}return await Hi4(J)}async function Hi4(J){let Z=Ki4(32).toString("hex"),Q=await Xv(J.ampURL,Z),Y=new AbortController;try{await NV(Q,Y.signal)}catch(K){C.error("Error opening browser",{error:K})}let X=await Xv(J.ampURL,Z,!1);s6.write(`If your browser does not open automatically, visit:
|
|
7625
7625
|
|
|
@@ -7627,7 +7627,7 @@ ${p0.blue.bold(X)}
|
|
|
7627
7627
|
|
|
7628
7628
|
`);try{return await oP4(J.ampURL,Z,J.secrets,Y),s6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return C.error("Login failed",{error:K}),g$.write(`
|
|
7629
7629
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7630
|
-
`),!1}}function Zi4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xv3(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 C1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!R7(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function fv3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function uv3(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 C1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!fv3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bv3(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 hv3(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 C1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function gv3(J){let Z=new hw().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)Nj(),process.exit(0);let w=B.originalError??B;Hj4(w)}),Tp4(Z,{version:"0.0.
|
|
7630
|
+
`),!1}}function Zi4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xv3(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 C1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!R7(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function fv3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function uv3(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 C1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!fv3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bv3(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 hv3(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 C1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function gv3(J){let Z=new hw().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)Nj(),process.exit(0);let w=B.originalError??B;Hj4(w)}),Tp4(Z,{version:"0.0.1774964363-g9f23e6",buildTimestamp:"2026-03-31T13:43:09.682Z",buildType:"'release'"}),Z.addHelpText("after",oR4()),Z.configureHelp({formatHelp:rR4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await av3(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,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await nv3(L,await $a0(N,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,w,N)=>{let L=N.optsWithGlobals(),O=await T3(L);await pj4(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,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await dj4(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",`
|
|
7631
7631
|
Actions:
|
|
7632
7632
|
create Create a new DTW thread and print its ID
|
|
7633
7633
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7691,8 +7691,8 @@ ${M}
|
|
|
7691
7691
|
|
|
7692
7692
|
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 mv3(J){C.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new hn({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:VZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new bV(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 C.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function pv3(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 dv3(J,Z,Q){if(J.remote&&!Z)throw new C1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new C1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new C1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new C1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new C1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new C1("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 C1("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 C1("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"
|
|
7693
7693
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function dz0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(G0,$0)=>{let F0=Number(process.hrtime.bigint()-$0)/1e6,n=BL4();C.info("Startup phase",{phase:G0,phaseMs:Math.round(F0),sinceMainMs:n===null?void 0:Math.round(n)})},{userInput:V,stdinInput:G}=await pv3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;dv3({...Z,streamJson:z},J.executeMode,V),L7(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;C.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await S9(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await R61(D);K("runMainThread:createWorkerDeps",F);let{serverStatus:U}=D;if(!W&&cz(U)){let G0=pk(Error(U.error.message));if(G0.message===E3.networkOffline||G0.message===E3.networkTimeout)throw mz0(J.ampURL);throw new C1(E3.invalidAPIKey,1)}let B=f6(U)?U:null,w=B?.user.email,N=qi4(w),L=E61({userEmail:w,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&M61(O,B);if(!W)await O61(Q,Z,U);let M=hy(U),A=M?.features??[],j=M?.team??null,I=$X0(Z,M);if(I instanceof Error)_3(I.message);if((J.executeMode||z)&&W8(Z.mode)&&!N)throw new C1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!VE(Z.mode,w))throw new C1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await LC4(V,G,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!w||!bJ(w))throw new C1("Headless DTW mode is only available for Amp employees",1);let G0=await D.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new C1("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&&!R7($0))throw new C1(`Invalid thread ID: ${$0}`,1);let F0=$0?void 0:await Qy3({dependencies:D,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),n=$0??F0?.threadId;if(!n)throw new C1("Failed to resolve headless thread ID",1);let a=await NR4(n);if(a.status==="already-running")await D.asyncDispose(),await zH(),process.exit(0);try{await qR4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:n,ownerUserId:F0?.ownerUserId,threadVersion:F0?.threadVersion,agentMode:F0?.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 zH(),process.exit(0)}let S=J.executeMode?void 0:async(G0)=>Yo(G0,"interactive"),T={threadService:D.threadService,workerDeps:H,createThread:async()=>{let G0=W?await D.serverStatusPromise:U,$0=await uQ0(J.settings,process.cwd(),hy(G0),I);if($0 instanceof Error)_3($0.message);return vt0(H,{threadMeta:$0?vG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:S})},validateThreadOwnership:async(G0,$0)=>{if($0?.nonBlockingOwnershipCheck){Qi4(G0,D.configService,D.viewerUserIDPromise).catch((F0)=>{if(F0 instanceof C1){if($0.onOwnershipError){$0.onOwnershipError(F0,G0);return}FH(F0,G0);return}C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:F0})});return}try{await Qi4(G0,D.configService,D.viewerUserIDPromise)}catch(F0){if(F0 instanceof C1)throw F0;C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:F0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:S,handleError:FH},b=async(G0)=>{try{if(G0==="dtw")return mv3({ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,clientID:sl4,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Rx4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof C1)throw $0;throw await FH($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")g$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7694
|
-
`),await zH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await D.configService.getLatest(),$0=bu(G0),F0=await p5.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(F0.ok)return C.info("User free tier status:",F0),F0.result;return}catch(G0){C.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new Tt0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await D.serverStatusPromise:D.serverStatus;await O61(Q,Z,G0);let $0=process.hrtime.bigint(),F0=M61(O,G0),n=f6(G0)?E61({userEmail:G0.user.email,features:G0.features}):!1;tl4({dtwEnabled:F0,hasV2TUIAccess:n});let a=await b(F0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await R1(a.threadHandles$);if(!t)throw new C1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let $0=G0 instanceof Error?G0:Error(String(G0));k.setInitError($0),await FH(G0,Z.threadId)});else F=process.hrtime.bigint(),tl4({dtwEnabled:E,hasV2TUIAccess:L}),f=await b(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await D.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),vv3({configService:D.configService,threadService:D.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(I4((G0)=>{if(!G0)return k0.of({});return F5(G0.thread$,G0.threadViewState$).pipe(w1(([$0,F0])=>({[$0.id]:F0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){VC4(D.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await Rj4({threadPool:f,...G0});if(await Yo($0,"execute"),Z.archive)await D.threadService.archive($0,!0),await Xo(D.threadService,$0);await D.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await Lf1();let G0=await qE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)i=!await D.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let $0=G0[0];if($0)q$.selectConfig($0)}else c=!0}F=process.hrtime.bigint();let o=La0("0.0.
|
|
7695
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Pn1({get:async(G)=>{if(G!==bh)return;try{let z=await Gi4(L61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==bh)return;await Vi4(sH.dirname(L61),{recursive:!0}),await Lv3(L61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:vz()});Px1(Y);let X=await SR4({...J,workspaceTrust:{current:!0,changes:kA0},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await XC4(J.mcpConfig);X=KC4(X,G)}let K=sH.dirname(X.getSettingsFilePath());EF4(sk,K);let V=await X.get("url","global");if(!V)V=o7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jW(V))C.info("Targeting custom Amp server",{ampURL:V});return X=wx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:jC4(await $a0(J,X))}}function cv3(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,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function lv3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=sH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Mv3:Xn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function iv3(){UL4();let J=cv3(process.argv),Z=lv3(process.argv,J),Q=RA4(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(jv3(C),C.info("Starting Amp CLI.",{version:"0.0.
|
|
7694
|
+
`),await zH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await D.configService.getLatest(),$0=bu(G0),F0=await p5.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(F0.ok)return C.info("User free tier status:",F0),F0.result;return}catch(G0){C.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new Tt0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await D.serverStatusPromise:D.serverStatus;await O61(Q,Z,G0);let $0=process.hrtime.bigint(),F0=M61(O,G0),n=f6(G0)?E61({userEmail:G0.user.email,features:G0.features}):!1;tl4({dtwEnabled:F0,hasV2TUIAccess:n});let a=await b(F0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await R1(a.threadHandles$);if(!t)throw new C1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let $0=G0 instanceof Error?G0:Error(String(G0));k.setInitError($0),await FH(G0,Z.threadId)});else F=process.hrtime.bigint(),tl4({dtwEnabled:E,hasV2TUIAccess:L}),f=await b(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await D.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),vv3({configService:D.configService,threadService:D.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(I4((G0)=>{if(!G0)return k0.of({});return F5(G0.thread$,G0.threadViewState$).pipe(w1(([$0,F0])=>({[$0.id]:F0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){VC4(D.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await Rj4({threadPool:f,...G0});if(await Yo($0,"execute"),Z.archive)await D.threadService.archive($0,!0),await Xo(D.threadService,$0);await D.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await Lf1();let G0=await qE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)i=!await D.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let $0=G0[0];if($0)q$.selectConfig($0)}else c=!0}F=process.hrtime.bigint();let o=La0("0.0.1774964363-g9f23e6",D.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let H0=new $o0(D.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await R1(f.threadHandles$);if(!G0)throw new C1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await QX0();K("runMainThread:loadSessionState",F),C.info("Loaded session state:",r);let D0={...r,launchCount:r.launchCount+1};zv((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&R7(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Hf4({codebaseContextService:D.codebaseContextService,history:new fn0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:p5,threadPool:f,createSystemPromptDeps:async()=>Di4(D),ideClient:q$,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:H0,updateService:o,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:sl4,logFile:{path:Y},sessionState:D0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-31T13:43:09.682Z"},(G0)=>new it0({...G0,threadPool:G0.threadPool},($0)=>new l11({...$0,threadState:$0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await D.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function T3(J){if(C.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)g$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7695
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Pn1({get:async(G)=>{if(G!==bh)return;try{let z=await Gi4(L61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==bh)return;await Vi4(sH.dirname(L61),{recursive:!0}),await Lv3(L61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:vz()});Px1(Y);let X=await SR4({...J,workspaceTrust:{current:!0,changes:kA0},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await XC4(J.mcpConfig);X=KC4(X,G)}let K=sH.dirname(X.getSettingsFilePath());EF4(sk,K);let V=await X.get("url","global");if(!V)V=o7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jW(V))C.info("Targeting custom Amp server",{ampURL:V});return X=wx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:jC4(await $a0(J,X))}}function cv3(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,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function lv3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=sH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Mv3:Xn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function iv3(){UL4();let J=cv3(process.argv),Z=lv3(process.argv,J),Q=RA4(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(jv3(C),C.info("Starting Amp CLI.",{version:"0.0.1774964363-g9f23e6",buildTimestamp:"2026-03-31T13:43:09.682Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new C1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gv3(Q).parseAsync(process.argv)}LF4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await iv3().catch(FH)});async function nv3(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"),s6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7696
7696
|
`);else if(!jW(J.ampURL))s6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7697
7697
|
`);let Y=process.env.AMP_API_KEY;if(Y)s6.write(`API key found in environment variable, storing...
|
|
7698
7698
|
`),await Z.set("apiKey",Y,J.ampURL),s6.write(`API key successfully stored.
|