@sourcegraph/amp 0.0.1771734754-g9b2f90 → 0.0.1771747379-gbb5ca2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4437,11 +4437,11 @@ ${U}`))}},error:(z)=>{if(!F)F=!0,q(Error(`Failed to spawn brew: ${z.message}`))}
4437
4437
  ${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
4438
4438
 
4439
4439
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4440
- npm install -g @sourcegraph/amp`;q(Error(D))}},error:(z)=>{if(!H)H=!0,q(Error(`Failed to spawn ${X}: ${z.message}`))},complete:()=>{if(!H)H=!0,K()}})})}g1();g1();pj();async function w91(J,Q){let Y=Q||"https://registry.npmjs.org",X=new AbortController,V=setTimeout(()=>X.abort(),5000);try{let K=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(!K.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=await K.json(),G=q["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=yZ6(J,G),H=W<0,F,z;if(q.time){let U=q.time[J],D=q.time[G],B=Date.now();if(U)F=Math.floor((B-new Date(U).getTime())/3600000);if(D)z=Math.floor((B-new Date(D).getTime())/3600000)}return T.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:W,hasUpdate:H,currentVersionAge:F,latestVersionAge:z}),{hasUpdate:H,latestVersion:G,currentVersion:J,currentVersionAge:F,latestVersionAge:z,source:"npm"}}catch(K){return T.debug("Error checking npm version",{error:K}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var zz8="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function L91(J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),5000);try{let Y=await fetch(`${zz8}?t=${Date.now()}`,{signal:Q.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 V=yZ6(J,X),K=V<0;return T.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return T.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Z)}}var Uz8=604800000;function kZ6(J){if(!J)return null;let Q=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Q))return null;let Z=Date.now()-Q;if(Z>Uz8)return{ageMs:Z};return null}function yZ6(J,Q){let Z=(K)=>{let[q,G]=K.split("-");return{parts:q?.split(".").map(Number)||[],label:G}},Y=Z(J),X=Z(Q),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let q=Y.parts[K]||0,G=X.parts[K]||0;if(q<G)return-1;if(q>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Bv1(J){try{let Q=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let Z=parseInt(Q[1],10)*1000,Y=Q[2],X=Z!==0?rF(Z):void 0;return{sha:Y,age:X}}catch{return null}}U0();function O91(J,Q){let Z=new F6,Y=Z.pipe(v4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new tV().scoped("update"),V=Y.subscribe({next:(K)=>{X.debug("emit new state",K)}});try{let K=process.env.AMP_TEST_UPDATE_STATUS;if(K){X.debug("using fake update status for testing",{status:K}),await gW(500),Z.next(K);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){X.debug("checking disabled");return}let G=await N91(),W=G==="binary"||G==="brew";X.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:W});let H=W?await L91(J):await w91(J,qO());if(!(H.latestVersion&&H.hasUpdate)){X.debug("no update available");return}let F=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let z=H.currentVersionAge-H.latestVersionAge,U=0.5;if(Math.abs(z)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:z}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!F())Z.next("update-available-brew");return}if(G==="binary"&&process.execPath!==Wv1()){if(X.debug("non-standard binary path, showing warning"),!F())Z.next("update-available-unrecognized-path");return}if(q==="warn"){if(!F())Z.next("update-available");return}if(!G){if(X.debug("auto-update not supported, falling back to warn mode"),!F())Z.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!F())Z.next("update-available");return}try{await su(H.latestVersion,G);let z=await SU(H.latestVersion),U={from:H.currentVersion,to:H.latestVersion,...z};if(z.status==="same")X.info("success",U),Z.next("updated");else X.warn("success with warning",U),Z.next("updated-with-warning")}catch(z){Z.next("update-error")}}catch(K){X.debug("check failed",{error:K})}finally{await gW(5000),Z.next("hidden"),V.unsubscribe(),Z.complete()}}),{state:Y}}pj();import{stderr as Mq}from"node:process";function vZ6(J){let Q=new wU().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 Vv1(Y.force||!1,Y.verbose||!1,"0.0.1771734754-g9b2f90"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new wU("update").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 Dz8(Y.targetVersion)});J.addCommand(Z)}async function Dz8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Mq.write(J0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4440
+ npm install -g @sourcegraph/amp`;q(Error(D))}},error:(z)=>{if(!H)H=!0,q(Error(`Failed to spawn ${X}: ${z.message}`))},complete:()=>{if(!H)H=!0,K()}})})}g1();g1();pj();async function w91(J,Q){let Y=Q||"https://registry.npmjs.org",X=new AbortController,V=setTimeout(()=>X.abort(),5000);try{let K=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(!K.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=await K.json(),G=q["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=yZ6(J,G),H=W<0,F,z;if(q.time){let U=q.time[J],D=q.time[G],B=Date.now();if(U)F=Math.floor((B-new Date(U).getTime())/3600000);if(D)z=Math.floor((B-new Date(D).getTime())/3600000)}return T.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:W,hasUpdate:H,currentVersionAge:F,latestVersionAge:z}),{hasUpdate:H,latestVersion:G,currentVersion:J,currentVersionAge:F,latestVersionAge:z,source:"npm"}}catch(K){return T.debug("Error checking npm version",{error:K}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var zz8="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function L91(J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),5000);try{let Y=await fetch(`${zz8}?t=${Date.now()}`,{signal:Q.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 V=yZ6(J,X),K=V<0;return T.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return T.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Z)}}var Uz8=604800000;function kZ6(J){if(!J)return null;let Q=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Q))return null;let Z=Date.now()-Q;if(Z>Uz8)return{ageMs:Z};return null}function yZ6(J,Q){let Z=(K)=>{let[q,G]=K.split("-");return{parts:q?.split(".").map(Number)||[],label:G}},Y=Z(J),X=Z(Q),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let q=Y.parts[K]||0,G=X.parts[K]||0;if(q<G)return-1;if(q>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Bv1(J){try{let Q=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let Z=parseInt(Q[1],10)*1000,Y=Q[2],X=Z!==0?rF(Z):void 0;return{sha:Y,age:X}}catch{return null}}U0();function O91(J,Q){let Z=new F6,Y=Z.pipe(v4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new tV().scoped("update"),V=Y.subscribe({next:(K)=>{X.debug("emit new state",K)}});try{let K=process.env.AMP_TEST_UPDATE_STATUS;if(K){X.debug("using fake update status for testing",{status:K}),await gW(500),Z.next(K);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){X.debug("checking disabled");return}let G=await N91(),W=G==="binary"||G==="brew";X.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:W});let H=W?await L91(J):await w91(J,qO());if(!(H.latestVersion&&H.hasUpdate)){X.debug("no update available");return}let F=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let z=H.currentVersionAge-H.latestVersionAge,U=0.5;if(Math.abs(z)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:z}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!F())Z.next("update-available-brew");return}if(G==="binary"&&process.execPath!==Wv1()){if(X.debug("non-standard binary path, showing warning"),!F())Z.next("update-available-unrecognized-path");return}if(q==="warn"){if(!F())Z.next("update-available");return}if(!G){if(X.debug("auto-update not supported, falling back to warn mode"),!F())Z.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!F())Z.next("update-available");return}try{await su(H.latestVersion,G);let z=await SU(H.latestVersion),U={from:H.currentVersion,to:H.latestVersion,...z};if(z.status==="same")X.info("success",U),Z.next("updated");else X.warn("success with warning",U),Z.next("updated-with-warning")}catch(z){Z.next("update-error")}}catch(K){X.debug("check failed",{error:K})}finally{await gW(5000),Z.next("hidden"),V.unsubscribe(),Z.complete()}}),{state:Y}}pj();import{stderr as Mq}from"node:process";function vZ6(J){let Q=new wU().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 Vv1(Y.force||!1,Y.verbose||!1,"0.0.1771747379-gbb5ca2"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new wU("update").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 Dz8(Y.targetVersion)});J.addCommand(Z)}async function Dz8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Mq.write(J0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4441
4441
 
4442
4442
  `));try{if(!J){Mq.write(J0.blue(`Checking for updates...
4443
- `));let{hasUpdate:Y,latestVersion:X}=Kv1()?await L91("0.0.1771734754-g9b2f90"):await w91("0.0.1771734754-g9b2f90",qO());if(!Y){let V=Bv1("0.0.1771734754-g9b2f90"),K=V?.age?`released ${V.age} ago`:`built ${rF(new Date("2026-02-22T04:38:13.614Z"))} ago`;Mq.write(J0.green(`✓ Amp is already up to date on version ${"0.0.1771734754-g9b2f90"} (${K})
4444
- `));let q=await SU("0.0.1771734754-g9b2f90");if(q.warning)Mq.write(`
4443
+ `));let{hasUpdate:Y,latestVersion:X}=Kv1()?await L91("0.0.1771747379-gbb5ca2"):await w91("0.0.1771747379-gbb5ca2",qO());if(!Y){let V=Bv1("0.0.1771747379-gbb5ca2"),K=V?.age?`released ${V.age} ago`:`built ${rF(new Date("2026-02-22T08:08:29.677Z"))} ago`;Mq.write(J0.green(`✓ Amp is already up to date on version ${"0.0.1771747379-gbb5ca2"} (${K})
4444
+ `));let q=await SU("0.0.1771747379-gbb5ca2");if(q.warning)Mq.write(`
4445
4445
  `+J0.yellow(q.warning)+`
4446
4446
  `);process.exit(0)}if(!X)Mq.write(J0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Mq.write(J0.blue(`Updating to version ${J}...
4447
4447
  `)),await su(J,void 0,(Y)=>{Mq.write(J0.dim(`Running: ${Y}
@@ -5364,7 +5364,7 @@ Ctrl-X, Y, Z to unlock`;if(z){let v=W.text.replace(/`([^`]+)`/g,"$1")+`
5364
5364
  `),new S("Ctrl+O",D),new S(" for ",N),new S("help",B),new S(`
5365
5365
 
5366
5366
 
5367
- `,N)])}),R];if(!G&&!z&&W.url){let _=W.url.replace(/^https?:\/\//,"");P.push(new Z8({uri:W.url,text:_,style:new u({color:Z.secondary,underline:!0})}))}if(A&&!z)P.push(A);let C=new P1({width:50,child:new b1({crossAxisAlignment:"start",mainAxisSize:"min",children:P})});return s0.child(new G0({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new _x1({width:ru1,height:su1,agentMode:this.widget.agentMode,glow:this._glow,backgroundColor:Z.background,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:O,...K==="disabled"&&{seed:42}}),new P1({width:2}),C]}))}}class tu1 extends o1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new NU6}}class NU6 extends l1{build(J){let Z=h1.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new P1({width:0,height:0});let V=Y.map((K)=>this.buildTodoItem(K,Z));return new c1({child:new i1({padding:C1.symmetric(1,0),child:new b1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Z1({text:new S(X,new u({bold:!0,color:Z.foreground}))}),...V]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new u({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),V=new u({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new G0({crossAxisAlignment:"start",children:[new Z1({text:new S(Z,X)}),new P1({width:1}),new C0({child:new Z1({text:new S(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class eu1 extends o1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y,onImpression:X,onAdInfoClick:V}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y,this.onImpression=X,this.onAdInfoClick=V}createState(){return new wU6}}class wU6 extends l1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=h1.of(J),Z=Q.colors.primary,Y=Q.colors.foreground,X=Q.colors.background,V=this.widget.ad;return new c1({decoration:new T6(X,new d0(new x0(Z,1,"rounded"),new x0(Z,1,"rounded"),void 0,new x0(Z,1,"rounded"))),child:new i1({padding:C1.horizontal(1),child:new b1({children:[new G0({crossAxisAlignment:"start",children:[new C0({child:new Z1({text:new S(V.content,new u({color:Y}))})}),new P1({width:4}),new i0({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new Z1({text:new S("Ad",new u({color:Y,dim:!0}))})})]}),new G0({crossAxisAlignment:"start",children:[new xg({text:V.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:C1.horizontal(1),color:Z,reverse:!0}),new P1({width:2}),new Z1({text:new S(V.destinationUrlHostname,new u({color:Y,dim:!0}))})]})]})})})}}class Jg1 extends o1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new LU6(this.props.autofocus??!0)}}class LU6 extends l1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Z=S0.of(J).colorScheme,Y=(W)=>{if(W.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(W.ctrlKey&&W.key==="c"||W.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},X=Q6.sizeOf(J),V=Math.min(60,X.width-4),K=X.height-4,q=[];if(this.widget.props.title)q.push(new Z1({text:new S(this.widget.props.title,new u({bold:!0,color:Z.primary}))}),new P1({height:1}));if(this.widget.props.message)q.push(new Z1({text:new S(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)q.push(new P1({height:1}));let G=[];if(this.widget.props.showCopyOption)G.push(new Z1({text:new S("Enter to copy",new u({dim:!0}))}));return G.push(new Z1({text:new S("Escape to close",new u({dim:!0}))})),q.push(new G0({children:G.flatMap((W,H)=>H<G.length-1?[W,new P1({width:1}),new Z1({text:new S("•",new u({dim:!0}))}),new P1({width:1})]:[W]),mainAxisSize:"min"})),new s0({child:new c1({constraints:new A0(V,V,0,K),decoration:new T6(Z.background,new d0(new x0(Z.primary,1,"rounded"),new x0(Z.primary,1,"rounded"),new x0(Z.primary,1,"rounded"),new x0(Z.primary,1,"rounded"))),padding:new C1(2,2,2,2),child:new b6({autofocus:this.autofocus,onKey:Y,child:new b1({children:q,mainAxisSize:"min"})})})})}}class Qg1 extends o1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new OU6(this.props.autofocus??!0)}}class OU6 extends l1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=S0.of(J).colorScheme,Z=(q)=>{if(q.key==="Enter"||q.key==="Escape"||q.ctrlKey&&q.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=Q6.sizeOf(J),X=Math.min(60,Y.width-4),V=Y.height-4,K=[];if(K.push(new Z1({text:new S("Ads make Amp Free possible",new u({bold:!0}))})),this.widget.props.provider)K.push(new P1({height:1}),new Z1({text:new S(`Ad source: ${this.widget.props.provider}`,new u({dim:!0}))}));return K.push(new P1({height:1}),new Z1({text:new S("Escape to close",new u({dim:!0}))})),new s0({child:new c1({constraints:new A0(X,X,0,V),decoration:new T6(Q.background,new d0(new x0(Q.primary,1,"rounded"),new x0(Q.primary,1,"rounded"),new x0(Q.primary,1,"rounded"),new x0(Q.primary,1,"rounded"))),padding:new C1(2,2,2,2),child:new b6({autofocus:this.autofocus,onKey:Z,child:new b1({children:K,mainAxisSize:"min"})})})})}}g1();L3();import{execSync as Sv8}from"node:child_process";tT1();KQ();n9();r3();FN();B$();OJ();IQ();D$();VI();l6();fh();SS();U0();var UD6=B6(eG(),1);import{writeFile as GD6}from"fs/promises";import WD6 from"path";g1();OJ();class Zg1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;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(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1771734754-g9b2f90"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ws(Q,this.configService)}catch(Q){T.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class MD extends o1{props;constructor(J){super();this.props=J}createState(){return new MU6}}class MU6 extends l1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class AU6 extends l1{controller=new s2;focusNode=new K4({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 Q=h1.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,q=d0.all(new x0(Z.foreground,1,"solid")),G=new $Y({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new G0({children:[new c1({decoration:{color:Z.background},child:new Z1({text:new S(">",new u({color:Z.foreground}))})}),new C0({child:G})]}),H=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S("",void 0,[new S("Command: ",new u({color:Z.foreground})),new S(this.widget.props.commandName,new u({color:Y.command,bold:!0}))])})}),F=[];if(K)F.push(new S("Enter",new u({color:Y.keybind}))),F.push(new S(" to submit, ",new u({color:Z.foreground,dim:!0})));F.push(new S("Esc",new u({color:Y.keybind}))),F.push(new S(" to cancel",new u({color:Z.foreground,dim:!0})));let z=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S("",void 0,F)})});return new c1({decoration:{border:q,color:Z.background},padding:C1.all(1),child:new b1({children:[H,new P1({height:1}),W,new f9,z]})})}}class om extends o1{props;constructor(J){super();this.props=J}createState(){return new AU6}}import{isDeepStrictEqual as Yg1}from"node:util";var Xv8=/[\\/_ +.#"@[({&]/,$v8=/[\\/_ +.#"@[({&]/g,Vv8=/[\s-]/,RU6=/[\s-]/g;function e31(J,Q,Z,Y,X,V,K){if(V===Q.length){if(X===J.length)return 1;return 0.99}let q=`${X},${V}`;if(K[q]!==void 0)return K[q];let G=Y.charAt(V),W=Z.indexOf(G,X),H=0,F,z,U,D;while(W>=0){if(F=e31(J,Q,Z,Y,W+1,V+1,K),F>H){if(W===X)F*=1;else if(Vv8.test(J.charAt(W-1))){if(F*=0.9,D=J.slice(X,W-1).match(RU6),D&&X>0)F*=0.999**D.length}else if(Xv8.test(J.charAt(W-1))){if(F*=0.8,U=J.slice(X,W-1).match($v8),U&&X>0)F*=0.999**U.length}else if(F*=0.3,X>0)F*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(V))F*=0.9999}if(F<0.1&&(Z.charAt(W-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Z.charAt(W-1)!==Y.charAt(V))){if(z=e31(J,Q,Z,Y,W+1,V+2,K),z*0.1>F)F=z*0.1}if(F>H)H=F;W=Z.indexOf(G,W+1)}return K[q]=H,H}function t31(J){return J.toLowerCase().replace(RU6," ")}function jU6(J,Q){let Z=e31(J,Q,t31(J),t31(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let q of Y){let G=e31(J,q,t31(J),t31(q),0,0,{});if(G===0)return Z;X+=G,V+=q.length}let K=X/Y.length*0.95;return Math.max(Z,K)}return Z}class ZT{}class YT{}class J21{}class Q21{}class EU6 extends o1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new PU6}}class PU6 extends l1{build(J){return this.widget.onContext(J),this.widget.child}}function Kv8(J,Q){if(J==="")return{matches:!0,score:1};let Z=jU6(Q,J);return{matches:Z>0.15,score:Z}}class m7 extends o1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new IU6}}class IU6 extends l1{textController;focusNode;scrollController=new t4;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s2(this.widget.props.controller?.query??""),this.focusNode=new K4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),U4.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((Q)=>Yg1(Q,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Yg1(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Q=this.cachedFiltered.findIndex((Z)=>Yg1(Z,this.widget.props.controller?.selectedItem));if(Q>=0)this.selectedIndex=Q}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 ZT){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof YT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof J21){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof Q21)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Q=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Q;this.widget.props.onSelectionChange?.(Q)}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,Q=this.widget.props.items,Z=this.widget.props.normalizeQuery?.(J)??J,Y=Q.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...Kv8(Z,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;OC(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return!1;let Z=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Q.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(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Z};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Q===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Q=h1.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=d0.all(new x0(Z.foreground,1,"solid")),V=this.widget.props.enabled??!0,K=new $Y({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Z.background,textColor:Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,border:null},maxLines:1}),q=new B2({shortcuts:new Map([[new r0("ArrowDown"),new ZT],[new r0("ArrowUp"),new YT],[new r0("Tab"),new ZT],[new r0("Tab",{shift:!0}),new YT],[new r0("n",{ctrl:!0}),new ZT],[new r0("p",{ctrl:!0}),new YT],[new r0("Enter"),new J21],[new r0("Escape"),new Q21]]),focusNode:this.focusNode,child:K}),G=new M7({actions:new Map([[ZT,new i6(this.invoke)],[YT,new i6(this.invoke)],[J21,new i6(this.invoke)],[Q21,new i6(this.invoke)]]),child:q}),W=new G0({children:[new c1({decoration:{color:Z.background},child:new Z1({text:new S(">",new u({color:Z.foreground}))})}),new C0({child:G})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new P1({height:10,child:new s0({child:new Z1({text:new S(B,new u({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new C0({child:new s0({child:new Z1({text:new S(this.widget.props.emptyStateText,new u({color:Z.foreground,dim:!0}))})})});else{let B=Y.map((N,w)=>{let L=w===this.selectedIndex,O=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,L,O,J);else{let A=L?Q.app.selectionBackground:void 0,R=L?Q.app.selectionForeground:Z.foreground;M=new c1({decoration:A?{color:A}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S(this.widget.props.getLabel(N),new u({color:R,dim:O}))})})}return new EU6(new i0({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:M}),(A)=>{this.itemContexts[w]=A})});H=new b1({children:B,crossAxisAlignment:"start"})}let F=new i0({onScroll:this.handleScroll,opaque:!1,child:new S4({controller:this.scrollController,autofocus:!1,child:H})}),z=[];if(this.widget.props.title){let B=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S(this.widget.props.title,new u({color:Q.app.command,bold:!0}))})});z.push(B)}if(z.push(W,new P1({height:1})),this.textController.text!==""){let B=Y.length>0?Y[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B,J);z.push(new C0({child:new b1({mainAxisAlignment:"spaceBetween",children:[new C0({child:F}),new c1({padding:C1.only({top:1}),child:new s0({child:N??new P1({height:1})})})]})}))}else z.push(new C0({child:F}));if(this.widget.props.footer)z.push(this.widget.props.footer);return new c1({decoration:{border:X,color:Z.background},padding:C1.symmetric(1,0),child:new b1({children:z})})}}function CU6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),V=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Xg1 extends m0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>CU6(X.pubDate).length));return new m7({items:Q,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,V,K,q)=>{let G=h1.of(q),{colors:W}=G,H=G.app,F=V?H.selectionBackground:void 0,z=V?H.selectionForeground:W.foreground,U=W.mutedForeground,D=(B,N)=>new P1({width:N,child:G0.end([new Z1({text:new S(B,new u({color:U}))})])});return new c1({decoration:F?{color:F}:void 0,padding:C1.symmetric(2,0),child:new G0({children:[new C0({child:new Z1({text:new S(X.title,new u({color:z})),overflow:"ellipsis",maxLines:1})}),new P1({width:2}),D(CU6(X.pubDate),Z)]})})}})}}l6();class $g1 extends o1{createState(){return new TU6}}class TU6 extends l1{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 Z=h1.of(J).colors;return new Z1({text:new S("●",new u({color:this.isGreen?Z.success:Z.mutedForeground,bold:!0})),maxLines:1})}}var qv8=/\/threads\/(T-[^/?#\s<>]+)/i;function Gv8(J){let Q=J.trim(),Y=Q.match(qv8)?.[1];if(Y&&W5(Y))return Y;let X=Q.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(W5(X))return X;return null}function Wv8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let K of J)Q.set(K.id,K);for(let K of J){let q=K.relationships.find((G)=>G.role==="child"&&Q.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(q){Y.set(K.id,q.type);let G=q.threadID,W=Z.get(G)||[];W.push(K),Z.set(G,W)}else X.push(K)}return M71.flatten(X,(K)=>Z.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Vg1(J,Q,Z){return new Z1({text:new S(`${J}${Q}`,new u({color:Z})),maxLines:1})}function Hv8(J,Q,Z,Y){return[Vg1("+",J,Y.success),f9.horizontal(1),Vg1("~",Q,Y.warning),f9.horizontal(1),Vg1("-",Z,Y.destructive)]}class Z21 extends m0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((D)=>D.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((D)=>D.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=new Set(Z),X=this.props.currentThreadID,V=[...Q].sort((D,B)=>{if(X){if(D.id===X)return-1;if(B.id===X)return 1}let N=Z.indexOf(D.id),w=Z.indexOf(B.id);if(N!==-1&&w!==-1)return N-w;if(N!==-1)return-1;if(w!==-1)return 1;return 0}),K=Wv8(V),q=Math.max(0,...K.map((D)=>D.description.timeAgo.length)),G=h1.of(J),W=new i1({padding:C1.symmetric(0,1),child:new s0({child:new Z1({text:new S("",new u({color:G.colors.foreground,dim:!0}),[new S("Ctrl+T",new u({color:G.colors.primary,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new u({color:G.colors.foreground,dim:!0}))])})})}),H="",F=null,z=(D)=>{if(D!==H)H=D,F=Gv8(D);return F};return new m7({items:K,getLabel:(D)=>`${D.title} ${D.id}`,filterItem:(D,B)=>{let N=z(B);if(N)return D.id.toLowerCase()===N.toLowerCase();return!0},normalizeQuery:(D)=>z(D)?"":D,onAccept:(D,B)=>this.props.onSelect?.(D.id,B),onDismiss:this.props.onDismiss,onSelectionChange:(D)=>{if(this.props.previewController){if(D)this.props.previewController.select(D.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(D,B,N,w)=>{let L=h1.of(w),{app:O,colors:M}=L,A=B?O.selectionBackground:void 0,R=B?O.selectionForeground:M.foreground,j=M.mutedForeground,P=(i,g)=>new P1({width:g,child:G0.end([new Z1({text:new S(i,new u({color:j}))})])}),C=this.props.threadViewStates[D.id],_=[],v=D.relationshipType==="handoff",h=new Zm({connectorColor:M.mutedForeground});if(D.depth>0){let i=[],g=D.ancestorsAreLast.slice(1);for(let r of g)i.push(new S(h.getAncestorPrefix(r),new u({color:h.connectorColor,dim:h.connectorDim})));let a=D.isLast?h.elbow:h.tee,d=h.getConnectorText(a);i.push(new S(d,new u({color:h.connectorColor,dim:h.connectorDim}))),_.push(new Z1({text:new S("",void 0,i)}))}let b=[],k=X===D.id?new S("(current) ",new u({color:M.success})):Y.has(D.id)?new S("(visited) ",new u({color:M.foreground,dim:!0})):null;if(k)b.push(new Z1({text:k}));if(kL(C))b.push(new $g1),b.push(new P1({width:1}));let f=D.title;if(D.relationshipType==="fork"){let i=f.match(/^Forked\((\d+)\): /);if(i)f=f.slice(i[0].length);else while(f.startsWith("Forked: "))f=f.slice(8);b.push(new Z1({text:new S("[fork] ",new u({color:M.primary}))}))}else if(v)b.push(new Z1({text:new S("[handoff] ",new u({color:M.accent}))}));if(b.push(new C0({child:new Z1({text:new S(f,new u({color:R})),overflow:"ellipsis",maxLines:1})})),b.push(new P1({width:2})),D.diffStats&&(D.diffStats.added>0||D.diffStats.changed>0||D.diffStats.deleted>0)){let i=B?{success:j,warning:j,destructive:j}:M;b.push(...Hv8(D.diffStats.added,D.diffStats.changed,D.diffStats.deleted,i)),b.push(new P1({width:2}))}return b.push(P(D.description.timeAgo,q)),new c1({decoration:A?{color:A}:void 0,padding:C1.symmetric(2,0),child:new G0({children:[..._,...b]})})}})}}class SU6 extends o1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new kU6}}class kU6 extends l1{build(J){return this.widget.onContext(J),this.widget.child}}var _U6=30,Fv8=30;class XT{}class $T{}class Y21{}class X21{}class Kg1 extends o1{props;constructor(J){super();this.props=J}createState(){return new yU6}}class yU6 extends l1{highlightedIndex=0;controller=new s2;focusNode;scrollController=new t4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new K4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;OC(J,{top:Z,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Z)=>Z.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof XT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof $T){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Y21){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof X21)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Z=this.filteredClusters[J];if(Z)this.widget.props.onAccept(Z)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Q=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Q};build(J){let{currentThreadID:Q}=this.widget.props,Z=h1.of(J),{colors:Y,app:X}=Z,q=Q6.of(J).size.width>=Fv8+_U6,G=d0.all(new x0(Y.foreground,1,"solid")),W=this.filteredClusters[this.highlightedIndex]??null,H=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S("Select a cluster",new u({color:X.command,bold:!0}))})}),F=new $Y({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),z=new B2({shortcuts:new Map([[new r0("ArrowDown"),new XT],[new r0("ArrowUp"),new $T],[new r0("Tab"),new XT],[new r0("Tab",{shift:!0}),new $T],[new r0("n",{ctrl:!0}),new XT],[new r0("p",{ctrl:!0}),new $T],[new r0("Enter"),new Y21],[new r0("Escape"),new X21]]),focusNode:this.focusNode,child:F}),U=new M7({actions:new Map([[XT,new i6(this.invoke)],[$T,new i6(this.invoke)],[Y21,new i6(this.invoke)],[X21,new i6(this.invoke)]]),child:z}),D=new G0({children:[new c1({decoration:{color:Y.background},child:new Z1({text:new S(">",new u({color:Y.foreground}))})}),new C0({child:U})]});this.itemContexts=[];let B=this.filteredClusters.map((A,R)=>{let j=R===this.highlightedIndex,P=Q?A.threads.some((h)=>h.id===Q):!1,C=j?X.selectionBackground:void 0,_=j?X.selectionForeground:Y.foreground,v=[new S(A.label,new u({color:_})),new S(` (${A.threads.length})`,new u({color:_,dim:!0}))];if(P)v.push(new S(" (current)",new u({color:j?X.selectionForeground:Y.success})));return new SU6(new i0({onClick:(h)=>this.handleItemClick(R,h.clickCount),child:new c1({decoration:C?{color:C}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S("",void 0,v)})})}),(h)=>{this.itemContexts[R]=h})}),N=new b1({children:B,crossAxisAlignment:"start"}),w=new C0({child:new i0({onScroll:this.handleScroll,child:new S4({controller:this.scrollController,autofocus:!1,child:N})})}),L=W?W.threads.map((A)=>({id:A.id,title:A.title,parentID:A.parentID,updatedAt:A.updatedAt})):[],O=W?new c1({padding:C1.all(1),child:new sO({threads:L,autofocus:!1,offsetY:2})}):null,M;if(q){let A=O?new C0({child:O}):new P1({width:_U6});M=new G0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,A]})}else{let A=[new C0({child:new i0({onScroll:this.handleScroll,child:new S4({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)A.push(new C0({child:O}));M=new b1({crossAxisAlignment:"stretch",children:A})}return new c1({decoration:{border:G,color:Y.background},padding:C1.symmetric(1,0),child:new b1({children:[H,D,new P1({height:1}),new C0({child:M})]})})}}g1();class vU6 extends l1{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){T.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){T.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Q=J.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Z=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Q),X=Z.includes(Q);return!Y&&!X}build(J){let Q=h1.of(J),{app:Z,colors:Y}=Q,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new m7({title:"Add Label",items:G,getLabel:(W)=>{if("__isCreateMarker"in W)return this.currentQuery.trim().toLowerCase();return W.name},onAccept:(W)=>{if("__isCreateMarker"in W)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(W.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(W,H,F,z)=>{let U=H?Z.selectionBackground:void 0,D=H?Z.selectionForeground:Y.foreground;if("__isCreateMarker"in W&&W.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new c1({decoration:U?{color:U}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S("",void 0,[new S("Create new label: ",new u({color:D})),new S(N,new u({color:D,bold:!0}))])})})}return new c1({decoration:U?{color:U}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S(W.name,new u({color:D}))})})},filterItem:(W,H)=>{if(this.currentQuery!==H)this.currentQuery=H,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in W&&W.__isCreateMarker)return this.shouldShowCreateMarker(H);let z=H.trim().toLowerCase();return z.length===0||W.name.includes(z)},sortItems:(W,H,F)=>{let z="__isCreateMarker"in W.item&&W.item.__isCreateMarker,U="__isCreateMarker"in H.item&&H.item.__isCreateMarker;if(z&&!U)return-1;if(!z&&U)return 1;return H.score-W.score}})}}class qg1 extends o1{props;constructor(J){super();this.props=J}createState(){return new vU6}}class AD extends o1{props;constructor(J){super();this.props=J}createState(){return new xU6}}class xU6 extends l1{_spinner=new b5;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=h1.of(J),{colors:Z,app:Y}=Q,X=d0.all(new x0(Z.foreground,1,"solid")),V=this._spinner.toBraille(),K=new Z1({textAlign:"center",text:new S("",void 0,[new S(V,new u({color:Y.processing})),new S(" ",void 0),new S(this.widget.props.message,new u({color:Z.foreground}))])}),G=[new C0({child:new b1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new P1({height:2,child:new c1({padding:C1.symmetric(2,0),child:new Z1({text:new S("",new u({dim:!0}),[new S("Press ",new u({color:Z.foreground})),new S("Esc",new u({color:Z.info})),new S(" to cancel",new u({color:Z.foreground}))])})})}));let W=new c1({decoration:new T6(Z.background,X),child:new P1({width:60,height:7,child:new b1({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new b6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:W});return W}}class eO extends o1{props;constructor(J){super();this.props=J}createState(){return new bU6}}class bU6 extends l1{scrollController=new t4;scrollAreaKey=new y3("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof KY}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Z=Q.size;if(typeof Z.height==="number"&&Z.height>0)return this.viewportHeight=Z.height,Z.height}return this.viewportHeight}build(J){let Q=h1.of(J),Z=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Z))return{title:Z.title,type:Z.type};if(Z instanceof Error&&Z.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Z.message};if(Z instanceof Error&&Z.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Z.message};let H=w71(Z);return{title:H.title,type:H.type,description:H.description}})(),X=Y.type==="error"?Q.app.toolError:Q.app.command,V=d0.all(new x0(Q.colors.border,1,"solid")),K=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S(Y.title,new u({color:X,bold:!0}))})}),q=this.isWidgetMessage(Z)?Z.widget:new Z1({text:new S(Y.description,new u({color:Q.colors.foreground})),selectable:!0}),G=new C0({child:new gJ({child:new c1({padding:C1.symmetric(1,0),child:new G0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new C0({child:new S4({controller:this.scrollController,autofocus:!0,child:q})}),new E5({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,F=this.scrollController.offset,z=this.getViewportHeight(),U=H+z;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(z,1),scrollOffset:Math.max(F,0)}}})]})})})}),W=new c1({padding:C1.symmetric(1,0),child:new Z1({text:(()=>{if(this.widget.props.onRetry)return new S("",void 0,[new S("Press ",new u({color:Q.colors.foreground,dim:!0})),new S("R",new u({color:Q.app.keybind})),new S(" to retry, ",new u({color:Q.colors.foreground,dim:!0})),new S("Esc",new u({color:Q.app.keybind})),new S(" to cancel",new u({color:Q.colors.foreground,dim:!0}))]);let H=this.resolveFooterStyle(this.widget.props.message);if(H==="none")return new S("",new u({color:Q.colors.foreground,dim:!0}));if(H==="help"){let F=new u({color:Q.app.keybind}),z=new u({color:Q.colors.foreground,dim:!0});return new S("",z,[new S("Press ",z),new S("Escape",F),new S(" to close • Use ",z),new S("↑↓",F),new S(" or ",z),new S("j/k",F),new S(" to scroll",z)])}return new S("Press any key to close",new u({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new b6({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c1({decoration:{border:V,color:Q.colors.background},padding:C1.all(1),child:new b1({mainAxisAlignment:"center",children:[K,new P1({height:1}),G,W]})})})}}class Gg1 extends m0{build(J){let Q=h1.of(J),{colors:Z,app:Y}=Q;return new s0({child:new Z1({text:new S("",void 0,[new S(`✓ Thread Shared
5367
+ `,N)])}),R];if(!G&&!z&&W.url){let _=W.url.replace(/^https?:\/\//,"");P.push(new Z8({uri:W.url,text:_,style:new u({color:Z.secondary,underline:!0})}))}if(A&&!z)P.push(A);let C=new P1({width:50,child:new b1({crossAxisAlignment:"start",mainAxisSize:"min",children:P})});return s0.child(new G0({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new _x1({width:ru1,height:su1,agentMode:this.widget.agentMode,glow:this._glow,backgroundColor:Z.background,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:O,...K==="disabled"&&{seed:42}}),new P1({width:2}),C]}))}}class tu1 extends o1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new NU6}}class NU6 extends l1{build(J){let Z=h1.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new P1({width:0,height:0});let V=Y.map((K)=>this.buildTodoItem(K,Z));return new c1({child:new i1({padding:C1.symmetric(1,0),child:new b1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Z1({text:new S(X,new u({bold:!0,color:Z.foreground}))}),...V]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new u({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),V=new u({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new G0({crossAxisAlignment:"start",children:[new Z1({text:new S(Z,X)}),new P1({width:1}),new C0({child:new Z1({text:new S(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class eu1 extends o1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y,onImpression:X,onAdInfoClick:V}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y,this.onImpression=X,this.onAdInfoClick=V}createState(){return new wU6}}class wU6 extends l1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=h1.of(J),Z=Q.colors.primary,Y=Q.colors.foreground,X=Q.colors.background,V=this.widget.ad;return new c1({decoration:new T6(X,new d0(new x0(Z,1,"rounded"),new x0(Z,1,"rounded"),void 0,new x0(Z,1,"rounded"))),child:new i1({padding:C1.horizontal(1),child:new b1({children:[new G0({crossAxisAlignment:"start",children:[new C0({child:new Z1({text:new S(V.content,new u({color:Y}))})}),new P1({width:4}),new i0({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new Z1({text:new S("Ad",new u({color:Y,dim:!0}))})})]}),new G0({crossAxisAlignment:"start",children:[new xg({text:V.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:C1.horizontal(1),color:Z,reverse:!0}),new P1({width:2}),new Z1({text:new S(V.destinationUrlHostname,new u({color:Y,dim:!0}))})]})]})})})}}class Jg1 extends o1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new LU6(this.props.autofocus??!0)}}class LU6 extends l1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Z=S0.of(J).colorScheme,Y=(W)=>{if(W.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(W.ctrlKey&&W.key==="c"||W.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},X=Q6.sizeOf(J),V=Math.min(60,X.width-4),K=X.height-4,q=[];if(this.widget.props.title)q.push(new Z1({text:new S(this.widget.props.title,new u({bold:!0,color:Z.primary}))}),new P1({height:1}));if(this.widget.props.message)q.push(new Z1({text:new S(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)q.push(new P1({height:1}));let G=[];if(this.widget.props.showCopyOption)G.push(new Z1({text:new S("Enter to copy",new u({dim:!0}))}));return G.push(new Z1({text:new S("Escape to close",new u({dim:!0}))})),q.push(new G0({children:G.flatMap((W,H)=>H<G.length-1?[W,new P1({width:1}),new Z1({text:new S("•",new u({dim:!0}))}),new P1({width:1})]:[W]),mainAxisSize:"min"})),new s0({child:new c1({constraints:new A0(V,V,0,K),decoration:new T6(Z.background,new d0(new x0(Z.primary,1,"rounded"),new x0(Z.primary,1,"rounded"),new x0(Z.primary,1,"rounded"),new x0(Z.primary,1,"rounded"))),padding:new C1(2,2,2,2),child:new b6({autofocus:this.autofocus,onKey:Y,child:new b1({children:q,mainAxisSize:"min"})})})})}}class Qg1 extends o1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new OU6(this.props.autofocus??!0)}}class OU6 extends l1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=S0.of(J).colorScheme,Z=(q)=>{if(q.key==="Enter"||q.key==="Escape"||q.ctrlKey&&q.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=Q6.sizeOf(J),X=Math.min(60,Y.width-4),V=Y.height-4,K=[];if(K.push(new Z1({text:new S("Ads make Amp Free possible",new u({bold:!0}))})),this.widget.props.provider)K.push(new P1({height:1}),new Z1({text:new S(`Ad source: ${this.widget.props.provider}`,new u({dim:!0}))}));return K.push(new P1({height:1}),new Z1({text:new S("Escape to close",new u({dim:!0}))})),new s0({child:new c1({constraints:new A0(X,X,0,V),decoration:new T6(Q.background,new d0(new x0(Q.primary,1,"rounded"),new x0(Q.primary,1,"rounded"),new x0(Q.primary,1,"rounded"),new x0(Q.primary,1,"rounded"))),padding:new C1(2,2,2,2),child:new b6({autofocus:this.autofocus,onKey:Z,child:new b1({children:K,mainAxisSize:"min"})})})})}}g1();L3();import{execSync as Sv8}from"node:child_process";tT1();KQ();n9();r3();FN();B$();OJ();IQ();D$();VI();l6();fh();SS();U0();var UD6=B6(eG(),1);import{writeFile as GD6}from"fs/promises";import WD6 from"path";g1();OJ();class Zg1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;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(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1771747379-gbb5ca2"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ws(Q,this.configService)}catch(Q){T.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class MD extends o1{props;constructor(J){super();this.props=J}createState(){return new MU6}}class MU6 extends l1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class AU6 extends l1{controller=new s2;focusNode=new K4({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 Q=h1.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,q=d0.all(new x0(Z.foreground,1,"solid")),G=new $Y({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new G0({children:[new c1({decoration:{color:Z.background},child:new Z1({text:new S(">",new u({color:Z.foreground}))})}),new C0({child:G})]}),H=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S("",void 0,[new S("Command: ",new u({color:Z.foreground})),new S(this.widget.props.commandName,new u({color:Y.command,bold:!0}))])})}),F=[];if(K)F.push(new S("Enter",new u({color:Y.keybind}))),F.push(new S(" to submit, ",new u({color:Z.foreground,dim:!0})));F.push(new S("Esc",new u({color:Y.keybind}))),F.push(new S(" to cancel",new u({color:Z.foreground,dim:!0})));let z=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S("",void 0,F)})});return new c1({decoration:{border:q,color:Z.background},padding:C1.all(1),child:new b1({children:[H,new P1({height:1}),W,new f9,z]})})}}class om extends o1{props;constructor(J){super();this.props=J}createState(){return new AU6}}import{isDeepStrictEqual as Yg1}from"node:util";var Xv8=/[\\/_ +.#"@[({&]/,$v8=/[\\/_ +.#"@[({&]/g,Vv8=/[\s-]/,RU6=/[\s-]/g;function e31(J,Q,Z,Y,X,V,K){if(V===Q.length){if(X===J.length)return 1;return 0.99}let q=`${X},${V}`;if(K[q]!==void 0)return K[q];let G=Y.charAt(V),W=Z.indexOf(G,X),H=0,F,z,U,D;while(W>=0){if(F=e31(J,Q,Z,Y,W+1,V+1,K),F>H){if(W===X)F*=1;else if(Vv8.test(J.charAt(W-1))){if(F*=0.9,D=J.slice(X,W-1).match(RU6),D&&X>0)F*=0.999**D.length}else if(Xv8.test(J.charAt(W-1))){if(F*=0.8,U=J.slice(X,W-1).match($v8),U&&X>0)F*=0.999**U.length}else if(F*=0.3,X>0)F*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(V))F*=0.9999}if(F<0.1&&(Z.charAt(W-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Z.charAt(W-1)!==Y.charAt(V))){if(z=e31(J,Q,Z,Y,W+1,V+2,K),z*0.1>F)F=z*0.1}if(F>H)H=F;W=Z.indexOf(G,W+1)}return K[q]=H,H}function t31(J){return J.toLowerCase().replace(RU6," ")}function jU6(J,Q){let Z=e31(J,Q,t31(J),t31(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let q of Y){let G=e31(J,q,t31(J),t31(q),0,0,{});if(G===0)return Z;X+=G,V+=q.length}let K=X/Y.length*0.95;return Math.max(Z,K)}return Z}class ZT{}class YT{}class J21{}class Q21{}class EU6 extends o1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new PU6}}class PU6 extends l1{build(J){return this.widget.onContext(J),this.widget.child}}function Kv8(J,Q){if(J==="")return{matches:!0,score:1};let Z=jU6(Q,J);return{matches:Z>0.15,score:Z}}class m7 extends o1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new IU6}}class IU6 extends l1{textController;focusNode;scrollController=new t4;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s2(this.widget.props.controller?.query??""),this.focusNode=new K4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),U4.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((Q)=>Yg1(Q,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Yg1(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Q=this.cachedFiltered.findIndex((Z)=>Yg1(Z,this.widget.props.controller?.selectedItem));if(Q>=0)this.selectedIndex=Q}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 ZT){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof YT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof J21){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof Q21)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Q=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Q;this.widget.props.onSelectionChange?.(Q)}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,Q=this.widget.props.items,Z=this.widget.props.normalizeQuery?.(J)??J,Y=Q.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...Kv8(Z,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;OC(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return!1;let Z=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Q.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(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Z};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Q===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Q=h1.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=d0.all(new x0(Z.foreground,1,"solid")),V=this.widget.props.enabled??!0,K=new $Y({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Z.background,textColor:Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,border:null},maxLines:1}),q=new B2({shortcuts:new Map([[new r0("ArrowDown"),new ZT],[new r0("ArrowUp"),new YT],[new r0("Tab"),new ZT],[new r0("Tab",{shift:!0}),new YT],[new r0("n",{ctrl:!0}),new ZT],[new r0("p",{ctrl:!0}),new YT],[new r0("Enter"),new J21],[new r0("Escape"),new Q21]]),focusNode:this.focusNode,child:K}),G=new M7({actions:new Map([[ZT,new i6(this.invoke)],[YT,new i6(this.invoke)],[J21,new i6(this.invoke)],[Q21,new i6(this.invoke)]]),child:q}),W=new G0({children:[new c1({decoration:{color:Z.background},child:new Z1({text:new S(">",new u({color:Z.foreground}))})}),new C0({child:G})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new P1({height:10,child:new s0({child:new Z1({text:new S(B,new u({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new C0({child:new s0({child:new Z1({text:new S(this.widget.props.emptyStateText,new u({color:Z.foreground,dim:!0}))})})});else{let B=Y.map((N,w)=>{let L=w===this.selectedIndex,O=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,L,O,J);else{let A=L?Q.app.selectionBackground:void 0,R=L?Q.app.selectionForeground:Z.foreground;M=new c1({decoration:A?{color:A}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S(this.widget.props.getLabel(N),new u({color:R,dim:O}))})})}return new EU6(new i0({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:M}),(A)=>{this.itemContexts[w]=A})});H=new b1({children:B,crossAxisAlignment:"start"})}let F=new i0({onScroll:this.handleScroll,opaque:!1,child:new S4({controller:this.scrollController,autofocus:!1,child:H})}),z=[];if(this.widget.props.title){let B=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S(this.widget.props.title,new u({color:Q.app.command,bold:!0}))})});z.push(B)}if(z.push(W,new P1({height:1})),this.textController.text!==""){let B=Y.length>0?Y[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B,J);z.push(new C0({child:new b1({mainAxisAlignment:"spaceBetween",children:[new C0({child:F}),new c1({padding:C1.only({top:1}),child:new s0({child:N??new P1({height:1})})})]})}))}else z.push(new C0({child:F}));if(this.widget.props.footer)z.push(this.widget.props.footer);return new c1({decoration:{border:X,color:Z.background},padding:C1.symmetric(1,0),child:new b1({children:z})})}}function CU6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),V=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Xg1 extends m0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>CU6(X.pubDate).length));return new m7({items:Q,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,V,K,q)=>{let G=h1.of(q),{colors:W}=G,H=G.app,F=V?H.selectionBackground:void 0,z=V?H.selectionForeground:W.foreground,U=W.mutedForeground,D=(B,N)=>new P1({width:N,child:G0.end([new Z1({text:new S(B,new u({color:U}))})])});return new c1({decoration:F?{color:F}:void 0,padding:C1.symmetric(2,0),child:new G0({children:[new C0({child:new Z1({text:new S(X.title,new u({color:z})),overflow:"ellipsis",maxLines:1})}),new P1({width:2}),D(CU6(X.pubDate),Z)]})})}})}}l6();class $g1 extends o1{createState(){return new TU6}}class TU6 extends l1{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 Z=h1.of(J).colors;return new Z1({text:new S("●",new u({color:this.isGreen?Z.success:Z.mutedForeground,bold:!0})),maxLines:1})}}var qv8=/\/threads\/(T-[^/?#\s<>]+)/i;function Gv8(J){let Q=J.trim(),Y=Q.match(qv8)?.[1];if(Y&&W5(Y))return Y;let X=Q.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(W5(X))return X;return null}function Wv8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let K of J)Q.set(K.id,K);for(let K of J){let q=K.relationships.find((G)=>G.role==="child"&&Q.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(q){Y.set(K.id,q.type);let G=q.threadID,W=Z.get(G)||[];W.push(K),Z.set(G,W)}else X.push(K)}return M71.flatten(X,(K)=>Z.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Vg1(J,Q,Z){return new Z1({text:new S(`${J}${Q}`,new u({color:Z})),maxLines:1})}function Hv8(J,Q,Z,Y){return[Vg1("+",J,Y.success),f9.horizontal(1),Vg1("~",Q,Y.warning),f9.horizontal(1),Vg1("-",Z,Y.destructive)]}class Z21 extends m0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((D)=>D.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((D)=>D.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=new Set(Z),X=this.props.currentThreadID,V=[...Q].sort((D,B)=>{if(X){if(D.id===X)return-1;if(B.id===X)return 1}let N=Z.indexOf(D.id),w=Z.indexOf(B.id);if(N!==-1&&w!==-1)return N-w;if(N!==-1)return-1;if(w!==-1)return 1;return 0}),K=Wv8(V),q=Math.max(0,...K.map((D)=>D.description.timeAgo.length)),G=h1.of(J),W=new i1({padding:C1.symmetric(0,1),child:new s0({child:new Z1({text:new S("",new u({color:G.colors.foreground,dim:!0}),[new S("Ctrl+T",new u({color:G.colors.primary,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new u({color:G.colors.foreground,dim:!0}))])})})}),H="",F=null,z=(D)=>{if(D!==H)H=D,F=Gv8(D);return F};return new m7({items:K,getLabel:(D)=>`${D.title} ${D.id}`,filterItem:(D,B)=>{let N=z(B);if(N)return D.id.toLowerCase()===N.toLowerCase();return!0},normalizeQuery:(D)=>z(D)?"":D,onAccept:(D,B)=>this.props.onSelect?.(D.id,B),onDismiss:this.props.onDismiss,onSelectionChange:(D)=>{if(this.props.previewController){if(D)this.props.previewController.select(D.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(D,B,N,w)=>{let L=h1.of(w),{app:O,colors:M}=L,A=B?O.selectionBackground:void 0,R=B?O.selectionForeground:M.foreground,j=M.mutedForeground,P=(i,g)=>new P1({width:g,child:G0.end([new Z1({text:new S(i,new u({color:j}))})])}),C=this.props.threadViewStates[D.id],_=[],v=D.relationshipType==="handoff",h=new Zm({connectorColor:M.mutedForeground});if(D.depth>0){let i=[],g=D.ancestorsAreLast.slice(1);for(let r of g)i.push(new S(h.getAncestorPrefix(r),new u({color:h.connectorColor,dim:h.connectorDim})));let a=D.isLast?h.elbow:h.tee,d=h.getConnectorText(a);i.push(new S(d,new u({color:h.connectorColor,dim:h.connectorDim}))),_.push(new Z1({text:new S("",void 0,i)}))}let b=[],k=X===D.id?new S("(current) ",new u({color:M.success})):Y.has(D.id)?new S("(visited) ",new u({color:M.foreground,dim:!0})):null;if(k)b.push(new Z1({text:k}));if(kL(C))b.push(new $g1),b.push(new P1({width:1}));let f=D.title;if(D.relationshipType==="fork"){let i=f.match(/^Forked\((\d+)\): /);if(i)f=f.slice(i[0].length);else while(f.startsWith("Forked: "))f=f.slice(8);b.push(new Z1({text:new S("[fork] ",new u({color:M.primary}))}))}else if(v)b.push(new Z1({text:new S("[handoff] ",new u({color:M.accent}))}));if(b.push(new C0({child:new Z1({text:new S(f,new u({color:R})),overflow:"ellipsis",maxLines:1})})),b.push(new P1({width:2})),D.diffStats&&(D.diffStats.added>0||D.diffStats.changed>0||D.diffStats.deleted>0)){let i=B?{success:j,warning:j,destructive:j}:M;b.push(...Hv8(D.diffStats.added,D.diffStats.changed,D.diffStats.deleted,i)),b.push(new P1({width:2}))}return b.push(P(D.description.timeAgo,q)),new c1({decoration:A?{color:A}:void 0,padding:C1.symmetric(2,0),child:new G0({children:[..._,...b]})})}})}}class SU6 extends o1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new kU6}}class kU6 extends l1{build(J){return this.widget.onContext(J),this.widget.child}}var _U6=30,Fv8=30;class XT{}class $T{}class Y21{}class X21{}class Kg1 extends o1{props;constructor(J){super();this.props=J}createState(){return new yU6}}class yU6 extends l1{highlightedIndex=0;controller=new s2;focusNode;scrollController=new t4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new K4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;OC(J,{top:Z,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Z)=>Z.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof XT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof $T){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Y21){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof X21)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Z=this.filteredClusters[J];if(Z)this.widget.props.onAccept(Z)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Q=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),U4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Q};build(J){let{currentThreadID:Q}=this.widget.props,Z=h1.of(J),{colors:Y,app:X}=Z,q=Q6.of(J).size.width>=Fv8+_U6,G=d0.all(new x0(Y.foreground,1,"solid")),W=this.filteredClusters[this.highlightedIndex]??null,H=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S("Select a cluster",new u({color:X.command,bold:!0}))})}),F=new $Y({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),z=new B2({shortcuts:new Map([[new r0("ArrowDown"),new XT],[new r0("ArrowUp"),new $T],[new r0("Tab"),new XT],[new r0("Tab",{shift:!0}),new $T],[new r0("n",{ctrl:!0}),new XT],[new r0("p",{ctrl:!0}),new $T],[new r0("Enter"),new Y21],[new r0("Escape"),new X21]]),focusNode:this.focusNode,child:F}),U=new M7({actions:new Map([[XT,new i6(this.invoke)],[$T,new i6(this.invoke)],[Y21,new i6(this.invoke)],[X21,new i6(this.invoke)]]),child:z}),D=new G0({children:[new c1({decoration:{color:Y.background},child:new Z1({text:new S(">",new u({color:Y.foreground}))})}),new C0({child:U})]});this.itemContexts=[];let B=this.filteredClusters.map((A,R)=>{let j=R===this.highlightedIndex,P=Q?A.threads.some((h)=>h.id===Q):!1,C=j?X.selectionBackground:void 0,_=j?X.selectionForeground:Y.foreground,v=[new S(A.label,new u({color:_})),new S(` (${A.threads.length})`,new u({color:_,dim:!0}))];if(P)v.push(new S(" (current)",new u({color:j?X.selectionForeground:Y.success})));return new SU6(new i0({onClick:(h)=>this.handleItemClick(R,h.clickCount),child:new c1({decoration:C?{color:C}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S("",void 0,v)})})}),(h)=>{this.itemContexts[R]=h})}),N=new b1({children:B,crossAxisAlignment:"start"}),w=new C0({child:new i0({onScroll:this.handleScroll,child:new S4({controller:this.scrollController,autofocus:!1,child:N})})}),L=W?W.threads.map((A)=>({id:A.id,title:A.title,parentID:A.parentID,updatedAt:A.updatedAt})):[],O=W?new c1({padding:C1.all(1),child:new sO({threads:L,autofocus:!1,offsetY:2})}):null,M;if(q){let A=O?new C0({child:O}):new P1({width:_U6});M=new G0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,A]})}else{let A=[new C0({child:new i0({onScroll:this.handleScroll,child:new S4({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)A.push(new C0({child:O}));M=new b1({crossAxisAlignment:"stretch",children:A})}return new c1({decoration:{border:G,color:Y.background},padding:C1.symmetric(1,0),child:new b1({children:[H,D,new P1({height:1}),new C0({child:M})]})})}}g1();class vU6 extends l1{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){T.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){T.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Q=J.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Z=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Q),X=Z.includes(Q);return!Y&&!X}build(J){let Q=h1.of(J),{app:Z,colors:Y}=Q,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new m7({title:"Add Label",items:G,getLabel:(W)=>{if("__isCreateMarker"in W)return this.currentQuery.trim().toLowerCase();return W.name},onAccept:(W)=>{if("__isCreateMarker"in W)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(W.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(W,H,F,z)=>{let U=H?Z.selectionBackground:void 0,D=H?Z.selectionForeground:Y.foreground;if("__isCreateMarker"in W&&W.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new c1({decoration:U?{color:U}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S("",void 0,[new S("Create new label: ",new u({color:D})),new S(N,new u({color:D,bold:!0}))])})})}return new c1({decoration:U?{color:U}:void 0,padding:C1.symmetric(2,0),child:new Z1({text:new S(W.name,new u({color:D}))})})},filterItem:(W,H)=>{if(this.currentQuery!==H)this.currentQuery=H,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in W&&W.__isCreateMarker)return this.shouldShowCreateMarker(H);let z=H.trim().toLowerCase();return z.length===0||W.name.includes(z)},sortItems:(W,H,F)=>{let z="__isCreateMarker"in W.item&&W.item.__isCreateMarker,U="__isCreateMarker"in H.item&&H.item.__isCreateMarker;if(z&&!U)return-1;if(!z&&U)return 1;return H.score-W.score}})}}class qg1 extends o1{props;constructor(J){super();this.props=J}createState(){return new vU6}}class AD extends o1{props;constructor(J){super();this.props=J}createState(){return new xU6}}class xU6 extends l1{_spinner=new b5;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=h1.of(J),{colors:Z,app:Y}=Q,X=d0.all(new x0(Z.foreground,1,"solid")),V=this._spinner.toBraille(),K=new Z1({textAlign:"center",text:new S("",void 0,[new S(V,new u({color:Y.processing})),new S(" ",void 0),new S(this.widget.props.message,new u({color:Z.foreground}))])}),G=[new C0({child:new b1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new P1({height:2,child:new c1({padding:C1.symmetric(2,0),child:new Z1({text:new S("",new u({dim:!0}),[new S("Press ",new u({color:Z.foreground})),new S("Esc",new u({color:Z.info})),new S(" to cancel",new u({color:Z.foreground}))])})})}));let W=new c1({decoration:new T6(Z.background,X),child:new P1({width:60,height:7,child:new b1({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new b6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:W});return W}}class eO extends o1{props;constructor(J){super();this.props=J}createState(){return new bU6}}class bU6 extends l1{scrollController=new t4;scrollAreaKey=new y3("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof KY}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Z=Q.size;if(typeof Z.height==="number"&&Z.height>0)return this.viewportHeight=Z.height,Z.height}return this.viewportHeight}build(J){let Q=h1.of(J),Z=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Z))return{title:Z.title,type:Z.type};if(Z instanceof Error&&Z.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Z.message};if(Z instanceof Error&&Z.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Z.message};let H=w71(Z);return{title:H.title,type:H.type,description:H.description}})(),X=Y.type==="error"?Q.app.toolError:Q.app.command,V=d0.all(new x0(Q.colors.border,1,"solid")),K=new c1({padding:C1.symmetric(1,0),child:new Z1({text:new S(Y.title,new u({color:X,bold:!0}))})}),q=this.isWidgetMessage(Z)?Z.widget:new Z1({text:new S(Y.description,new u({color:Q.colors.foreground})),selectable:!0}),G=new C0({child:new gJ({child:new c1({padding:C1.symmetric(1,0),child:new G0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new C0({child:new S4({controller:this.scrollController,autofocus:!0,child:q})}),new E5({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,F=this.scrollController.offset,z=this.getViewportHeight(),U=H+z;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(z,1),scrollOffset:Math.max(F,0)}}})]})})})}),W=new c1({padding:C1.symmetric(1,0),child:new Z1({text:(()=>{if(this.widget.props.onRetry)return new S("",void 0,[new S("Press ",new u({color:Q.colors.foreground,dim:!0})),new S("R",new u({color:Q.app.keybind})),new S(" to retry, ",new u({color:Q.colors.foreground,dim:!0})),new S("Esc",new u({color:Q.app.keybind})),new S(" to cancel",new u({color:Q.colors.foreground,dim:!0}))]);let H=this.resolveFooterStyle(this.widget.props.message);if(H==="none")return new S("",new u({color:Q.colors.foreground,dim:!0}));if(H==="help"){let F=new u({color:Q.app.keybind}),z=new u({color:Q.colors.foreground,dim:!0});return new S("",z,[new S("Press ",z),new S("Escape",F),new S(" to close • Use ",z),new S("↑↓",F),new S(" or ",z),new S("j/k",F),new S(" to scroll",z)])}return new S("Press any key to close",new u({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new b6({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c1({decoration:{border:V,color:Q.colors.background},padding:C1.all(1),child:new b1({mainAxisAlignment:"center",children:[K,new P1({height:1}),G,W]})})})}}class Gg1 extends m0{build(J){let Q=h1.of(J),{colors:Z,app:Y}=Q;return new s0({child:new Z1({text:new S("",void 0,[new S(`✓ Thread Shared
5368
5368
 
5369
5369
  `,new u({color:Y.toolSuccess,bold:!0})),new S(`This thread has been shared with Amp support for debugging and bug prioritization.
5370
5370
  `,new u({color:Z.foreground})),new S(`This is not a support request.
@@ -5756,7 +5756,7 @@ ${X}`,Q);this.line=Z,this.column=Y,this.codeblock=X}}/*!
5756
5756
  `)}function iB6(J,Q){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Z,Y)=>{let X=Y.optsWithGlobals(),V=await Q(X),K=await V.settings.get("proxy"),q=FA0({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(W,H)=>V.secrets.get(W,H)}}),G=await N4.userDisplayBalanceInfo({},{config:q});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(J0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(J0.red("Error: ")+G.error.message+`
5757
5757
  `),process.exit(1)}process.stdout.write(await Sb8(G.result.displayText)+`
5758
5758
  `),process.exit(0)})}var tg8=jJ1.join(XZ,"logs","headless.log"),mp1=jJ1.join(lI,"device-id.json");function eg8(){return yG.some((J)=>J.listConfigs().length>0)}try{if(process.platform==="win32")await Promise.resolve().then(() => B6(PT(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){H3.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
5759
- `)}function Jm8(J){process.emitWarning=(Q,Z,Y,X)=>{let V=typeof Q==="string"?Q:Q.message||String(Q),K=Z||"Warning",q=!1;J.warn(V,{name:K,code:Y})}}function d7(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LQ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")LQ("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli")LQ("systemPrompt",Q.systemPrompt)}function Qm8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function Zm8(J){try{let Q=new URL(J);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function RJ1(J){let Y=Zm8(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 Y6(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var zO6=[{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??jX,description:`Custom settings file path (overrides the default location ${jX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${JO})`},{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:u7(),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:WN.SMART.key,description:`Set the agent mode (${SY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SY().map((J)=>J.mode).concat("large","deep")},{name:"dtw",long:"dtw",type:"switch",description:"Use the DTW-backed thread provider in the TUI (experimental)",hidden:!0,aliases:["deliver-me-to-agg"]},{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:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text to append (SDK use only)",hidden:!0}],UO6=(J)=>("deprecated"in J)&&J.deprecated===!0,Ym8=(J)=>("hidden"in J)&&J.hidden===!0,Xm8=(J)=>("default"in J),$m8=(J)=>("default"in J)?J.default:void 0;function Vm8(J,Q){let Z=Q.args[0],Y=Q.commands.map((V)=>V.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let V=Y.filter((q)=>Z.includes(q)||q.includes(Z)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new Y6(o8.unknownCommand(Z),1,K)}}async function IJ1(J){return{...J,getThreadEnvironment:LU,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new y$(J.fileSystem),generateThreadTitle:WI,deleteThread:(Q)=>J.threadService.delete(Q),getServerStatus:()=>MZ(J.configService)}}var EJ1=z0.file(sg8.homedir()),pp1=process.env.XDG_CONFIG_HOME?z0.file(process.env.XDG_CONFIG_HOME):K0.joinPath(EJ1,".config");function Km8(J){return I96({playNotificationSound:async(Q)=>{if(J.useNotificationsForService){P96(Q);let Z=h91(),Y=pv1();if((!Z||Y||wY6())&&J.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(oW("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(oW("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(h91()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function qm8(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>S1.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function e5(J,Q){$A0("0.0.1771734754-g9b2f90");let Z=$o({storage:J.settings,secretStorage:J.secrets,workspaceRoots:S1.of([z0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:EJ1,userConfigDir:pp1});zY6(Z);let Y=await Z.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let{toolService:X,dispose:V}=M96({configService:Z}),K=new Map,q=()=>K.clear(),G=new sL1(Z,J.settings.getWorkspaceRootPath()),W=Jb0({configService:Z,filesystem:o4}),H=yk0({configService:Z,trustStore:G,skillMCPServers:W.skillMCPServers,createOAuthProvider:async(v,h,b)=>{let k=`${v}:${h}`,f=K.get(k);if(f)return T.debug("Reusing existing OAuth provider for server",{serverName:v,serverUrl:h}),f;T.debug("Creating OAuth provider for server",{serverName:v,serverUrl:h});let m=(async()=>{let i=new tN(J.secrets),g=await i.getClientInfo(v,h),a=b?.scopes??g?.scopes,d=vQ6();T.info("OAuth headless mode check",{useHeadless:d,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:a4.isTTY});let r;if(d)r=J.executeMode?yQ6():kQ6(v);let w1=new BL1({storage:i,serverName:v,serverUrl:h,clientId:b?.clientId??g?.clientId,clientSecret:b?.clientSecret??g?.clientSecret,authUrl:b?.authUrl??g?.authUrl,tokenUrl:b?.tokenUrl??g?.tokenUrl,scopes:a,headlessAuthHandler:r});return T.debug("OAuth provider created",{serverName:v,serverUrl:h,hasManualClientId:!!(b?.clientId??g?.clientId),willUseDCR:!(b?.clientId??g?.clientId),scopes:a,headlessMode:d,executeMode:J.executeMode}),w1})();return K.set(k,m),m}}),F=_41({configService:Z,filesystem:o4,spawn:oh}),z;if(J.executeMode){let v=await b66({toolService:X,providers:[H,F],initialTimeout:15000});z=v.registrations;for(let[h,b]of v.initErrors)T.warn(`${h} provider initialization slow or failed:`,b)}else z=c_1({toolService:X,providers:[H,F]});if(Q.jetbrains)TN("JetBrains");else if(Q.ide&&FZ6())TN("VS Code");else if(Q.ide&&zZ6())TN("Neovim");else if(Q.ide&&eg8()){let v=yG.find((h)=>h.listConfigs().length>0);if(v){let h=Go(v.ideName);if(h)TN(h)}}if(J.executeMode)VA0(!0);let U,D=F5.status.pipe(B0((v)=>Boolean(v.connected&&v.authenticated&&v.ideName&&RA0(v.ideName))),P6()).subscribe((v)=>{if(v){if(!U)U=X.registerTool(x66)}else U?.dispose(),U=void 0}),B;if(!J.executeMode){let v=await J.settings.get("fuzzy.alwaysIncludePaths")??[];B=new Z91(process.cwd(),{alwaysIncludePaths:v},!0)}else B=new class extends Z91{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};{let v=await J.secrets.get("apiKey",J.ampURL);if(T.info("API key lookup before login",{found:Boolean(v),ampURL:J.ampURL}),!v){a4.write(`No API key found. Starting login flow...
5759
+ `)}function Jm8(J){process.emitWarning=(Q,Z,Y,X)=>{let V=typeof Q==="string"?Q:Q.message||String(Q),K=Z||"Warning",q=!1;J.warn(V,{name:K,code:Y})}}function d7(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LQ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")LQ("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli")LQ("systemPrompt",Q.systemPrompt)}function Qm8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function Zm8(J){try{let Q=new URL(J);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function RJ1(J){let Y=Zm8(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 Y6(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var zO6=[{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??jX,description:`Custom settings file path (overrides the default location ${jX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${JO})`},{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:u7(),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:WN.SMART.key,description:`Set the agent mode (${SY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SY().map((J)=>J.mode).concat("large","deep")},{name:"dtw",long:"dtw",type:"switch",description:"Use the DTW-backed thread provider in the TUI (experimental)",hidden:!0,aliases:["deliver-me-to-agg"]},{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:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text to append (SDK use only)",hidden:!0}],UO6=(J)=>("deprecated"in J)&&J.deprecated===!0,Ym8=(J)=>("hidden"in J)&&J.hidden===!0,Xm8=(J)=>("default"in J),$m8=(J)=>("default"in J)?J.default:void 0;function Vm8(J,Q){let Z=Q.args[0],Y=Q.commands.map((V)=>V.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let V=Y.filter((q)=>Z.includes(q)||q.includes(Z)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new Y6(o8.unknownCommand(Z),1,K)}}async function IJ1(J){return{...J,getThreadEnvironment:LU,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new y$(J.fileSystem),generateThreadTitle:WI,deleteThread:(Q)=>J.threadService.delete(Q),getServerStatus:()=>MZ(J.configService)}}var EJ1=z0.file(sg8.homedir()),pp1=process.env.XDG_CONFIG_HOME?z0.file(process.env.XDG_CONFIG_HOME):K0.joinPath(EJ1,".config");function Km8(J){return I96({playNotificationSound:async(Q)=>{if(J.useNotificationsForService){P96(Q);let Z=h91(),Y=pv1();if((!Z||Y||wY6())&&J.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(oW("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(oW("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(h91()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function qm8(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>S1.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function e5(J,Q){$A0("0.0.1771747379-gbb5ca2");let Z=$o({storage:J.settings,secretStorage:J.secrets,workspaceRoots:S1.of([z0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:EJ1,userConfigDir:pp1});zY6(Z);let Y=await Z.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let{toolService:X,dispose:V}=M96({configService:Z}),K=new Map,q=()=>K.clear(),G=new sL1(Z,J.settings.getWorkspaceRootPath()),W=Jb0({configService:Z,filesystem:o4}),H=yk0({configService:Z,trustStore:G,skillMCPServers:W.skillMCPServers,createOAuthProvider:async(v,h,b)=>{let k=`${v}:${h}`,f=K.get(k);if(f)return T.debug("Reusing existing OAuth provider for server",{serverName:v,serverUrl:h}),f;T.debug("Creating OAuth provider for server",{serverName:v,serverUrl:h});let m=(async()=>{let i=new tN(J.secrets),g=await i.getClientInfo(v,h),a=b?.scopes??g?.scopes,d=vQ6();T.info("OAuth headless mode check",{useHeadless:d,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:a4.isTTY});let r;if(d)r=J.executeMode?yQ6():kQ6(v);let w1=new BL1({storage:i,serverName:v,serverUrl:h,clientId:b?.clientId??g?.clientId,clientSecret:b?.clientSecret??g?.clientSecret,authUrl:b?.authUrl??g?.authUrl,tokenUrl:b?.tokenUrl??g?.tokenUrl,scopes:a,headlessAuthHandler:r});return T.debug("OAuth provider created",{serverName:v,serverUrl:h,hasManualClientId:!!(b?.clientId??g?.clientId),willUseDCR:!(b?.clientId??g?.clientId),scopes:a,headlessMode:d,executeMode:J.executeMode}),w1})();return K.set(k,m),m}}),F=_41({configService:Z,filesystem:o4,spawn:oh}),z;if(J.executeMode){let v=await b66({toolService:X,providers:[H,F],initialTimeout:15000});z=v.registrations;for(let[h,b]of v.initErrors)T.warn(`${h} provider initialization slow or failed:`,b)}else z=c_1({toolService:X,providers:[H,F]});if(Q.jetbrains)TN("JetBrains");else if(Q.ide&&FZ6())TN("VS Code");else if(Q.ide&&zZ6())TN("Neovim");else if(Q.ide&&eg8()){let v=yG.find((h)=>h.listConfigs().length>0);if(v){let h=Go(v.ideName);if(h)TN(h)}}if(J.executeMode)VA0(!0);let U,D=F5.status.pipe(B0((v)=>Boolean(v.connected&&v.authenticated&&v.ideName&&RA0(v.ideName))),P6()).subscribe((v)=>{if(v){if(!U)U=X.registerTool(x66)}else U?.dispose(),U=void 0}),B;if(!J.executeMode){let v=await J.settings.get("fuzzy.alwaysIncludePaths")??[];B=new Z91(process.cwd(),{alwaysIncludePaths:v},!0)}else B=new class extends Z91{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};{let v=await J.secrets.get("apiKey",J.ampURL);if(T.info("API key lookup before login",{found:Boolean(v),ampURL:J.ampURL}),!v){a4.write(`No API key found. Starting login flow...
5760
5760
  `);let h=await Gm8(J),b=await J.secrets.get("apiKey",J.ampURL);if(T.info("Login flow completed",{success:h,storedKeyPresent:Boolean(b),ampURL:J.ampURL}),!h)await QO(),process.exit(1)}}{let v=await Z.getLatest(),h=v.settings.url,b=v.secrets.isSet?.[h];T.info("Config secrets state after login",{configURL:h,apiKeySet:b?.apiKey??!1})}let N=k0(MZ(Z).pipe(V9((v)=>v!=="pending"))),w=await Vb0({isDevelopment:!1}),L=await N;T.info("Server status resolved",{status:"ready",isAuthenticated:S5(L),isError:Kw(L),errorMessage:Kw(L)?L.error.message:void 0});let O=new I_1(w,Z),M=new P_1(w,{lazy:!0});T.info("Starting Amp background services");let A=Boolean(Q.dtw||Q.headless);if(A)T.info("DTW mode enabled: thread sync service disabled");let R=A?qm8():O16({threadService:O,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),j;F5.status.subscribe((v)=>{j=v});let P=new BD1({workspaceRoots:[z0.file(process.cwd())],fileSystem:Q.jetbrains||Q.ide?$O1:o4,getCurrentFile:()=>{if(!j?.openFile)return;try{return z0.parse(j.openFile)}catch(v){T.warn("Failed to parse current file URI",{uri:j.openFile,error:v});return}},getOpenFiles:()=>{if(!j?.visibleFiles?.length)return[];let v=j.openFile;return j.visibleFiles.filter((h)=>h!==v).map((h)=>{try{return z0.parse(h)}catch(b){return T.warn("Failed to parse visible file URI",{uri:h,error:b}),null}}).filter((h)=>h!==null)}}),C=new lv1,_={codebaseContextService:P,configService:Z,toolService:X,mcpService:H,skillService:W,toolboxService:F,trustStore:G,threadService:O,threadHistoryService:M,threadSyncService:R,threadStorage:w,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:B,fileSystem:Q.jetbrains||Q.ide?$O1:o4,terminal:C,serverStatus:L};return{..._,async asyncDispose(){if(_.mcpService.hasAuthenticatingClients())T.info("Waiting for OAuth authentication to complete before exit..."),await _.mcpService.waitForAuthentication();for(let v of z.values())v.dispose();await _.mcpService.dispose(),q(),await _.threadService.asyncDispose(),_.configService.unsubscribe(),V(),_.fuzzyServer.dispose(),_.threadSyncService.dispose(),_.settingsStorage[Symbol.dispose](),D.unsubscribe(),U?.dispose()}}}async function Gm8(J){if(!J.executeMode){if(!await wv1("Would you like to log in to Amp? [(y)es, (n)o]: "))return a4.write(`Login cancelled. Run the command again to retry.
5761
5761
  `),!1}return await NO6(J)}async function NO6(J){let Q=ng8(32).toString("hex"),Z=await Nv1(J.ampURL,Q),Y=new AbortController;try{await DK(Z,Y.signal)}catch(V){T.error("Error opening browser",{error:V})}let X=await Nv1(J.ampURL,Q,!1);a4.write(`If your browser does not open automatically, visit:
5762
5762
 
@@ -5764,7 +5764,7 @@ ${J0.blue.bold(X)}
5764
5764
 
5765
5765
  `);try{return await bZ6(J.ampURL,Q,J.secrets,Y),a4.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return T.error("Login failed",{error:V}),H3.write(`
5766
5766
  Login failed: ${V instanceof Error?V.message:String(V)}
5767
- `),!1}}function Wm8(){let J=new wU().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)YO(),process.exit(0);let D=U.originalError??U;l81(D)}),J.option("-V, --version","Print the version number and exit",()=>{let D;try{D=`, ${rF(new Date("2026-02-22T04:38:13.614Z"))} ago`}catch{}a4.write(`0.0.1771734754-g9b2f90 (released 2026-02-22T04:38:13.614Z${D??""})
5767
+ `),!1}}function Wm8(){let J=new wU().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)YO(),process.exit(0);let D=U.originalError??U;l81(D)}),J.option("-V, --version","Print the version number and exit",()=>{let D;try{D=`, ${rF(new Date("2026-02-22T08:08:29.677Z"))} ago`}catch{}a4.write(`0.0.1771747379-gbb5ca2 (released 2026-02-22T08:08:29.677Z${D??""})
5768
5768
  `),process.exit(0)}),J.addHelpText("after",GZ6()),J.configureHelp({formatHelp:WZ6}),J.command("logout").description("Log out by removing stored API key").action(async(U,D)=>{let B=D.optsWithGlobals(),N=await X9(B);await wm8(N)}),J.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(U,D)=>{let B=D.optsWithGlobals(),N=await X9(B);await Nm8(N,await ey1(B,N.settings))}),J.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(U,D,B)=>{let N=B.optsWithGlobals(),w=await X9(N);await LQ6(U??"get",w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.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(U,D)=>{let B=D.optsWithGlobals(),N=await X9(B);await OQ6(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
5769
5769
  Actions:
5770
5770
  add-message <message> Send a user message and wait for message_added
@@ -5821,8 +5821,8 @@ See: https://ampcode.com/news/stick-a-fork-in-it
5821
5821
 
5822
5822
  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 Hm8(J,{nonBlockingOwnershipCheck:Q=!1,onOwnershipError:Z}={},Y){if(!W5(J))throw new Y6(o8.invalidThreadId);let X=Date.now();if(T.info(`[fetchAndStartThread] Begin switch to thread ${J}`),Q)DO6(J,Y.configService).catch((W)=>{if(W instanceof Y6){if(Z){Z(W,J);return}gI(W,J);return}T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W})});else try{await DO6(J,Y.configService)}catch(W){if(W instanceof Y6)throw W;T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W})}let V=Date.now(),K=await Y.threadService.get(J)??void 0;T.info(`[fetchAndStartThread] Loaded thread in ${Date.now()-V}ms`),T.info(`[fetchAndStartThread] Loaded thread ${J}, agentMode: ${K?.agentMode??"undefined"}`);let q=Date.now(),G=await zm1(Y.workerDeps,{threadMeta:Y.visibility?Aq(Y.visibility):void 0,agentMode:K?void 0:Y.agentMode,thread:K,onFirstAssistantMessage:wO6});return T.info(`[fetchAndStartThread] Started worker in ${Date.now()-q}ms (total ${Date.now()-X}ms)`),G}async function Fm8(J){if(!J.userEmail||!hR(J.userEmail))throw new Y6("DTW TUI mode is only available for Amp employees",1);let Q=await J.secretStorage.get("apiKey",J.ampURL);T.info("[createDTWRuntime] Creating DTW provider",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL,hasApiKey:Boolean(Q)});let Z;try{Z=await CU.create({ampURL:J.ampURL,apiKey:Q,configService:J.configService,threadId:J.threadId,workerUrl:process.env.AMP_WORKER_URL})}catch(Y){throw T.error("[createDTWRuntime] Failed to create DTW provider",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL,error:Y}),Y}T.info("[createDTWRuntime] Creating DTW runtime",{threadId:Z.threadId});try{return await UC.create({provider:Z,deps:{threadService:J.threadService,configService:J.configService,toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:LU,fileChangeTrackerStorage:new y$(J.fileSystem),osFileSystem:J.fileSystem,deleteThread:(Y)=>J.threadService.delete(Y),generateThreadTitle:WI,mcpService:J.mcpService,ampURL:J.ampURL}})}catch(Y){throw T.error("[createDTWRuntime] Failed to create DTW runtime",{threadId:Z.threadId,error:Y}),Y}}async function zm8(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Q=(await rI()).trimEnd();return{userInput:J.execute,stdinInput:Q||null}}return{userInput:(await rI()).trimEnd(),stdinInput:null}}function Um8(J,Q,Z){if(J.streamJson&&!Q)throw new Y6("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Q)throw new Y6("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new Y6("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Q)throw new Y6("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Q)throw new Y6("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 Y6("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"}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&Z===""&&!J.streamJsonInput&&!J.headless)throw new Y6("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"
5823
5823
  Or pipe via stdin: echo "your message" | amp --execute`)}async function PJ1(J,Q,Z){let{userInput:Y,stdinInput:X}=await zm8(Q),V=!!Q.streamJson||!!Q.streamJsonThinking;Um8({...Q,streamJson:V},J.executeMode,Y),d7(Z,Q);let K=await e5(J,Q),q=await IJ1(K),{serverStatus:G}=K;if(Kw(G)){let b=uI(Error(G.error.message));if(b.message===o8.networkOffline||b.message===o8.networkTimeout)throw RJ1(J.ampURL);throw new Y6(o8.invalidAPIKey,1)}let W=S5(G)?G.user.email:void 0,H=S5(G)?G.features:[],F=S5(G)?G.workspace:null,z=Qm8(W),U=S5(G)?{...G.user,features:H,team:F??void 0}:null,D=tu(Q,U);if(D instanceof Error)z9(D.message);if((J.executeMode||V)&&C5(Q.mode)&&!z)throw new Y6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!W||!hR(W))throw new Y6("Headless DTW mode is only available for Amp employees",1);let b=await K.secretStorage.get("apiKey",J.ampURL);if(!b)throw new Y6("API key required for headless mode. Please run `amp login` first.",1);let k=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(k&&!W5(k))throw new Y6(`Invalid thread ID: ${k}`,1);await SQ6({ampURL:J.ampURL,apiKey:b,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:k,configService:K.configService,mcpService:K.mcpService,toolService:K.toolService,skillService:K.skillService,fileSystem:K.fileSystem}),await K.asyncDispose(),process.exit(0)}let B={threadService:K.threadService,workerDeps:q,createThread:async()=>{let b=await d81(J.settings,process.cwd(),U,D);if(b instanceof Error)z9(b.message);return zm1(q,{threadMeta:b?Aq(b):void 0,agentMode:Q.mode,onFirstAssistantMessage:wO6})},switchToThread:(b,k)=>Hm8(b,{nonBlockingOwnershipCheck:k?.nonBlockingOwnershipCheck??!1,onOwnershipError:k?.onOwnershipError},{configService:K.configService,threadService:K.threadService,workerDeps:q,visibility:D,agentMode:Q.mode})},N=async()=>{try{if(Q.dtw)return Fm8({userEmail:W,secretStorage:K.secretStorage,ampURL:J.ampURL,configService:K.configService,threadService:K.threadService,toolService:K.toolService,skillService:K.skillService,mcpService:K.mcpService,fileSystem:K.fileSystem,threadId:Q.threadId});return gB6(B,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(b){if(b instanceof Y6)throw b;throw await gI(b,Q.threadId),Error("handleError should have called process.exit()")}};if(Q.format==="jsonl")H3.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5824
- `),await QO(),process.exit(1);let w=(async()=>{try{let b=await K.configService.getLatest(),k=bi(b),f=await N4.getUserFreeTierStatus({},{config:K.configService,signal:AbortSignal.timeout(k)});if(f.ok)return T.info("User free tier status:",f),f.result}catch(b){throw T.error("Failed to fetch free tier status:",b),b}})(),L=await N(),O=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=await K.configService.getLatest();if(Km8({configService:K.configService,threadService:K.threadService,config:M,useNotificationsForService:O,threadViewStates$:()=>L.threadViewStates$}),J.executeMode){if(iZ6(K.mcpService,J.settings),!(L instanceof QM))throw new Y6("Execute mode is not supported in DTW runtime",1);let b=L.getWorkerForExecuteMode();if(await XQ6({worker:b,threadID:b.threadID,userInput:Y,stdinInput:X,dependencies:K,streamJson:V,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:J.ampURL,isDogfooding:z,agentMode:Q.mode,labels:Q.label}),Q.archive)await N4.archiveThread({thread:b.threadID,archived:!0},{config:K.configService});await K.asyncDispose(),process.exit(0)}let A=!1,R=!1,j=!1;if(Q.jetbrains||Q.ide){await CA0();let b=vN({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)R=!await K.configService.get("jetbrains.skipInstall")}else if(b.length===1){let k=b[0];if(k)F5.selectConfig(k)}else j=!0}let P=O91("0.0.1771734754-g9b2f90",K.settingsStorage),C=new $41(K.threadStorage),_=new M91(K.mcpService,J.settings.getWorkspaceRootPath());if(Y)await L.sendMessage({content:[{type:"text",text:Y}]});let v=await Rq();T.info("Loaded session state:",v);let h={...v,launchCount:v.launchCount+1};jq(h);try{await Fm1({codebaseContextService:K.codebaseContextService,stdout:process.stdout,history:new o81,fuzzyServer:K.fuzzyServer,settingsStorage:K.settingsStorage,threadService:K.threadService,threadHistoryService:K.threadHistoryService,threadFuzzyIndexer:C,skillService:K.skillService,configService:K.configService,internalAPIClient:N4,ampURL:J.ampURL,runtime:L,ideClient:F5,mcpService:K.mcpService,toolboxService:K.toolboxService,mcpTrustHandler:_,showJetBrainsInstaller:R,showIdePicker:A,showIdePickerHint:j,openThreadSwitcher:Q.openThreadSwitcher,updateService:P,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:h,freeTierStatusPromise:w,workspace:F??null,features:H,isDogfooding:z,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-02-22T04:38:13.614Z"})}finally{await L.dispose?.()}await K.asyncDispose(),process.exit(0)}async function X9(J){if(T.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)H3.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5825
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await uk0({get:async(q)=>{if(q!==yv)return;try{let G=await og8(mp1,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(q,G)=>{if(q!==yv)return;await ag8(jJ1.dirname(mp1),{recursive:!0}),await rg8(mp1,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:fY()});KA0(Y);let X=await nQ6({...J,workspaceTrust:{current:!0,changes:yS},getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let q=await cZ6(J.mcpConfig);X=lZ6(X,q)}let V=jJ1.dirname(X.getSettingsFilePath());E96(lI,V);let K=await X.get("url","global");if(!K)K=k2;if(T.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!PF(K))T.info("Targeting custom Amp server",{ampURL:K});return X=rM0(X),{executeMode:Q,isTTY:Z,ampURL:K,settings:X,secrets:XY6(await ey1(J,X))}}function Dm8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(q,G)=>G.toUpperCase()),K=J[Z+1];if(K&&!K.startsWith("--"))Q[V]=K,Z++}}return Q}async function Bm8(){let J=Dm8(process.argv),Q=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));EJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Q?tg8:void 0)});let Z=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Z||!Y&&!X)J0.level=0;if(Jm8(T),T.info("Starting Amp CLI.",{version:"0.0.1771734754-g9b2f90",buildTimestamp:"2026-02-22T04:38:13.614Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Y6(o8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Wm8().parseAsync(process.argv)}R96().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Bm8().catch(gI)});async function Nm8(J,Q){let Z=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Z)await J.settings.set("url",process.env.AMP_URL,"global"),a4.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5824
+ `),await QO(),process.exit(1);let w=(async()=>{try{let b=await K.configService.getLatest(),k=bi(b),f=await N4.getUserFreeTierStatus({},{config:K.configService,signal:AbortSignal.timeout(k)});if(f.ok)return T.info("User free tier status:",f),f.result}catch(b){throw T.error("Failed to fetch free tier status:",b),b}})(),L=await N(),O=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=await K.configService.getLatest();if(Km8({configService:K.configService,threadService:K.threadService,config:M,useNotificationsForService:O,threadViewStates$:()=>L.threadViewStates$}),J.executeMode){if(iZ6(K.mcpService,J.settings),!(L instanceof QM))throw new Y6("Execute mode is not supported in DTW runtime",1);let b=L.getWorkerForExecuteMode();if(await XQ6({worker:b,threadID:b.threadID,userInput:Y,stdinInput:X,dependencies:K,streamJson:V,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:J.ampURL,isDogfooding:z,agentMode:Q.mode,labels:Q.label}),Q.archive)await N4.archiveThread({thread:b.threadID,archived:!0},{config:K.configService});await K.asyncDispose(),process.exit(0)}let A=!1,R=!1,j=!1;if(Q.jetbrains||Q.ide){await CA0();let b=vN({jetbrainsOnly:Q.jetbrains});if(b.length===0){if(Q.jetbrains)R=!await K.configService.get("jetbrains.skipInstall")}else if(b.length===1){let k=b[0];if(k)F5.selectConfig(k)}else j=!0}let P=O91("0.0.1771747379-gbb5ca2",K.settingsStorage),C=new $41(K.threadStorage),_=new M91(K.mcpService,J.settings.getWorkspaceRootPath());if(Y)await L.sendMessage({content:[{type:"text",text:Y}]});let v=await Rq();T.info("Loaded session state:",v);let h={...v,launchCount:v.launchCount+1};jq(h);try{await Fm1({codebaseContextService:K.codebaseContextService,stdout:process.stdout,history:new o81,fuzzyServer:K.fuzzyServer,settingsStorage:K.settingsStorage,threadService:K.threadService,threadHistoryService:K.threadHistoryService,threadFuzzyIndexer:C,skillService:K.skillService,configService:K.configService,internalAPIClient:N4,ampURL:J.ampURL,runtime:L,ideClient:F5,mcpService:K.mcpService,toolboxService:K.toolboxService,mcpTrustHandler:_,showJetBrainsInstaller:R,showIdePicker:A,showIdePickerHint:j,openThreadSwitcher:Q.openThreadSwitcher,updateService:P,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:h,freeTierStatusPromise:w,workspace:F??null,features:H,isDogfooding:z,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-02-22T08:08:29.677Z"})}finally{await L.dispose?.()}await K.asyncDispose(),process.exit(0)}async function X9(J){if(T.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)H3.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5825
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await uk0({get:async(q)=>{if(q!==yv)return;try{let G=await og8(mp1,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(q,G)=>{if(q!==yv)return;await ag8(jJ1.dirname(mp1),{recursive:!0}),await rg8(mp1,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:fY()});KA0(Y);let X=await nQ6({...J,workspaceTrust:{current:!0,changes:yS},getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let q=await cZ6(J.mcpConfig);X=lZ6(X,q)}let V=jJ1.dirname(X.getSettingsFilePath());E96(lI,V);let K=await X.get("url","global");if(!K)K=k2;if(T.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!PF(K))T.info("Targeting custom Amp server",{ampURL:K});return X=rM0(X),{executeMode:Q,isTTY:Z,ampURL:K,settings:X,secrets:XY6(await ey1(J,X))}}function Dm8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(q,G)=>G.toUpperCase()),K=J[Z+1];if(K&&!K.startsWith("--"))Q[V]=K,Z++}}return Q}async function Bm8(){let J=Dm8(process.argv),Q=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));EJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Q?tg8:void 0)});let Z=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Z||!Y&&!X)J0.level=0;if(Jm8(T),T.info("Starting Amp CLI.",{version:"0.0.1771747379-gbb5ca2",buildTimestamp:"2026-02-22T08:08:29.677Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Y6(o8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Wm8().parseAsync(process.argv)}R96().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Bm8().catch(gI)});async function Nm8(J,Q){let Z=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Z)await J.settings.set("url",process.env.AMP_URL,"global"),a4.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5826
5826
  `);else if(!PF(J.ampURL))a4.write(`Logging in to ${new URL(J.ampURL).hostname}
5827
5827
  `);let Y=process.env.AMP_API_KEY;if(Y)a4.write(`API key found in environment variable, storing...
5828
5828
  `),await Q.set("apiKey",Y,J.ampURL),a4.write(`API key successfully stored.
@@ -5838,7 +5838,7 @@ Or pipe via stdin: echo "your message" | amp --execute`)}async function PJ1(J,Q,
5838
5838
  `)),await X.asyncDispose(),process.exit(0)}catch(V){await X.asyncDispose(),z9(`Failed to ${Y?"archive":"unarchive"} thread: ${V instanceof Error?V.message:String(V)}`)}}async function Mm8(J,Q,Z){let Y=await e5(Q,J);try{let X=zM(Z);if(!X)UM(Z);await Y.threadService.delete(X),a4.write(J0.green(`✓ Thread ${X} deleted
5839
5839
  `)),await Y.asyncDispose(),process.exit(0)}catch(X){await Y.asyncDispose(),z9(`Failed to delete thread: ${X instanceof Error?X.message:String(X)}`)}}async function Am8(J,Q,Z,Y){d7(Y,J);let X=await e5(Q,J);try{let V=zM(Z);if(!V)UM(Z);let q=await jH(V,X),G=FU(q);a4.write(G+`
5840
5840
  `),await X.asyncDispose(),process.exit(0)}catch(V){await X.asyncDispose();let K=`Failed to render thread as markdown: ${V instanceof Error?V.message:String(V)}`;z9(K)}}async function Rm8(J,Q,Z,Y){d7(Y,J);let X=await e5(Q,J);try{let V=zM(Z);if(!V)UM(Z);let q=await jH(V,X),G=JSON.stringify(q,null,2);a4.write(G+`
5841
- `),await X.asyncDispose(),process.exit(0)}catch(V){await X.asyncDispose();let K=`Failed to export thread: ${V instanceof Error?V.message:String(V)}`;z9(K)}}async function jm8(J,Q,Z,Y,X){d7(X,J);let V=await e5(Q,J);try{let K=await CJ1(Z),q=await jH(K,V),G=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),F=parseInt(Y.toolProgressDelay||"800",10),z=parseInt(Y.exitDelay||"3",10)*1000,U=Y.indicator!==!1,D=await IJ1(V),B=q.id;await V.threadStorage.set(B,q);let N=await i5.getOrCreateForThread(D,B);await N.resume();let w=Y41.fromWorker(N),L=new $41(V.threadStorage),O=new M91(V.mcpService,Q.settings.getWorkspaceRootPath()),M=O91("0.0.1771734754-g9b2f90",V.settingsStorage),A=_41({configService:V.configService,filesystem:o4,spawn:oh}),R=new QM({threadService:V.threadService,workerDeps:D,createThread:async()=>w,switchToThread:async()=>w},w);try{await Fm1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new o81,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadFuzzyIndexer:L,skillService:V.skillService,configService:V.configService,internalAPIClient:N4,ampURL:Q.ampURL,runtime:R,ideClient:F5,mcpService:V.mcpService,toolboxService:A,mcpTrustHandler:O,showJetBrainsInstaller:!1,updateService:M,isDogfooding:!1,replayMode:{thread:q,typingEnabled:G,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:F,exitDelayMs:z,showIndicator:U},freeTierStatusPromise:Promise.resolve({canUseAmpFree:!0,isDailyGrantEnabled:!1}),features:[],buildTimestamp:"2026-02-22T04:38:13.614Z"})}finally{await R.dispose?.()}await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose(),await gI(K,Z)}}async function Em8(J,Q,Z,Y,X){d7(Y,J);let V=await e5(Q,J);try{let K=zM(Z);if(!K)UM(Z);let q=K,G=await N4.getUserInfo({},{config:V.configService}),W=G.ok?G.result:null,H=tu(J,W);if(!H&&!X)z9("Must specify either --visibility or --support");if(H&&X)z9("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)z9(H.message);if(H)await V.threadSyncService.updateThreadMeta(q,Aq(H)),a4.write(J0.green("✓ ")+`Thread ${q} visibility changed to ${H}.
5841
+ `),await X.asyncDispose(),process.exit(0)}catch(V){await X.asyncDispose();let K=`Failed to export thread: ${V instanceof Error?V.message:String(V)}`;z9(K)}}async function jm8(J,Q,Z,Y,X){d7(X,J);let V=await e5(Q,J);try{let K=await CJ1(Z),q=await jH(K,V),G=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),F=parseInt(Y.toolProgressDelay||"800",10),z=parseInt(Y.exitDelay||"3",10)*1000,U=Y.indicator!==!1,D=await IJ1(V),B=q.id;await V.threadStorage.set(B,q);let N=await i5.getOrCreateForThread(D,B);await N.resume();let w=Y41.fromWorker(N),L=new $41(V.threadStorage),O=new M91(V.mcpService,Q.settings.getWorkspaceRootPath()),M=O91("0.0.1771747379-gbb5ca2",V.settingsStorage),A=_41({configService:V.configService,filesystem:o4,spawn:oh}),R=new QM({threadService:V.threadService,workerDeps:D,createThread:async()=>w,switchToThread:async()=>w},w);try{await Fm1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new o81,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadFuzzyIndexer:L,skillService:V.skillService,configService:V.configService,internalAPIClient:N4,ampURL:Q.ampURL,runtime:R,ideClient:F5,mcpService:V.mcpService,toolboxService:A,mcpTrustHandler:O,showJetBrainsInstaller:!1,updateService:M,isDogfooding:!1,replayMode:{thread:q,typingEnabled:G,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:F,exitDelayMs:z,showIndicator:U},freeTierStatusPromise:Promise.resolve({canUseAmpFree:!0,isDailyGrantEnabled:!1}),features:[],buildTimestamp:"2026-02-22T08:08:29.677Z"})}finally{await R.dispose?.()}await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose(),await gI(K,Z)}}async function Em8(J,Q,Z,Y,X){d7(Y,J);let V=await e5(Q,J);try{let K=zM(Z);if(!K)UM(Z);let q=K,G=await N4.getUserInfo({},{config:V.configService}),W=G.ok?G.result:null,H=tu(J,W);if(!H&&!X)z9("Must specify either --visibility or --support");if(H&&X)z9("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)z9(H.message);if(H)await V.threadSyncService.updateThreadMeta(q,Aq(H)),a4.write(J0.green("✓ ")+`Thread ${q} visibility changed to ${H}.
5842
5842
  `);if(X){await jH(q,V);let F=typeof X==="string"?X:void 0;await Ek0(V.threadService,q,V.configService,F),a4.write(J0.green("✓ ")+`Thread ${q} has been shared with Amp support. These thread reports will be aggregated and analysed.
5843
5843
  `)}await V.asyncDispose(),process.exit(0)}catch(K){await V.asyncDispose(),z9(`Failed to update thread: ${K instanceof Error?K.message:String(K)}`)}}async function Pm8(J,Q,Z,Y,X,V){d7(V,J);let K=await e5(Q,J);try{let q=await CJ1(Z);await jH(q,K);let G=Y;if(!G){let B=(await rI()).trimEnd();if(B)G=B}if(!G)z9(`Goal must be provided via stdin or --goal argument.
5844
5844
  Example: echo "Continue the auth work" | amp threads handoff T-xxx
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1771734754-g9b2f90",
3
+ "version": "0.0.1771747379-gbb5ca2",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {