@sourcegraph/amp 0.0.1774945076-g24095c → 0.0.1774945762-g24095c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6200,11 +6200,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6200
6200
|
${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
|
|
6201
6201
|
|
|
6202
6202
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6203
|
-
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();mM();async function uY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=jP4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],w=Date.now();if(D)U=Math.floor((w-new Date(D).getTime())/3600000);if(B)H=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return C.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var $Q3="https://static.ampcode.com/cli/cli-version.txt";async function bY0(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=jP4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var JQ3=604800000;function AP4(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 jP4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,z=X.parts[V]||0;if(G<z)return-1;if(G>z)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function pa0(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?AF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function da0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(d6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new _z().scoped("update"),V=Q.startDelayMs??0;if(V>0)await ZF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await ZF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await fY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await bY0(J):await uY0(J,Ej());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==fa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await ON(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await ZF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}mM();import{stderr as kG}from"node:process";function RP4(J){let Z=new hw().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await ka0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6203
|
+
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();mM();async function uY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=jP4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],w=Date.now();if(D)U=Math.floor((w-new Date(D).getTime())/3600000);if(B)H=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return C.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var $Q3="https://static.ampcode.com/cli/cli-version.txt";async function bY0(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=jP4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var JQ3=604800000;function AP4(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 jP4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,z=X.parts[V]||0;if(G<z)return-1;if(G>z)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function pa0(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?AF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function da0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(d6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new _z().scoped("update"),V=Q.startDelayMs??0;if(V>0)await ZF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await ZF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await fY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await bY0(J):await uY0(J,Ej());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==fa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await ON(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await ZF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}mM();import{stderr as kG}from"node:process";function RP4(J){let Z=new hw().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await ka0(Y.force||!1,Y.verbose||!1,"0.0.1774945762-g24095c"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new hw("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await ZQ3(Y.targetVersion)});J.addCommand(Q)}async function ZQ3(J){let Z=process.platform==="win32"&&xY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")kG.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6204
6204
|
|
|
6205
6205
|
`));try{if(!J){kG.write(o0.blue(`Checking for updates...
|
|
6206
|
-
`));let{hasUpdate:K,latestVersion:V}=xY0()?await bY0("0.0.
|
|
6207
|
-
`));let F=await ON("0.0.
|
|
6206
|
+
`));let{hasUpdate:K,latestVersion:V}=xY0()?await bY0("0.0.1774945762-g24095c"):await uY0("0.0.1774945762-g24095c",Ej());if(!K){let G=pa0("0.0.1774945762-g24095c"),z=G?.age?`released ${G.age} ago`:`built ${AF(new Date("2026-03-31T08:33:08.299Z"))} ago`;kG.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774945762-g24095c"} (${z})
|
|
6207
|
+
`));let F=await ON("0.0.1774945762-g24095c",Q);if(F.warning)kG.write(`
|
|
6208
6208
|
`+o0.yellow(F.warning)+`
|
|
6209
6209
|
`);process.exit(0)}if(!V)kG.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}kG.write(o0.blue(`Updating to version ${J}...
|
|
6210
6210
|
`)),await Ti(J,void 0,(K)=>{kG.write(o0.dim(`Running: ${K}
|
|
@@ -7376,7 +7376,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7376
7376
|
`),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 P(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new P(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new P(`
|
|
7377
7377
|
`))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new n0({padding:C0.symmetric(0,1),child:new e({text:new P(void 0,void 0,K)})})})}}class V01 extends y${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=RG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new X01({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 jh4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?v9:0,z=Y-G;if(z<=0)return null;let F=Z-G;if(F<0||F>=z)return null;let q=Math.max(1,Math.floor(z/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?v9:0,z=Y-G;if(z<=0)return null;let F=Math.max(0,Math.min(z-1,Z-G));if(K===1)return 0;let q=z/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function dR3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let z=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=G>0?V/G:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function cR3(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 lR3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),z=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+z.length}let K=J.label.length,V=0;for(let G of Q){let z=G.points[Z];if(!z)continue;V+=z.value;let F=2+G.name.length+2+Y(z.value).length;K=Math.max(K,F)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function iR3(J,Z,Q,Y,X,K,V){let G;try{let D=x1.of(J),B=f0.of(J);G={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let z=new g({color:G.foreground,bold:!0}),F=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],U=new g({color:G.foreground,underline:!0}),H=(D,B)=>new P(B,U,void 0,nY0(D),()=>{b3(J,D)});if(Y.length<=1){if(W.push(new P(`${Z.label}: `,z)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new P(K(Z.value),F));if(Z.meta)W.push(new P(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new P(`${Z.label}
|
|
7378
7378
|
`,z));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],L=N.points[Q];if(!L)continue;B+=L.value;let O=N.color??X[w%X.length]??G.foreground;if(W.push(new P("● ",new g({color:O}))),W.push(new P(`${N.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new P(K(L.value),F));if(w<Y.length-1||D)W.push(new P(`
|
|
7379
|
-
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),F))}return new d0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new e({text:new P(void 0,void 0,W)})})}$E();m0();_7();KE();B$();x3();_2();wd();TX();JJ();rJ();ZQ();LA();c4();ug();TP();O1();m0();JJ();class G01{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.1774945076-g24095c"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){C.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class zL extends l0{props;constructor(J){super();this.props=J}createState(){return new Rh4}}class Rh4 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 Ih4 extends p0{controller=new r7;focusNode=new z6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new P(">",new g({color:Q.foreground}))})}),new y1({child:z})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new g({color:Y.keybind}))),W.push(new P(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new P("Esc",new g({color:Y.keybind}))),W.push(new P(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,W)})});return new d0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new u3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Ih4}}ZQ();import{mkdtemp as oR3,readFile as rR3,rmdir as sR3,unlink as tR3,writeFile as eR3}from"node:fs/promises";import{tmpdir as $I3}from"node:os";import yh4 from"node:path";m0();m0();class Ph4{_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 HR extends Ph4{_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 Ch4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{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 F01 extends a3{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 wq(this)}createRenderObject(){return new Th4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Th4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var nR3=500;class q01{_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 HR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=f6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(C.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},nR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class PG0{}class CG0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new _h4(this.props)}}class _h4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new Na;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new q01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Ch4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof PG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new PG0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new A7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[PG0,new D6(this.invoke)]]),child:Q});return new wa({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 z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{qR.of(this.context).insert(this.overlayEntry)}catch(J){C.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new P(Q,new g({color:f0.of(J).app.command})),new P(" ",new g({color:Z})));return X.push(new P(Y,new g({color:Z}))),[{child:new e({text:new P(" ",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=K4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new P(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=K4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=K4.sizeOf(J).width,w=D+4,N=Math.floor(B*0.9),L=Math.max(Math.min(w,N),Math.min(30,N)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new e8({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:H})})})});return new F01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Sh4(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 kh4(J){switch(J.type){case"file":return J.path;case"hint":return`${aR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function vh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function aR3(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(`
|
|
7379
|
+
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),F))}return new d0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new e({text:new P(void 0,void 0,W)})})}$E();m0();_7();KE();B$();x3();_2();wd();TX();JJ();rJ();ZQ();LA();c4();ug();TP();O1();m0();JJ();class G01{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.1774945762-g24095c"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){C.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class zL extends l0{props;constructor(J){super();this.props=J}createState(){return new Rh4}}class Rh4 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 Ih4 extends p0{controller=new r7;focusNode=new z6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new P(">",new g({color:Q.foreground}))})}),new y1({child:z})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new g({color:Y.keybind}))),W.push(new P(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new P("Esc",new g({color:Y.keybind}))),W.push(new P(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,W)})});return new d0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new u3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Ih4}}ZQ();import{mkdtemp as oR3,readFile as rR3,rmdir as sR3,unlink as tR3,writeFile as eR3}from"node:fs/promises";import{tmpdir as $I3}from"node:os";import yh4 from"node:path";m0();m0();class Ph4{_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 HR extends Ph4{_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 Ch4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class z01{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 F01 extends a3{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 wq(this)}createRenderObject(){return new Th4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Th4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var nR3=500;class q01{_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 HR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=f6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(C.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},nR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class PG0{}class CG0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new _h4(this.props)}}class _h4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new Na;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new q01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Ch4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof PG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new PG0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new A7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[PG0,new D6(this.invoke)]]),child:Q});return new wa({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 z01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{qR.of(this.context).insert(this.overlayEntry)}catch(J){C.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new P(Q,new g({color:f0.of(J).app.command})),new P(" ",new g({color:Z})));return X.push(new P(Y,new g({color:Z}))),[{child:new e({text:new P(" ",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=K4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new P(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=K4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=K4.sizeOf(J).width,w=D+4,N=Math.floor(B*0.9),L=Math.max(Math.min(w,N),Math.min(30,N)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new e8({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:H})})})});return new F01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function Sh4(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 kh4(J){switch(J.type){case"file":return J.path;case"hint":return`${aR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function vh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function aR3(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(`
|
|
7380
7380
|
`))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 DR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new xh4(this.props)}}var JI3=":";class xh4 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 G=X.query.toLowerCase().startsWith(JI3);if(G!==this._isCommitMode)this._isCommitMode=G,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=J.kind==="commit"?"@:":"@@",z=K+G+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=`git-commit(${J.hash})`,z=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Rb4(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 oR3(yh4.join($I3(),"amp-edit-")),Q=yh4.join(Z,"message.amp.md");await eR3(Q,J,"utf-8"),await mK(Q);try{let Y=await rR3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")C.error("Failed to read temporary file",Y)}try{await tR3(Q),await sR3(Z)}catch(Y){C.warn("Failed to clean up temporary file",Y)}}catch(Z){C.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new W1({mainAxisSize:"min",children:[new e({text:new P("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((z,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new P(z.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new P(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new P("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((z,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new P(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new P(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new P(" ")}),new e({text:new P(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new CG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(z)=>kh4(z),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(z,F,q)=>{let W=q?Z.selection:void 0,U=Z.secondary,H=Z.foreground,D=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new P("",void 0,[new P(F.shortHash,new g({color:Z.secondary})),new P(" ",new g({})),new P(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new P(` ${F.relativeDate}`,new g({color:D,dim:!0}))})]})});let w=[];switch(F.type){case"file":w.push(new P("@",new g({color:U}))),w.push(new P(F.path,new g({color:H})));break;case"hint":w.push(new P(F.kind==="commit"?"@:":"@@",new g({color:B}))),w.push(new P(" ",new g({}))),w.push(new P(F.message,new g({color:B})));break}let N=vh4(F);if(N)w.push(new P(" - ",new g({color:D,dim:!0}))),w.push(new P(N,new g({color:D,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new P("",void 0,w),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let z=[];if(X)z.push(X);if(X&&K)z.push(new e({text:new P(" ")}));if(K)z.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:z})});G.push(F)}if(G.push(new y1({child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class fh4 extends p0{controller=new r7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new z6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=TV)return!1;let Z=await YL(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=K4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new DR({controller:this.controller,triggers:[new yq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new s4({focusNode:this.focusNode,child:G}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new d0({padding:C0.symmetric(1,0),child:new e({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new g({color:Y.keybind})),new P(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new g({color:Q.foreground,dim:!0})),new P("Enter",new g({color:Y.keybind})),new P(" to submit, ",new g({color:Q.foreground,dim:!0})),new P("Esc",new g({color:Y.keybind})),new P(" to clear",new g({color:Q.foreground,dim:!0}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class W01 extends l0{props;constructor(J){super();this.props=J}createState(){return new fh4}}import{isDeepStrictEqual as U01}from"node:util";var ZI3=/[\\/_ +.#"@[({&]/,QI3=/[\\/_ +.#"@[({&]/g,YI3=/[\s-]/,uh4=/[\s-]/g;function _G0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,U,H,D;while(F>=0){if(W=_G0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(YI3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(uh4),D&&X>0)W*=0.999**D.length}else if(ZI3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(QI3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=_G0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function TG0(J){return J.toLowerCase().replace(uh4," ")}function bh4(J,Z){let Q=_G0(J,Z,TG0(J),TG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=_G0(J,G,TG0(J),TG0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Uy{}class Hy{}class SG0{}class kG0{}class hh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new gh4}}class gh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function XI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=bh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new mh4}}class mh4 extends p0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r7(this.widget.props.controller?.query??""),this.focusNode=new z6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>U01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!U01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>U01(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 Uy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Hy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof SG0){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 kG0)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,...XI3(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;Vy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Uy],[new D4("ArrowUp"),new Hy],[new D4("Tab"),new Uy],[new D4("Tab",{shift:!0}),new Hy],[new D4("n",{ctrl:!0}),new Uy],[new D4("p",{ctrl:!0}),new Hy],[new D4("Enter"),new SG0],[new D4("Escape"),new kG0]]),focusNode:this.focusNode,child:G}),F=new A7({actions:new Map([[Uy,new D6(this.invoke)],[Hy,new D6(this.invoke)],[SG0,new D6(this.invoke)],[kG0,new D6(this.invoke)]]),child:z}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new P(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new P(w,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new P(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new P(this.widget.props.getLabel(N),new g({color:j,dim:E}))})})}return new hh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:w,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let w=new d0({padding:C0.symmetric(1,0),child:new e({text:new P(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(w)}if(!K)H.push(q,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);H.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:N??new R0({height:1})})})]})}))}else H.push(new y1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function ph4(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 H01 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)=>ph4(X.pubDate).length));return new $7({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let z=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,w)=>new R0({width:w,child:W1.end([new e({text:new P(B,new g({color:H}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new P(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(ph4(X.pubDate),Q)]})})}})}}uP();class D01 extends l0{createState(){return new dh4}}class dh4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new P("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function KI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return QV0.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 B01(J,Z,Q){return new e({text:new P(`${J}${Z}`,new g({color:Q})),maxLines:1})}function VI3(J,Z,Q,Y){return[B01("+",J,Y.success),u3.horizontal(1),B01("~",Z,Y.warning),u3.horizontal(1),B01("-",Q,Y.destructive)]}function GI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class vG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new ch4}}class ch4 extends p0{spinner=new V3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=KI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new n0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new P("",new g({color:U.colors.foreground,dim:!0}),[new P("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new P(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,w=(L)=>{if(L!==D)D=L,B=C2(L);return B};return new $7({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=w(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>w(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!GI3(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:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new P(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new on({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new P(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,H0=d.getConnectorText(r);a.push(new P(H0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new P("",void 0,a)}))}let p=[],h=z===L.id?new P("(current) ",new g({color:R.success})):G.has(L.id)?new P("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(ww(y))p.push(new D01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new P("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new P("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new P(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...VI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function lh4(J){return 1-(1-J)**3}function ih4(J,Z,Q){return J+(Z-J)*Q}function Ia(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=lh4(Y),V=lh4(X);return{x:ih4(J.startOffset.x,J.targetOffset.x,K),y:ih4(J.startOffset.y,J.targetOffset.y,V)}}var zI3={nodeWidth:3,horizontalSpacing:3};class Dy{options;constructor(J={}){this.options={...zI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:z}}),D};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var FI3={nodeWidth:3,nodeHeight:2};class By{options;constructor(J={}){this.options={...FI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var qI3={nodeWidth:3,nodeHeight:2},WI3={x:0,y:0};class xG0{options;constructor(J={}){this.options={...qI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=WI3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new P("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(w.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);w.push(...y)}}let N=new x0({crossAxisAlignment:"start",children:w}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:N})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new bG(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new P(V,new g({color:z,bold:F}))}),new e({text:new P(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new P(G,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new e({text:new P("│ ",new g({color:F}),[new P(U+H,new g({color:q??F})),new P(" │",new g({color:F}))])}))}return W.push(new e({text:new P(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+G;if(H>=0&&H<Y)F[H]="▲"}V.push(new e({text:new P(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+G,B=H.map((L)=>L.position.x+G),w=Math.min(...B),N=Math.max(...B);for(let L=w;L<=N;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===w)q[L]="└";else if(L===N)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===w)q[L]="└";else if(L===N)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new P(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+G;if(D>=0&&D<Y)W[D]="│"}return V.push(new e({text:new P(W.join(""),new g({color:z}))})),V}}var UI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},HI3={x:0,y:0};class w01{options;constructor(J={}){this.options={...UI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=HI3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new P("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(w.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);w.push(...y)}}let N=new x0({crossAxisAlignment:"start",children:w}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:N})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new bG(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new P(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new P(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((w)=>w.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,H=W.map((w)=>w.position.x+G),D=Math.min(...H),B=Math.max(...H);for(let w=D;w<=B;w++)if(w>=0&&w<Y){let N=w===U,L=H.includes(w);if(N&&L)if(W.length===1)F[w]="│";else if(w===D)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===D)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(L)if(w===D)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return V.push(new e({text:new P(F.join(""),new g({color:z}))})),V}}class Pa extends a3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new nh4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class nh4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class BR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new rh4}}var ah4=400,oh4=300,DI3=16;class rh4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Dy({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new By;renderer=new w01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:ah4,durationY:oh4};let Z=Math.max(ah4,oh4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ia(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},DI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Pa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class th4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new eh4}}class eh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var sh4=30,BI3=30;class wy{}class Ny{}class fG0{}class uG0{}class N01 extends l0{props;constructor(J){super();this.props=J}createState(){return new $g4}}class $g4 extends p0{highlightedIndex=0;controller=new r7;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new z6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Vy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ny){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof fG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof uG0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=K4.of(J).size.width>=BI3+sh4,z=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new IZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new g$({shortcuts:new Map([[new D4("ArrowDown"),new wy],[new D4("ArrowUp"),new Ny],[new D4("Tab"),new wy],[new D4("Tab",{shift:!0}),new Ny],[new D4("n",{ctrl:!0}),new wy],[new D4("p",{ctrl:!0}),new Ny],[new D4("Enter"),new fG0],[new D4("Escape"),new uG0]]),focusNode:this.focusNode,child:W}),H=new A7({actions:new Map([[wy,new D6(this.invoke)],[Ny,new D6(this.invoke)],[fG0,new D6(this.invoke)],[uG0,new D6(this.invoke)]]),child:U}),D=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new P(">",new g({color:Y.foreground}))})}),new y1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new P(M.label,new g({color:T})),new P(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new P(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new th4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new P("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),w=new x0({children:B,crossAxisAlignment:"start"}),N=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:w})})}),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 BR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new y1({child:O}):new R0({width:sh4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:w})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new R0({height:1}),new y1({child:E})]})})}}m0();PX();mM();TX();JJ();c4();w4();TP();var O01=B4(eW(),1);import{execSync as wR}from"node:child_process";import{writeFile as Ly}from"node:fs/promises";import wI3 from"node:os";import xq from"node:path";var Jg4="c446b2e9b16cdc06df2ec285894d6421",NI3="5ea19563777f4ade8707fc56f7e7a388",LI3="amp-thread-worker",Zg4=[{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 OI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function qL(J){if(!J||!OI3(J.meta))return!1;return J.meta.usesDtw===!0}function E01(J){let Z=new URL(`https://dash.cloudflare.com/${Jg4}/workers/durable-objects/view/${NI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function M01(J){let Z=new URL(`https://dash.cloudflare.com/${Jg4}/workers/services/view/${LI3}/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 EI3(J,Z){if(MV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function A01(J,Z){let Q=EI3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Ca(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ta(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ta(J){return J.path??f9(J.uri)}function Qg4(J,Z,Q){let Y=Ca("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Yg4(J,Z){return A01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7381
7381
|
${Y}`).join(`
|
|
7382
7382
|
|
|
@@ -7605,7 +7605,7 @@ ${t.content||""}`:t.content||"",T0=[],r0=t.baseDir.startsWith("file://")?Az0(t.b
|
|
|
7605
7605
|
`),process.exit(1)}process.stdout.write(await QS3(z.result.displayText)+`
|
|
7606
7606
|
`),process.exit(0)})}mM();import{stdout as YS3}from"node:process";function XS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${AF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function ad4(J){YS3.write(`${XS3(J)}
|
|
7607
7607
|
`)}function od4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{ad4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{ad4(Z),process.exit(0)})}var Rx3=aH.join(nZ,"logs","headless.log"),t61=aH.join(Zv,"device-id.json"),wn4=`cli-tui-${In4(16).toString("hex")}`;async function Ix3(){for(let J of GE)try{if((await J.listConfigs()).length>0)return J}catch(Z){C.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(ay(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){A2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7608
|
-
`)}function Px3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function e7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function _n4(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 Cx3(J){try{return await Cn4(J,"utf-8")}catch{return J}}async function e61(J,Z,Q){let Y=_n4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Y51(X,S2.HARNESS_SYSTEM_PROMPT)&&!Sn4(K))throw new C1("You are not allowed to do this.",1);aJ("systemPrompt",await Cx3(Y))}function Sn4(J){return!!(J&&J10(J))}function Y51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function $51(J){return(J.userEmail?dJ(J.userEmail):!1)||Y51(J.features,S2.DTW_TUI)}function Nn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function J51(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return $51({userEmail:Z.user.email,features:Z.features})}function Z51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Tx3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function UF0(J){let Y=Tx3(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 Ln4(J){if(!e6.write(J))await Ex3(e6,"drain")}var On4=[{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(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cn0})`},{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:a7(),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:uz.SMART.key,description:`Set the agent mode (${bz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:bz().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}],En4=(J)=>("deprecated"in J)&&J.deprecated===!0,_x3=(J)=>("hidden"in J)&&J.hidden===!0,Sx3=(J)=>("default"in J),kx3=(J)=>("default"in J)?J.default:void 0,kn4=[{name:"toggle-skills-count",entryPoint:Io0}];function vx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new C1(E3.unknownCommand(Q),1,V)}}async function X51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>fX(J.configService),pluginService:J.pluginService}}function vn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(Tn4.homedir()),Q51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function yx3(J){return Wq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){qq4(Z);let Q=AX0(),Y=mo0();if((!Q||Y||ST4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(AX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function xx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Q7(J,Z,Q){let Y=Q?.deferAuth??!1;Xf1("0.0.
|
|
7608
|
+
`)}function Px3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function e7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function _n4(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 Cx3(J){try{return await Cn4(J,"utf-8")}catch{return J}}async function e61(J,Z,Q){let Y=_n4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Y51(X,S2.HARNESS_SYSTEM_PROMPT)&&!Sn4(K))throw new C1("You are not allowed to do this.",1);aJ("systemPrompt",await Cx3(Y))}function Sn4(J){return!!(J&&J10(J))}function Y51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function $51(J){return(J.userEmail?dJ(J.userEmail):!1)||Y51(J.features,S2.DTW_TUI)}function Nn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function J51(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return $51({userEmail:Z.user.email,features:Z.features})}function Z51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Tx3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function UF0(J){let Y=Tx3(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 Ln4(J){if(!e6.write(J))await Ex3(e6,"drain")}var On4=[{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(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cn0})`},{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:a7(),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:uz.SMART.key,description:`Set the agent mode (${bz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:bz().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}],En4=(J)=>("deprecated"in J)&&J.deprecated===!0,_x3=(J)=>("hidden"in J)&&J.hidden===!0,Sx3=(J)=>("default"in J),kx3=(J)=>("default"in J)?J.default:void 0,kn4=[{name:"toggle-skills-count",entryPoint:Io0}];function vx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new C1(E3.unknownCommand(Q),1,V)}}async function X51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>fX(J.configService),pluginService:J.pluginService}}function vn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(Tn4.homedir()),Q51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function yx3(J){return Wq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){qq4(Z);let Q=AX0(),Y=mo0();if((!Q||Y||ST4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(AX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function xx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Q7(J,Z,Q){let Y=Q?.deferAuth??!1;Xf1("0.0.1774945762-g24095c");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:HF0,userConfigDir:Q51});_T4(X);let K=await X.getLatest();C.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),C.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)C.info("No API key found, continuing startup with deferred auth");else{e6.write(`No API key found. Starting login flow...
|
|
7609
7609
|
`);let W0=await fx3(J),r=await J.secrets.get("apiKey",J.ampURL);if(C.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await GH(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];C.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let G=j1(fX(X).pipe(T5((a)=>a!=="pending"))),z=Y?"pending":await G;if(!Y)C.info("Server status resolved",{status:"ready",isAuthenticated:o6(z),isError:hW(z),errorMessage:hW(z)?z.error.message:void 0});let{toolService:F,dispose:q}=Kq4({configService:X}),W=new Map,U=()=>W.clear(),H=new uT0(X,J.settings.getWorkspaceRootPath()),D=zt1({configService:X,filesystem:a8}),B=Ya1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let H0=`${a}:${W0}`,L0=W.get(H0);if(L0)return C.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;C.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let G0=(async()=>{let J0=new BE(J.secrets),z0=await J0.getClientInfo(a,W0),i=r?.scopes??z0?.scopes,o=YI4();C.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:e6.isTTY});let t;if(o)t=J.executeMode?QI4():ZI4(a);let $0=new wR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??z0?.clientId,clientSecret:r?.clientSecret??z0?.clientSecret,authUrl:r?.authUrl??z0?.authUrl,tokenUrl:r?.tokenUrl??z0?.tokenUrl,scopes:i,headlessAuthHandler:t});return C.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??z0?.clientId),willUseDCR:!(r?.clientId??z0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(H0,G0),G0}}),w=bg0({configService:X,filesystem:a8,spawn:P$0}),N;if(J.executeMode){let a=await FG4({toolService:F,providers:[B,w],initialTimeout:15000});N=a.registrations;for(let[W0,r]of a.initErrors)C.warn(`${W0} provider initialization slow or failed:`,r)}else N=hg0({toolService:F,providers:[B,w]});if(Z.jetbrains)QE("JetBrains");else if(Z.ide&&pI4())QE("VS Code");else if(Z.ide&&dI4())QE("Neovim");else if(Z.ide){let a=await Ix3();if(a){let W0=_10(a.ideName);if(W0)QE(W0)}}if(J.executeMode)Kf1(!0);let L,O=w$.status.pipe(D1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&nf1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(zG4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new WY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends WY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Bt1({isDevelopment:!1}),A=new hS0(M,X,{maxThreads:200});C.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=J51(j,z),_=Boolean(R||Z.headless);if(_)C.info("DTW mode enabled: thread sync service disabled");let T=_?xx3():xt1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;w$.status.subscribe((a)=>{u=a});let m=new iA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:a8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){C.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return C.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new co0,k=process.env.PLUGINS??"off",f=Z.headless?HT4():void 0,d=f??new wX0({configService:X}),p=d instanceof wX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=eT0({configService:X,fileSystem:a8,platform:d,internalPlugins:kn4,pluginFilter:k}),n=ta1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:w,trustStore:H,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:a8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:z,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())C.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of N.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function fx3(J){if(!J.executeMode){if(!await HX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return e6.write(`Login cancelled. Run the command again to retry.
|
|
7610
7610
|
`),!1}return await yn4(J)}async function yn4(J){let Z=In4(32).toString("hex"),Q=await Fv(J.ampURL,Z),Y=new AbortController;try{await AV(Q,Y.signal)}catch(K){C.error("Error opening browser",{error:K})}let X=await Fv(J.ampURL,Z,!1);e6.write(`If your browser does not open automatically, visit:
|
|
7611
7611
|
|
|
@@ -7613,7 +7613,7 @@ ${o0.blue.bold(X)}
|
|
|
7613
7613
|
|
|
7614
7614
|
`);try{return await nC4(J.ampURL,Z,J.secrets,Y),e6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return C.error("Login failed",{error:K}),A2.write(`
|
|
7615
7615
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7616
|
-
`),!1}}function Mn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function ux3(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 bx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function hx3(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(!bx3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function gx3(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 mx3(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 px3(J){let Z=new hw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Dj(),process.exit(0);let w=B.originalError??B;YR4(w)}),od4(Z,{version:"0.0.
|
|
7616
|
+
`),!1}}function Mn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function ux3(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 bx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function hx3(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(!bx3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function gx3(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 mx3(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 px3(J){let Z=new hw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Dj(),process.exit(0);let w=B.originalError??B;YR4(w)}),od4(Z,{version:"0.0.1774945762-g24095c",buildTimestamp:"2026-03-31T08:33:08.299Z",buildType:"'release'"}),Z.addHelpText("after",hI4()),Z.configureHelp({formatHelp:gI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await m3(N);await rx3(L)}),Z.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await m3(N);await ox3(L,await Aa0(N,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,w,N)=>{let L=N.optsWithGlobals(),O=await m3(L);await kR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,w)=>{let N=w.optsWithGlobals(),L=await m3(N);await vR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7617
7617
|
Actions:
|
|
7618
7618
|
create Create a new DTW thread and print its ID
|
|
7619
7619
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7677,8 +7677,8 @@ ${M}
|
|
|
7677
7677
|
|
|
7678
7678
|
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 dx3(J){C.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new rn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:uY,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new mV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw C.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function cx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Dv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Dv()).trimEnd(),stdinInput:null}}function lx3(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"
|
|
7679
7679
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function DF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(G0,J0)=>{let z0=Number(process.hrtime.bigint()-J0)/1e6,i=KO4();C.info("Startup phase",{phase:G0,phaseMs:Math.round(z0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:G}=await cx3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;lx3({...Z,streamJson:z},J.executeMode,V),e7(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;C.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await Q7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await X51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!W&&hW(D)){let G0=nk(Error(D.error.message));if(G0.message===E3.networkOffline||G0.message===E3.networkTimeout)throw UF0(J.ampURL);throw new C1(E3.invalidAPIKey,1)}let B=o6(D)?D:null,w=B?.user.email,N=Sn4(w),L=$51({userEmail:w,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&J51(O,B);if(!W)await e61(Q,Z,D);let M=Z51(D),A=M?.features??[],j=M?.team??null,R=DX0(Z,M);if(R instanceof Error)k3(R.message);if((J.executeMode||z)&&D8(Z.mode)&&!N)throw new C1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!XE(Z.mode,w))throw new C1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await wT4(V,G,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!w||!dJ(w))throw new C1("Headless DTW mode is only available for Amp employees",1);let G0=await U.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new C1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new C1(`Invalid thread ID: ${J0}`,1);let z0=J0?void 0:await Xf3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??z0?.threadId;if(!i)throw new C1("Failed to resolve headless thread ID",1);let o=await GI4(i);if(o.status==="already-running")await U.asyncDispose(),await GH(),process.exit(0);try{await JI4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:z0?.ownerUserId,threadVersion:z0?.threadVersion,agentMode:z0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await GH(),process.exit(0)}let _=J.executeMode?void 0:async(G0)=>Lo(G0,"interactive"),T={threadService:U.threadService,workerDeps:H,createThread:async()=>{let G0=W?await U.serverStatusPromise:D,J0=await sQ0(J.settings,process.cwd(),Z51(G0),R);if(J0 instanceof Error)k3(J0.message);return Qe0(H,{threadMeta:J0?xG(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(G0,J0)=>{if(J0?.nonBlockingOwnershipCheck){An4(G0,U.configService).catch((z0)=>{if(z0 instanceof C1){if(J0.onOwnershipError){J0.onOwnershipError(z0,G0);return}zH(z0,G0);return}C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})});return}try{await An4(G0,U.configService)}catch(z0){if(z0 instanceof C1)throw z0;C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:zH},u=async(G0)=>{try{if(G0==="dtw")return dx3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:wn4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Rf4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof C1)throw J0;throw await zH(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")A2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7680
|
-
`),await GH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await U.configService.getLatest(),J0=au(G0),z0=await c6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(z0.ok)return C.info("User free tier status:",z0),z0.result;return}catch(G0){C.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new et0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await U.serverStatusPromise:U.serverStatus;await e61(Q,Z,G0);let J0=process.hrtime.bigint(),z0=J51(O,G0),i=o6(G0)?$51({userEmail:G0.user.email,features:G0.features}):!1;Nn4({dtwEnabled:z0,hasV2TUIAccess:i});let o=await u(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new C1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let J0=G0 instanceof Error?G0:Error(String(G0));k.setInitError(J0),await zH(G0,Z.threadId)});else F=process.hrtime.bigint(),Nn4({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(),yx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((G0)=>{if(!G0)return k0.of({});return D5(G0.thread$,G0.threadViewState$).pipe(D1(([J0,z0])=>({[J0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){XT4(U.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:U,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},J0=await DR4({threadPool:f,...G0});if(await Lo(J0,"execute"),Z.archive)await c6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await ef1();let G0=await zE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let J0=G0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=da0("0.0.
|
|
7681
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(G)=>{if(G!==rh)return;try{let z=await Cn4(t61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==rh)return;await Pn4(aH.dirname(t61),{recursive:!0}),await Mx3(t61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:xz()});Vf1(Y);let X=await EI4({...J,workspaceTrust:{current:!0,changes:ru},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await QT4(J.mcpConfig);X=YT4(X,G)}let K=aH.dirname(X.getSettingsFilePath());Fq4(Zv,K);let V=await X.get("url","global");if(!V)V=F7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!MV(V))C.info("Targeting custom Amp server",{ampURL:V});return X=sx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:MT4(await Aa0(J,X))}}function ix3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function nx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=aH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Rx3:Cn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ax3(){XO4();let J=ix3(process.argv),Z=nx3(process.argv,J),Q=Dj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Px3(C),C.info("Starting Amp CLI.",{version:"0.0.
|
|
7680
|
+
`),await GH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await U.configService.getLatest(),J0=au(G0),z0=await c6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(z0.ok)return C.info("User free tier status:",z0),z0.result;return}catch(G0){C.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new et0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await U.serverStatusPromise:U.serverStatus;await e61(Q,Z,G0);let J0=process.hrtime.bigint(),z0=J51(O,G0),i=o6(G0)?$51({userEmail:G0.user.email,features:G0.features}):!1;Nn4({dtwEnabled:z0,hasV2TUIAccess:i});let o=await u(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new C1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let J0=G0 instanceof Error?G0:Error(String(G0));k.setInitError(J0),await zH(G0,Z.threadId)});else F=process.hrtime.bigint(),Nn4({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(),yx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((G0)=>{if(!G0)return k0.of({});return D5(G0.thread$,G0.threadViewState$).pipe(D1(([J0,z0])=>({[J0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){XT4(U.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:U,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},J0=await DR4({threadPool:f,...G0});if(await Lo(J0,"execute"),Z.archive)await c6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await ef1();let G0=await zE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let J0=G0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=da0("0.0.1774945762-g24095c",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ro0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await j1(f.threadHandles$);if(!G0)throw new C1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await LX0();K("runMainThread:loadSessionState",F),C.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Pj((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Hu4({codebaseContextService:U.codebaseContextService,history:new Xa0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:c6,threadPool:f,createSystemPromptDeps:async()=>vn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:wn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-31T08:33:08.299Z"},(G0)=>new Be0({...G0,threadPool:G0.threadPool},(J0)=>new j41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function m3(J){if(C.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)A2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7681
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await za1({get:async(G)=>{if(G!==rh)return;try{let z=await Cn4(t61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==rh)return;await Pn4(aH.dirname(t61),{recursive:!0}),await Mx3(t61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:xz()});Vf1(Y);let X=await EI4({...J,workspaceTrust:{current:!0,changes:ru},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await QT4(J.mcpConfig);X=YT4(X,G)}let K=aH.dirname(X.getSettingsFilePath());Fq4(Zv,K);let V=await X.get("url","global");if(!V)V=F7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!MV(V))C.info("Targeting custom Amp server",{ampURL:V});return X=sx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:MT4(await Aa0(J,X))}}function ix3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function nx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=aH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Rx3:Cn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ax3(){XO4();let J=ix3(process.argv),Z=nx3(process.argv,J),Q=Dj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(Px3(C),C.info("Starting Amp CLI.",{version:"0.0.1774945762-g24095c",buildTimestamp:"2026-03-31T08:33:08.299Z"}),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 px3(Q).parseAsync(process.argv)}Gq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ax3().catch(zH)});async function ox3(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"),e6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7682
7682
|
`);else if(!MV(J.ampURL))e6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7683
7683
|
`);let Y=process.env.AMP_API_KEY;if(Y)e6.write(`API key found in environment variable, storing...
|
|
7684
7684
|
`),await Z.set("apiKey",Y,J.ampURL),e6.write(`API key successfully stored.
|