@sourcegraph/amp 0.0.1774656301-g0342e2 → 0.0.1774672496-g0342e2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +8 -8
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6219,11 +6219,11 @@ ${D}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
6219
6219
  ${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))H+=`
6220
6220
 
6221
6221
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6222
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();dM();async function lY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=PP4(J,F),W=q<0,U,D;if(G.time){let H=G.time[J],B=G.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(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var $Q3="https://static.ampcode.com/cli/cli-version.txt";async function iY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${$Q3}?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=PP4(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 JQ3=604800000;function RP4(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>JQ3)return{ageMs:Q};return null}function PP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)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 $o0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}L1();function Jo0(J,Z,Q={}){let Y=new Z4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new CG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);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 cY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await iY0(J):await lY0(J,Rj());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!==aa0()){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 bi(U.latestVersion,q);let H=await ww(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(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}dM();import{stderr as Dq}from"node:process";function CP4(J){let Z=new bN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await da0(Y.force||!1,Y.verbose||!1,"0.0.1774656301-g0342e2"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new bN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await ZQ3(Y.targetVersion)});J.addCommand(Q)}async function ZQ3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Dq.write(i0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6222
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();dM();async function lY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=PP4(J,F),W=q<0,U,D;if(G.time){let H=G.time[J],B=G.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(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var $Q3="https://static.ampcode.com/cli/cli-version.txt";async function iY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${$Q3}?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=PP4(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 JQ3=604800000;function RP4(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>JQ3)return{ageMs:Q};return null}function PP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)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 $o0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}L1();function Jo0(J,Z,Q={}){let Y=new Z4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new CG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);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 cY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await iY0(J):await lY0(J,Rj());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!==aa0()){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 bi(U.latestVersion,q);let H=await ww(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(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}dM();import{stderr as Dq}from"node:process";function CP4(J){let Z=new bN().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await da0(Y.force||!1,Y.verbose||!1,"0.0.1774672496-g0342e2"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new bN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await ZQ3(Y.targetVersion)});J.addCommand(Q)}async function ZQ3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Dq.write(i0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6223
6223
 
6224
6224
  `));try{if(!J){Dq.write(i0.blue(`Checking for updates...
6225
- `));let{hasUpdate:Y,latestVersion:X}=la0()?await iY0("0.0.1774656301-g0342e2"):await lY0("0.0.1774656301-g0342e2",Rj());if(!Y){let K=$o0("0.0.1774656301-g0342e2"),V=K?.age?`released ${K.age} ago`:`built ${MF(new Date("2026-03-28T00:09:09.564Z"))} ago`;Dq.write(i0.green(`✓ Amp is already up to date on version ${"0.0.1774656301-g0342e2"} (${V})
6226
- `));let z=await ww("0.0.1774656301-g0342e2");if(z.warning)Dq.write(`
6225
+ `));let{hasUpdate:Y,latestVersion:X}=la0()?await iY0("0.0.1774672496-g0342e2"):await lY0("0.0.1774672496-g0342e2",Rj());if(!Y){let K=$o0("0.0.1774672496-g0342e2"),V=K?.age?`released ${K.age} ago`:`built ${MF(new Date("2026-03-28T04:38:51.425Z"))} ago`;Dq.write(i0.green(`✓ Amp is already up to date on version ${"0.0.1774672496-g0342e2"} (${V})
6226
+ `));let z=await ww("0.0.1774672496-g0342e2");if(z.warning)Dq.write(`
6227
6227
  `+i0.yellow(z.warning)+`
6228
6228
  `);process.exit(0)}if(!X)Dq.write(i0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Dq.write(i0.blue(`Updating to version ${J}...
6229
6229
  `)),await bi(J,void 0,(Y)=>{Dq.write(i0.dim(`Running: ${Y}
@@ -7394,7 +7394,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
7394
7394
  `),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(`
7395
7395
  `))}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 J0({text:new C(void 0,void 0,K)})})})}}class O01 extends f${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=xz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new w01({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 Ph4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function aI3(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let G=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?G: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=z>0?V/z: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?G: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=z>0?V/z:0,H=Math.round((1-D)*(W-1));return{x:U,y:H}}default:return null}}function oI3(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 rI3(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function sI3(J,Z,Q,Y,X,K,V){let z;try{let H=x1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new g({color:z.foreground,bold:!0}),F=new g({color:z.foreground}),q=new g({color:z.foreground,dim:!0}),W=[],U=new g({color:z.foreground,underline:!0}),D=(H,B)=>new C(B,U,void 0,QX0(H),()=>{b3(J,H)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,G)),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}
7396
7396
  `,G));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]??z.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(`
7397
- `))}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:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}YE();m0();_2();FE();w$();x3();S7();Rd();_X();E$();tJ();KQ();EA();h4();ig();fP();L1();m0();E$();class E01{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.1774656301-g0342e2"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await P40(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 VL extends l0{props;constructor(J){super();this.props=J}createState(){return new Ch4}}class Ch4 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 Th4 extends p0{controller=new r2;focusNode=new G6({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,z=c1.all(new g1(Q.foreground,1,"solid")),G=new TZ({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 J0({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new J0({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 J0({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new u3,U]})})}}class Ta extends l0{props;constructor(J){super();this.props=J}createState(){return new Th4}}KQ();import{mkdtemp as $R3,readFile as JR3,rmdir as ZR3,unlink as QR3,writeFile as YR3}from"node:fs/promises";import{tmpdir as XR3}from"node:os";import uh4 from"node:path";m0();m0();class _h4{_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 MI extends _h4{_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 Sh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class M01{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 A01 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 Bq(this)}createRenderObject(){return new kh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class kh4 extends b4{_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 tI3=500;class j01{_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 MI(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 z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.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)},tI3)}_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 _a{}class Sa{}class ka{}class uz0{}class bz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new vh4(this.props)}}class vh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new Ia;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new j01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Sh4(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 _a)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Sa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof ka)return this.controller.acceptSelected(),"handled";if(J instanceof uz0)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 z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new TZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new p$({shortcuts:new Map([[new B4("ArrowDown"),new _a],[new B4("ArrowUp"),new Sa],[new B4("n",{ctrl:!0}),new _a],[new B4("p",{ctrl:!0}),new Sa],[new B4("Enter"),new ka],[new B4("Escape"),new uz0],[new B4("Tab"),new ka]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M2({actions:new Map([[_a,new H6(this.invoke)],[Sa,new H6(this.invoke)],[ka,new H6(this.invoke)],[uz0,new H6(this.invoke)]]),child:Q});return new ja({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 M01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{LI.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 J0({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,z=0;try{let I=this.layerLink.getTargetTransform();if(I)z=I.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let I=this.props.controller.getCursorVisualRow(),_=z+I+1;q=V-_-F}else q=z-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 I=W;I<U;I++){let _=Z.options[I];if(!_)continue;let S=I===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,S);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 J0({text:new C(f,new g({color:p,backgroundColor:S?d:void 0}))}),m=f}let x=V4.of(J),T=x5(m,x.supportsEmojiWidth);H=Math.max(H,T),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(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({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 A01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function yh4(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 xh4(J){switch(J.type){case"file":return J.path;case"hint":return`${eI3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function fh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function eI3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class yq{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(`
7397
+ `))}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:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}YE();m0();_2();FE();w$();x3();S7();Rd();_X();E$();tJ();KQ();EA();h4();ig();fP();L1();m0();E$();class E01{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.1774672496-g0342e2"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await P40(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 VL extends l0{props;constructor(J){super();this.props=J}createState(){return new Ch4}}class Ch4 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 Th4 extends p0{controller=new r2;focusNode=new G6({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,z=c1.all(new g1(Q.foreground,1,"solid")),G=new TZ({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 J0({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new J0({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 J0({text:new C("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new u3,U]})})}}class Ta extends l0{props;constructor(J){super();this.props=J}createState(){return new Th4}}KQ();import{mkdtemp as $R3,readFile as JR3,rmdir as ZR3,unlink as QR3,writeFile as YR3}from"node:fs/promises";import{tmpdir as XR3}from"node:os";import uh4 from"node:path";m0();m0();class _h4{_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 MI extends _h4{_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 Sh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class M01{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 A01 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 Bq(this)}createRenderObject(){return new kh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class kh4 extends b4{_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 tI3=500;class j01{_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 MI(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 z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.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)},tI3)}_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 _a{}class Sa{}class ka{}class uz0{}class bz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new vh4(this.props)}}class vh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new Ia;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new j01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Sh4(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 _a)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Sa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof ka)return this.controller.acceptSelected(),"handled";if(J instanceof uz0)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 z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new TZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new p$({shortcuts:new Map([[new B4("ArrowDown"),new _a],[new B4("ArrowUp"),new Sa],[new B4("n",{ctrl:!0}),new _a],[new B4("p",{ctrl:!0}),new Sa],[new B4("Enter"),new ka],[new B4("Escape"),new uz0],[new B4("Tab"),new ka]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M2({actions:new Map([[_a,new H6(this.invoke)],[Sa,new H6(this.invoke)],[ka,new H6(this.invoke)],[uz0,new H6(this.invoke)]]),child:Q});return new ja({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 M01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{LI.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 J0({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,z=0;try{let I=this.layerLink.getTargetTransform();if(I)z=I.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let I=this.props.controller.getCursorVisualRow(),_=z+I+1;q=V-_-F}else q=z-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 I=W;I<U;I++){let _=Z.options[I];if(!_)continue;let S=I===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,S);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 J0({text:new C(f,new g({color:p,backgroundColor:S?d:void 0}))}),m=f}let x=V4.of(J),T=x5(m,x.supportsEmojiWidth);H=Math.max(H,T),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(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({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 A01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function yh4(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 xh4(J){switch(J.type){case"file":return J.path;case"hint":return`${eI3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function fh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function eI3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class yq{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
7398
  `))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 AI extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bh4(this.props)}}var KR3=":";class bh4 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 yq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let z=X.query.toLowerCase().startsWith(KR3);if(z!==this._isCommitMode)this._isCommitMode=z,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),z=J.kind==="commit"?"@:":"@@",G=K+z+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.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),z=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(z),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),z=`git-commit(${J.hash})`,G=K+z+" "+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({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=Cb4(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 $R3(uh4.join(XR3(),"amp-edit-")),Q=uh4.join(Z,"message.amp.md");await YR3(Q,J,"utf-8"),await mK(Q);try{let Y=await JR3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await QR3(Q),await ZR3(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 J0({text:new C("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((G,F)=>{let q=new Y4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new J0({text:new C(G.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new J0({text:new C(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new J0({text:new C("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((G,F)=>{let q=this.props.onImageClick!==void 0,W=new Y4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new J0({text:new C(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new J0({text:new C(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new J0({text:new C(" ")}),new J0({text:new C(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new bz0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(G)=>xh4(G),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:(G,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 J0({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 J0({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=fh4(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 J0({text:new C("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),z=[];if(this.props.topWidget)z.push(this.props.topWidget);if(X||K){let G=[];if(X)G.push(X);if(X&&K)G.push(new J0({text:new C(" ")}));if(K)G.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:G})});z.push(F)}if(z.push(new y1({child:V})),this.props.bottomWidget)z.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:z})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class hh4 extends p0{controller=new r2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({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>=CV)return!1;let Z=await ZL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=V4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),z=new AI({controller:this.controller,triggers:[new yq],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}),G=new s4({focusNode:this.focusNode,child:z}),F=new d0({constraints:new R1({maxHeight:V}),padding:C0.symmetric(1,0),child:G}),q=new d0({padding:C0.symmetric(1,0),child:new J0({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 J0({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 I0({height:1}),new y1({child:F}),new I0({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 I01 extends l0{props;constructor(J){super();this.props=J}createState(){return new hh4}}import{isDeepStrictEqual as R01}from"node:util";var VR3=/[\\/_ +.#"@[({&]/,zR3=/[\\/_ +.#"@[({&]/g,GR3=/[\s-]/,gh4=/[\s-]/g;function gz0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,D,H;while(F>=0){if(W=gz0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(GR3.test(J.charAt(F-1))){if(W*=0.9,H=J.slice(X,F-1).match(gh4),H&&X>0)W*=0.999**H.length}else if(VR3.test(J.charAt(F-1))){if(W*=0.8,D=J.slice(X,F-1).match(zR3),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=gz0(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(G,F+1)}return V[z]=q,q}function hz0(J){return J.toLowerCase().replace(gh4," ")}function mh4(J,Z){let Q=gz0(J,Z,hz0(J),hz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=gz0(J,z,hz0(J),hz0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Hy{}class By{}class mz0{}class pz0{}class ph4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new dh4}}class dh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function FR3(J,Z){if(J==="")return{matches:!0,score:1};let Q=mh4(Z,J);return{matches:Q>0.15,score:Q}}class e9 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new ch4}}class ch4 extends p0{textController;focusNode;scrollController=new I5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r2(this.widget.props.controller?.query??""),this.focusNode=new G6({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)=>R01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!R01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>R01(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 Hy){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 By){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 mz0){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 pz0)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,...FR3(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,z=new TZ({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}),G=new p$({shortcuts:new Map([[new B4("ArrowDown"),new Hy],[new B4("ArrowUp"),new By],[new B4("Tab"),new Hy],[new B4("Tab",{shift:!0}),new By],[new B4("n",{ctrl:!0}),new Hy],[new B4("p",{ctrl:!0}),new By],[new B4("Enter"),new mz0],[new B4("Escape"),new pz0]]),focusNode:this.focusNode,child:z}),F=new M2({actions:new Map([[Hy,new H6(this.invoke)],[By,new H6(this.invoke)],[mz0,new H6(this.invoke)],[pz0,new H6(this.invoke)]]),child:G}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new J0({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 I0({height:10,child:new X4({child:new J0({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 J0({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 J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new ph4(new Y4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Y4({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 J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({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 I0({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 lh4(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 P01 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)=>lh4(X.pubDate).length));return new e9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,D=F.mutedForeground,H=(B,N)=>new I0({width:N,child:W1.end([new J0({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 J0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(lh4(X.pubDate),Q)]})})}})}}class C01 extends l0{createState(){return new ih4}}class ih4 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 J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function qR3(J){return AY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function WR3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return UV0.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 T01(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function UR3(J,Z,Q,Y){return[T01("+",J,Y.success),u3.horizontal(1),T01("~",Z,Y.warning),u3.horizontal(1),T01("-",Q,Y.destructive)]}function DR3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class dz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new nh4}}class nh4 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||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((L,O)=>{if(G){if(L.id===G)return-1;if(O.id===G)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=WR3(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 J0({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=qR3(L);return B};return new e9({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(!DR3(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:I}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:I.foreground,u=I.mutedForeground,m=(s,F0)=>new I0({width:F0,child:W1.end([new J0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[L.id],T=[],f=L.relationshipType==="handoff",d=new Za({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],F0=L.ancestorsAreLast.slice(1);for(let L0 of F0)s.push(new C(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let o=L.isLast?d.elbow:d.tee,q0=d.getConnectorText(o);s.push(new C(q0,new g({color:d.connectorColor,dim:d.connectorDim}))),T.push(new J0({text:new C("",void 0,s)}))}let p=[],h=G===L.id?new C("(current) ",new g({color:I.success})):z.has(L.id)?new C("(visited) ",new g({color:I.foreground,dim:!0})):null;if(h)p.push(new J0({text:h}));if(BN(x))p.push(new C01),p.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new J0({text:new C("[fork] ",new g({color:I.primary}))}))}else if(f)p.push(new J0({text:new C("[handoff] ",new g({color:I.accent}))}));if(p.push(new y1({child:new J0({text:new C(n,new g({color:S})),overflow:"ellipsis",maxLines:1})})),p.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:u,warning:u,destructive:u}:I;p.push(...UR3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),p.push(new I0({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:[...T,...p]})})}})}}function ah4(J){return 1-(1-J)**3}function oh4(J,Z,Q){return J+(Z-J)*Q}function va(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=ah4(Y),V=ah4(X);return{x:oh4(J.startOffset.x,J.targetOffset.x,K),y:oh4(J.startOffset.y,J.targetOffset.y,V)}}var HR3={nodeWidth:3,horizontalSpacing:3};class Ny{options;constructor(J={}){this.options={...HR3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+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:G}}),H};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var BR3={nodeWidth:3,nodeHeight:2};class wy{options;constructor(J={}){this.options={...BR3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var NR3={nodeWidth:3,nodeHeight:2},wR3={x:0,y:0};class lz0{options;constructor(J={}){this.options={...NR3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=wR3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({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 I=J.filter((u)=>u.position.y===j);I.sort((u,m)=>u.position.x-m.position.x);let _=[],S=0;for(let u of I){if(u.position.x>S)_.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,x,T,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((T)=>T.position.y===j-1),m=I,x=this.renderConnectors(u,m,Z,H,F,q);N.push(...x)}}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 I0({width:H,height:E}),new e6({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),I=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,S=O+I*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:_,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new fz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:G,bold:F}))}),new J0({text:new C(z,new g({color:G,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,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new J0({text:new C(z,new g({color:F}))})];for(let U of X){let D=" ".repeat(K-U.length);W.push(new J0({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 J0({text:new C(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let D=U.position.x+z;if(D>=0&&D<Y)F[D]="▲"}V.push(new J0({text:new C(F.join(""),new g({color:G}))}));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+z,B=D.map((L)=>L.position.x+z),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 J0({text:new C(q.join(""),new g({color:G}))}));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+z;if(H>=0&&H<Y)W[H]="│"}return V.push(new J0({text:new C(W.join(""),new g({color:G}))})),V}}var LR3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},OR3={x:0,y:0};class _01{options;constructor(J={}){this.options={...LR3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=OR3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({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 I=J.filter((u)=>u.position.y===j);I.sort((u,m)=>u.position.x-m.position.x);let _=[],S=0;for(let u of I){if(u.position.x>S)_.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1;_.push(this.renderNode(m,x,T,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((T)=>T.position.y===j-1),m=I,x=this.renderConnectors(u,m,Z,H,F,q);N.push(...x)}}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 I0({width:H,height:E}),new e6({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),I=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,S=O+I*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:_,top:S,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new fz(new z5({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 J0({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 J0({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=[],z=Math.floor(this.options.nodeWidth/2),G=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+z,D=W.map((N)=>N.position.x+z),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 J0({text:new C(F.join(""),new g({color:G}))})),V}}class ya extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new rh4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class rh4 extends b4{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 jI extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new eh4}}var sh4=400,th4=300,ER3=16;class eh4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Ny({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new wy;renderer=new _01;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((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))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((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:sh4,durationY:th4};let Z=Math.max(sh4,th4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=va(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},ER3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/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,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let 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},z=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),G=new ya({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:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Jg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Zg4}}class Zg4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var $g4=30,MR3=30;class Ly{}class Oy{}class iz0{}class nz0{}class S01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Qg4}}class Qg4 extends p0{highlightedIndex=0;controller=new r2;focusNode;scrollController=new I5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new G6({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 Ly){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Oy){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof iz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof nz0)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,z=V4.of(J).size.width>=MR3+$g4,G=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new TZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new p$({shortcuts:new Map([[new B4("ArrowDown"),new Ly],[new B4("ArrowUp"),new Oy],[new B4("Tab"),new Ly],[new B4("Tab",{shift:!0}),new Oy],[new B4("n",{ctrl:!0}),new Ly],[new B4("p",{ctrl:!0}),new Oy],[new B4("Enter"),new iz0],[new B4("Escape"),new nz0]]),focusNode:this.focusNode,child:W}),D=new M2({actions:new Map([[Ly,new H6(this.invoke)],[Oy,new H6(this.invoke)],[iz0,new H6(this.invoke)],[nz0,new H6(this.invoke)]]),child:U}),H=new W1({children:[new d0({decoration:{color:Y.background},child:new J0({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,I=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:S})),new C(` (${M.threads.length})`,new g({color:S,dim:!0}))];if(I)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Jg4(new Y4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Y4({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 jI({threads:L,autofocus:!1,offsetY:2})}):null,E;if(z){let M=O?new y1({child:O}):new I0({width:$g4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Y4({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:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new y1({child:E})]})})}}m0();import{execSync as II}from"node:child_process";import{writeFile as Ey}from"node:fs/promises";import AR3 from"node:os";import xq from"node:path";dM();_X();E$();h4();H4();fP();var v01=N4(eW(),1);var Yg4="c446b2e9b16cdc06df2ec285894d6421",jR3="5ea19563777f4ade8707fc56f7e7a388",IR3="amp-thread-worker",Xg4=[{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 RR3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function GL(J){if(!J||!RR3(J.meta))return!1;return J.meta.usesDtw===!0}function y01(J){let Z=new URL(`https://dash.cloudflare.com/${Yg4}/workers/durable-objects/view/${jR3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function x01(J){let Z=new URL(`https://dash.cloudflare.com/${Yg4}/workers/services/view/${IR3}/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 PR3(J,Z){if(AV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function f01(J,Z){let Q=PR3(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 xa(J,Z,Q){let Y=`select(.pid == ${Z})`,X=fa(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function fa(J){return J.path??f9(J.uri)}function Kg4(J,Z,Q){let Y=xa("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Vg4(J,Z){return f01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
7399
7399
  ${Y}`).join(`
7400
7400
 
@@ -7623,7 +7623,7 @@ ${t.content||""}`:t.content||"",T0=[],e0=t.baseDir.startsWith("file://")?vG0(t.b
7623
7623
  `),process.exit(1)}process.stdout.write(await FS3(G.result.displayText)+`
7624
7624
  `),process.exit(0)})}dM();import{stdout as qS3}from"node:process";function WS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${MF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function td4(J){qS3.write(`${WS3(J)}
7625
7625
  `)}function ed4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{td4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{td4(Z),process.exit(0)})}var kx3=lD.join(sZ,"logs","headless.log"),F51=lD.join(Yv,"device-id.json"),En4=`cli-tui-${Tn4(16).toString("hex")}`;async function vx3(){for(let J of WE)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(() => N4(ry(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){R7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7626
- `)}function yx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function e2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")rJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")rJ("experimental.agentMode",Z.mode)}function vn4(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 xx3(J){try{return await Sn4(J,"utf-8")}catch{return J}}async function q51(J,Z,Q){let Y=vn4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!B51(X,k7.HARNESS_SYSTEM_PROMPT)&&!yn4(K))throw new C1("You are not allowed to do this.",1);rJ("systemPrompt",await xx3(Y))}function yn4(J){return!!(J&&L10(J))}function B51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function W51(J){return(J.userEmail?oJ(J.userEmail):!1)||B51(J.features,k7.DTW_TUI)}function Mn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function U51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return W51({userEmail:Z.user.email,features:Z.features})}function D51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function fx3(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 AF0(J){let Y=fx3(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 An4(J){if(!X5.write(J))await Cx3(X5,"drain")}var jn4=[{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??fK,description:`Custom settings file path (overrides the default location ${fK})`},{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 ${gn0})`},{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:a2(),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:xG.SMART.key,description:`Set the agent mode (${fG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fG().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}],In4=(J)=>("deprecated"in J)&&J.deprecated===!0,ux3=(J)=>("hidden"in J)&&J.hidden===!0,bx3=(J)=>("default"in J),hx3=(J)=>("default"in J)?J.default:void 0,xn4=[{name:"toggle-skills-count",entryPoint:bo0}];function gx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new C1(E3.unknownCommand(Q),1,V)}}async function N51(J){return{...J,getThreadEnvironment:NZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new gV(J.fileSystem),generateThreadTitle:n80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>ZQ(J.configService),pluginService:J.pluginService}}function fn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:NZ,filesystem:J.fileSystem,threadService:J.threadService}}var jF0=Y1.file(kn4.homedir()),H51=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(jF0,".config");function mx3(J){return jq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Aq4(Z);let Q=vX0(),Y=eo0();if((!Q||Y||xT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(vX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function px3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Z2(J,Z,Q){let Y=Q?.deferAuth??!1;jf1("0.0.1774656301-g0342e2");let X=v10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(Y1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:jF0,userConfigDir:H51});yT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
7626
+ `)}function yx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function e2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")rJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")rJ("experimental.agentMode",Z.mode)}function vn4(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 xx3(J){try{return await Sn4(J,"utf-8")}catch{return J}}async function q51(J,Z,Q){let Y=vn4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!B51(X,k7.HARNESS_SYSTEM_PROMPT)&&!yn4(K))throw new C1("You are not allowed to do this.",1);rJ("systemPrompt",await xx3(Y))}function yn4(J){return!!(J&&L10(J))}function B51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function W51(J){return(J.userEmail?oJ(J.userEmail):!1)||B51(J.features,k7.DTW_TUI)}function Mn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function U51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return W51({userEmail:Z.user.email,features:Z.features})}function D51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function fx3(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 AF0(J){let Y=fx3(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 An4(J){if(!X5.write(J))await Cx3(X5,"drain")}var jn4=[{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??fK,description:`Custom settings file path (overrides the default location ${fK})`},{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 ${gn0})`},{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:a2(),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:xG.SMART.key,description:`Set the agent mode (${fG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fG().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}],In4=(J)=>("deprecated"in J)&&J.deprecated===!0,ux3=(J)=>("hidden"in J)&&J.hidden===!0,bx3=(J)=>("default"in J),hx3=(J)=>("default"in J)?J.default:void 0,xn4=[{name:"toggle-skills-count",entryPoint:bo0}];function gx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new C1(E3.unknownCommand(Q),1,V)}}async function N51(J){return{...J,getThreadEnvironment:NZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new gV(J.fileSystem),generateThreadTitle:n80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>ZQ(J.configService),pluginService:J.pluginService}}function fn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:NZ,filesystem:J.fileSystem,threadService:J.threadService}}var jF0=Y1.file(kn4.homedir()),H51=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(jF0,".config");function mx3(J){return jq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Aq4(Z);let Q=vX0(),Y=eo0();if((!Q||Y||xT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(vX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function px3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Z2(J,Z,Q){let Y=Q?.deferAuth??!1;jf1("0.0.1774672496-g0342e2");let X=v10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(Y1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:jF0,userConfigDir:H51});yT4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
7627
7627
  `);let o=await dx3(J),q0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:o,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!o)await zD(),process.exit(1);V=!0}}{let F0=await X.getLatest(),o=F0.settings.url,q0=F0.secrets.isSet?.[o];P.info("Config secrets state after login",{configURL:o,apiKeySet:q0?.apiKey??!1})}let z=A1(ZQ(X).pipe(M5((F0)=>F0!=="pending"))),G=Y?"pending":await z;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(G),isError:hW(G),errorMessage:hW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=wq4({configService:X}),W=new Map,U=()=>W.clear(),D=new Q_0(X,J.settings.getWorkspaceRootPath()),H=Tt1({configService:X,filesystem:O8}),B=ja1({configService:X,trustStore:D,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(F0,o,q0)=>{let L0=`${F0}:${o}`,H0=W.get(L0);if(H0)return P.debug("Reusing existing OAuth provider for server",{serverName:F0,serverUrl:o}),H0;P.debug("Creating OAuth provider for server",{serverName:F0,serverUrl:o});let $0=(async()=>{let z0=new EE(J.secrets),i=await z0.getClientInfo(F0,o),a=q0?.scopes??i?.scopes,t=WR4();P.info("OAuth headless mode check",{useHeadless:t,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:X5.isTTY});let e;if(t)e=J.executeMode?qR4():FR4(F0);let G0=new uI0({storage:z0,serverName:F0,serverUrl:o,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:a,headlessAuthHandler:e});return P.debug("OAuth provider created",{serverName:F0,serverUrl:o,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:a,headlessMode:t,executeMode:J.executeMode}),G0})();return W.set(L0,$0),$0}}),N=sg0({configService:X,filesystem:O8,spawn:y$0}),w;if(J.executeMode){let F0=await Mz4({toolService:F,providers:[B,N],initialTimeout:15000});w=F0.registrations;for(let[o,q0]of F0.initErrors)P.warn(`${o} provider initialization slow or failed:`,q0)}else w=tg0({toolService:F,providers:[B,N]});if(Z.jetbrains)VE("JetBrains");else if(Z.ide&&rR4())VE("VS Code");else if(Z.ide&&sR4())VE("Neovim");else if(Z.ide){let F0=await vx3();if(F0){let o=d10(F0.ideName);if(o)VE(o)}}if(J.executeMode)If1(!0);let L,O=L$.status.pipe(U1((F0)=>Boolean(F0.connected&&F0.authenticated&&F0.ideName&&Uu1(F0.ideName))),x4()).subscribe((F0)=>{if(F0){if(!L)L=F.registerTool(Ez4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let F0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new EY0(process.cwd(),{alwaysIncludePaths:F0},!0)}else E=new class extends EY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await ft1({isDevelopment:!1}),A=new Yv0(M,X),j=new aS0(M,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let I=Z.takeMeBack?!1:void 0,_=U51(I,G),S=Boolean(_||Z.headless);if(S)P.info("DTW mode enabled: thread sync service disabled");let u=S?px3():H04({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;L$.status.subscribe((F0)=>{m=F0});let x=new Mj0({workspaceRoots:[Y1.file(process.cwd())],fileSystem:O8,getCurrentFile:()=>{if(!m?.openFile)return;try{return Y1.parse(m.openFile)}catch(F0){P.warn("Failed to parse current file URI",{uri:m.openFile,error:F0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let F0=m.openFile;return m.visibleFiles.filter((o)=>o!==F0).map((o)=>{try{return Y1.parse(o)}catch(q0){return P.warn("Failed to parse visible file URI",{uri:o,error:q0}),null}}).filter((o)=>o!==null)}}),T=new Zr0,f=process.env.PLUGINS??"off",d=Z.headless?wT4():void 0,p=d??new PX0({configService:X}),h=p instanceof PX0?p:void 0;if(h)h.pluginExecutorKind=_?"local":"unknown";let n=L_0({configService:X,fileSystem:O8,platform:p,internalPlugins:xn4,pluginFilter:f}),c=wo1({pluginService:n,toolService:F}),s={codebaseContextService:x,configService:X,toolService:F,mcpService:B,skillService:H,toolboxService:N,trustStore:D,threadService:A,threadHistoryService:j,threadSyncService:u,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:O8,terminal:T,pluginService:n,pluginPlatform:h,headlessPluginPlatform:d,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let F0 of w.values())F0.dispose();await s.mcpService.dispose(),U(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),q(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function dx3(J){if(!J.executeMode){if(!await jX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return X5.write(`Login cancelled. Run the command again to retry.
7628
7628
  `),!1}return await un4(J)}async function un4(J){let Z=Tn4(32).toString("hex"),Q=await Wv(J.ampURL,Z),Y=new AbortController;try{await MV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await Wv(J.ampURL,Z,!1);X5.write(`If your browser does not open automatically, visit:
7629
7629
 
@@ -7631,7 +7631,7 @@ ${i0.blue.bold(X)}
7631
7631
 
7632
7632
  `);try{return await sC4(J.ampURL,Z,J.secrets,Y),X5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),R7.write(`
7633
7633
  Login failed: ${K instanceof Error?K.message:String(K)}
7634
- `),!1}}function Rn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function cx3(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 lx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function ix3(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(!lx3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function nx3(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 ax3(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 ox3(J){let Z=new bN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)wj(),process.exit(0);let N=B.originalError??B;HI4(N)}),ed4(Z,{version:"0.0.1774656301-g0342e2",buildTimestamp:"2026-03-28T00:09:09.564Z",buildType:"'release'"}),Z.addHelpText("after",nR4()),Z.configureHelp({formatHelp:aR4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await m3(w);await Qf3(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 m3(w);await Zf3(L,await ya0(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 m3(L);await mI4(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 m3(w);await pI4(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",`
7634
+ `),!1}}function Rn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function cx3(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 lx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function ix3(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(!lx3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function nx3(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 ax3(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 ox3(J){let Z=new bN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)wj(),process.exit(0);let N=B.originalError??B;HI4(N)}),ed4(Z,{version:"0.0.1774672496-g0342e2",buildTimestamp:"2026-03-28T04:38:51.425Z",buildType:"'release'"}),Z.addHelpText("after",nR4()),Z.configureHelp({formatHelp:aR4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await m3(w);await Qf3(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 m3(w);await Zf3(L,await ya0(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 m3(L);await mI4(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 m3(w);await pI4(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",`
7635
7635
  Actions:
7636
7636
  create Create a new DTW thread and print its ID
7637
7637
  add-message <message> Send a user message and wait for message_added
@@ -7695,8 +7695,8 @@ ${M}
7695
7695
 
7696
7696
  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 rx3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Qa({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:NZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new gV(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 sx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Nv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Nv()).trimEnd(),stdinInput:null}}function tx3(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"
7697
7697
  Or pipe via stdin: echo "your message" | amp --execute`)}async function IF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=($0,z0)=>{let i=Number(process.hrtime.bigint()-z0)/1e6,a=NO4();P.info("Startup phase",{phase:$0,phaseMs:Math.round(i),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:V,stdinInput:z}=await sx3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;tx3({...Z,streamJson:G},J.executeMode,V),e2(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 Z2(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let D=await N51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:H}=U;if(!W&&hW(H)){let $0=ok(Error(H.error.message));if($0.message===E3.networkOffline||$0.message===E3.networkTimeout)throw AF0(J.ampURL);throw new C1(E3.invalidAPIKey,1)}let B=m6(H)?H:null,N=B?.user.email,w=yn4(N),L=W51({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&U51(O,B);if(!W)await q51(Q,Z,H);let M=D51(H),A=M?.features??[],j=M?.team??null,I=IX0(Z,M);if(I instanceof Error)p3(I.message);if((J.executeMode||G)&&N8(Z.mode)&&!w)throw new C1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!GE(Z.mode,N))throw new C1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await ET4(V,z,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!oJ(N))throw new C1("Headless DTW mode is only available for Amp employees",1);let $0=await U.secretStorage.get("apiKey",J.ampURL);if(!$0)throw new C1("API key required for headless mode. Please run `amp login` first.",1);let z0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(z0&&!b9(z0))throw new C1(`Invalid thread ID: ${z0}`,1);let i=z0?void 0:await qf3({dependencies:U,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),a=z0??i?.threadId;if(!a)throw new C1("Failed to resolve headless thread ID",1);let t=await BR4(a);if(t.status==="already-running")await U.asyncDispose(),await zD(),process.exit(0);try{await GR4({ampURL:J.ampURL,apiKey:$0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:a,ownerUserId:i?.ownerUserId,threadVersion:i?.threadVersion,agentMode:i?.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 t.release(),await U.asyncDispose()}await zD(),process.exit(0)}let _=J.executeMode?void 0:async($0)=>Ro($0,"interactive"),S={threadService:U.threadService,workerDeps:D,createThread:async()=>{let $0=W?await U.serverStatusPromise:H,z0=await KY0(J.settings,process.cwd(),D51($0),I);if(z0 instanceof Error)p3(z0.message);return Be0(D,{threadMeta:z0?vz(z0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async($0,z0)=>{if(z0?.nonBlockingOwnershipCheck){Pn4($0,U.configService).catch((i)=>{if(i instanceof C1){if(z0.onOwnershipError){z0.onOwnershipError(i,$0);return}Lj(i,$0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})});return}try{await Pn4($0,U.configService)}catch(i){if(i instanceof C1)throw i;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:Lj},u=async($0)=>{try{if($0==="dtw")return rx3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:En4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Cf4(S,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof C1)throw z0;throw await Lj(z0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")R7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7698
- `),await zD(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await U.configService.getLatest(),z0=Fb($0),i=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(z0)});if(i.ok)return P.info("User free tier status:",i),i.result;return}catch($0){P.error("Failed to fetch free tier status:",$0);return}})(),T=!J.executeMode?new qe0:null,f,d=null;if(T)f=T,d=(async()=>{let $0=W?await U.serverStatusPromise:U.serverStatus;await q51(Q,Z,$0);let z0=process.hrtime.bigint(),i=U51(O,$0),a=m6($0)?W51({userEmail:$0.user.email,features:$0.features}):!1;Mn4({dtwEnabled:i,hasV2TUIAccess:a});let t=await u(i?"dtw":"worker");if(K("runMainThread:createThreadPool",z0),T.attach(t),V){let e=await A1(t.threadHandles$);if(!e)throw new C1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async($0)=>{let z0=$0 instanceof Error?$0:Error(String($0));T.setInitError(z0),await Lj($0,Z.threadId)});else F=process.hrtime.bigint(),Mn4({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(),mx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(D4(($0)=>{if(!$0)return k0.of({});return H5($0.thread$,$0.threadViewState$).pipe(U1(([z0,i])=>({[z0.id]:i})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){GT4(U.mcpService,J.settings);let $0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},z0=await RI4({threadPool:f,...$0});if(await Ro(z0,"execute"),Z.archive)await g6.archiveThread({thread:z0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await Lu1();let $0=await DE({jetbrainsOnly:Z.jetbrains});if($0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if($0.length===1){let z0=$0[0];if(z0)L$.selectConfig(z0)}else c=!0}F=process.hrtime.bigint();let s=Jo0("0.0.1774656301-g0342e2",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let F0=new nS0(U.threadStorage);K("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let o=new uo0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let $0=await A1(f.threadHandles$);if(!$0)throw new C1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let q0=await TX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",q0);let L0={...q0,launchCount:q0.launchCount+1};kj(($0)=>({...$0,launchCount:$0.launchCount+1}));let H0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Nu4({codebaseContextService:U.codebaseContextService,history:new Ba0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,threadHistoryService:U.threadHistoryService,threadFuzzyIndexer:F0,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>fn4(U),ideClient:L$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:o,updateService:s,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:H0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:En4,logFile:{path:Y},sessionState:L0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-28T00:09:09.564Z"},($0)=>new Te0({...$0,threadPool:$0.threadPool},(z0)=>new f41({...z0,threadState:z0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function m3(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)R7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7699
- `);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 Ta1({get:async(z)=>{if(z!==Kg)return;try{let G=await Sn4(F51,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Kg)return;await _n4(lD.dirname(F51),{recursive:!0}),await Tx3(F51,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});Rf1(Y);let X=await TR4({...J,workspaceTrust:{current:!0,changes:iu},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await VT4(J.mcpConfig);X=zT4(X,z)}let K=lD.dirname(X.getSettingsFilePath());Mq4(Yv,K);let V=await X.get("url","global");if(!V)V=G2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!AV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Bf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:RT4(await ya0(J,X))}}function ex3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function $f3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lD.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?kx3:gn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Jf3(){BO4();let J=ex3(process.argv),Z=$f3(process.argv,J),Q=Rj4(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(yx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774656301-g0342e2",buildTimestamp:"2026-03-28T00:09:09.564Z"}),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 ox3(Q).parseAsync(process.argv)}Oq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Jf3().catch(Lj)});async function Zf3(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"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7698
+ `),await zD(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await U.configService.getLatest(),z0=Fb($0),i=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(z0)});if(i.ok)return P.info("User free tier status:",i),i.result;return}catch($0){P.error("Failed to fetch free tier status:",$0);return}})(),T=!J.executeMode?new qe0:null,f,d=null;if(T)f=T,d=(async()=>{let $0=W?await U.serverStatusPromise:U.serverStatus;await q51(Q,Z,$0);let z0=process.hrtime.bigint(),i=U51(O,$0),a=m6($0)?W51({userEmail:$0.user.email,features:$0.features}):!1;Mn4({dtwEnabled:i,hasV2TUIAccess:a});let t=await u(i?"dtw":"worker");if(K("runMainThread:createThreadPool",z0),T.attach(t),V){let e=await A1(t.threadHandles$);if(!e)throw new C1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async($0)=>{let z0=$0 instanceof Error?$0:Error(String($0));T.setInitError(z0),await Lj($0,Z.threadId)});else F=process.hrtime.bigint(),Mn4({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(),mx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(D4(($0)=>{if(!$0)return k0.of({});return H5($0.thread$,$0.threadViewState$).pipe(U1(([z0,i])=>({[z0.id]:i})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){GT4(U.mcpService,J.settings);let $0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},z0=await RI4({threadPool:f,...$0});if(await Ro(z0,"execute"),Z.archive)await g6.archiveThread({thread:z0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await Lu1();let $0=await DE({jetbrainsOnly:Z.jetbrains});if($0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if($0.length===1){let z0=$0[0];if(z0)L$.selectConfig(z0)}else c=!0}F=process.hrtime.bigint();let s=Jo0("0.0.1774672496-g0342e2",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let F0=new nS0(U.threadStorage);K("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let o=new uo0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let $0=await A1(f.threadHandles$);if(!$0)throw new C1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let q0=await TX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",q0);let L0={...q0,launchCount:q0.launchCount+1};kj(($0)=>({...$0,launchCount:$0.launchCount+1}));let H0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Nu4({codebaseContextService:U.codebaseContextService,history:new Ba0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,threadHistoryService:U.threadHistoryService,threadFuzzyIndexer:F0,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:f,createSystemPromptDeps:async()=>fn4(U),ideClient:L$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:o,updateService:s,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:H0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:En4,logFile:{path:Y},sessionState:L0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-28T04:38:51.425Z"},($0)=>new Te0({...$0,threadPool:$0.threadPool},(z0)=>new f41({...z0,threadState:z0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function m3(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)R7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7699
+ `);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 Ta1({get:async(z)=>{if(z!==Kg)return;try{let G=await Sn4(F51,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Kg)return;await _n4(lD.dirname(F51),{recursive:!0}),await Tx3(F51,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});Rf1(Y);let X=await TR4({...J,workspaceTrust:{current:!0,changes:iu},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await VT4(J.mcpConfig);X=zT4(X,z)}let K=lD.dirname(X.getSettingsFilePath());Mq4(Yv,K);let V=await X.get("url","global");if(!V)V=G2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!AV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Bf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:RT4(await ya0(J,X))}}function ex3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function $f3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=lD.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?kx3:gn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Jf3(){BO4();let J=ex3(process.argv),Z=$f3(process.argv,J),Q=Rj4(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(yx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774672496-g0342e2",buildTimestamp:"2026-03-28T04:38:51.425Z"}),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 ox3(Q).parseAsync(process.argv)}Oq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Jf3().catch(Lj)});async function Zf3(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"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7700
7700
  `);else if(!AV(J.ampURL))X5.write(`Logging in to ${new URL(J.ampURL).hostname}
7701
7701
  `);let Y=process.env.AMP_API_KEY;if(Y)X5.write(`API key found in environment variable, storing...
7702
7702
  `),await Z.set("apiKey",Y,J.ampURL),X5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1774656301-g0342e2",
3
+ "version": "0.0.1774672496-g0342e2",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {