@sourcegraph/amp 0.0.1774829165-g4f37d2 → 0.0.1774846380-g30c5db
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
|
@@ -6220,11 +6220,11 @@ ${D}`))}},error:(U)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6220
6220
|
${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))H+=`
|
|
6221
6221
|
|
|
6222
6222
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6223
|
-
npm install -g @sourcegraph/amp`;G(Error(H))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();gM();async function bY0(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=wP4(J,F),W=q<0,U,D;if(z.time){let H=z.time[J],B=z.time[F],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:D}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:D,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var iZ3="https://static.ampcode.com/cli/cli-version.txt";async function hY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${iZ3}?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=wP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var nZ3=604800000;function NP4(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>nZ3)return{ageMs:Q};return null}function wP4(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 da0(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?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function ca0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(l6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Cz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await $F(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 $F(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 uY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await hY0(J):await bY0(J,Mj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let D=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!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(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ua0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let H=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await $F(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}gM();import{stderr as Uq}from"node:process";function LP4(J){let Z=new fN().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 ka0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6223
|
+
npm install -g @sourcegraph/amp`;G(Error(H))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();gM();async function bY0(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=wP4(J,F),W=q<0,U,D;if(z.time){let H=z.time[J],B=z.time[F],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:D}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:D,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var iZ3="https://static.ampcode.com/cli/cli-version.txt";async function hY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${iZ3}?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=wP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var nZ3=604800000;function NP4(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>nZ3)return{ageMs:Q};return null}function wP4(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 da0(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?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function ca0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(l6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Cz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await $F(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 $F(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 uY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await hY0(J):await bY0(J,Mj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let D=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!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(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ua0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let H=await Nw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await $F(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}gM();import{stderr as Uq}from"node:process";function LP4(J){let Z=new fN().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 ka0(Y.force||!1,Y.verbose||!1,"0.0.1774846380-g30c5db"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new fN("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 aZ3(Y.targetVersion)});J.addCommand(Q)}async function aZ3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Uq.write(i0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6224
6224
|
|
|
6225
6225
|
`));try{if(!J){Uq.write(i0.blue(`Checking for updates...
|
|
6226
|
-
`));let{hasUpdate:Y,latestVersion:X}=ya0()?await hY0("0.0.
|
|
6227
|
-
`));let G=await Nw("0.0.
|
|
6226
|
+
`));let{hasUpdate:Y,latestVersion:X}=ya0()?await hY0("0.0.1774846380-g30c5db"):await bY0("0.0.1774846380-g30c5db",Mj());if(!Y){let K=da0("0.0.1774846380-g30c5db"),V=K?.age?`released ${K.age} ago`:`built ${EF(new Date("2026-03-30T04:56:52.817Z"))} ago`;Uq.write(i0.green(`✓ Amp is already up to date on version ${"0.0.1774846380-g30c5db"} (${V})
|
|
6227
|
+
`));let G=await Nw("0.0.1774846380-g30c5db");if(G.warning)Uq.write(`
|
|
6228
6228
|
`+i0.yellow(G.warning)+`
|
|
6229
6229
|
`);process.exit(0)}if(!X)Uq.write(i0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Uq.write(i0.blue(`Updating to version ${J}...
|
|
6230
6230
|
`)),await Ti(J,void 0,(Y)=>{Uq.write(i0.dim(`Running: ${Y}
|
|
@@ -7395,7 +7395,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7395
7395
|
`),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 C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
|
|
7396
7396
|
`))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class z01 extends x${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=IG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new V01({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 Lh4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?v9:0,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?v9: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 hR3(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?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),D=F+Z*U+Math.floor(U/2),H=G>0?V/G:0,B=Math.round((1-H)*(W-1));return{x:D,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),D=G>0?V/G:0,H=Math.round((1-D)*(W-1));return{x:U,y:H}}default:return null}}function gR3(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 mR3(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 pR3(J,Z,Q,Y,X,K,V){let G;try{let H=x1.of(J),B=f0.of(J);G={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let z=new g({color:G.foreground,bold:!0}),F=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],U=new g({color:G.foreground,underline:!0}),D=(H,B)=>new C(B,U,void 0,aY0(H),()=>{u3(J,H)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,z)),Z.link)W.push(D(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
|
|
7397
7397
|
`,z));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(D(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||H)W.push(new C(`
|
|
7398
|
-
`))}if(H)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}tO();m0();S7();YE();N$();y3();S2();Nd();TX();O$();rJ();YQ();wA();d4();ug();kP();O1();m0();O$();class F01{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.1774829165-g4f37d2"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await D40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Oh4}}class Oh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Eh4 extends p0{controller=new s7;focusNode=new z6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new PZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:z})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Eh4}}YQ();import{mkdtemp as lR3,readFile as iR3,rmdir as nR3,unlink as aR3,writeFile as oR3}from"node:fs/promises";import{tmpdir as rR3}from"node:os";import Th4 from"node:path";m0();m0();class Mh4{_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 wR extends Mh4{_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 Ah4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class q01{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 W01 extends o3{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 Hq(this)}createRenderObject(){return new jh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class jh4 extends u4{_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(Z6(!!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)}}m0();var dR3=500;class U01{_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 wR(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=f6(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(P.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)},dR3)}_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 Aa{}class ja{}class Ra{}class CG0{}class TG0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Rh4(this.props)}}class Rh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new U01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Ah4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.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 Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof CG0)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 PZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new H4("ArrowDown"),new Aa],[new H4("ArrowUp"),new ja],[new H4("n",{ctrl:!0}),new Aa],[new H4("p",{ctrl:!0}),new ja],[new H4("Enter"),new Ra],[new H4("Escape"),new CG0],[new H4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new A7({actions:new Map([[Aa,new H6(this.invoke)],[ja,new H6(this.invoke)],[Ra,new H6(this.invoke)],[CG0,new H6(this.invoke)]]),child:Q});return new Na({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 q01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{HR.of(this.context).insert(this.overlayEntry)}catch(J){P.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 C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),D=[],H=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;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?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);H=Math.max(H,k),D.push(u)}let B=V4.sizeOf(J).width,N=H+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=D.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:D})})})});return new W01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Ih4(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 Ph4(J){switch(J.type){case"file":return J.path;case"hint":return`${cR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Ch4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function cR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(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(`
|
|
7398
|
+
`))}if(H)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}tO();m0();S7();YE();N$();y3();S2();Nd();TX();O$();rJ();YQ();wA();d4();ug();kP();O1();m0();O$();class F01{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.1774846380-g30c5db"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await D40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class KL extends l0{props;constructor(J){super();this.props=J}createState(){return new Oh4}}class Oh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Eh4 extends p0{controller=new s7;focusNode=new z6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new PZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:z})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Eh4}}YQ();import{mkdtemp as lR3,readFile as iR3,rmdir as nR3,unlink as aR3,writeFile as oR3}from"node:fs/promises";import{tmpdir as rR3}from"node:os";import Th4 from"node:path";m0();m0();class Mh4{_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 wR extends Mh4{_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 Ah4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class q01{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 W01 extends o3{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 Hq(this)}createRenderObject(){return new jh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class jh4 extends u4{_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(Z6(!!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)}}m0();var dR3=500;class U01{_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 wR(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=f6(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(P.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)},dR3)}_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 Aa{}class ja{}class Ra{}class CG0{}class TG0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Rh4(this.props)}}class Rh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new U01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Ah4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.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 Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof CG0)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 PZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new H4("ArrowDown"),new Aa],[new H4("ArrowUp"),new ja],[new H4("n",{ctrl:!0}),new Aa],[new H4("p",{ctrl:!0}),new ja],[new H4("Enter"),new Ra],[new H4("Escape"),new CG0],[new H4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new A7({actions:new Map([[Aa,new H6(this.invoke)],[ja,new H6(this.invoke)],[Ra,new H6(this.invoke)],[CG0,new H6(this.invoke)]]),child:Q});return new Na({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 q01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{HR.of(this.context).insert(this.overlayEntry)}catch(J){P.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 C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),D=[],H=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;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?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);H=Math.max(H,k),D.push(u)}let B=V4.sizeOf(J).width,N=H+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=D.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:D})})})});return new W01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Ih4(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 Ph4(J){switch(J.type){case"file":return J.path;case"hint":return`${cR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function Ch4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function cR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(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(`
|
|
7399
7399
|
`))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 LR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new _h4(this.props)}}var sR3=":";class _h4 extends p0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new V3;_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(sR3);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 z6({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=Ob4(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 lR3(Th4.join(rR3(),"amp-edit-")),Q=Th4.join(Z,"message.amp.md");await oR3(Q,J,"utf-8"),await gK(Q);try{let Y=await iR3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await aR3(Q),await nR3(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.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 W1({mainAxisSize:"min",children:[new e({text:new C("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((z,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new C(z.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new C(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new C("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((z,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new C(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new C(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new C(" ")}),new e({text:new C(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new TG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(z)=>Ph4(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,U=Z.secondary,D=Z.foreground,H=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new C("",void 0,[new C(F.shortHash,new g({color:Z.secondary})),new C(" ",new g({})),new C(F.message,new g({color:D}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new C(` ${F.relativeDate}`,new g({color:H,dim:!0}))})]})});let N=[];switch(F.type){case"file":N.push(new C("@",new g({color:U}))),N.push(new C(F.path,new g({color:D})));break;case"hint":N.push(new C(F.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new C(" ",new g({}))),N.push(new C(F.message,new g({color:B})));break}let w=Ch4(F);if(w)N.push(new C(" - ",new g({color:H,dim:!0}))),N.push(new C(w,new g({color:H,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new C("",void 0,N),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 e({text:new C(" ")}));if(K)z.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:z})});G.push(F)}if(G.push(new y1({child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class Sh4 extends p0{controller=new s7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new z6({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>=PV)return!1;let Z=await JL(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=f0.of(J),{colors:Q,app:Y}=Z,K=V4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new LR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new s4({focusNode:this.focusNode,child:G}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new d0({padding:C0.symmetric(1,0),child:new e({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class D01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Sh4}}import{isDeepStrictEqual as H01}from"node:util";var tR3=/[\\/_ +.#"@[({&]/,eR3=/[\\/_ +.#"@[({&]/g,$I3=/[\s-]/,kh4=/[\s-]/g;function SG0(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,U,D,H;while(F>=0){if(W=SG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if($I3.test(J.charAt(F-1))){if(W*=0.9,H=J.slice(X,F-1).match(kh4),H&&X>0)W*=0.999**H.length}else if(tR3.test(J.charAt(F-1))){if(W*=0.8,D=J.slice(X,F-1).match(eR3),D&&X>0)W*=0.999**D.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(U=SG0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function _G0(J){return J.toLowerCase().replace(kh4," ")}function vh4(J,Z){let Q=SG0(J,Z,_G0(J),_G0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=SG0(J,G,_G0(J),_G0(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 Dy{}class Hy{}class kG0{}class vG0{}class yh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new xh4}}class xh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function JI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=vh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new fh4}}class fh4 extends p0{textController;focusNode;scrollController=new R5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s7(this.widget.props.controller?.query??""),this.focusNode=new z6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>H01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!H01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>H01(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 Dy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Hy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof kG0){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 vG0)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,...JI3(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;Gy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new PZ({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 m$({shortcuts:new Map([[new H4("ArrowDown"),new Dy],[new H4("ArrowUp"),new Hy],[new H4("Tab"),new Dy],[new H4("Tab",{shift:!0}),new Hy],[new H4("n",{ctrl:!0}),new Dy],[new H4("p",{ctrl:!0}),new Hy],[new H4("Enter"),new kG0],[new H4("Escape"),new vG0]]),focusNode:this.focusNode,child:G}),F=new A7({actions:new Map([[Dy,new H6(this.invoke)],[Hy,new H6(this.invoke)],[kG0,new H6(this.invoke)],[vG0,new H6(this.invoke)]]),child:z}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new yh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let N=new d0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:w??new R0({height:1})})})]})}))}else D.push(new y1({child:U}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function uh4(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 B01 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)=>uh4(X.pubDate).length));return new $7({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=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,D=F.mutedForeground,H=(B,N)=>new R0({width:N,child:W1.end([new e({text:new C(B,new g({color:D}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(uh4(X.pubDate),Q)]})})}})}}class N01 extends l0{createState(){return new bh4}}class bh4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function ZI3(J){return MY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function QI3(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 YV0.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 w01(J,Z,Q){return new e({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function YI3(J,Z,Q,Y){return[w01("+",J,Y.success),f3.horizontal(1),w01("~",Z,Y.warning),f3.horizontal(1),w01("-",Q,Y.destructive)]}function XI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class yG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new hh4}}class hh4 extends p0{spinner=new V3;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=QI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(L)=>{if(L!==H)H=L,B=ZI3(L);return B};return new $7({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!XI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new C(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new on({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new C(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,D0=d.getConnectorText(r);a.push(new C(D0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new C("",void 0,a)}))}let p=[],h=z===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(DN(y))p.push(new N01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new C("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...YI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function gh4(J){return 1-(1-J)**3}function mh4(J,Z,Q){return J+(Z-J)*Q}function Ia(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=gh4(Y),V=gh4(X);return{x:mh4(J.startOffset.x,J.targetOffset.x,K),y:mh4(J.startOffset.y,J.targetOffset.y,V)}}var KI3={nodeWidth:3,horizontalSpacing:3};class By{options;constructor(J={}){this.options={...KI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),D=Math.max(...W),H=Math.floor((U+D)/2);return Y.push({node:q,position:{x:H,y:z}}),H};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var VI3={nodeWidth:3,nodeHeight:2};class Ny{options;constructor(J={}){this.options={...VI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var GI3={nodeWidth:3,nodeHeight:2},zI3={x:0,y:0};class fG0{options;constructor(J={}){this.options={...GI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=zI3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,H,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:H,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new fG(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new g({color:z,bold:F}))}),new e({text:new C(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new C(G,new g({color:F}))})];for(let U of X){let D=" ".repeat(K-U.length);W.push(new e({text:new C("│ ",new g({color:F}),[new C(U+D,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new e({text:new C(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let D=U.position.x+G;if(D>=0&&D<Y)F[D]="▲"}V.push(new e({text:new C(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let D=Z.filter((L)=>L.node.parentID===U.node.id);if(D.length===0)continue;let H=U.position.x+G,B=D.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===H)if(D.length===1&&B[0]===H)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new C(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+G;if(H>=0&&H<Y)W[H]="│"}return V.push(new e({text:new C(W.join(""),new g({color:z}))})),V}}var FI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},qI3={x:0,y:0};class L01{options;constructor(J={}){this.options={...FI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=qI3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,H,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:H,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new fG(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,D=W.map((N)=>N.position.x+G),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=D.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new e({text:new C(F.join(""),new g({color:z}))})),V}}class Pa extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new ph4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class ph4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class OR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new lh4}}var dh4=400,ch4=300,WI3=16;class lh4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new By({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Ny;renderer=new L01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:dh4,durationY:ch4};let Z=Math.max(dh4,ch4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ia(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},WI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Pa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class nh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new ah4}}class ah4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var ih4=30,UI3=30;class wy{}class Ly{}class uG0{}class bG0{}class O01 extends l0{props;constructor(J){super();this.props=J}createState(){return new oh4}}class oh4 extends p0{highlightedIndex=0;controller=new s7;focusNode;scrollController=new R5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new z6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Gy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ly){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof uG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof bG0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=UI3+ih4,z=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new PZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new m$({shortcuts:new Map([[new H4("ArrowDown"),new wy],[new H4("ArrowUp"),new Ly],[new H4("Tab"),new wy],[new H4("Tab",{shift:!0}),new Ly],[new H4("n",{ctrl:!0}),new wy],[new H4("p",{ctrl:!0}),new Ly],[new H4("Enter"),new uG0],[new H4("Escape"),new bG0]]),focusNode:this.focusNode,child:W}),D=new A7({actions:new Map([[wy,new H6(this.invoke)],[Ly,new H6(this.invoke)],[uG0,new H6(this.invoke)],[bG0,new H6(this.invoke)]]),child:U}),H=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new C(">",new g({color:Y.foreground}))})}),new y1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new nh4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new d0({padding:C0.all(1),child:new OR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new y1({child:O}):new R0({width:ih4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new R0({height:1}),new y1({child:E})]})})}}m0();import{execSync as ER}from"node:child_process";import{writeFile as Oy}from"node:fs/promises";import DI3 from"node:os";import yq from"node:path";gM();TX();O$();d4();N4();kP();var M01=B4(tW(),1);var rh4="c446b2e9b16cdc06df2ec285894d6421",HI3="5ea19563777f4ade8707fc56f7e7a388",BI3="amp-thread-worker",sh4=[{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 NI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function GL(J){if(!J||!NI3(J.meta))return!1;return J.meta.usesDtw===!0}function A01(J){let Z=new URL(`https://dash.cloudflare.com/${rh4}/workers/durable-objects/view/${HI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function j01(J){let Z=new URL(`https://dash.cloudflare.com/${rh4}/workers/services/view/${BI3}/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 wI3(J,Z){if(MV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function R01(J,Z){let Q=wI3(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 Ca(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ta(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ta(J){return J.path??f9(J.uri)}function th4(J,Z,Q){let Y=Ca("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function eh4(J,Z){return R01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7400
7400
|
${Y}`).join(`
|
|
7401
7401
|
|
|
@@ -7624,7 +7624,7 @@ ${t.content||""}`:t.content||"",T0=[],e0=t.baseDir.startsWith("file://")?jz0(t.b
|
|
|
7624
7624
|
`),process.exit(1)}process.stdout.write(await JS3(z.result.displayText)+`
|
|
7625
7625
|
`),process.exit(0)})}gM();import{stdout as ZS3}from"node:process";function QS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${EF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function cd4(J){ZS3.write(`${QS3(J)}
|
|
7626
7626
|
`)}function ld4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{cd4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{cd4(Z),process.exit(0)})}var Ax3=cD.join(aZ,"logs","headless.log"),e61=cD.join(Qv,"device-id.json"),Un4=`cli-tui-${En4(16).toString("hex")}`;async function jx3(){for(let J of KE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(oy(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){I2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7627
|
-
`)}function Rx3(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 $2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Rn4(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 Ix3(J){try{return await An4(J,"utf-8")}catch{return J}}async function $51(J,Z,Q){let Y=Rn4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!X51(X,k2.HARNESS_SYSTEM_PROMPT)&&!In4(K))throw new C1("You are not allowed to do this.",1);aJ("systemPrompt",await Ix3(Y))}function In4(J){return!!(J&&J10(J))}function X51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function J51(J){return(J.userEmail?dJ(J.userEmail):!1)||X51(J.features,k2.DTW_TUI)}function Dn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function Z51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return J51({userEmail:Z.user.email,features:Z.features})}function Q51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Px3(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 DF0(J){let Y=Px3(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 Hn4(J){if(!Y5.write(J))await Lx3(Y5,"drain")}var Bn4=[{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??xK,description:`Custom settings file path (overrides the default location ${xK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Tn0})`},{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:o7(),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}],Nn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Cx3=(J)=>("hidden"in J)&&J.hidden===!0,Tx3=(J)=>("default"in J),_x3=(J)=>("default"in J)?J.default:void 0,Pn4=[{name:"toggle-skills-count",entryPoint:Po0}];function Sx3(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 K51(J){return{...J,getThreadEnvironment:DZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>$Q(J.configService),pluginService:J.pluginService}}function Cn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:DZ,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(jn4.homedir()),Y51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function kx3(J){return Uq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Wq4(Z);let Q=jX0(),Y=po0();if((!Q||Y||PT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(ND("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(ND("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(jX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function vx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Q7(J,Z,Q){let Y=Q?.deferAuth??!1;Yf1("0.0.
|
|
7627
|
+
`)}function Rx3(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 $2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function Rn4(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 Ix3(J){try{return await An4(J,"utf-8")}catch{return J}}async function $51(J,Z,Q){let Y=Rn4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!X51(X,k2.HARNESS_SYSTEM_PROMPT)&&!In4(K))throw new C1("You are not allowed to do this.",1);aJ("systemPrompt",await Ix3(Y))}function In4(J){return!!(J&&J10(J))}function X51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function J51(J){return(J.userEmail?dJ(J.userEmail):!1)||X51(J.features,k2.DTW_TUI)}function Dn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function Z51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return J51({userEmail:Z.user.email,features:Z.features})}function Q51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Px3(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 DF0(J){let Y=Px3(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 Hn4(J){if(!Y5.write(J))await Lx3(Y5,"drain")}var Bn4=[{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??xK,description:`Custom settings file path (overrides the default location ${xK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Tn0})`},{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:o7(),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}],Nn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Cx3=(J)=>("hidden"in J)&&J.hidden===!0,Tx3=(J)=>("default"in J),_x3=(J)=>("default"in J)?J.default:void 0,Pn4=[{name:"toggle-skills-count",entryPoint:Po0}];function Sx3(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 K51(J){return{...J,getThreadEnvironment:DZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>$Q(J.configService),pluginService:J.pluginService}}function Cn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:DZ,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(jn4.homedir()),Y51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function kx3(J){return Uq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Wq4(Z);let Q=jX0(),Y=po0();if((!Q||Y||PT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(ND("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(ND("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(jX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function vx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Q7(J,Z,Q){let Y=Q?.deferAuth??!1;Yf1("0.0.1774846380-g30c5db");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:HF0,userConfigDir:Y51});IT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
|
|
7628
7628
|
`);let W0=await yx3(J),r=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await VD(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];P.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let G=A1($Q(X).pipe(M5((a)=>a!=="pending"))),z=Y?"pending":await G;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(z),isError:bW(z),errorMessage:bW(z)?z.error.message:void 0});let{toolService:F,dispose:q}=Vq4({configService:X}),W=new Map,U=()=>W.clear(),D=new bT0(X,J.settings.getWorkspaceRootPath()),H=zt1({configService:X,filesystem:O8}),B=Ya1({configService:X,trustStore:D,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let D0=`${a}:${W0}`,L0=W.get(D0);if(L0)return P.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;P.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let G0=(async()=>{let J0=new HE(J.secrets),z0=await J0.getClientInfo(a,W0),i=r?.scopes??z0?.scopes,o=QI4();P.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Y5.isTTY});let t;if(o)t=J.executeMode?ZI4():JI4(a);let $0=new wR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??z0?.clientId,clientSecret:r?.clientSecret??z0?.clientSecret,authUrl:r?.authUrl??z0?.authUrl,tokenUrl:r?.tokenUrl??z0?.tokenUrl,scopes:i,headlessAuthHandler:t});return P.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??z0?.clientId),willUseDCR:!(r?.clientId??z0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(D0,G0),G0}}),N=hg0({configService:X,filesystem:O8,spawn:P$0}),w;if(J.executeMode){let a=await qG4({toolService:F,providers:[B,N],initialTimeout:15000});w=a.registrations;for(let[W0,r]of a.initErrors)P.warn(`${W0} provider initialization slow or failed:`,r)}else w=gg0({toolService:F,providers:[B,N]});if(Z.jetbrains)JE("JetBrains");else if(Z.ide&&mI4())JE("VS Code");else if(Z.ide&&pI4())JE("Neovim");else if(Z.ide){let a=await jx3();if(a){let W0=_10(a.ideName);if(W0)JE(W0)}}if(J.executeMode)Xf1(!0);let L,O=w$.status.pipe(H1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&nf1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(FG4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new DY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends DY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Bt1({isDevelopment:!1}),A=new gS0(M,X,{maxThreads:200});P.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=Z51(j,z),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let T=_?vx3():xt1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;w$.status.subscribe((a)=>{u=a});let m=new nA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:O8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){P.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return P.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new lo0,k=process.env.PLUGINS??"off",f=Z.headless?FT4():void 0,d=f??new wX0({configService:X}),p=d instanceof wX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=$_0({configService:X,fileSystem:O8,platform:d,internalPlugins:Pn4,pluginFilter:k}),n=ta1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:H,toolboxService:N,trustStore:D,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:O8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:z,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of w.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function yx3(J){if(!J.executeMode){if(!await HX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return Y5.write(`Login cancelled. Run the command again to retry.
|
|
7629
7629
|
`),!1}return await Tn4(J)}async function Tn4(J){let Z=En4(32).toString("hex"),Q=await qv(J.ampURL,Z),Y=new AbortController;try{await EV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await qv(J.ampURL,Z,!1);Y5.write(`If your browser does not open automatically, visit:
|
|
7630
7630
|
|
|
@@ -7632,7 +7632,7 @@ ${i0.blue.bold(X)}
|
|
|
7632
7632
|
|
|
7633
7633
|
`);try{return await dC4(J.ampURL,Z,J.secrets,Y),Y5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),I2.write(`
|
|
7634
7634
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7635
|
-
`),!1}}function wn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xx3(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||!b9(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function fx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function ux3(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(!fx3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bx3(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 hx3(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 gx3(J){let Z=new fN().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)Dj(),process.exit(0);let N=B.originalError??B;YR4(N)}),ld4(Z,{version:"0.0.
|
|
7635
|
+
`),!1}}function wn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xx3(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||!b9(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function fx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function ux3(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(!fx3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bx3(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 hx3(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 gx3(J){let Z=new fN().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)Dj(),process.exit(0);let N=B.originalError??B;YR4(N)}),ld4(Z,{version:"0.0.1774846380-g30c5db",buildTimestamp:"2026-03-30T04:56:52.817Z",buildType:"'release'"}),Z.addHelpText("after",bI4()),Z.configureHelp({formatHelp:hI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await g3(w);await ax3(L)}),Z.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await g3(w);await nx3(L,await Aa0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await g3(L);await kR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await g3(w);await vR4(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",`
|
|
7636
7636
|
Actions:
|
|
7637
7637
|
create Create a new DTW thread and print its ID
|
|
7638
7638
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7696,8 +7696,8 @@ ${M}
|
|
|
7696
7696
|
|
|
7697
7697
|
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 mx3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new rn({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:DZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new hV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function px3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Bv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Bv()).trimEnd(),stdinInput:null}}function dx3(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"
|
|
7698
7698
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function BF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(G0,J0)=>{let z0=Number(process.hrtime.bigint()-J0)/1e6,i=KO4();P.info("Startup phase",{phase:G0,phaseMs:Math.round(z0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:G}=await px3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;dx3({...Z,streamJson:z},J.executeMode,V),$2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;P.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await Q7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let D=await K51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:H}=U;if(!W&&bW(H)){let G0=ak(Error(H.error.message));if(G0.message===E3.networkOffline||G0.message===E3.networkTimeout)throw DF0(J.ampURL);throw new C1(E3.invalidAPIKey,1)}let B=m6(H)?H:null,N=B?.user.email,w=In4(N),L=J51({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&Z51(O,B);if(!W)await $51(Q,Z,H);let M=Q51(H),A=M?.features??[],j=M?.team??null,R=BX0(Z,M);if(R instanceof Error)m3(R.message);if((J.executeMode||z)&&N8(Z.mode)&&!w)throw new C1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!QE(Z.mode,N))throw new C1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await UT4(V,G,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!dJ(N))throw new C1("Headless DTW mode is only available for Amp employees",1);let G0=await U.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new C1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new C1(`Invalid thread ID: ${J0}`,1);let z0=J0?void 0:await Zf3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??z0?.threadId;if(!i)throw new C1("Failed to resolve headless thread ID",1);let o=await VI4(i);if(o.status==="already-running")await U.asyncDispose(),await VD(),process.exit(0);try{await $I4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:z0?.ownerUserId,threadVersion:z0?.threadVersion,agentMode:z0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await VD(),process.exit(0)}let _=J.executeMode?void 0:async(G0)=>Lo(G0,"interactive"),T={threadService:U.threadService,workerDeps:D,createThread:async()=>{let G0=W?await U.serverStatusPromise:H,J0=await eQ0(J.settings,process.cwd(),Q51(G0),R);if(J0 instanceof Error)m3(J0.message);return Xe0(D,{threadMeta:J0?vG(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(G0,J0)=>{if(J0?.nonBlockingOwnershipCheck){Ln4(G0,U.configService).catch((z0)=>{if(z0 instanceof C1){if(J0.onOwnershipError){J0.onOwnershipError(z0,G0);return}Hj(z0,G0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})});return}try{await Ln4(G0,U.configService)}catch(z0){if(z0 instanceof C1)throw z0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:Hj},u=async(G0)=>{try{if(G0==="dtw")return mx3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:Un4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Of4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof C1)throw J0;throw await Hj(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")I2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7699
|
-
`),await VD(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await U.configService.getLatest(),J0=ou(G0),z0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(z0.ok)return P.info("User free tier status:",z0),z0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new $e0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await U.serverStatusPromise:U.serverStatus;await $51(Q,Z,G0);let J0=process.hrtime.bigint(),z0=Z51(O,G0),i=m6(G0)?J51({userEmail:G0.user.email,features:G0.features}):!1;Dn4({dtwEnabled:z0,hasV2TUIAccess:i});let o=await u(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await A1(o.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 J0=G0 instanceof Error?G0:Error(String(G0));k.setInitError(J0),await Hj(G0,Z.threadId)});else F=process.hrtime.bigint(),Dn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),kx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(D4((G0)=>{if(!G0)return k0.of({});return H5(G0.thread$,G0.threadViewState$).pipe(H1(([J0,z0])=>({[J0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){JT4(U.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:U,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...G0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await ef1();let G0=await GE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let J0=G0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=ca0("0.0.
|
|
7700
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(G)=>{if(G!==rh)return;try{let z=await An4(e61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==rh)return;await Mn4(cD.dirname(e61),{recursive:!0}),await Ox3(e61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:vz()});Kf1(Y);let X=await OI4({...J,workspaceTrust:{current:!0,changes:su},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 eC4(J.mcpConfig);X=$T4(X,G)}let K=cD.dirname(X.getSettingsFilePath());qq4(Qv,K);let V=await X.get("url","global");if(!V)V=F7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!MV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=rx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:wT4(await Aa0(J,X))}}function cx3(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 lx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=cD.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Ax3:Tn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ix3(){XO4();let J=cx3(process.argv),Z=lx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)i0.level=0;if(Rx3(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7699
|
+
`),await VD(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await U.configService.getLatest(),J0=ou(G0),z0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(z0.ok)return P.info("User free tier status:",z0),z0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new $e0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await U.serverStatusPromise:U.serverStatus;await $51(Q,Z,G0);let J0=process.hrtime.bigint(),z0=Z51(O,G0),i=m6(G0)?J51({userEmail:G0.user.email,features:G0.features}):!1;Dn4({dtwEnabled:z0,hasV2TUIAccess:i});let o=await u(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await A1(o.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 J0=G0 instanceof Error?G0:Error(String(G0));k.setInitError(J0),await Hj(G0,Z.threadId)});else F=process.hrtime.bigint(),Dn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),kx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(D4((G0)=>{if(!G0)return k0.of({});return H5(G0.thread$,G0.threadViewState$).pipe(H1(([J0,z0])=>({[J0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){JT4(U.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:U,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...G0});if(await Lo(J0,"execute"),Z.archive)await g6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await ef1();let G0=await GE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let J0=G0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=ca0("0.0.1774846380-g30c5db",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Io0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await A1(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 OX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let D0={...r,launchCount:r.launchCount+1};Cj((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await zu4({codebaseContextService:U.codebaseContextService,history:new Xa0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>Cn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Un4,logFile:{path:Y},sessionState:D0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T04:56:52.817Z"},(G0)=>new we0({...G0,threadPool:G0.threadPool},(J0)=>new R41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function g3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)I2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7700
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(G)=>{if(G!==rh)return;try{let z=await An4(e61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==rh)return;await Mn4(cD.dirname(e61),{recursive:!0}),await Ox3(e61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:vz()});Kf1(Y);let X=await OI4({...J,workspaceTrust:{current:!0,changes:su},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 eC4(J.mcpConfig);X=$T4(X,G)}let K=cD.dirname(X.getSettingsFilePath());qq4(Qv,K);let V=await X.get("url","global");if(!V)V=F7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!MV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=rx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:wT4(await Aa0(J,X))}}function cx3(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 lx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=cD.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Ax3:Tn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ix3(){XO4();let J=cx3(process.argv),Z=lx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)i0.level=0;if(Rx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774846380-g30c5db",buildTimestamp:"2026-03-30T04:56:52.817Z"}),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 gx3(Q).parseAsync(process.argv)}zq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ix3().catch(Hj)});async function nx3(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"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7701
7701
|
`);else if(!MV(J.ampURL))Y5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7702
7702
|
`);let Y=process.env.AMP_API_KEY;if(Y)Y5.write(`API key found in environment variable, storing...
|
|
7703
7703
|
`),await Z.set("apiKey",Y,J.ampURL),Y5.write(`API key successfully stored.
|