@sourcegraph/amp 0.0.1775174787-g17eb31 → 0.0.1775191387-gd1bef3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6222,11 +6222,11 @@ ${D}`))}},error:(H)=>{if(!W)W=!0,F(Error(`Failed to spawn brew: ${H.message}`))}
|
|
|
6222
6222
|
${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))U+=`
|
|
6223
6223
|
|
|
6224
6224
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6225
|
-
npm install -g @sourcegraph/amp`;F(Error(U))}},error:(H)=>{if(!q)q=!0,F(Error(`Failed to spawn ${X}: ${H.message}`))},complete:()=>{if(!q)q=!0,V()}})})}c0();c0();eM();async function hY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let F=await fetch(X,{signal:K.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await F.json(),G=z.version??z["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=VP4(J,G),W=q<0,H,D;if(z.time){let U=z.time[J],B=z.time[G],w=Date.now();if(U)H=Math.floor((w-new Date(U).getTime())/3600000);if(B)D=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:D}),{hasUpdate:W,latestVersion:G,currentVersion:J,currentVersionAge:H,latestVersionAge:D,source:"npm"}}catch(F){return C.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var CZ3="https://static.ampcode.com/cli/cli-version.txt";async function gY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${CZ3}?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=VP4(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 TZ3=604800000;function KP4(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>TZ3)return{ageMs:Q};return null}function VP4(J,Z){let Q=(V)=>{let[F,z]=V.split("-");return{parts:F?.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 F=Y.parts[V]||0,z=X.parts[V]||0;if(F<z)return-1;if(F>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 ga0(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?fG(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function ma0(J,Z,Q={}){let Y=new z4,X=Y.pipe(g6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new uz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await xG(V);let F=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 xG(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 G=await Z.get("updates.mode");if(G==="disabled"){K.debug("checking disabled");return}let q=await bY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:G,packageManager:q,isBinaryDistribution:W});let H=W?await gY0(J):await hY0(J,fj());if(!(H.latestVersion&&H.hasUpdate)){K.debug("no update available");return}let D=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let U=H.currentVersionAge-H.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!G)G=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:G});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ya0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(G==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await ki(H.latestVersion,q);let U=await TN(H.latestVersion),B={from:H.currentVersion,to:H.latestVersion,...U};if(U.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await xG(5000),Y.next("hidden"),F.unsubscribe(),Y.complete()}}),{state:X}}eM();import{stderr as Cq}from"node:process";function FP4(J){let Z=new ow().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 Ca0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6225
|
+
npm install -g @sourcegraph/amp`;F(Error(U))}},error:(H)=>{if(!q)q=!0,F(Error(`Failed to spawn ${X}: ${H.message}`))},complete:()=>{if(!q)q=!0,V()}})})}c0();c0();eM();async function hY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let F=await fetch(X,{signal:K.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await F.json(),G=z.version??z["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=VP4(J,G),W=q<0,H,D;if(z.time){let U=z.time[J],B=z.time[G],w=Date.now();if(U)H=Math.floor((w-new Date(U).getTime())/3600000);if(B)D=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:D}),{hasUpdate:W,latestVersion:G,currentVersion:J,currentVersionAge:H,latestVersionAge:D,source:"npm"}}catch(F){return C.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var CZ3="https://static.ampcode.com/cli/cli-version.txt";async function gY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${CZ3}?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=VP4(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 TZ3=604800000;function KP4(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>TZ3)return{ageMs:Q};return null}function VP4(J,Z){let Q=(V)=>{let[F,z]=V.split("-");return{parts:F?.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 F=Y.parts[V]||0,z=X.parts[V]||0;if(F<z)return-1;if(F>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 ga0(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?fG(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function ma0(J,Z,Q={}){let Y=new z4,X=Y.pipe(g6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new uz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await xG(V);let F=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 xG(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 G=await Z.get("updates.mode");if(G==="disabled"){K.debug("checking disabled");return}let q=await bY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:G,packageManager:q,isBinaryDistribution:W});let H=W?await gY0(J):await hY0(J,fj());if(!(H.latestVersion&&H.hasUpdate)){K.debug("no update available");return}let D=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let U=H.currentVersionAge-H.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!G)G=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:G});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ya0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(G==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await ki(H.latestVersion,q);let U=await TN(H.latestVersion),B={from:H.currentVersion,to:H.latestVersion,...U};if(U.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await xG(5000),Y.next("hidden"),F.unsubscribe(),Y.complete()}}),{state:X}}eM();import{stderr as Cq}from"node:process";function FP4(J){let Z=new ow().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 Ca0(Y.force||!1,Y.verbose||!1,"0.0.1775191387-gd1bef3"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new ow("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 _Z3(Y.targetVersion)});J.addCommand(Q)}async function _Z3(J){let Q=process.platform==="win32"&&xj()?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Cq.write(p0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6226
6226
|
|
|
6227
6227
|
`));try{if(!J){Cq.write(p0.blue(`Checking for updates...
|
|
6228
|
-
`));let{hasUpdate:K,latestVersion:V}=xj()?await gY0("0.0.
|
|
6229
|
-
`));let G=await TN("0.0.
|
|
6228
|
+
`));let{hasUpdate:K,latestVersion:V}=xj()?await gY0("0.0.1775191387-gd1bef3"):await hY0("0.0.1775191387-gd1bef3",fj());if(!K){let F=ga0("0.0.1775191387-gd1bef3"),z=F?.age?`released ${F.age} ago`:`built ${fG(new Date("2026-04-03T04:46:44.547Z"))} ago`;Cq.write(p0.green(`✓ Amp is already up to date on version ${"0.0.1775191387-gd1bef3"} (${z})
|
|
6229
|
+
`));let G=await TN("0.0.1775191387-gd1bef3",Q);if(G.warning)Cq.write(`
|
|
6230
6230
|
`+p0.yellow(G.warning)+`
|
|
6231
6231
|
`);process.exit(0)}if(!V)Cq.write(p0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}Cq.write(p0.blue(`Updating to version ${J}...
|
|
6232
6232
|
`)),await ki(J,void 0,(K)=>{Cq.write(p0.dim(`Running: ${K}
|
|
@@ -7419,7 +7419,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
|
|
|
7419
7419
|
`),K=[];for(let V=0;V<X.length;V++){let G=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 G)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new P(q.slice(1,-1),new m({color:Y.app.keybind,bold:!0})));else K.push(new P(q,new m({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new P(`
|
|
7420
7420
|
`))}return new l0({decoration:{color:Q.colorScheme.background,border:Y4.all(new V4(Y.app.keybind,1,"rounded"))},child:new d0({padding:C0.symmetric(0,1),child:new J0({text:new P(void 0,void 0,K)})})})}}class E01 extends T${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=SF0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new L01({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 ih4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let F=Q;return F>=0&&F<K?F:null}case"bar":case"stacked-bar":{let F=V?R9:0,z=Y-F;if(z<=0)return null;let G=Z-F;if(G<0||G>=z)return null;let q=Math.max(1,Math.floor(z/K)),W=Math.floor(G/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let F=V?R9:0,z=Y-F;if(z<=0)return null;let G=Math.max(0,Math.min(z-1,Z-F));if(K===1)return 0;let q=z/(K-1),W=Math.round(G/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function xI3(J,Z,Q,Y,X,K,V,F){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 G=K?R9:0,q=Q-G,W=Y-(K?z:0);if(q<=0||W<=0)return null;let H=Math.max(1,Math.floor(q/X)),D=G+Z*H+Math.floor(H/2),U=F>0?V/F:0,B=Math.round((1-U)*(W-1));return{x:D,y:B}}case"line":case"sparkline":case"stacked-area":{let G=K?R9:0,q=Q-G,W=Y-(K?z:0);if(q<=0||W<=0)return null;let H=X>1?G+Math.round(Z/(X-1)*(q-1)):G+Math.floor(q/2),D=F>0?V/F:0,U=Math.round((1-D)*(W-1));return{x:H,y:U}}default:return null}}function fI3(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 uI3(J,Z,Q,Y,X){if(Q.length<=1){let F=Y(J.value),z=J.meta?` (${J.meta})`:"";return J.label.length+2+F.length+z.length}let K=J.label.length,V=0;for(let F of Q){let z=F.points[Z];if(!z)continue;V+=z.value;let G=2+F.name.length+2+Y(z.value).length;K=Math.max(K,G)}if(X){let F=9+Y(V).length;K=Math.max(K,F)}return K}function bI3(J,Z,Q,Y,X,K,V){let F;try{let U=h1.of(J),B=u0.of(J);F={foreground:U.colorScheme.foreground,background:U.colorScheme.background,border:B.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let z=new m({color:F.foreground,bold:!0}),G=new m({color:F.foreground}),q=new m({color:F.foreground,dim:!0}),W=[],H=new m({color:F.foreground,underline:!0}),D=(U,B)=>new P(B,H,void 0,lY0(U),()=>{m3(J,U)});if(Y.length<=1){if(W.push(new P(`${Z.label}: `,z)),Z.link)W.push(D(Z.link,K(Z.value)));else W.push(new P(K(Z.value),G));if(Z.meta)W.push(new P(` (${Z.meta})`,q))}else{let U=V==="stacked-bar"||V==="stacked-area";W.push(new P(`${Z.label}
|
|
7421
7421
|
`,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]??F.foreground;if(W.push(new P("● ",new m({color:O}))),W.push(new P(`${N.name}: `,q)),L.link)W.push(D(L.link,K(L.value)));else W.push(new P(K(L.value),G));if(w<Y.length-1||U)W.push(new P(`
|
|
7422
|
-
`))}if(U)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),G))}return new l0({decoration:{color:F.background,border:Y4.all(new V4(F.border,1,"rounded"))},child:new J0({text:new P(void 0,void 0,W)})})}aU();c0();J7();NE();H$();S3();R2();Md();kX();rZ();YY();$Q();SA();p4();mg();mP();O1();c0();rZ();class M01{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.1775174787-g17eb31"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await N40(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 EL extends a0{props;constructor(J){super();this.props=J}createState(){return new nh4}}class nh4 extends n0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class ah4 extends n0{controller=new l7;focusNode=new w6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,F=Y4.all(new V4(Q.foreground,1,"solid")),z=new sY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let U=D.trim();if(X&&U.length===0)return;this.widget.props.onSubmit(U)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),G=new N1({children:[new l0({decoration:{color:Q.background},child:new J0({text:new P(">",new m({color:Q.foreground}))})}),new p1({child:z})]}),q=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P("",void 0,[new P("Command: ",new m({color:Q.foreground})),new P(this.widget.props.commandName,new m({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new m({color:Y.keybind}))),W.push(new P(" to submit, ",new m({color:Q.foreground,dim:!0})));W.push(new P("Esc",new m({color:Y.keybind}))),W.push(new P(" to cancel",new m({color:Q.foreground,dim:!0})));let H=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P("",void 0,W)})});return new l0({decoration:{border:F,color:Q.background},padding:C0.all(1),child:new b0({children:[q,new I0({height:1}),G,new v3,H]})})}}class _a extends a0{props;constructor(J){super();this.props=J}createState(){return new ah4}}$Q();class oh4 extends n0{controller=new l7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new w6({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>=vV)return!1;let Z=await nN(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,K=w4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),F=new cF({controller:this.controller,triggers:[new hq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:Y6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new V6({focusNode:this.focusNode,child:F}),G=new l0({constraints:new P1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P("",void 0,[new P("Command: ",new m({color:Q.foreground})),new P(this.widget.props.commandName,new m({color:Y.command,bold:!0}))])})}),W=new l0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new m({color:Y.keybind})),new P(" again to clear input",new m({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new m({color:Q.foreground,dim:!0})),new P("Enter",new m({color:Y.keybind})),new P(" to submit, ",new m({color:Q.foreground,dim:!0})),new P("Esc",new m({color:Y.keybind})),new P(" to clear",new m({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new p1({child:G}),new I0({height:1}),W];return new l0({decoration:{border:Y4.all(new V4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new b0({children:H})})}}class A01 extends a0{props;constructor(J){super();this.props=J}createState(){return new oh4}}import{isDeepStrictEqual as j01}from"node:util";var hI3=/[\\/_ +.#"@[({&]/,gI3=/[\\/_ +.#"@[({&]/g,mI3=/[\s-]/,rh4=/[\s-]/g;function yF0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let F=`${X},${K}`;if(V[F]!==void 0)return V[F];let z=Y.charAt(K),G=Q.indexOf(z,X),q=0,W,H,D,U;while(G>=0){if(W=yF0(J,Z,Q,Y,G+1,K+1,V),W>q){if(G===X)W*=1;else if(mI3.test(J.charAt(G-1))){if(W*=0.9,U=J.slice(X,G-1).match(rh4),U&&X>0)W*=0.999**U.length}else if(hI3.test(J.charAt(G-1))){if(W*=0.8,D=J.slice(X,G-1).match(gI3),D&&X>0)W*=0.999**D.length}else if(W*=0.3,X>0)W*=0.999**(G-X);if(J.charAt(G)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(G-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(G-1)!==Y.charAt(K))){if(H=yF0(J,Z,Q,Y,G+1,K+2,V),H*0.1>W)W=H*0.1}if(W>q)q=W;G=Q.indexOf(z,G+1)}return V[F]=q,q}function vF0(J){return J.toLowerCase().replace(rh4," ")}function sh4(J,Z){let Q=yF0(J,Z,vF0(J),vF0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let F of Y){let z=yF0(J,F,vF0(J),vF0(F),0,0,{});if(z===0)return Q;X+=z,K+=F.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Py{}class Cy{}class xF0{}class fF0{}class th4 extends a0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new eh4}}class eh4 extends n0{build(J){return this.widget.onContext(J),this.widget.child}}function pI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=sh4(Z,J);return{matches:Q>0.15,score:Q}}class i9 extends a0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new $g4}}class $g4 extends n0{textController;focusNode;scrollController=new i5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new l7(this.widget.props.controller?.query??""),this.focusNode=new w6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y5.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)=>j01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!j01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>j01(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 Py){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),Y5.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Cy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),Y5.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof xF0){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 fF0)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,...pI3(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;kX0(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(),Y5.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=Y4.all(new V4(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,F=new sY({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new LZ({shortcuts:new Map([[new v4("ArrowDown"),new Py],[new v4("ArrowUp"),new Cy],[new v4("Tab"),new Py],[new v4("Tab",{shift:!0}),new Cy],[new v4("n",{ctrl:!0}),new Py],[new v4("p",{ctrl:!0}),new Cy],[new v4("Enter"),new xF0],[new v4("Escape"),new fF0]]),focusNode:this.focusNode,child:F}),G=new H2({actions:new Map([[Py,new T6(this.invoke)],[Cy,new T6(this.invoke)],[xF0,new T6(this.invoke)],[fF0,new T6(this.invoke)]]),child:z}),q=new N1({children:[new l0({decoration:{color:Q.background},child:new J0({text:new P(">",new m({color:Q.foreground}))})}),new p1({child:G})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new X4({child:new J0({text:new P(w,new m({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new p1({child:new X4({child:new J0({text:new P(this.widget.props.emptyStateText,new m({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 l0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new P(this.widget.props.getLabel(N),new m({color:j,dim:E}))})})}return new th4(new G4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new b0({children:w,crossAxisAlignment:"start"})}let H=new G4({onScroll:this.handleScroll,opaque:!1,child:new b6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let w=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P(this.widget.props.title,new m({color:Z.app.command,bold:!0}))})});D.push(w)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);D.push(new p1({child:new b0({mainAxisAlignment:"spaceBetween",children:[new p1({child:H}),new l0({padding:C0.only({top:1}),child:new X4({child:N??new I0({height:1})})})]})}))}else D.push(new p1({child:H}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new l0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new b0({children:D})})}}function Jg4(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 R01 extends $4{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)=>Jg4(X.pubDate).length));return new i9({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,F)=>{let z=u0.of(F),{colors:G}=z,q=z.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:G.foreground,D=G.mutedForeground,U=(B,w)=>new I0({width:w,child:N1.end([new J0({text:new P(B,new m({color:D}))})])});return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[new p1({child:new J0({text:new P(X.title,new m({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),U(Jg4(X.pubDate),Q)]})})}})}}HE();class I01 extends a0{createState(){return new Zg4}}class Zg4 extends n0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=u0.of(J).colors;return new J0({text:new P("●",new m({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function dI3(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 F=V.relationships.find((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(F){Y.set(V.id,F.type);let z=F.threadID,G=Q.get(z)||[];G.push(V),Q.set(z,G)}else X.push(V)}return MV0.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 P01(J,Z,Q){return new J0({text:new P(`${J}${Z}`,new m({color:Q})),maxLines:1})}function cI3(J,Z,Q,Y){return[P01("+",J,Y.success),v3.horizontal(1),P01("~",Z,Y.warning),v3.horizontal(1),P01("-",Q,Y.destructive)]}function lI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class uF0 extends a0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Qg4}}class Qg4 extends n0{spinner=new L5;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||[],F=new Set(V),z=Z.currentThreadID,G=[...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=dI3(G),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=u0.of(J),D=new d0({padding:C0.symmetric(0,1),child:new X4({child:new J0({text:new P("",new m({color:H.colors.foreground,dim:!0}),[new P("Alt+W/Ctrl+T",new m({color:H.colors.primary,dim:!0})),new P(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new m({color:H.colors.foreground,dim:!0}))])})})}),U="",B=null,w=(L)=>{if(L!==U)U=L,B=R7(L);return B};return new i9({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(!lI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:D,renderItem:(L,O,E,M)=>{let A=u0.of(M),{app:j,colors:I}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,H0)=>new I0({width:H0,child:N1.end([new J0({text:new P(s,new m({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new Na({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],H0=L.ancestorsAreLast.slice(1);for(let L0 of H0)s.push(new P(d.getAncestorPrefix(L0),new m({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,q0=d.getConnectorText(r);s.push(new P(q0,new m({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new P("",void 0,s)}))}let g=[],b=z===L.id?new P("(current) ",new m({color:I.success})):F.has(L.id)?new P("(visited) ",new m({color:I.foreground,dim:!0})):null;if(b)g.push(new J0({text:b}));if(tM(x))g.push(new I01),g.push(new I0({width:1}));let i=L.title;if(L.relationshipType==="fork"){let s=i.match(/^Forked\((\d+)\): /);if(s)i=i.slice(s[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);g.push(new J0({text:new P("[fork] ",new m({color:I.primary}))}))}else if(f)g.push(new J0({text:new P("[handoff] ",new m({color:I.accent}))}));if(g.push(new p1({child:new J0({text:new P(i,new m({color:S})),overflow:"ellipsis",maxLines:1})})),g.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;g.push(...cI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),g.push(new I0({width:2}))}return g.push(p(L.description.timeAgo,W)),new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[...k,...g]})})}})}}c0();class oK{message;constructor(J){this.message=J}}class N7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function bF0(J){if(J instanceof oK)return{title:"Info",description:J.message,type:"info"};return C.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}c0();oQ();eM();kX();rZ();p4();U4();mP();var T01=D4(WH(),1);import{execSync as _R}from"node:child_process";import{writeFile as Ty}from"node:fs/promises";import iI3 from"node:os";import oq from"node:path";var Yg4="c446b2e9b16cdc06df2ec285894d6421",nI3="5ea19563777f4ade8707fc56f7e7a388",aI3="amp-thread-worker",Xg4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function oI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function AL(J){if(!J||!oI3(J.meta))return!1;return J.meta.usesDtw===!0}function _01(J){let Z=new URL(`https://dash.cloudflare.com/${Yg4}/workers/durable-objects/view/${nI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function S01(J){let Z=new URL(`https://dash.cloudflare.com/${Yg4}/workers/services/view/${aI3}/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 rI3(J,Z){if(uW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function k01(J,Z){let Q=rI3(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 Sa(J,Z,Q){let Y=`select(.pid == ${Z})`,X=ka(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function ka(J){return J.path??_9(J.uri)}function Kg4(J,Z,Q){let Y=Sa("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Vg4(J,Z){return k01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7422
|
+
`))}if(U)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),G))}return new l0({decoration:{color:F.background,border:Y4.all(new V4(F.border,1,"rounded"))},child:new J0({text:new P(void 0,void 0,W)})})}aU();c0();J7();NE();H$();S3();R2();Md();kX();rZ();YY();$Q();SA();p4();mg();mP();O1();c0();rZ();class M01{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.1775191387-gd1bef3"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await N40(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 EL extends a0{props;constructor(J){super();this.props=J}createState(){return new nh4}}class nh4 extends n0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class ah4 extends n0{controller=new l7;focusNode=new w6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,F=Y4.all(new V4(Q.foreground,1,"solid")),z=new sY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let U=D.trim();if(X&&U.length===0)return;this.widget.props.onSubmit(U)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),G=new N1({children:[new l0({decoration:{color:Q.background},child:new J0({text:new P(">",new m({color:Q.foreground}))})}),new p1({child:z})]}),q=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P("",void 0,[new P("Command: ",new m({color:Q.foreground})),new P(this.widget.props.commandName,new m({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new m({color:Y.keybind}))),W.push(new P(" to submit, ",new m({color:Q.foreground,dim:!0})));W.push(new P("Esc",new m({color:Y.keybind}))),W.push(new P(" to cancel",new m({color:Q.foreground,dim:!0})));let H=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P("",void 0,W)})});return new l0({decoration:{border:F,color:Q.background},padding:C0.all(1),child:new b0({children:[q,new I0({height:1}),G,new v3,H]})})}}class _a extends a0{props;constructor(J){super();this.props=J}createState(){return new ah4}}$Q();class oh4 extends n0{controller=new l7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new w6({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>=vV)return!1;let Z=await nN(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,K=w4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),F=new cF({controller:this.controller,triggers:[new hq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:Y6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new V6({focusNode:this.focusNode,child:F}),G=new l0({constraints:new P1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P("",void 0,[new P("Command: ",new m({color:Q.foreground})),new P(this.widget.props.commandName,new m({color:Y.command,bold:!0}))])})}),W=new l0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new m({color:Y.keybind})),new P(" again to clear input",new m({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new m({color:Q.foreground,dim:!0})),new P("Enter",new m({color:Y.keybind})),new P(" to submit, ",new m({color:Q.foreground,dim:!0})),new P("Esc",new m({color:Y.keybind})),new P(" to clear",new m({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new p1({child:G}),new I0({height:1}),W];return new l0({decoration:{border:Y4.all(new V4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new b0({children:H})})}}class A01 extends a0{props;constructor(J){super();this.props=J}createState(){return new oh4}}import{isDeepStrictEqual as j01}from"node:util";var hI3=/[\\/_ +.#"@[({&]/,gI3=/[\\/_ +.#"@[({&]/g,mI3=/[\s-]/,rh4=/[\s-]/g;function yF0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let F=`${X},${K}`;if(V[F]!==void 0)return V[F];let z=Y.charAt(K),G=Q.indexOf(z,X),q=0,W,H,D,U;while(G>=0){if(W=yF0(J,Z,Q,Y,G+1,K+1,V),W>q){if(G===X)W*=1;else if(mI3.test(J.charAt(G-1))){if(W*=0.9,U=J.slice(X,G-1).match(rh4),U&&X>0)W*=0.999**U.length}else if(hI3.test(J.charAt(G-1))){if(W*=0.8,D=J.slice(X,G-1).match(gI3),D&&X>0)W*=0.999**D.length}else if(W*=0.3,X>0)W*=0.999**(G-X);if(J.charAt(G)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(G-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(G-1)!==Y.charAt(K))){if(H=yF0(J,Z,Q,Y,G+1,K+2,V),H*0.1>W)W=H*0.1}if(W>q)q=W;G=Q.indexOf(z,G+1)}return V[F]=q,q}function vF0(J){return J.toLowerCase().replace(rh4," ")}function sh4(J,Z){let Q=yF0(J,Z,vF0(J),vF0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let F of Y){let z=yF0(J,F,vF0(J),vF0(F),0,0,{});if(z===0)return Q;X+=z,K+=F.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Py{}class Cy{}class xF0{}class fF0{}class th4 extends a0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new eh4}}class eh4 extends n0{build(J){return this.widget.onContext(J),this.widget.child}}function pI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=sh4(Z,J);return{matches:Q>0.15,score:Q}}class i9 extends a0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new $g4}}class $g4 extends n0{textController;focusNode;scrollController=new i5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new l7(this.widget.props.controller?.query??""),this.focusNode=new w6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y5.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)=>j01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!j01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>j01(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 Py){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),Y5.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Cy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),Y5.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof xF0){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 fF0)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,...pI3(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;kX0(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(),Y5.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=Y4.all(new V4(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,F=new sY({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new LZ({shortcuts:new Map([[new v4("ArrowDown"),new Py],[new v4("ArrowUp"),new Cy],[new v4("Tab"),new Py],[new v4("Tab",{shift:!0}),new Cy],[new v4("n",{ctrl:!0}),new Py],[new v4("p",{ctrl:!0}),new Cy],[new v4("Enter"),new xF0],[new v4("Escape"),new fF0]]),focusNode:this.focusNode,child:F}),G=new H2({actions:new Map([[Py,new T6(this.invoke)],[Cy,new T6(this.invoke)],[xF0,new T6(this.invoke)],[fF0,new T6(this.invoke)]]),child:z}),q=new N1({children:[new l0({decoration:{color:Q.background},child:new J0({text:new P(">",new m({color:Q.foreground}))})}),new p1({child:G})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new X4({child:new J0({text:new P(w,new m({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new p1({child:new X4({child:new J0({text:new P(this.widget.props.emptyStateText,new m({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 l0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new P(this.widget.props.getLabel(N),new m({color:j,dim:E}))})})}return new th4(new G4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new b0({children:w,crossAxisAlignment:"start"})}let H=new G4({onScroll:this.handleScroll,opaque:!1,child:new b6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let w=new l0({padding:C0.symmetric(1,0),child:new J0({text:new P(this.widget.props.title,new m({color:Z.app.command,bold:!0}))})});D.push(w)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);D.push(new p1({child:new b0({mainAxisAlignment:"spaceBetween",children:[new p1({child:H}),new l0({padding:C0.only({top:1}),child:new X4({child:N??new I0({height:1})})})]})}))}else D.push(new p1({child:H}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new l0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new b0({children:D})})}}function Jg4(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 R01 extends $4{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)=>Jg4(X.pubDate).length));return new i9({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,F)=>{let z=u0.of(F),{colors:G}=z,q=z.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:G.foreground,D=G.mutedForeground,U=(B,w)=>new I0({width:w,child:N1.end([new J0({text:new P(B,new m({color:D}))})])});return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[new p1({child:new J0({text:new P(X.title,new m({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),U(Jg4(X.pubDate),Q)]})})}})}}HE();class I01 extends a0{createState(){return new Zg4}}class Zg4 extends n0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=u0.of(J).colors;return new J0({text:new P("●",new m({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function dI3(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 F=V.relationships.find((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(F){Y.set(V.id,F.type);let z=F.threadID,G=Q.get(z)||[];G.push(V),Q.set(z,G)}else X.push(V)}return MV0.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 P01(J,Z,Q){return new J0({text:new P(`${J}${Z}`,new m({color:Q})),maxLines:1})}function cI3(J,Z,Q,Y){return[P01("+",J,Y.success),v3.horizontal(1),P01("~",Z,Y.warning),v3.horizontal(1),P01("-",Q,Y.destructive)]}function lI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class uF0 extends a0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Qg4}}class Qg4 extends n0{spinner=new L5;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||[],F=new Set(V),z=Z.currentThreadID,G=[...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=dI3(G),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=u0.of(J),D=new d0({padding:C0.symmetric(0,1),child:new X4({child:new J0({text:new P("",new m({color:H.colors.foreground,dim:!0}),[new P("Alt+W/Ctrl+T",new m({color:H.colors.primary,dim:!0})),new P(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new m({color:H.colors.foreground,dim:!0}))])})})}),U="",B=null,w=(L)=>{if(L!==U)U=L,B=R7(L);return B};return new i9({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(!lI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:D,renderItem:(L,O,E,M)=>{let A=u0.of(M),{app:j,colors:I}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,H0)=>new I0({width:H0,child:N1.end([new J0({text:new P(s,new m({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new Na({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],H0=L.ancestorsAreLast.slice(1);for(let L0 of H0)s.push(new P(d.getAncestorPrefix(L0),new m({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,q0=d.getConnectorText(r);s.push(new P(q0,new m({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new P("",void 0,s)}))}let g=[],b=z===L.id?new P("(current) ",new m({color:I.success})):F.has(L.id)?new P("(visited) ",new m({color:I.foreground,dim:!0})):null;if(b)g.push(new J0({text:b}));if(tM(x))g.push(new I01),g.push(new I0({width:1}));let i=L.title;if(L.relationshipType==="fork"){let s=i.match(/^Forked\((\d+)\): /);if(s)i=i.slice(s[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);g.push(new J0({text:new P("[fork] ",new m({color:I.primary}))}))}else if(f)g.push(new J0({text:new P("[handoff] ",new m({color:I.accent}))}));if(g.push(new p1({child:new J0({text:new P(i,new m({color:S})),overflow:"ellipsis",maxLines:1})})),g.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;g.push(...cI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),g.push(new I0({width:2}))}return g.push(p(L.description.timeAgo,W)),new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[...k,...g]})})}})}}c0();class oK{message;constructor(J){this.message=J}}class N7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function bF0(J){if(J instanceof oK)return{title:"Info",description:J.message,type:"info"};return C.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}c0();oQ();eM();kX();rZ();p4();U4();mP();var T01=D4(WH(),1);import{execSync as _R}from"node:child_process";import{writeFile as Ty}from"node:fs/promises";import iI3 from"node:os";import oq from"node:path";var Yg4="c446b2e9b16cdc06df2ec285894d6421",nI3="5ea19563777f4ade8707fc56f7e7a388",aI3="amp-thread-worker",Xg4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function oI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function AL(J){if(!J||!oI3(J.meta))return!1;return J.meta.usesDtw===!0}function _01(J){let Z=new URL(`https://dash.cloudflare.com/${Yg4}/workers/durable-objects/view/${nI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function S01(J){let Z=new URL(`https://dash.cloudflare.com/${Yg4}/workers/services/view/${aI3}/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 rI3(J,Z){if(uW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function k01(J,Z){let Q=rI3(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 Sa(J,Z,Q){let Y=`select(.pid == ${Z})`,X=ka(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function ka(J){return J.path??_9(J.uri)}function Kg4(J,Z,Q){let Y=Sa("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Vg4(J,Z){return k01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7423
7423
|
${Y}`).join(`
|
|
7424
7424
|
|
|
7425
7425
|
`)}function C01(J){if(J===void 0||!Number.isFinite(J)||J<=0)return"n/a";return`${fG(J)} ago (\`${new Date(J).toISOString()}\`)`}function sI3(J){if(!J)return"n/a";let Z=Date.parse(J);if(!Number.isFinite(Z))return`\`${J}\``;return C01(Z)}function ML(J){if(J===void 0||J===null)return"n/a";return`\`${String(J)}\``}function hF0(J,Z="#"){let{thread:Q,threadViewState:Y}=J,X=(V)=>`${Z} ${V}`,K=[X("Thread"),`- ID: \`${Q.id}\``,`- Title: ${H10(Q)}`,`- URL: \`${tW(new URL(J.ampURL),Q.id).toString()}\``,`- Created: ${C01(Q.created)}`,`- Agent mode: ${ML(Q.agentMode)}`,`- Effective mode: \`${J.effectiveAgentMode}\``,`- DTW backed: ${AL(Q)?"yes":"no"}`,`- Executor type: ${ML(Q.meta?.executorType)}`,`- Messages: \`${Q.messages.length}\` total / \`${F8(Q)}\` human / \`${Q.queuedMessages?.length??0}\` queued`];if(Q.meta?.status!==void 0)K.push(`- Merge status: ${ML(Q.meta.status??"null")}`);if(Q.meta?.lastKnownAgentState)K.push(`- Last known agent state: \`${Q.meta.lastKnownAgentState.state}\` at ${sI3(Q.meta.lastKnownAgentState.updatedAt)}`);if(J.initialTreePath)K.push(`- Initial tree: \`${J.initialTreePath}\``);if(J.currentWorkspacePath)K.push(`- Current workspace: \`${J.currentWorkspacePath}\``);if(K.push("",X("Runtime"),`- Amp URL: \`${uW(J.ampURL)?Z7:J.ampURL}\``,`- Thread pool mode: \`${J.threadPoolIsDTW?"dtw":"worker"}\``,`- Connection state: ${ML(J.transportState)}`,`- Connection role: ${ML(J.transportRole)}`,`- Processing: ${J.isProcessing?"yes":"no"}`,`- PID: ${ML(J.pid)}`,`- Client ID: ${ML(J.clientId)}`),J.logFile)K.push(`- Log file: \`${ka(J.logFile)}\``);if(!Y)return K.push("",X("View State"),"- No live thread view state available."),K.join(`
|
|
@@ -7640,7 +7640,7 @@ ${t.content||""}`:t.content||"",T0=[],r0=t.baseDir.startsWith("file://")?Oz0(t.b
|
|
|
7640
7640
|
`),process.exit(1)}process.stdout.write(await uS3(z.result.displayText)+`
|
|
7641
7641
|
`),process.exit(0)})}eM();import{stdout as bS3}from"node:process";function hS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${fG(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function bd4(J){bS3.write(`${hS3(J)}
|
|
7642
7642
|
`)}function hd4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{bd4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{bd4(Z),process.exit(0)})}var Xf3=KU.join(_X,"logs","headless.log"),e61=KU.join(Bv,"device-id.json"),Vn4=`cli-tui-${Bn4(16).toString("hex")}`;async function Kf3(){for(let J of OE)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(() => D4(Zx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){m$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7643
|
-
`)}function Vf3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",F=!1;J.warn(K,{name:V,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")cJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")cJ("experimental.agentMode",Z.mode)}function On4(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 Ff3(J){try{return await Nn4(J,"utf-8")}catch{return J}}async function $51(J,Z,Q){let Y=On4(J,Z);if(!Y)return;let X=P6(Q)?Q.features:[],K=P6(Q)?Q.user.email:void 0;if(!Y51(X,I2.HARNESS_SYSTEM_PROMPT)&&!En4(K))throw new T1("You are not allowed to do this.",1);cJ("systemPrompt",await Ff3(Y))}function En4(J){return!!(J&&v00(J))}function Y51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function J51(J){return(J.userEmail?F$(J.userEmail):!1)||Y51(J.features,I2.DTW_TUI)}function Fn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function Z51(J,Z){if(typeof J==="boolean")return J;if(!P6(Z))return!1;return J51({userEmail:Z.user.email,features:Z.features})}function zf3(J){return J!=="pending"}function Qx(J){if(!P6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Gf3(J){let Z=Qx(J);if(Z)return Z.id;if(YG(J))throw Error(J.error.message);throw Error("unreachable")}function qf3(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 zG0(J){let Y=qf3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function zn4(J){if(!a6.write(J))await Jf3(a6,"drain")}var Gn4=[{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 ${In0})`},{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:c7(),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:az.SMART.key,description:`Set the agent mode (${oz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:oz().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}],qn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Wf3=(J)=>("hidden"in J)&&J.hidden===!0,Hf3=(J)=>("default"in J),Df3=(J)=>("default"in J)?J.default:void 0,Mn4=[{name:"toggle-skills-count",entryPoint:Ue0}];function Uf3(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((F)=>Q.includes(F)||F.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(N3.unknownCommand(Q),1,V)}}async function X51(J){return{...J,getThreadEnvironment:qZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new lV(J.fileSystem),generateThreadTitle:d80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>e$(J.configService),pluginService:J.pluginService}}function An4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:qZ,filesystem:J.fileSystem,threadService:J.threadService}}var GG0=F1.file(Ln4.homedir()),Q51=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(GG0,".config");function Bf3(J){return Jq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){$q4(Z);let Q=PX0(),Y=xo0();if((!Q||Y||CP4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(PD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(PD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(PX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function C9(J,Z,Q){let Y=Q?.deferAuth??!1;Kf1("0.0.
|
|
7643
|
+
`)}function Vf3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",F=!1;J.warn(K,{name:V,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")cJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")cJ("experimental.agentMode",Z.mode)}function On4(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 Ff3(J){try{return await Nn4(J,"utf-8")}catch{return J}}async function $51(J,Z,Q){let Y=On4(J,Z);if(!Y)return;let X=P6(Q)?Q.features:[],K=P6(Q)?Q.user.email:void 0;if(!Y51(X,I2.HARNESS_SYSTEM_PROMPT)&&!En4(K))throw new T1("You are not allowed to do this.",1);cJ("systemPrompt",await Ff3(Y))}function En4(J){return!!(J&&v00(J))}function Y51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function J51(J){return(J.userEmail?F$(J.userEmail):!1)||Y51(J.features,I2.DTW_TUI)}function Fn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function Z51(J,Z){if(typeof J==="boolean")return J;if(!P6(Z))return!1;return J51({userEmail:Z.user.email,features:Z.features})}function zf3(J){return J!=="pending"}function Qx(J){if(!P6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Gf3(J){let Z=Qx(J);if(Z)return Z.id;if(YG(J))throw Error(J.error.message);throw Error("unreachable")}function qf3(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 zG0(J){let Y=qf3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function zn4(J){if(!a6.write(J))await Jf3(a6,"drain")}var Gn4=[{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 ${In0})`},{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:c7(),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:az.SMART.key,description:`Set the agent mode (${oz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:oz().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}],qn4=(J)=>("deprecated"in J)&&J.deprecated===!0,Wf3=(J)=>("hidden"in J)&&J.hidden===!0,Hf3=(J)=>("default"in J),Df3=(J)=>("default"in J)?J.default:void 0,Mn4=[{name:"toggle-skills-count",entryPoint:Ue0}];function Uf3(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((F)=>Q.includes(F)||F.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(N3.unknownCommand(Q),1,V)}}async function X51(J){return{...J,getThreadEnvironment:qZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new lV(J.fileSystem),generateThreadTitle:d80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>e$(J.configService),pluginService:J.pluginService}}function An4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:qZ,filesystem:J.fileSystem,threadService:J.threadService}}var GG0=F1.file(Ln4.homedir()),Q51=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(GG0,".config");function Bf3(J){return Jq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){$q4(Z);let Q=PX0(),Y=xo0();if((!Q||Y||CP4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(PD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(PD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(PX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function C9(J,Z,Q){let Y=Q?.deferAuth??!1;Kf1("0.0.1775191387-gd1bef3");let X=j10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(F1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:GG0,userConfigDir:Q51});cf4(X);let K=await X.getLatest();C.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let g=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(g),C.info("API key lookup before login",{found:Boolean(g),ampURL:J.ampURL,deferAuth:Y}),!g)if(Y)C.info("No API key found, continuing startup with deferred auth");else{a6.write(`No API key found. Starting login flow...
|
|
7644
7644
|
`);let b=await wf3(J),i=await J.secrets.get("apiKey",J.ampURL);if(C.info("Login flow completed",{success:b,storedKeyPresent:Boolean(i),ampURL:J.ampURL}),!b)await ED(),process.exit(1);V=!0}}{let g=await X.getLatest(),b=g.settings.url,i=g.secrets.isSet?.[b];C.info("Config secrets state after login",{configURL:b,apiKeySet:i?.apiKey??!1})}let F=I1(e$(X).pipe(v5(zf3))),z=Y?"pending":await F;if(!Y)C.info("Server status resolved",{status:"ready",isAuthenticated:P6(z),isError:YG(z),errorMessage:YG(z)?z.error.message:void 0});let G=F.then((g)=>Gf3(g)),{toolService:q,dispose:W}=DJ0({configService:X}),H=new Map,D=()=>H.clear(),U=new yT0(X,J.settings.getWorkspaceRootPath()),B=zt1({configService:X,filesystem:I8}),w=Qa1({configService:X,trustStore:U,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(g,b,i)=>{let c=`${g}:${b}`,s=H.get(c);if(s)return C.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:b}),s;C.debug("Creating OAuth provider for server",{serverName:g,serverUrl:b});let H0=(async()=>{let r=new CE(J.secrets),q0=await r.getClientInfo(g,b),L0=i?.scopes??q0?.scopes,D0=rR4();C.info("OAuth headless mode check",{useHeadless:D0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:a6.isTTY});let $0;if(D0)$0=J.executeMode?oR4():aR4(g);let F0=new DR0({storage:r,serverName:g,serverUrl:b,clientId:i?.clientId??q0?.clientId,clientSecret:i?.clientSecret??q0?.clientSecret,authUrl:i?.authUrl??q0?.authUrl,tokenUrl:i?.tokenUrl??q0?.tokenUrl,scopes:L0,headlessAuthHandler:$0});return C.debug("OAuth provider created",{serverName:g,serverUrl:b,hasManualClientId:!!(i?.clientId??q0?.clientId),willUseDCR:!(i?.clientId??q0?.clientId),scopes:L0,headlessMode:D0,executeMode:J.executeMode}),F0})();return H.set(c,H0),H0}}),N=fg0({configService:X,filesystem:I8,spawn:_$0}),L;if(J.executeMode){let g=await JF4({toolService:q,providers:[w,N],initialTimeout:15000});L=g.registrations;for(let[b,i]of g.initErrors)C.warn(`${b} provider initialization slow or failed:`,i)}else L=ug0({toolService:q,providers:[w,N]});if(Z.jetbrains)UE("JetBrains");else if(Z.ide&&vI4())UE("VS Code");else if(Z.ide&&yI4())UE("Neovim");else if(Z.ide){let g=await Kf3();if(g){let b=y10(g.ideName);if(b)UE(b)}}if(J.executeMode)Vf1(!0);let O,E=t$.status.pipe(B1((g)=>Boolean(g.connected&&g.authenticated&&g.ideName&&af1(g.ideName))),f4()).subscribe((g)=>{if(g){if(!O)O=q.registerTool($F4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let g=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new NY0(process.cwd(),{alwaysIncludePaths:g},!0)}else M=new class extends NY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new fS0(Z80(X),{maxThreads:200});C.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=Z51(j,z),_=new Ee0,S=process.env.PLUGINS??"off",h=Z.headless?Cf4():void 0,p=h??new zV0({configService:X}),x=p instanceof zV0?p:void 0;if(x)x.pluginExecutorKind=I?"local":"unknown";let k=rT0({configService:X,fileSystem:I8,platform:p,internalPlugins:Mn4,pluginFilter:S}),f=ta1({pluginService:k,toolService:q}),d={configService:X,toolService:q,mcpService:w,skillService:B,toolboxService:N,trustStore:U,threadService:A,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,fileSystem:I8,terminal:_,pluginService:k,pluginPlatform:x,headlessPluginPlatform:h,serverStatus:z,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:V};return{...d,async asyncDispose(){if(d.mcpService.hasAuthenticatingClients())C.info("Waiting for OAuth authentication to complete before exit..."),await d.mcpService.waitForAuthentication();for(let g of L.values())g.dispose();await d.mcpService.dispose(),D(),await d.threadService.asyncDispose(),d.configService.unsubscribe(),W(),d.fuzzyServer.dispose(),d.settingsStorage[Symbol.dispose](),E.unsubscribe(),O?.dispose(),f.dispose(),await d.pluginService.dispose()}}}async function wf3(J){if(!J.executeMode){if(!await NX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return a6.write(`Login cancelled. Run the command again to retry.
|
|
7645
7645
|
`),!1}return await jn4(J)}async function jn4(J){let Z=Bn4(32).toString("hex"),Q=await Rv(J.ampURL,Z),Y=new AbortController;try{await RV(Q,Y.signal)}catch(K){C.error("Error opening browser",{error:K})}let X=await Rv(J.ampURL,Z,!1);a6.write(`If your browser does not open automatically, visit:
|
|
7646
7646
|
|
|
@@ -7648,7 +7648,7 @@ ${p0.blue.bold(X)}
|
|
|
7648
7648
|
|
|
7649
7649
|
`);try{return await aC4(J.ampURL,Z,J.secrets,Y),a6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return C.error("Login failed",{error:K}),m$.write(`
|
|
7650
7650
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7651
|
-
`),!1}}function Wn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Nf3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!U9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function Lf3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Of3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Lf3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Ef3(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 Mf3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Af3(J){let Z=new ow().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)Pj(),process.exit(0);let w=B.originalError??B;ij4(w)}),hd4(Z,{version:"0.0.
|
|
7651
|
+
`),!1}}function Wn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Nf3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!U9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function Lf3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Of3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Lf3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Ef3(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 Mf3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Af3(J){let Z=new ow().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)Pj(),process.exit(0);let w=B.originalError??B;ij4(w)}),hd4(Z,{version:"0.0.1775191387-gd1bef3",buildTimestamp:"2026-04-03T04:46:44.547Z",buildType:"'release'"}),Z.addHelpText("after",_I4()),Z.configureHelp({formatHelp:SI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await P3(N);await Sf3(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 P3(N);await _f3(L,await ji(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 P3(L);await AR4(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 P3(N);await jR4(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",`
|
|
7652
7652
|
Actions:
|
|
7653
7653
|
create Create a new DTW thread and print its ID
|
|
7654
7654
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7712,8 +7712,8 @@ ${M}
|
|
|
7712
7712
|
|
|
7713
7713
|
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 jf3(J){C.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new La({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:qZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new lV(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 Rf3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Yy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Yy()).trimEnd(),stdinInput:null}}function If3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7714
7714
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function qG0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(D0,$0)=>{let F0=Number(process.hrtime.bigint()-$0)/1e6,n=aL4();C.info("Startup phase",{phase:D0,phaseMs:Math.round(F0),sinceMainMs:n===null?void 0:Math.round(n)})},{userInput:V,stdinInput:F}=await Rf3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;If3({...Z,streamJson:z},J.executeMode,V),O7(Q,Z);let G=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 H=await C9(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let D=await X51(H);K("runMainThread:createWorkerDeps",G);let{serverStatus:U}=H;if(!W&&YG(U)){let D0=Xv(Error(U.error.message));if(D0.message===N3.networkOffline||D0.message===N3.networkTimeout)throw zG0(J.ampURL);throw new T1(N3.invalidAPIKey,1)}let B=P6(U)?U:null,w=B?.user.email,N=En4(w),L=J51({userEmail:w,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&Z51(O,B);if(!W)await $51(Q,Z,U);let M=Qx(U),A=M?.features??[],j=M?.team??null,I=FV0(Z,M);if(I instanceof Error)C3(I.message);if((J.executeMode||z)&&g8(Z.mode)&&!N)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!wE(Z.mode,w))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Sf4(V,F,H.configService),await H.asyncDispose(),process.exit(0);if(Z.headless){if(!w||!F$(w))throw new T1("Headless DTW mode is only available for Amp employees",1);let D0=await H.secretStorage.get("apiKey",J.ampURL);if(!D0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!U9($0))throw new T1(`Invalid thread ID: ${$0}`,1);let F0=$0?void 0:await gf3({dependencies:H,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),n=$0??F0?.threadId;if(!n)throw new T1("Failed to resolve headless thread ID",1);let a=await $I4(n);if(a.status==="already-running")await H.asyncDispose(),await ED(),process.exit(0);try{await iR4({ampURL:J.ampURL,apiKey:D0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:n,ownerUserId:F0?.ownerUserId,threadVersion:F0?.threadVersion,agentMode:F0?.agentMode,initialToolDiscovery:Promise.all([H.mcpService.initialized,H.toolboxService.initialized]).then(()=>{return}),configService:H.configService,mcpService:H.mcpService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,pluginService:H.pluginService,pluginPlatform:H.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await a.release(),await H.asyncDispose()}await ED(),process.exit(0)}let _=J.executeMode?void 0:async(D0)=>Eo(D0,"interactive"),S={threadService:H.threadService,workerDeps:D,createThread:async()=>{let D0=W?await H.serverStatusPromise:U,$0=await YY0(J.settings,process.cwd(),Qx(D0),I);if($0 instanceof Error)C3($0.message);return xe0(D,{threadMeta:$0?oF($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(D0,$0)=>{if($0?.nonBlockingOwnershipCheck){Hn4(D0,H.configService,H.viewerUserIDPromise).catch((F0)=>{if(F0 instanceof T1){if($0.onOwnershipError){$0.onOwnershipError(F0,D0);return}MD(F0,D0);return}C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:F0})});return}try{await Hn4(D0,H.configService,H.viewerUserIDPromise)}catch(F0){if(F0 instanceof T1)throw F0;C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:F0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:MD},h=async(D0)=>{try{if(D0==="dtw")return jf3({ampURL:J.ampURL,configService:H.configService,threadService:H.threadService,mcpService:H.mcpService,clientID:Vn4,toolboxService:H.toolboxService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Su4(S,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof T1)throw $0;throw await MD($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")m$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7715
|
-
`),await ED(),process.exit(1);let p=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let D0=await H.configService.getLatest(),$0=tu(D0),F0=await p5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout($0)});if(F0.ok)return C.info("User free tier status:",F0),F0.result;return}catch(D0){C.error("Failed to fetch free tier status:",D0);return}})(),k=!J.executeMode?new Se0:null,f,d=null;if(k)f=k,d=(async()=>{let D0=W?await H.serverStatusPromise:H.serverStatus;await $51(Q,Z,D0);let $0=process.hrtime.bigint(),F0=Z51(O,D0),n=P6(D0)?J51({userEmail:D0.user.email,features:D0.features}):!1;Fn4({dtwEnabled:F0,hasV2TUIAccess:n});let a=await h(F0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await I1(a.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(D0)=>{let $0=D0 instanceof Error?D0:Error(String(D0));k.setInitError($0),await MD(D0,Z.threadId)});else G=process.hrtime.bigint(),Fn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",G);let g=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let b=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Bf3({configService:H.configService,threadService:H.threadService,config:b,useNotificationsForService:g,threadViewStates$:()=>f.threadHandles$.pipe(P4((D0)=>{if(!D0)return k0.of({});return F5(D0.thread$,D0.threadViewState$).pipe(B1(([$0,F0])=>({[$0.id]:F0})))}))}),K("runMainThread:createCliNotificationService",G),J.executeMode){Mf4(H.mcpService,J.settings);let D0={userInput:V,stdinInput:F,dependencies:H,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await KR4({threadPool:f,...D0});if(await Eo($0,"execute"),Z.archive)await H.threadService.archive($0,!0),await Mo(H.threadService,$0);await H.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await $u1();let D0=await EE({jetbrainsOnly:Z.jetbrains});if(D0.length===0){if(Z.jetbrains)i=!await H.configService.get("jetbrains.skipInstall")}else if(D0.length===1){let $0=D0[0];if($0)t$.selectConfig($0)}else c=!0}G=process.hrtime.bigint();let s=ma0("0.0.
|
|
7716
|
-
`);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 Fa1({get:async(F)=>{if(F!==$g)return;try{let z=await Nn4(e61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(F,z)=>{if(F!==$g)return;await wn4(KU.dirname(e61),{recursive:!0}),await Zf3(e61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:iz()});Ff1(Y);let X=await yY0({...J,workspaceTrust:{current:!0,changes:mA0},getHook:process.env.AMP_URL?(F,z)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let F=await Of4(J.mcpConfig);X=Ef4(X,F)}let K=KU.dirname(X.getSettingsFilePath());eG4(Bv,K);let V=await X.get("url","global");if(!V)V=Z7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!uW(V))C.info("Targeting custom Amp server",{ampURL:V});return X=$x1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:OX0(await ji(J,X))}}function Pf3(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,(F,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Cf3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=KU.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Xf3:In0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Tf3(){nL4();let J=Pf3(process.argv),Z=Cf3(process.argv,J),Q=Qj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)p0.level=0;if(Vf3(C),C.info("Starting Amp CLI.",{version:"0.0.
|
|
7715
|
+
`),await ED(),process.exit(1);let p=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let D0=await H.configService.getLatest(),$0=tu(D0),F0=await p5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout($0)});if(F0.ok)return C.info("User free tier status:",F0),F0.result;return}catch(D0){C.error("Failed to fetch free tier status:",D0);return}})(),k=!J.executeMode?new Se0:null,f,d=null;if(k)f=k,d=(async()=>{let D0=W?await H.serverStatusPromise:H.serverStatus;await $51(Q,Z,D0);let $0=process.hrtime.bigint(),F0=Z51(O,D0),n=P6(D0)?J51({userEmail:D0.user.email,features:D0.features}):!1;Fn4({dtwEnabled:F0,hasV2TUIAccess:n});let a=await h(F0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await I1(a.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(D0)=>{let $0=D0 instanceof Error?D0:Error(String(D0));k.setInitError($0),await MD(D0,Z.threadId)});else G=process.hrtime.bigint(),Fn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",G);let g=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let b=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Bf3({configService:H.configService,threadService:H.threadService,config:b,useNotificationsForService:g,threadViewStates$:()=>f.threadHandles$.pipe(P4((D0)=>{if(!D0)return k0.of({});return F5(D0.thread$,D0.threadViewState$).pipe(B1(([$0,F0])=>({[$0.id]:F0})))}))}),K("runMainThread:createCliNotificationService",G),J.executeMode){Mf4(H.mcpService,J.settings);let D0={userInput:V,stdinInput:F,dependencies:H,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await KR4({threadPool:f,...D0});if(await Eo($0,"execute"),Z.archive)await H.threadService.archive($0,!0),await Mo(H.threadService,$0);await H.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await $u1();let D0=await EE({jetbrainsOnly:Z.jetbrains});if(D0.length===0){if(Z.jetbrains)i=!await H.configService.get("jetbrains.skipInstall")}else if(D0.length===1){let $0=D0[0];if($0)t$.selectConfig($0)}else c=!0}G=process.hrtime.bigint();let s=ma0("0.0.1775191387-gd1bef3",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let H0=new De0(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let D0=await I1(f.threadHandles$);if(!D0)throw new T1("No active thread is available yet.",1);await D0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let r=await GV0();K("runMainThread:loadSessionState",G),C.info("Loaded session state:",r);let q0={...r,launchCount:r.launchCount+1};Zy((D0)=>({...D0,launchCount:D0.launchCount+1}));let L0=Z.threadId&&U9(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await Hb4({history:new Qa0,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:p5,threadPool:f,createSystemPromptDeps:async()=>An4(H),ideClient:t$,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:H0,updateService:s,pluginPlatform:H.pluginPlatform,pluginService:H.pluginService},{initialServerStatus:H.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:H.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:i,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Vn4,logFile:{path:Y},sessionState:q0,freeTierStatusPromise:p,workspace:j??null,features:A,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-03T04:46:44.547Z"},(D0)=>new de0({...D0,threadPool:D0.threadPool},($0)=>new j41({...$0,threadState:$0.threadState}))),K("runMainThread:mountApp-returned",G),d)await d}finally{await f.dispose().catch((D0)=>{C.error("Failed to dispose thread pool during shutdown",D0)})}await H.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function P3(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)m$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7716
|
+
`);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 Fa1({get:async(F)=>{if(F!==$g)return;try{let z=await Nn4(e61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(F,z)=>{if(F!==$g)return;await wn4(KU.dirname(e61),{recursive:!0}),await Zf3(e61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:iz()});Ff1(Y);let X=await yY0({...J,workspaceTrust:{current:!0,changes:mA0},getHook:process.env.AMP_URL?(F,z)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let F=await Of4(J.mcpConfig);X=Ef4(X,F)}let K=KU.dirname(X.getSettingsFilePath());eG4(Bv,K);let V=await X.get("url","global");if(!V)V=Z7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!uW(V))C.info("Targeting custom Amp server",{ampURL:V});return X=$x1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:OX0(await ji(J,X))}}function Pf3(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,(F,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Cf3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=KU.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Xf3:In0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Tf3(){nL4();let J=Pf3(process.argv),Z=Cf3(process.argv,J),Q=Qj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)p0.level=0;if(Vf3(C),C.info("Starting Amp CLI.",{version:"0.0.1775191387-gd1bef3",buildTimestamp:"2026-04-03T04:46:44.547Z"}),process.platform==="win32"&&xj())sI4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(N3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");if(process.argv.includes("--neo")){await Hf4();return}await Af3(Q).parseAsync(process.argv)}sG4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Tf3().catch(MD)});async function _f3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),a6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7717
7717
|
`);else if(!uW(J.ampURL))a6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7718
7718
|
`);let Y=process.env.AMP_API_KEY;if(Y)a6.write(`API key found in environment variable, storing...
|
|
7719
7719
|
`),await Z.set("apiKey",Y,J.ampURL),a6.write(`API key successfully stored.
|