@sourcegraph/amp 0.0.1774930833-ga819cc → 0.0.1774932368-g0d0b3f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6200,11 +6200,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6200
6200
|
${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
|
|
6201
6201
|
|
|
6202
6202
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6203
|
-
npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function bY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=RP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return C.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var ZQ3="https://static.ampcode.com/cli/cli-version.txt";async function hY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${ZQ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=RP4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var QQ3=604800000;function jP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>QQ3)return{ageMs:Q};return null}function RP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function da0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function ca0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(d6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await uY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await hY0(J):await bY0(J,Lj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ua0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await _i(U.latestVersion,q);let D=await ww(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Sz}from"node:process";function IP4(J){let Z=new uN().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 va0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6203
|
+
npm install -g @sourcegraph/amp`;z(Error(D))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();hM();async function bY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=RP4(J,F),W=q<0,U,H;if(G.time){let D=G.time[J],B=G.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(z){return C.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var ZQ3="https://static.ampcode.com/cli/cli-version.txt";async function hY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${ZQ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=RP4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var QQ3=604800000;function jP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>QQ3)return{ageMs:Q};return null}function RP4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function da0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function ca0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(d6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await uY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await hY0(J):await bY0(J,Lj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ua0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await _i(U.latestVersion,q);let D=await ww(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hM();import{stderr as Sz}from"node:process";function IP4(J){let Z=new uN().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 va0(Y.force||!1,Y.verbose||!1,"0.0.1774932368-g0d0b3f"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new uN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await YQ3(Y.targetVersion)});J.addCommand(Q)}async function YQ3(J){let Z=process.platform==="win32"&&fY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Sz.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6204
6204
|
|
|
6205
6205
|
`));try{if(!J){Sz.write(o0.blue(`Checking for updates...
|
|
6206
|
-
`));let{hasUpdate:K,latestVersion:V}=fY0()?await hY0("0.0.
|
|
6207
|
-
`));let F=await ww("0.0.
|
|
6206
|
+
`));let{hasUpdate:K,latestVersion:V}=fY0()?await hY0("0.0.1774932368-g0d0b3f"):await bY0("0.0.1774932368-g0d0b3f",Lj());if(!K){let z=da0("0.0.1774932368-g0d0b3f"),G=z?.age?`released ${z.age} ago`:`built ${MF(new Date("2026-03-31T04:49:57.536Z"))} ago`;Sz.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774932368-g0d0b3f"} (${G})
|
|
6207
|
+
`));let F=await ww("0.0.1774932368-g0d0b3f",Q);if(F.warning)Sz.write(`
|
|
6208
6208
|
`+o0.yellow(F.warning)+`
|
|
6209
6209
|
`);process.exit(0)}if(!V)Sz.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}Sz.write(o0.blue(`Updating to version ${J}...
|
|
6210
6210
|
`)),await _i(J,void 0,(K)=>{Sz.write(o0.dim(`Running: ${K}
|
|
@@ -7376,7 +7376,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7376
7376
|
`),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new P(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new P(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new P(`
|
|
7377
7377
|
`))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new n0({padding:C0.symmetric(0,1),child:new e({text:new P(void 0,void 0,K)})})})}}class G01 extends x${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=Iz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new V01({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function Rh4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?v9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function aR3(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=z>0?V/z:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=z>0?V/z:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function oR3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function rR3(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function sR3(J,Z,Q,Y,X,K,V){let z;try{let D=x1.of(J),B=f0.of(J);z={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new g({color:z.foreground,bold:!0}),F=new g({color:z.foreground}),q=new g({color:z.foreground,dim:!0}),W=[],U=new g({color:z.foreground,underline:!0}),H=(D,B)=>new P(B,U,void 0,aY0(D),()=>{b3(J,D)});if(Y.length<=1){if(W.push(new P(`${Z.label}: `,G)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new P(K(Z.value),F));if(Z.meta)W.push(new P(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new P(`${Z.label}
|
|
7378
7378
|
`,G));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??z.foreground;if(W.push(new P("● ",new g({color:O}))),W.push(new P(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new P(K(L.value),F));if(N<Y.length-1||D)W.push(new P(`
|
|
7379
|
-
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new P(void 0,void 0,W)})})}tO();m0();_7();YE();B$();x3();_2();wd();CX();L$();rJ();ZQ();NA();d4();bg();_P();O1();m0();L$();class F01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774930833-ga819cc"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await D40(Z,this.configService)}catch(Z){C.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VL extends l0{props;constructor(J){super();this.props=J}createState(){return new Ih4}}class Ih4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Ph4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new P(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new g({color:Y.keybind}))),W.push(new P(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new P("Esc",new g({color:Y.keybind}))),W.push(new P(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new u3,U]})})}}class Aa extends l0{props;constructor(J){super();this.props=J}createState(){return new Ph4}}ZQ();import{mkdtemp as $I3,readFile as JI3,rmdir as ZI3,unlink as QI3,writeFile as YI3}from"node:fs/promises";import{tmpdir as XI3}from"node:os";import xh4 from"node:path";m0();m0();class Ch4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class DR extends Ch4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Th4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class q01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class W01 extends o3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new _h4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class _h4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var tR3=500;class U01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new DR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(C.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},tR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class ja{}class Ra{}class Ia{}class Cz0{}class Tz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sh4(this.props)}}class Sh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new La;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new U01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Th4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof ja)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ia)return this.controller.acceptSelected(),"handled";if(J instanceof Cz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new ja],[new D4("ArrowUp"),new Ra],[new D4("n",{ctrl:!0}),new ja],[new D4("p",{ctrl:!0}),new Ra],[new D4("Enter"),new Ia],[new D4("Escape"),new Cz0],[new D4("Tab"),new Ia]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new A7({actions:new Map([[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Ia,new D6(this.invoke)],[Cz0,new D6(this.invoke)]]),child:Q});return new wa({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new q01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{WR.of(this.context).insert(this.overlayEntry)}catch(J){C.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new P(Q,new g({color:f0.of(J).app.command})),new P(" ",new g({color:Z})));return X.push(new P(Y,new g({color:Z}))),[{child:new e({text:new P(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=K4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new P(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=K4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=K4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new t8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new W01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function kh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function vh4(J){switch(J.type){case"file":return J.path;case"hint":return`${eR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function yh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function eR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class yq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7379
|
+
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),F))}return new d0({decoration:{color:z.background,border:c1.all(new g1(z.border,1,"rounded"))},child:new e({text:new P(void 0,void 0,W)})})}tO();m0();_7();YE();B$();x3();_2();wd();CX();L$();rJ();ZQ();NA();d4();bg();_P();O1();m0();L$();class F01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774932368-g0d0b3f"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await D40(Z,this.configService)}catch(Z){C.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VL extends l0{props;constructor(J){super();this.props=J}createState(){return new Ih4}}class Ih4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Ph4 extends p0{controller=new r7;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new g1(Q.foreground,1,"solid")),G=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new P(">",new g({color:Q.foreground}))})}),new y1({child:G})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new g({color:Y.keybind}))),W.push(new P(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new P("Esc",new g({color:Y.keybind}))),W.push(new P(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,W)})});return new d0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new u3,U]})})}}class Aa extends l0{props;constructor(J){super();this.props=J}createState(){return new Ph4}}ZQ();import{mkdtemp as $I3,readFile as JI3,rmdir as ZI3,unlink as QI3,writeFile as YI3}from"node:fs/promises";import{tmpdir as XI3}from"node:os";import xh4 from"node:path";m0();m0();class Ch4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class DR extends Ch4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Th4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class q01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class W01 extends o3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new _h4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class _h4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var tR3=500;class U01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new DR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let z of this._triggers){let G=z.detect(Z,Y);if(G&&(!X||G.start>X.start))X=G}if(!this.currentState.isActive&&X&&X.query.length>0){let z=f6(Z),G=Y,F=G;while(F<z.length){let q=z[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>G){let W=[...z.slice(0,G),...z.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(C.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},tR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class ja{}class Ra{}class Ia{}class Cz0{}class Tz0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sh4(this.props)}}class Sh4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new La;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new U01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Th4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof ja)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ia)return this.controller.acceptSelected(),"handled";if(J instanceof Cz0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let z=Math.max(0,Q-Y);V=Math.min(V,z),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new ja],[new D4("ArrowUp"),new Ra],[new D4("n",{ctrl:!0}),new ja],[new D4("p",{ctrl:!0}),new Ra],[new D4("Enter"),new Ia],[new D4("Escape"),new Cz0],[new D4("Tab"),new Ia]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new A7({actions:new Map([[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[Ia,new D6(this.invoke)],[Cz0,new D6(this.invoke)]]),child:Q});return new wa({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new q01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{WR.of(this.context).insert(this.overlayEntry)}catch(J){C.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new P(Q,new g({color:f0.of(J).app.command})),new P(" ",new g({color:Z})));return X.push(new P(Y,new g({color:Z}))),[{child:new e({text:new P(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=K4.sizeOf(J).height,z=0;try{let R=this.layerLink.getTargetTransform();if(R)z=R.position.y}catch{}let G=this.props.autoOverlayPosition?z<V/3:!1,F=2,q;if(G){let R=this.props.controller.getCursorVisualRow(),_=z+R+1;q=V-_-F}else q=z-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new P(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=K4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=K4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(G)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new t8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new W01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function kh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function vh4(J){switch(J.type){case"file":return J.path;case"hint":return`${eR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function yh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function eR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class yq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
7380
7380
|
`))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class BR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new fh4(this.props)}}var KI3=":";class fh4 extends p0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new V3;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new yq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let z=X.query.toLowerCase().startsWith(KI3);if(z!==this._isCommitMode)this._isCommitMode=z,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=J.kind==="commit"?"@:":"@@",G=K+z+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),z=`git-commit(${J.hash})`,G=K+z+" "+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+z.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new G6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Ib4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await $I3(xh4.join(XI3(),"amp-edit-")),Q=xh4.join(Z,"message.amp.md");await YI3(Q,J,"utf-8"),await gK(Q);try{let Y=await JI3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")C.error("Failed to read temporary file",Y)}try{await QI3(Q),await ZI3(Z)}catch(Y){C.warn("Failed to clean up temporary file",Y)}}catch(Z){C.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new W1({mainAxisSize:"min",children:[new e({text:new P("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((G,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new P(G.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new P(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new P("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((G,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new P(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new P(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new P(" ")}),new e({text:new P(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new Tz0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(G)=>vh4(G),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(G,F,q)=>{let W=q?Z.selection:void 0,U=Z.secondary,H=Z.foreground,D=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new P("",void 0,[new P(F.shortHash,new g({color:Z.secondary})),new P(" ",new g({})),new P(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new P(` ${F.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(F.type){case"file":N.push(new P("@",new g({color:U}))),N.push(new P(F.path,new g({color:H})));break;case"hint":N.push(new P(F.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new P(" ",new g({}))),N.push(new P(F.message,new g({color:B})));break}let w=yh4(F);if(w)N.push(new P(" - ",new g({color:D,dim:!0}))),N.push(new P(w,new g({color:D,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new P("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),z=[];if(this.props.topWidget)z.push(this.props.topWidget);if(X||K){let G=[];if(X)G.push(X);if(X&&K)G.push(new e({text:new P(" ")}));if(K)G.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:G})});z.push(F)}if(z.push(new y1({child:V})),this.props.bottomWidget)z.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:z})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class uh4 extends p0{controller=new r7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=CV)return!1;let Z=await ZL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=K4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),z=new BR({controller:this.controller,triggers:[new yq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),G=new s4({focusNode:this.focusNode,child:z}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:G}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new d0({padding:C0.symmetric(1,0),child:new e({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new g({color:Y.keybind})),new P(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new g({color:Q.foreground,dim:!0})),new P("Enter",new g({color:Y.keybind})),new P(" to submit, ",new g({color:Q.foreground,dim:!0})),new P("Esc",new g({color:Y.keybind})),new P(" to clear",new g({color:Q.foreground,dim:!0}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class H01 extends l0{props;constructor(J){super();this.props=J}createState(){return new uh4}}import{isDeepStrictEqual as D01}from"node:util";var VI3=/[\\/_ +.#"@[({&]/,zI3=/[\\/_ +.#"@[({&]/g,GI3=/[\s-]/,bh4=/[\s-]/g;function Sz0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,H,D;while(F>=0){if(W=Sz0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(GI3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(bh4),D&&X>0)W*=0.999**D.length}else if(VI3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(zI3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Sz0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function _z0(J){return J.toLowerCase().replace(bh4," ")}function hh4(J,Z){let Q=Sz0(J,Z,_z0(J),_z0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=Sz0(J,z,_z0(J),_z0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Hy{}class Dy{}class kz0{}class vz0{}class gh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new mh4}}class mh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function FI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=hh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new ph4}}class ph4 extends p0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r7(this.widget.props.controller?.query??""),this.focusNode=new G6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>D01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!D01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>D01(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Hy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Dy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof kz0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof vz0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...FI3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Hy],[new D4("ArrowUp"),new Dy],[new D4("Tab"),new Hy],[new D4("Tab",{shift:!0}),new Dy],[new D4("n",{ctrl:!0}),new Hy],[new D4("p",{ctrl:!0}),new Dy],[new D4("Enter"),new kz0],[new D4("Escape"),new vz0]]),focusNode:this.focusNode,child:z}),F=new A7({actions:new Map([[Hy,new D6(this.invoke)],[Dy,new D6(this.invoke)],[kz0,new D6(this.invoke)],[vz0,new D6(this.invoke)]]),child:G}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new P(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new P(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new P(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new P(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new gh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new d0({padding:C0.symmetric(1,0),child:new e({text:new P(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:w??new R0({height:1})})})]})}))}else H.push(new y1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function dh4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class B01 extends J4{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>dh4(X.pubDate).length));return new $7({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new R0({width:N,child:W1.end([new e({text:new P(B,new g({color:H}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new P(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(dh4(X.pubDate),Q)]})})}})}}bP();class N01 extends l0{createState(){return new ch4}}class ch4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new P("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function qI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return YV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function w01(J,Z,Q){return new e({text:new P(`${J}${Z}`,new g({color:Q})),maxLines:1})}function WI3(J,Z,Q,Y){return[w01("+",J,Y.success),u3.horizontal(1),w01("~",Z,Y.warning),u3.horizontal(1),w01("-",Q,Y.destructive)]}function UI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class yz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new lh4}}class lh4 extends p0{spinner=new V3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((L,O)=>{if(G){if(L.id===G)return-1;if(O.id===G)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=qI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new n0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new P("",new g({color:U.colors.foreground,dim:!0}),[new P("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new P(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=C2(L);return B};return new $7({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!UI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new P(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new rn({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new P(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,H0=d.getConnectorText(r);a.push(new P(H0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new P("",void 0,a)}))}let p=[],h=G===L.id?new P("(current) ",new g({color:R.success})):z.has(L.id)?new P("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(DN(y))p.push(new N01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new P("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new P("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new P(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...WI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function ih4(J){return 1-(1-J)**3}function nh4(J,Z,Q){return J+(Z-J)*Q}function Pa(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=ih4(Y),V=ih4(X);return{x:nh4(J.startOffset.x,J.targetOffset.x,K),y:nh4(J.startOffset.y,J.targetOffset.y,V)}}var HI3={nodeWidth:3,horizontalSpacing:3};class By{options;constructor(J={}){this.options={...HI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:G}}),D};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var DI3={nodeWidth:3,nodeHeight:2};class Ny{options;constructor(J={}){this.options={...DI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var BI3={nodeWidth:3,nodeHeight:2},NI3={x:0,y:0};class fz0{options;constructor(J={}){this.options={...BI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=NI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new P("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new uz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new P(V,new g({color:G,bold:F}))}),new e({text:new P(z,new g({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new P(z,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new e({text:new P("│ ",new g({color:F}),[new P(U+H,new g({color:q??F})),new P(" │",new g({color:F}))])}))}return W.push(new e({text:new P(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+z;if(H>=0&&H<Y)F[H]="▲"}V.push(new e({text:new P(F.join(""),new g({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+z,B=H.map((L)=>L.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new P(q.join(""),new g({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+z;if(D>=0&&D<Y)W[D]="│"}return V.push(new e({text:new P(W.join(""),new g({color:G}))})),V}}var wI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},LI3={x:0,y:0};class L01{options;constructor(J={}){this.options={...wI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=LI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new P("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new uz(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new P(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new P(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,H=W.map((N)=>N.position.x+z),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new e({text:new P(F.join(""),new g({color:G}))})),V}}class Ca extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new ah4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class ah4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class NR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new sh4}}var oh4=400,rh4=300,OI3=16;class sh4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new By({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Ny;renderer=new L01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:oh4,durationY:rh4};let Z=Math.max(oh4,rh4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Pa(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},OI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new Ca({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class eh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new $g4}}class $g4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var th4=30,EI3=30;class wy{}class Ly{}class uz0{}class bz0{}class O01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Jg4}}class Jg4 extends p0{highlightedIndex=0;controller=new r7;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new G6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;zy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ly){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof uz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof bz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=K4.of(J).size.width>=EI3+th4,G=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new P("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new IZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new m$({shortcuts:new Map([[new D4("ArrowDown"),new wy],[new D4("ArrowUp"),new Ly],[new D4("Tab"),new wy],[new D4("Tab",{shift:!0}),new Ly],[new D4("n",{ctrl:!0}),new wy],[new D4("p",{ctrl:!0}),new Ly],[new D4("Enter"),new uz0],[new D4("Escape"),new bz0]]),focusNode:this.focusNode,child:W}),H=new A7({actions:new Map([[wy,new D6(this.invoke)],[Ly,new D6(this.invoke)],[uz0,new D6(this.invoke)],[bz0,new D6(this.invoke)]]),child:U}),D=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new P(">",new g({color:Y.foreground}))})}),new y1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new P(M.label,new g({color:T})),new P(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new P(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new eh4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new P("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new d0({padding:C0.all(1),child:new NR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(z){let M=O?new y1({child:O}):new R0({width:th4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new R0({height:1}),new y1({child:E})]})})}}m0();IX();hM();CX();L$();d4();N4();_P();var M01=B4(eW(),1);import{execSync as wR}from"node:child_process";import{writeFile as Oy}from"node:fs/promises";import MI3 from"node:os";import xq from"node:path";var Zg4="c446b2e9b16cdc06df2ec285894d6421",AI3="5ea19563777f4ade8707fc56f7e7a388",jI3="amp-thread-worker",Qg4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function RI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function GL(J){if(!J||!RI3(J.meta))return!1;return J.meta.usesDtw===!0}function A01(J){let Z=new URL(`https://dash.cloudflare.com/${Zg4}/workers/durable-objects/view/${AI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function j01(J){let Z=new URL(`https://dash.cloudflare.com/${Zg4}/workers/services/view/${jI3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function II3(J,Z){if(EV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function R01(J,Z){let Q=II3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Ta(J,Z,Q){let Y=`select(.pid == ${Z})`,X=_a(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function _a(J){return J.path??f9(J.uri)}function Yg4(J,Z,Q){let Y=Ta("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Xg4(J,Z){return R01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
7381
7381
|
${Y}`).join(`
|
|
7382
7382
|
|
|
@@ -7589,7 +7589,7 @@ $1`).trim()}function _p4(J){let Z=JSON.parse(J.data);if(!Array.isArray(Z)){let K
|
|
|
7589
7589
|
|
|
7590
7590
|
`;G.push(new P(`${W}${q}`,z))};if(X&&X.trim())G.push(new P(X.trimEnd(),new g({color:Y.foreground,dim:!0})));if(K!==void 0&&K!==0)F(`exit code: ${K}`);if(V)F(`(${V}, command and output not shown to agent)`);else if(Z.hidden)F("(Command and output not shown to agent)");if(G.length===0)return null;return new e({text:new P("",void 0,G),selectable:!0})}function Wd4(J,Z){let Q=f0.of(Z),Y=YL(J);if(Y?.visibility===QL)return Q.app.shellModeHidden;if(Y?.visibility===Wz0)return Q.app.shellMode;return Q.app.userMessage}function Ud4(J,Z,Q,Y){if(Z.length===0)return null;let K=f0.maybeOf(J)?.colors??x1.of(J).colorScheme,V=[new e({text:new P("Images: ",new g({color:K.foreground,dim:!0}))})];for(let z=0;z<Z.length;z++){let G=z;if(V.push(new Q4({onClick:()=>Y(G),cursor:"pointer",child:new e({text:new P(`[image ${z+1}]`,new g({color:Q.color,italic:Q.italic,underline:!0}))})})),z<Z.length-1)V.push(new e({text:new P(" ")}))}return new n0({padding:C0.only({}),child:new W1({mainAxisSize:"min",children:V})})}function Hd4(J,Z){if(Z.length===0)return null;let Q=[];for(let Y of Z)Q.push(new e({text:new P(`Loaded ${FQ(Y.uri)} (${Y.lineCount} lines)`,new g({color:f0.of(J).app.toolSuccess,dim:!0})),selectable:!0}));if(Q.length===1)return Q[0];return new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:Q})}function Dd4(J){let Z=[];for(let Q of J.content)if(Q.type==="text")Z.push(Q.text);return Z.join(`
|
|
7591
7591
|
`).trim()}function e11(J,Z,Q,Y){let X=[];if(X.push(new P(J,Z)),Q)X.push(new P(" (interrupted)",new g({color:Y,italic:!0})));return new e({text:new P("",void 0,X),selectable:!0})}class ky extends J4{props;constructor(J){super();this.props=J}build(J){let Z=this.props.message,Q=f0.of(J),{colors:Y}=Q,X="",K,V,z=null;if(Z.role==="info"){let W=fD(Z);if(!W)return new d0;X=`${cb4(W.hidden??!1)} ${W.args.cmd}`;let H=Wd4(X,J);K=H,V=H,z=J41(J,W)}else{X=Dd4(Z);let W=Z.interrupted?Y.warning:Y.success;V=W,K=W}let G=new g({color:V,italic:!0}),F=[];if(Z.role==="user"){let W=Z.content.filter((D)=>D.type==="image"),H=Ud4(J,W,G,(D)=>{let B=W[D];if(B)this.props.onShowImagePreview(B,D)});if(H)F.push(H)}if(X){if(F.length>0)F.push(new R0({height:1}));F.push(e11(X,G,Z.role==="user"?Z.interrupted:void 0,Y.warning))}if(z){if(F.length>0)F.push(new R0({height:1}));F.push(z)}if(Z.role==="user"&&Z.discoveredGuidanceFiles){let W=Hd4(J,Z.discoveredGuidanceFiles);if(W){if(F.length>0)F.push(new R0({height:1}));F.push(W)}}let q;if(F.length===0)q=new d0;else if(F.length===1)q=F[0];else q=new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:F});return new d0({decoration:{color:Y.background,border:new c1(void 0,void 0,void 0,new g1(K,2,"solid"))},padding:C0.only({left:1}),child:q})}}class NG0 extends J4{props;constructor(J){super();this.props=J}build(J){let Z=f0.of(J),Q=Z.colors,Y=this.props.message,X="",K=Z.app.selectedMessage,V=Z.app.selectedMessage,z=null,G=fD(Y);if(G){X=`${G.hidden?"$$":"$"} ${G.args.cmd}`;let N=Wd4(X,J);K=N,V=N,z=J41(J,G)}else if(Y.role==="user")X=Dd4(Y),V=Y.interrupted?Q.warning:Q.success;let F=new g({color:V,italic:!0}),q=[];if(Y.role==="user"){let N=Y.content.filter((O)=>O.type==="image"),L=Ud4(J,N,F,(O)=>{let E=N[O];if(E)this.props.onShowImagePreview(E,O)});if(L)q.push(L)}if(X){if(q.length>0)q.push(new R0({height:1}));q.push(e11(X,F,Y.role==="user"?Y.interrupted:void 0,Q.warning))}if(z){if(q.length>0)q.push(new R0({height:1}));q.push(z)}if(Y.role==="user"&&Y.discoveredGuidanceFiles){let B=Hd4(J,Y.discoveredGuidanceFiles);if(B){if(q.length>0)q.push(new R0({height:1}));q.push(B)}}let W;if(q.length===0)W=new d0;else if(q.length===1)W=q[0];else W=new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:q});let U=new d0({decoration:{border:c1.all(new g1(K,2,"solid")),color:Q.background},padding:C0.only({left:1,right:1}),width:1/0,child:W});if(this.props.isShowingRestoreConfirmation){let B=new Nd4({affectedFiles:this.props.affectedFiles,onConfirm:this.props.onRestoreConfirm,onCancel:this.props.onRestoreCancel}),N=[];if(this.props.showRestoreHint)N.push(new $41,new R0({height:1}));return N.push(B,new R0({height:1})),new x0({children:[...N,new oY({forceDim:!0,child:new d0({decoration:{border:new c1(void 0,void 0,void 0,new g1(K,2,"solid")),color:Q.background},padding:C0.only({left:1,right:1}),width:1/0,child:W})})]})}if(this.props.isShowingEditConfirmation){let B=new wd4({affectedFiles:this.props.affectedFiles,onConfirm:this.props.onEditConfirm,onCancel:this.props.onEditCancel}),N=this.props.pendingEditText??X,w=e11(N,F,void 0,Q.warning),L=new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:[w,new R0({height:1}),B]});return new d0({decoration:{border:c1.all(new g1(K,2,"solid")),color:Q.background},padding:C0.only({left:1,right:1}),width:1/0,child:L})}let D=!(this.props.showEditHint??!0)?U:new bX0({child:new z5({children:[U,new t6({left:2,right:0,bottom:0,child:new e({text:new P("",void 0,[new P("e",new g({color:Z.app.keybind})),new P(" to edit",new g({color:Q.foreground,dim:!0}))])})})]})});if(!this.props.isFirstMessage||!this.props.showRestoreHint)return new n0({padding:C0.only({}),child:D});return new n0({padding:C0.only({}),child:new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:[new $41,new R0({height:1}),D]})})}}class $41 extends J4{build(J){let Z=f0.of(J),Q=Z.colors,Y=Z.app,X=[new P(" r",new g({color:Y.keybind})),new P(" to restore ",new g({color:Q.foreground,dim:!0}))];return new z5({children:[new d0({decoration:{color:Q.background,border:new c1(new g1(Q.selection,2,"solid"),void 0,void 0,void 0)},width:1/0,height:1}),new t6({left:0,right:0,top:0,child:new X4({child:new e({text:new P("",void 0,X)})})})]})}}function Bd4(J,Z){if(Z.length===0)return null;let Y=f0.of(J).colors,X=CH(J),K=[];for(let V=0;V<Z.length;V++){let z=Z[V];if(V>0)K.push(new P(`
|
|
7592
|
-
`));let G=z.startsWith("file://")?V1.parse(z):V1.file(z),F=Q9(G,X??void 0);K.push(new P(` • ${F}`,new g({color:Y.foreground,dim:!0})))}return new e({text:new P("",void 0,K)})}class Nd4 extends J4{props;constructor(J){super();this.props=J}build(J){let Z=this.props.affectedFiles,Q=Z.length>0,Y=Q?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",X=f0.of(J),K=[new e({text:new P(Y,new g({color:X.app.command,bold:!0}))}),new R0({height:1})],V=Bd4(J,Z);if(V)K.push(V),K.push(new R0({height:1}));let z=[{value:"confirm",label:Q?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return K.push(new $$({options:z,onSelect:(G)=>{if(G==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:C0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:K})}}class wd4 extends J4{props;constructor(J){super();this.props=J}build(J){let Z=this.props.affectedFiles,Q=f0.of(J),Y=[],X=Bd4(J,Z);if(X)Y.push(new e({text:new P("This will restore the following files:",new g({color:Q.app.command,bold:!0}))})),Y.push(new R0({height:1})),Y.push(X),Y.push(new R0({height:1}));let K=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new $$({options:K,onSelect:(V)=>{if(V==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:C0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class wG0 extends l0{controller;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;onDoubleAtTrigger;submitOnEnter;constructor(J){super();this.controller=J.controller,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview,this.onDoubleAtTrigger=J.onDoubleAtTrigger,this.submitOnEnter=J.submitOnEnter??!0}createState(){return new Ld4}}class Ld4 extends p0{currentShellModeStatus;imageAttachments=[];get controller(){return this.widget.controller}initState(){this.controller.addListener(this.textChangeListener);let J=YL(this.controller.text);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Z=this.widget.message.content.filter((Q)=>Q.type==="image");this.imageAttachments=Z}}dispose(){this.controller.removeListener(this.textChangeListener),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Q=YL(J)?.visibility;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=async(J)=>{let Z=await ZL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.widget.onShowImagePreview(Z,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Q,Y)=>Y!==J)})})};build(J){let Z=f0.of(J),Q=Z.colors,Y=Z.app,X=this.currentShellModeStatus?db4(Z,this.currentShellModeStatus):Y.selectedMessage,K=null,V=this.widget.message&&fD(this.widget.message);if(V)K=J41(J,V);let z=K?new n0({padding:C0.only({top:1}),child:K}):void 0,G=new BR({controller:this.controller,triggers:[new yq],bottomWidget:z,completionBuilder:this.widget.completionBuilder,onSubmitted:this.handleSubmit,theme:Q,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:Uz0(Z),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0,onDoubleAtTrigger:this.widget.onDoubleAtTrigger,submitKey:this.widget.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}}}),F=[];if(this.currentShellModeStatus===QL)F.push(new P("shell mode (incognito)",new g({color:Z.app.shellModeHidden})));else if(this.currentShellModeStatus===Wz0)F.push(new P("shell mode",new g({color:Z.app.shellMode})));else F.push(new P("esc",new g({color:Y.keybind})),new P(" to cancel",new g({color:Q.foreground,dim:!0})));return new bX0({child:new t8({decoration:{color:Q.background,border:c1.all(new g1(X,2,"solid"))},padding:C0.only({left:1,right:1}),overlays:[{child:new e({text:new P("",void 0,F)}),position:"bottom",alignment:"left"}],child:G})})}}d4();function aa(J){if(J.type==="message"){let K=J.message;if(K.role==="user"){let G=l3(K.content),F=K.content.filter((W)=>W.type==="image").length,q=(K.discoveredGuidanceFiles??[]).map((W)=>`${W.uri}|${W.lineCount}`).join("||");return`${J.id}|user|${K.interrupted?1:0}|${F}|${G}|${q}`}if(K.role==="assistant"){let G=l3(K.content),F=K.state?.type??"none",q=K.content.filter((B)=>B.type==="thinking"),W=K.content.filter((B)=>B.type==="tool_use"),U=q.map((B)=>`${YR(B.thinking)}:${Sq(B)?"1":"0"}:${B.signature.length}`).join("|"),H=K.usage,D=H?`${H.inputTokens}|${H.outputTokens}|${H.cacheCreationInputTokens??""}|${H.cacheReadInputTokens??""}|${H.model??""}`:"no-usage";return`${J.id}|assistant|${F}|${q.length}|${W.length}|${G}|${U}|${D}|${K.turnElapsedMs??""}`}let z=K.content.map((G)=>G.type).join(",");return`${J.id}|info|${z}`}let Q=J.toolResult.run.status,Y=J.toolResult.userInput,X=Y?`accepted:${Y.accepted?1:0}|ask:${Y.askAnswers?Object.keys(Y.askAnswers).length:0}`:"none";return`${J.id}|tool|${Q}|${J.toolUse.id}|${X}`}function Od4(J){return(J.normalizedName??J.name)===M9}function k_3(J,Z,Q){let X=f0.maybeOf(J)?.colors??x1.of(J).colorScheme,V=Z.trimStart().startsWith("You're absolutely right"),z=new M3(`${Q}-text`),G=[];if(V)G.push(new t11({key:z,markdown:Z,defaultColor:X.foreground}));else G.push(new j3({key:z,markdown:Z}));if(G.length===1)return G[0];return new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:G})}class Z41{options;constructor(J){this.options=J}getRenderItems(){let J=[];for(let[Z,Q]of this.options.items.entries())J.push({type:"item",item:Q,sourceIndex:Z});return J}getSourceIndex(J){return J.sourceIndex}includesSourceIndex(J,Z){return J.sourceIndex===Z}getCacheIdentity(J){if(J.item.type==="message"){let Z=J.item.message;return`message:${Z.dtwMessageID??`${Z.role}:${Z.messageId}`}`}return`tool:${J.item.toolUse.id}`}getRenderSignature(J){let Z=aa(J.item),Q=this._getTaskSignatureSuffix(J);if(Q)return`${Z}|${Q}`;return Z}buildWidget(J,Z,Q){if(Z.item.type==="toolResult"&&Od4(Z.item.toolUse))return this._buildCollapsibleTaskItem(J,Z,Q);return this.buildThreadItemWidget(J,Z.item,Z.sourceIndex)}buildThreadItemWidget(J,Z,Q){let Y=new M3(`thread-item-${Z.id}`);if(Z.type==="message"){let K=Z.message;if(K.role==="user"){let W,U=(H,D)=>{this.options.onShowImagePreview(H,D,()=>{})};if(!this.options.isInSelectionMode)W=new ky({message:K,isFirstMessage:Q>0,onShowImagePreview:U});else{let H=this.options.onGetOrdinalFromUserMessageIndex(Q);if(H===null)W=new ky({message:K,isFirstMessage:Q>0,onShowImagePreview:U});else if(this.options.stateController.editingMessageOrdinal===H&&this.options.stateController.editingController)W=new wG0({controller:this.options.stateController.editingController,message:K,onSubmitted:(D,B)=>{this.options.onEditConfirmationRequest(D,B)},completionBuilder:this.options.completionBuilder,autocompleteHandle:this.options.autocompleteHandle,onShowImagePreview:this.options.onShowImagePreview,onDoubleAtTrigger:this.options.onDoubleAtTrigger,submitOnEnter:this.options.submitOnEnter});else if(this.options.stateController.selectedUserMessageOrdinal===H)W=new NG0({message:K,isFirstMessage:Q>0,showRestoreHint:this.options.showRestoreHint,isShowingRestoreConfirmation:this.options.stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this.options.stateController.isShowingEditConfirmation,affectedFiles:[...this.options.stateController.affectedFiles],pendingEditText:this.options.stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.options.onRestoreConfirm()},onRestoreCancel:()=>{this.options.onRestoreCancel()},onEditConfirm:()=>{this.options.onEditConfirm()},onEditCancel:()=>{this.options.onEditCancel()},onShowImagePreview:U});else W=new ky({message:K,isFirstMessage:Q>0,onShowImagePreview:U})}return W}if(K.role==="assistant"){let W=this._buildAssistantMessageWidget(J,K,Q,Z.id);return new d0({key:Y,child:W})}let V=K,z=[],G=this.options.onGetOrdinalFromUserMessageIndex(Q),F=this.options.isInSelectionMode&&G!==null&&this.options.stateController.selectedUserMessageOrdinal===G,q=(W,U)=>{this.options.onShowImagePreview(W,U,()=>{})};for(let W of V.content){if(W.type!=="manual_bash_invocation")continue;if(this.options.stateController.editingMessageOrdinal===G&&this.options.stateController.editingController)z.push(new wG0({controller:this.options.stateController.editingController,message:V,onSubmitted:(U,H)=>{this.options.onEditConfirmationRequest(U,H)},completionBuilder:this.options.completionBuilder,autocompleteHandle:this.options.autocompleteHandle,onShowImagePreview:this.options.onShowImagePreview,onDoubleAtTrigger:this.options.onDoubleAtTrigger,submitOnEnter:this.options.submitOnEnter}));else if(!this.options.isInSelectionMode||!F)z.push(new ky({message:V,isFirstMessage:Q>0,onShowImagePreview:q}));else z.push(new NG0({message:V,isFirstMessage:Q>0,showRestoreHint:this.options.showRestoreHint,isShowingRestoreConfirmation:this.options.stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this.options.stateController.isShowingEditConfirmation,affectedFiles:[...this.options.stateController.affectedFiles],pendingEditText:this.options.stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.options.onRestoreConfirm()},onRestoreCancel:()=>{this.options.onRestoreCancel()},onEditConfirm:()=>{this.options.onEditConfirm()},onEditCancel:()=>{this.options.onEditCancel()},onShowImagePreview:q,showEditHint:!this.options.isDTWMode}))}if(z.length===0)return new d0;if(z.length===1)return z[0];return new x0({crossAxisAlignment:"stretch",children:z})}let X=new gQ({toolUse:Z.toolUse,toolRun:Z.toolResult.run,toolProgress:this.options.toolProgressByToolUseID.get(Z.toolUse.id),userInput:Z.toolResult.userInput,subagentContent:this.options.subagentContentByParentID[Z.toolUse.id]});return new d0({key:Y,child:X})}_getTaskSignatureSuffix(J){if(J.item.type!=="toolResult"||!Od4(J.item.toolUse))return;let Z=this._isTaskCompleted(J.item.toolResult.run.status);return`task:${this.options.stateController.denseViewItemStates.get(J.item.id)??!Z?"1":"0"}`}_isTaskCompleted(J){return J!=="in-progress"&&J!=="queued"&&J!=="blocked-on-user"}_buildCollapsibleTaskItem(J,Z,Q){if(Z.item.type!=="toolResult")return this.buildThreadItemWidget(J,Z.item,Z.sourceIndex);let Y=Z.item.toolUse,X=Z.item.toolResult.run,K=na(J,Y,X),V=this._isTaskCompleted(X.status),z=this.options.stateController.denseViewItemStates.get(Z.item.id)??!V,G=new ia({toolUse:Y,toolRun:X,subagentContent:this.options.subagentContentByParentID[Y.id],hideHeader:!0});return new uq({key:new M3(`task-${Z.item.id}`),title:K,child:G,expanded:z,onChanged:(F)=>{this.options.onStateUpdate(()=>{this.options.stateController.setDenseViewItemState(Z.item.id,F),this.options.onInvalidateSourceIndex(Z.sourceIndex)})}})}_getThinkingBlockExpanded(J,Z){let Q=`${J}-${Z}`;return this.options.stateController.thinkingBlockStates.get(Q)??R7.instance.allExpanded}_toggleThinkingBlock(J,Z){return(Q)=>{let Y=`${J}-${Z}`;this.options.onStateUpdate(()=>{this.options.stateController.setThinkingBlockState(Y,Q),this.options.onInvalidateSourceIndex(J)})}}_buildThinkingBlock(J,Z,Q,Y,X){let K=Q===X,V=Y.state?.type==="streaming"&&K,z=Y.state?.type==="cancelled"&&K;return new XR({key:new M3(`thinking-${Z}-${Q}`),thinkingBlock:J,expanded:this._getThinkingBlockExpanded(Z,Q),onToggle:this._toggleThinkingBlock(Z,Q),isStreaming:V,isCancelled:z})}_buildAssistantMessageWidget(J,Z,Q,Y){let X=this.options.showThinkingBlocks?Z.content.map((U,H)=>({block:U,index:H})).filter((U)=>U.block.type==="thinking"&&Sq(U.block)):[],K=X.length>0,V=X.length>0?X.at(-1).index:-1,z=Z.content.filter((U)=>U.type==="text"&&!U.hidden),G=[];X.forEach(({block:U,index:H},D)=>{if(D>0)G.push(new R0({height:1}));G.push(this._buildThinkingBlock(U,Q,H,Z,V))});let F=l3(z);if(K&&F.trim().length>0)G.push(new R0({height:1}));if(F.trim())G.push(k_3(J,F,Y));let q=NV0(J),W=Z.usage!=null&&(Z.usage.inputTokens>0||Z.usage.outputTokens>0);if(q&&W){let H=f0.maybeOf(J)?.colors??x1.of(J).colorScheme,D=B_4(Z.usage);G.push(new n0({padding:C0.only({top:1}),child:new e({text:new P(D,new g({color:H.foreground,dim:!0}))})}))}if(G.length===0)return new d0;if(G.length===1)return G[0];return new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:G})}}class LG0 extends S3{}class OG0 extends S3{}class Q41 extends S3{}class Y41 extends S3{}class X41 extends S3{}class K41 extends S3{}class V41 extends S3{}class z41 extends S3{}function Ed4(J){return J.type==="item"&&"item"in J&&"sourceIndex"in J}function v_3(J){let Z=fD(J);if(Z)return`${Z.hidden?"$$":"$"}${Z.args.cmd}`;return l3(J.content)}class oa extends l0{items;subagentContentByParentID;toolProgressByToolUseID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onShowForkDeprecation;getAffectedFiles;hasStartedStreamingResponse=!1;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;onDoubleAtTrigger;stateController;denseView;submitOnEnter;threadViewState;isDTWMode;get userMessageIndices(){let J=[];for(let Z=0;Z<this.items.length;Z++){let Q=this.items[Z];if(Q?.type==="message"){if(Q.message.role==="user"||AW(Q.message))J.push(Z)}}return J}get navigableItemIndices(){let J=[];for(let Z=0;Z<this.items.length;Z++){let Q=this.items[Z];if(Q?.type==="message"){if(Q.message.role==="user"||AW(Q.message))J.push(Z)}else if(Q?.type==="toolResult"&&Q.toolUse.name==="chart")J.push(Z)}return J}constructor({key:J,items:Z,subagentContentByParentID:Q={},toolProgressByToolUseID:Y=new Map,controller:X,autofocus:K=!1,onNewMessage:V,showScrollbar:z=!0,onCopy:G,onMessageEditSubmit:F,onMessageRestoreSubmit:q,onShowForkDeprecation:W,getAffectedFiles:U,hasStartedStreamingResponse:H=!1,focusNode:D,onDismissFocus:B,isInSelectionMode:N=!1,isInHandoffMode:w=!1,completionBuilder:L,onShowImagePreview:O,onSelectionChanged:E,onDoubleAtTrigger:M,stateController:A,denseView:j,submitOnEnter:R=!0,threadViewState:_,isDTWMode:T=!1}){super(J?{key:J}:{});this.items=Z,this.subagentContentByParentID=Q,this.toolProgressByToolUseID=Y,this.controller=X,this.autofocus=K,this.onNewMessage=V,this.showScrollbar=z,this.onCopy=G,this.onMessageEditSubmit=F,this.onMessageRestoreSubmit=q,this.onShowForkDeprecation=W,this.getAffectedFiles=U,this.hasStartedStreamingResponse=H,this.focusNode=D,this.onDismissFocus=B,this.isInSelectionMode=N,this.isInHandoffMode=w,this.completionBuilder=L,this.onShowImagePreview=O,this.onSelectionChanged=E,this.onDoubleAtTrigger=M,this.stateController=A,this.denseView=j,this.submitOnEnter=R,this.threadViewState=_,this.isDTWMode=T}createState(){return new Md4}}class Md4 extends p0{_controller=null;_isDisposed=!1;_globalToggleListener;_denseToggleListener;_renderItems=[];_streamingIndexes=new Set;_viewportHeight=25;_renderItemCacheKeys=[];_widgetCache=new Map;_lastCostDisplayState=null;_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;_controllerUnsubscribe=null;_lastDenseViewState=null;_renderDelegate=null;get controller(){return this._controller}get _stateController(){return this.widget.stateController}get _isDenseViewEnabled(){return this.widget.denseView}_createRenderDelegate(){let J=new Z41({items:this.widget.items,toolProgressByToolUseID:this.widget.toolProgressByToolUseID,subagentContentByParentID:this.widget.subagentContentByParentID,stateController:this._stateController,isInSelectionMode:this.widget.isInSelectionMode,showRestoreHint:!!this.widget.onMessageRestoreSubmit,isDTWMode:this.widget.isDTWMode,completionBuilder:this.widget.completionBuilder,onShowImagePreview:this.widget.onShowImagePreview,onDoubleAtTrigger:this.widget.onDoubleAtTrigger,submitOnEnter:this.widget.submitOnEnter,autocompleteHandle:this._autocompleteHandle,showThinkingBlocks:!this._isDenseViewEnabled,onGetOrdinalFromUserMessageIndex:(Z)=>this.getOrdinalFromUserMessageIndex(Z),onEditConfirmationRequest:(Z,Q)=>{this.handleEditConfirmationRequest(Z,Q)},onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onStateUpdate:(Z)=>{this.setState(()=>{Z()})},onInvalidateSourceIndex:(Z)=>{this._clearCacheForSourceIndex(Z)}});if(this._isDenseViewEnabled)return new s11({items:this.widget.items,toolProgressByToolUseID:this.widget.toolProgressByToolUseID,subagentContentByParentID:this.widget.subagentContentByParentID,stateController:this._stateController,hasStartedStreamingResponse:this.widget.hasStartedStreamingResponse,threadViewState:this.widget.threadViewState,buildThreadItemWidget:(Z,Q,Y)=>J.buildThreadItemWidget(Z,Q,Y),onStateUpdate:(Z)=>{this.setState(()=>{Z()})},onInvalidateRenderItemIndex:(Z)=>{let Q=this._getCacheKeyForRenderItem(Z);this._widgetCache.delete(Q)}});return J}_getRenderDelegate(){if(!this._renderDelegate)this._renderDelegate=this._createRenderDelegate();return this._renderDelegate}dismiss(){C6.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Z){if(Z<=0)return null;if(J===null)return Z-1;if(J<=0)return 0;return J-1}_navigateDown(J,Z){if(Z<=0)return null;if(J===null)return null;if(J>=Z-1)return null;return J+1}_ordinalToIndex(J,Z){if(Z===null)return null;if(Z<0||Z>=J.length)return null;return J[Z]??null}_getUserCount(){return this.widget.navigableItemIndices.length}_updateRenderItems(){this._renderDelegate=this._createRenderDelegate(),this._renderItems=this._renderDelegate.getRenderItems(),this._renderDelegate.onRenderItemsUpdated?.(this._renderItems),this._rebuildRenderItemCacheKeys()}_getSourceIndexForRenderItem(J){return this._getRenderDelegate().getSourceIndex(J)}_rebuildRenderItemCacheKeys(){let J=new Map;this._renderItemCacheKeys=this._renderItems.map((Z)=>{let Q=this._getRenderDelegate().getCacheIdentity(Z),Y=J.get(Q)??0;return J.set(Q,Y+1),`${Q}:${Y}`})}_toolAuxiliarySignature(J,Z=this.widget.toolProgressByToolUseID,Q=this.widget.subagentContentByParentID){let Y=Z.get(J),X=Y?`${Y.status}|${Y.content}`:"none",K=BG0(Q[J]);return`progress:${X}|subagents:${K}`}_getCacheKeyForRenderItem(J){return this._renderItemCacheKeys[J]??`missing:${J}`}_clearSelectedUserMessage(){let J=this._stateController.selectedUserMessageOrdinal,Z=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Z!=null)this._clearCacheForSourceIndex(Z);this._stateController.setSelectedUserMessageOrdinal(null)})}_selectUserMessageByOrdinal(J){let Z=this._stateController.selectedUserMessageOrdinal,Q=J,Y=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null,X=this.getUserMessageIndexFromOrdinal(Q);if(Y!==null)this._clearCacheForSourceIndex(Y);if(X!==null)this._clearCacheForSourceIndex(X);if(this.setState(()=>{this._stateController.setSelectedUserMessageOrdinal(Q)}),X!==null)C6.instance.addPostFrameCallback(()=>{let K=this._getRenderIndexForSourceIndex(X);this.scrollToMessage(K??X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Z=this._stateController.editingMessageOrdinal,Q=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null,Y=J!==null?this.getUserMessageIndexFromOrdinal(J):null;if(Q!==null)this._clearCacheForSourceIndex(Q);if(Y!==null)this._clearCacheForSourceIndex(Y);if(J===null)this.setState(()=>{this._stateController.stopEditing()});else{let X=this.getUserMessageIndexFromOrdinal(J),K=X!==null?this.widget.items[X]:null,V=K?.type==="message"&&(K.message.role==="user"||K.message.role==="info")?v_3(K.message):"";this.setState(()=>{this._stateController.startEditing(J,V)})}}getUserMessageIndexFromOrdinal(J){return this.widget.navigableItemIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Q=this.widget.navigableItemIndices.indexOf(J);return Q>=0?Q:null}getLatestUserMessageOrdinal(){let J=this.widget.navigableItemIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Z=this._getUserCount(),Q=this._stateController.selectedUserMessageOrdinal,Y=J==="up"?this._navigateUp(Q,Z):this._navigateDown(Q,Z);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._stateController.editingMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._stateController.editingMessageOrdinal);if(J!=null)this._clearCacheForSourceIndex(J);return this.setState(()=>{this._stateController.stopEditing()}),C6.instance.addPostFrameCallback(()=>{this.widget.focusNode?.requestFocus()}),"handled"}else if(this._stateController.selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._stateController.stopEditing()}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this.getUserMessageIndexFromOrdinal(J),Q=Z!==null?this.widget.items[Z]:null;if(Q?.type==="message"&&AW(Q.message)&&this.widget.isDTWMode)return"handled";return this._selectEditingUserMessageByOrdinal(J),"handled"}return"ignored"};handleRestoreMessage=()=>{if(!this.widget.onMessageRestoreSubmit)return"ignored";let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this.getUserMessageIndexFromOrdinal(J);if(Z===null)return"ignored";if(Z===0)return"ignored";let Q=this.widget.items[Z];if(Q?.type==="message"&&(Q.message.role==="user"||AW(Q.message)))this.showRestoreConfirmation(Q.message,Z);return"handled"}return"ignored"};async showRestoreConfirmation(J,Z){let Q=[];if(this.widget.getAffectedFiles)try{Q=await this.widget.getAffectedFiles(J)}catch{Q=[]}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!0),this._stateController.setAffectedFiles(Q)}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let Y=this._getRenderIndexForSourceIndex(Z);this.scrollToMessage(Y??Z)})}handleRestoreConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){if(Z===0)return"ignored";let Q=this.widget.items[Z];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let Q=this._getRenderIndexForSourceIndex(Z);this.scrollToMessage(Q??Z)})}}return"handled"};handleForkMessage=()=>{if(this._stateController.selectedUserMessageOrdinal!==null&&this.widget.onShowForkDeprecation)return this.widget.onShowForkDeprecation(),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss(),"handled";return"ignored"};handleEditConfirmationRequest=async(J,Z)=>{if(J.trim()===""&&Z.length===0)return;let Q=this._stateController.editingMessageOrdinal;if(Q!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,Q);if(Y!=null){let X=this.widget.items[Y],K=[];if(this.widget.getAffectedFiles&&X?.type==="message")try{K=await this.widget.getAffectedFiles(X.message)}catch{K=[]}if(K.length===0&&X?.type==="message"&&(X.message.role==="user"||X.message.role==="info")){this.widget.onMessageEditSubmit?.(X.message,J,Z),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.stopEditing()}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!0),this._stateController.setPendingEditText(J),this._stateController.setPendingEditImageAttachments(Z),this._stateController.setAffectedFiles(K),this._stateController.stopEditing()}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let V=this._getRenderIndexForSourceIndex(Y);this.scrollToMessage(V??Y)})}}};handleEditConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal,Z=this._stateController.pendingEditText;if(J!==null&&Z!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){let Y=this.widget.items[Q];if(Y?.type==="message"&&(Y.message.role==="user"||Y.message.role==="info"))this.widget.onMessageEditSubmit?.(Y.message,Z,[...this._stateController.pendingEditImageAttachments]),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let Q=this._getRenderIndexForSourceIndex(Z);this.scrollToMessage(Q??Z)})}}};initState(){if(super.initState(),this._lastDenseViewState=this._isDenseViewEnabled,this._updateRenderItems(),this._controller=this.widget.controller||new j5,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._stateController.clearThinkingBlockStates(),this._widgetCache.clear()})},R7.instance.addListener(this._globalToggleListener),this._denseToggleListener=()=>{this.setState(()=>{this._stateController.clearDenseViewItemStates(),this._widgetCache.clear()})},kJ.instance.addListener(this._denseToggleListener),this._controllerUnsubscribe=this._stateController.subscribe(()=>{this.setState(()=>{})}),this.widget.items.length>0)C6.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),this._lastDenseViewState!==this._isDenseViewEnabled){if(this._lastDenseViewState=this._isDenseViewEnabled,this._stateController.clearDenseViewItemStates(),this._widgetCache.clear(),!this._isDenseViewEnabled)kJ.instance.setAllExpanded(!1)}if(this._updateRenderItems(),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let X=this.getLatestUserMessageOrdinal();if(X!==null)this._selectUserMessageByOrdinal(X)}let Q=Math.min(J.items.length,this.widget.items.length);for(let X=0;X<Q;X++){let K=J.items[X],V=this.widget.items[X];if(K&&V){if(K.type!==V.type){this._clearCacheForSourceIndex(X);continue}if(aa(K)!==aa(V))this._clearCacheForSourceIndex(X)}}if(J.toolProgressByToolUseID!==this.widget.toolProgressByToolUseID||J.subagentContentByParentID!==this.widget.subagentContentByParentID)for(let[X,K]of this.widget.items.entries()){if(K?.type!=="toolResult")continue;let V=this._toolAuxiliarySignature(K.toolUse.id,J.toolProgressByToolUseID,J.subagentContentByParentID),z=this._toolAuxiliarySignature(K.toolUse.id);if(V!==z)this._clearCacheForSourceIndex(X)}this._cleanupOrphanedCacheEntries(),this._updateStreamingIndexes();for(let X of this._streamingIndexes)if(X>=this._renderItems.length)this._streamingIndexes.delete(X)}_cleanupOrphanedCacheEntries(){let J=new Set(this._renderItemCacheKeys);for(let Z of this._widgetCache.keys())if(!J.has(Z))this._widgetCache.delete(Z)}_clearCacheForSourceIndex(J){for(let[Z,Q]of this._renderItems.entries()){let Y=this._getCacheKeyForRenderItem(Z);if(this._getRenderDelegate().includesSourceIndex(Q,J))this._widgetCache.delete(Y)}}_getRenderIndexForSourceIndex(J){for(let[Z,Q]of this._renderItems.entries())if(this._getRenderDelegate().includesSourceIndex(Q,J))return Z;return null}_isMessageStreaming(J){if(!Ed4(J))return!1;if(J.item.type!=="message")return!1;let Z=J.item.message;if(Z.role!=="assistant")return!1;return Z.state.type==="streaming"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this._renderItems.length)this._streamingIndexes.delete(J);for(let J=0;J<this._renderItems.length;J++){let Z=this._renderItems[J];if(!Z)continue;let Q=this._isMessageStreaming(Z);if(Q&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Q&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Z=J.size;if(typeof Z.height==="number"&&Z.height>0)return this._viewportHeight=Z.height,Z.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)R7.instance.removeListener(this._globalToggleListener);if(this._denseToggleListener)kJ.instance.removeListener(this._denseToggleListener);if(this._controllerUnsubscribe)this._controllerUnsubscribe(),this._controllerUnsubscribe=null;if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Z=f0.of(J),Q=NV0(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Q)this._widgetCache.clear();this._lastCostDisplayState=Q;let Y=this._getTotalItemCount(J),X=[];for(let U=0;U<Y;U++)if(X.push(this._buildItemAtIndex(J,U)),U<Y-1)X.push(new R0({height:1}));let K=new T6({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new x0({key:new M3("message-list-column"),crossAxisAlignment:"start",children:X})}),z=[new n0({padding:C0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:K})];if(this.widget.showScrollbar&&this._controller){let U=new N9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack});z.push(new t6({right:1,top:0,bottom:0,child:new R0({width:1,child:U})}))}let G=new z5({children:z}),F=new p$({child:G,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),q=new Map([[LG0,new D6(this.handleNavigateUserMessageUp)],[OG0,new D6(this.handleNavigateUserMessageDown)],[Q41,new D6(this.handleEscape)],[Y41,new D6(this.handleScrollDown)],[X41,new D6(this.handleScrollUp)],[K41,new D6(this.handleEditMessage)],[V41,new D6(this.handleRestoreMessage)],[z41,new D6(this.handleForkMessage)]]),W=new Map([[D4.key("Tab"),new LG0],[D4.shift("Tab"),new OG0],[D4.key("Escape"),new Q41],[D4.key("j"),new Y41],[D4.key("k"),new X41],[D4.key("e"),new K41],[D4.key("f"),new z41]]);if(this.widget.onMessageRestoreSubmit)W.set(D4.key("r"),new V41);if(!a7())W.set(D4.key("ArrowUp"),new LG0),W.set(D4.key("ArrowDown"),new OG0);if(this.widget.focusNode)return new s4({focusNode:this.widget.focusNode,child:new A7({actions:q,child:new m$({shortcuts:W,focusNode:this.widget.focusNode,child:F})})});return F}_getTotalItemCount(J){return this._renderItems.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._stateController.isShowingRestoreConfirmation||this._stateController.isShowingEditConfirmation){let Q=this._stateController.selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}let Z=this._stateController.editingMessageOrdinal;if(Z!==null){let Q=this.getUserMessageIndexFromOrdinal(Z);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Z){let Q=this._renderItems[Z];if(!Q)return new d0;let Y=Ed4(Q)?Q.item:null,X=Y?.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),K=this._getSourceIndexForRenderItem(Q),V=this._shouldDimItem(K);if(!X){let F=`${this._getRenderDelegate().getRenderSignature(Q)}|dim:${V?1:0}`,q=this._getCacheKeyForRenderItem(Z),W=this._widgetCache.get(q);if(W&&W.sig===F)return W.widget;let U=this._getRenderDelegate().buildWidget(J,Q,Z),H=V?new oY({forceDim:!0,child:U}):U;return this._widgetCache.set(q,{sig:F,widget:H}),H}let G=this._getRenderDelegate().buildWidget(J,Q,Z);return V?new oY({forceDim:!0,child:G}):G}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Z=!1,offsetPercent:Q=0.25,edge:Y="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let K=this._getMessageRelativeOffset(J,Y);if(K===null)return!1;let V=this._getViewportHeight(),z=Math.floor(V*Q),G=K-z;if(Z)this._controller.animateTo(G,X);else this._controller.jumpTo(G);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Z=new M3("message-list-column"),Q=(Y)=>{if(Y.widget.key?.equals(Z))return Y;for(let X of Y.children){let K=Q(X);if(K)return K}return null};return Q(J)}_getMessageRelativeOffset(J,Z){let Q=this._getColumnElement();if(!Q)return null;let Y=J*2,X=Q.children[Y];if(!X?.renderObject)return null;let K=X.renderObject,V=Q.renderObject;if(!V)return null;let z=K.localToGlobal({x:0,y:0}),G=V.localToGlobal({x:0,y:0}),F=0;if(Z==="bottom")F=K.size.height;return z.y+F-G.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Z=this._getViewportHeight(),Q=this._controller?.offset??0,Y=J+Z;return{totalContentHeight:Math.max(Y,0),viewportHeight:Math.max(Z,1),scrollOffset:Math.max(Q,0)}}}class EG0{_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_pendingEditImageAttachments=[];_affectedFiles=[];_thinkingBlockStates=new Map;_denseViewItemStates=new Map;_denseViewItemTouched=new Set;_editingController=null;listeners=new Set;get selectedUserMessageOrdinal(){return this._selectedUserMessageOrdinal}setSelectedUserMessageOrdinal(J){if(this._selectedUserMessageOrdinal===J)return;this._selectedUserMessageOrdinal=J,this.notify()}get editingMessageOrdinal(){return this._editingMessageOrdinal}get isShowingRestoreConfirmation(){return this._isShowingRestoreConfirmation}setIsShowingRestoreConfirmation(J){if(this._isShowingRestoreConfirmation===J)return;this._isShowingRestoreConfirmation=J,this.notify()}get isShowingEditConfirmation(){return this._isShowingEditConfirmation}setIsShowingEditConfirmation(J){if(this._isShowingEditConfirmation===J)return;this._isShowingEditConfirmation=J,this.notify()}get pendingEditText(){return this._pendingEditText}setPendingEditText(J){if(this._pendingEditText===J)return;this._pendingEditText=J,this.notify()}get pendingEditImageAttachments(){return this._pendingEditImageAttachments}setPendingEditImageAttachments(J){this._pendingEditImageAttachments=[...J],this.notify()}get affectedFiles(){return this._affectedFiles}setAffectedFiles(J){this._affectedFiles=[...J],this.notify()}get thinkingBlockStates(){return this._thinkingBlockStates}get denseViewItemStates(){return this._denseViewItemStates}get denseViewItemTouched(){return this._denseViewItemTouched}setThinkingBlockState(J,Z){if(this._thinkingBlockStates.get(J)===Z)return;this._thinkingBlockStates.set(J,Z),this.notify()}clearThinkingBlockStates(){if(this._thinkingBlockStates.size===0)return;this._thinkingBlockStates.clear(),this.notify()}setDenseViewItemState(J,Z){if(this._denseViewItemStates.get(J)===Z)return;this._denseViewItemStates.set(J,Z),this._denseViewItemTouched.add(J),this.notify()}setDenseViewItemTouched(J){if(this._denseViewItemTouched.has(J))return;this._denseViewItemTouched.add(J),this.notify()}clearDenseViewItemStates(){if(this._denseViewItemStates.size===0)return;this._denseViewItemStates.clear(),this._denseViewItemTouched.clear(),this.notify()}get editingController(){return this._editingController}startEditing(J,Z){if(this._editingMessageOrdinal===J&&this._editingController)return;this._editingController?.dispose(),this._editingController=new r7,this._editingController.text=Z,this._editingMessageOrdinal=J,this.notify()}stopEditing(){if(this._editingMessageOrdinal===null&&!this._editingController)return;this._editingMessageOrdinal=null,this._editingController?.dispose(),this._editingController=null,this.notify()}subscribe(J){return this.listeners.add(J),()=>this.listeners.delete(J)}notify(){for(let J of[...this.listeners])J()}reset(){this._selectedUserMessageOrdinal=null,this._editingMessageOrdinal=null,this._isShowingRestoreConfirmation=!1,this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[],this._thinkingBlockStates.clear(),this._denseViewItemStates.clear(),this._denseViewItemTouched.clear(),this._editingController?.dispose(),this._editingController=null,this.notify()}}class G41 extends l0{message;onDestruct;constructor({key:J,message:Z,onDestruct:Q}){super(J?{key:J}:{});this.message=Z,this.onDestruct=Q}createState(){return new Ad4}}class Ad4 extends p0{scrollController;focusNode;viewportHeight=1;scrollListenerAttached=!1;initState(){this.scrollController=new j5,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0),this.focusNode=new G6}dispose(){this.scrollController.dispose(),this.focusNode.dispose()}formatDate(J){return new Date(J).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let K=Y.children||[];for(let V of K){if(V&&"size"in V){let G=V.size;if(typeof G?.height==="number"&&G.height>0)return G.height}let z=Z(V,X+1);if(z>0)return z}}return 0},Q=Z(J);if(Q>0)return Q;return this.viewportHeight}build(J){let Q=x1.of(J).colorScheme,X=f0.of(J).app,K=K4.of(J);if(!this.scrollListenerAttached)this.scrollController.addListener(()=>{this.updateViewportHeight(),this.setState(()=>{})}),this.scrollListenerAttached=!0;let V=new g({color:Q.primary,bold:!0}),z=new g({color:Q.foreground,dim:!0}),G=new g({color:Q.foreground}),F=new g({color:X.keybind}),q=new g({color:Q.foreground}),W=K.size.width,U=K.size.height,H=W-4,B=Math.min(20,U-4),N=Math.max(40,Math.min(60,H)),w=new n0({padding:C0.only({top:1,left:2,right:2,bottom:1}),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new X4({child:new e({text:new P(this.widget.message.title,V)})}),new X4({child:new e({text:new P(this.formatDate(this.widget.message.visibleFrom),z)})})]})}),L=new W1({crossAxisAlignment:"stretch",children:[new y1({child:new T6({autofocus:!0,controller:this.scrollController,child:new d0({constraints:new I1(N-5,N-5,0,Number.POSITIVE_INFINITY),child:new n0({padding:C0.only({left:2,right:2}),child:new e({text:new P(this.widget.message.body,G)})})})})}),new N9({controller:this.scrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let M=this.scrollController.maxScrollExtent,A=this.scrollController.offset,j=this.viewportHeight,R=M+j;return{totalContentHeight:Math.max(R,0),viewportHeight:Math.max(j,1),scrollOffset:Math.max(A,0)}}})]}),O=new n0({padding:C0.symmetric(2,1),child:new X4({child:new e({text:new P("",q,[new P("Destroy message ",q),new P("(Esc)",F)])})})}),E=new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[w,new bz({fit:"loose",child:L}),O]});return new s4({autofocus:!0,focusNode:this.focusNode,onKey:(M)=>{if(M.key==="Escape")return this.widget.onDestruct(),"handled";return"ignored"},child:new X4({child:new d0({constraints:new I1(N,N,0,B),decoration:new $6(Q.background,c1.all(new g1(Q.primary,1,"rounded"))),child:E})})})}}class F41 extends l0{request;onDismiss;constructor({request:J,onDismiss:Z}){super();this.request=J,this.onDismiss=Z}createState(){return new jd4}}class jd4 extends p0{textController;focusNode;errorMessage=null;initState(){this.textController=new r7,this.focusNode=new G6}dispose(){this.textController.dispose(),this.focusNode.dispose()}handleSubmit=()=>{let J=this.textController.text.trim();if(!J){this.setState(()=>{this.errorMessage="Please enter the callback URL or authorization code"});return}this.widget.request.resolve(J),this.widget.onDismiss()};build(J){let Q=x1.of(J).colorScheme,X=f0.of(J).app,K=K4.of(J),V=K.size.width,z=K.size.height,G=V-4,F=Math.max(50,Math.min(80,G)),q=new g({color:Q.primary,bold:!0}),W=new g({color:X.link,bold:!0}),U=new g({color:Q.foreground,dim:!0}),H=new g({color:X.keybind}),D=new g({color:X.toolError}),B=this.widget.request.serverName,N=[new e({text:new P("1. Open this URL in your browser (select to copy):",U)}),new R0({height:1}),new n0({padding:C0.only({left:3}),child:new p$({child:new e({text:new P(this.widget.request.authorizationUrl,W),selectable:!0})})}),new R0({height:1}),new e({text:new P("2. Authorize the application",U)}),new R0({height:1}),new e({text:new P("3. After redirect fails, copy the URL from your browser address bar",U)}),new R0({height:1}),new e({text:new P("4. Paste the localhost URL below:",U)})],w=[new e({text:new P(`OAuth Required: ${B}`,q)}),new R0({height:1}),...N,new R0({height:1}),new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,placeholder:"Paste callback URL or authorization code...",onSubmitted:this.handleSubmit})];if(this.errorMessage)w.push(new R0({height:1})),w.push(new e({text:new P(this.errorMessage,D)}));w.push(new R0({height:1})),w.push(new W1({children:[new e({text:new P("",void 0,[new P("Enter",H),new P(" submit · ",U),new P("Esc",H),new P(" cancel",U)])})]}));let L=new d0({constraints:new I1(F-4,F-4,0,z-6),decoration:{color:Q.background,border:c1.all(new g1(Q.primary,1,"rounded"))},padding:C0.all(2),child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:w})});return new X4({child:L})}}var y_3=30;class q41 extends l0{originX;originY;sparkleColors;durationSeconds;fps;onComplete;constructor({originX:J,originY:Z,sparkleColors:Q,durationSeconds:Y=Jh4,fps:X=y_3,onComplete:K,key:V}){super(V?{key:V}:{});this.originX=J,this.originY=Z,this.sparkleColors=Q,this.durationSeconds=Y,this.fps=X,this.onComplete=K}createState(){return new Rd4}}class Rd4 extends p0{elapsedSeconds=0;timer=null;particles=[];completed=!1;animationStartTimeMs=0;initState(){super.initState(),this.restart()}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.originX!==J.originX||this.widget.originY!==J.originY||this.widget.durationSeconds!==J.durationSeconds||this.widget.fps!==J.fps)this.restart()}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null;super.dispose()}restart(){if(this.timer)clearInterval(this.timer),this.timer=null;this.elapsedSeconds=0,this.completed=!1,this.animationStartTimeMs=performance.now();let J=Qh4(this.widget.originX,this.widget.originY);if(this.particles=Yh4(J,Zh4),this.widget.fps<=0){this.elapsedSeconds=this.widget.durationSeconds,this.complete();return}let Z=Math.max(16,Math.floor(1000/this.widget.fps));this.timer=setInterval(()=>{if(!this.mounted)return;if(this.elapsedSeconds=Math.min(this.widget.durationSeconds,(performance.now()-this.animationStartTimeMs)/1000),this.elapsedSeconds>=this.widget.durationSeconds){this.elapsedSeconds=this.widget.durationSeconds,this.setState(()=>{}),this.complete();return}this.setState(()=>{})},Z)}complete(){if(this.completed)return;if(this.completed=!0,this.timer)clearInterval(this.timer),this.timer=null;this.widget.onComplete?.()}build(J){let Z=x1.of(J),Q=this.widget.sparkleColors.length>0?this.widget.sparkleColors:[Z.colorScheme.primary,Z.colorScheme.warning];return new Id4({originX:this.widget.originX,originY:this.widget.originY,elapsedSeconds:this.elapsedSeconds,sparkleColors:Q,particles:this.particles})}}class Id4 extends x${props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new fK(this)}createRenderObject(){return new Pd4(this.props.originX,this.props.originY,this.props.elapsedSeconds,this.props.sparkleColors,this.props.particles)}updateRenderObject(J){J.update(this.props.originX,this.props.originY,this.props.elapsedSeconds,this.props.sparkleColors,this.props.particles)}}class Pd4 extends u4{_originX;_originY;_elapsedSeconds;_sparkleColors;_particles;constructor(J,Z,Q,Y,X){super();this._originX=J;this._originY=Z;this._elapsedSeconds=Q;this._sparkleColors=Y;this._particles=X}update(J,Z,Q,Y,X){this._originX=J,this._originY=Z,this._elapsedSeconds=Q,this._sparkleColors=Y,this._particles=X,this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Z=J.constrain(J.biggest.width,J.biggest.height);this.setSize(Z.width,Z.height),super.performLayout()}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,K=Math.floor(this.size.width),V=Math.floor(this.size.height),z=this._originX-Y,G=this._originY-X,F=this._sparkleColors;for(let q of this._particles){let W=Xh4(q,{elapsedSeconds:this._elapsedSeconds,originX:z,originY:G});if(!W)continue;let U=Math.round(W.x),H=Math.round(W.y);if(U<0||U>=K||H<0||H>=V)continue;let D=W.progress,B=D>0.85?".":q.glyph,N=F[q.colorIndex%F.length];if(!N)continue;if(J.setCell(Y+U,X+H,{char:B,width:1,style:{fg:N,dim:D>0.65,bold:q.kind==="burst"&&D<0.25}}),!(q.kind==="rain"&&D>0.2))continue;let L=H-1;if(L<0||L>=V)continue;J.setCell(Y+U,X+L,{char:".",width:1,style:{fg:N,dim:!0}});let O=H-2;if(O<0||O>=V)continue;J.setCell(Y+U,X+O,{char:".",width:1,style:{fg:N,dim:!0}})}}}function x_3(J,Z,Q=process.platform){if(Q==="win32"){let Y=J.replace(/\\/g,"/").toLowerCase(),X=Z.replace(/\\/g,"/").toLowerCase();return Y===X}return J===Z}class W41 extends l0{props;constructor(J){super();this.props=J}createState(){return new Cd4}}class Cd4 extends p0{filterByWorkspace=!0;cachedEntries=[];initState(){this.cachedEntries=this.computeFilteredEntries()}handleKeyEvent=(J)=>{if(J.ctrlKey&&J.key.toLowerCase()==="t"||J.altKey&&J.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.cachedEntries=this.computeFilteredEntries()}),"handled";return"ignored"};computeFilteredEntries(){let{entries:J,currentCwd:Z}=this.widget.props,Q;if(this.filterByWorkspace)Q=J.filter((K)=>K.cwd===void 0||x_3(K.cwd,Z));else Q=[...J];Q=Q.reverse();let Y=new Set,X=[];for(let K of Q){if(!Y.has(K.text))Y.add(K.text),X.push(K);if(X.length>=200)break}return X}handleAccept=(J)=>{this.widget.props.onAccept(J.text)};handleDismiss=()=>{this.widget.props.onDismiss()};build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.cachedEntries,K=this.filterByWorkspace?"Showing: current workspace":"Showing: all workspaces",V=new d0({padding:C0.symmetric(1,0),child:new W1({children:[new e({text:new P("",void 0,[new P("Alt+W/Ctrl+T",new g({color:Q.foreground})),new P(` toggle filter · ${K}`,new g({color:Q.foreground,dim:!0}))])})]})}),z=new $7({items:X,getLabel:(G)=>G.text.slice(0,60),filterItem:(G,F)=>{if(!F)return!0;return G.text.toLowerCase().includes(F.toLowerCase())},sortItems:()=>0,onAccept:this.handleAccept,onDismiss:this.handleDismiss,title:"Prompt History",emptyStateText:this.filterByWorkspace?"No history for this workspace":"No prompt history",maxRenderItems:100,footer:V,renderItem:(G,F,q,W)=>{let U=F?Y.selectionBackground:void 0,H=F?Y.selectionForeground:Q.foreground,D=80,B=G.text.replace(/\n/g," ");if(B.length>80)B=B.slice(0,79)+"…";return new d0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new e({text:new P(B,new g({color:H}))})})}});return new s4({onKey:this.handleKeyEvent,child:z,debugLabel:"PromptHistoryPicker"})}}var f_3=900;class U41 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Td4}}class Td4 extends p0{pendingInterruptQueuedMessageIDs=new Set;isInterruptArrowEmphasized=!1;interruptBlinkTimer=null;getQueuedMessageID(J){return J.queuedMessage.dtwMessageID??J.id}parseQueuedMessageID(J){let Z=s6.safeParse(J);if(!Z.success)return;return Z.data}initState(){super.initState(),this.updateInterruptBlinkAnimationState()}didUpdateWidget(J){super.didUpdateWidget(J),this.updateInterruptBlinkAnimationState()}dispose(){this.stopInterruptBlinkAnimation(),super.dispose()}build(J){let{queuedMessages:Z,title:Q="Queue"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return this.updateInterruptBlinkAnimationState(),new R0({width:0,height:0});let Y=new Set(Z.map((K)=>this.getQueuedMessageID(K)));for(let K of Z)if(K.interrupt)this.pendingInterruptQueuedMessageIDs.delete(this.getQueuedMessageID(K));for(let K of this.pendingInterruptQueuedMessageIDs)if(!Y.has(K))this.pendingInterruptQueuedMessageIDs.delete(K);this.updateInterruptBlinkAnimationState();let X=Z.map((K)=>this.buildQueueItem(K));return new d0({child:new n0({padding:C0.symmetric(1,0),child:new x0({crossAxisAlignment:"stretch",children:[new e({text:new P(Q,new g({bold:!0}))}),...X]})})})}buildQueueItem(J){let Q=f0.maybeOf(this.context)?.colors??x1.of(this.context).colorScheme,Y=this.getQueuedMessageID(J),X=J.interrupt===!0||this.pendingInterruptQueuedMessageIDs.has(Y),V=J.queuedMessage.content.filter((B)=>B.type==="text").map((B)=>B.text).join(" ").trim(),G=J.queuedMessage.content.filter((B)=>B.type==="image").length,F=V.split(`
|
|
7592
|
+
`));let G=z.startsWith("file://")?V1.parse(z):V1.file(z),F=Q9(G,X??void 0);K.push(new P(` • ${F}`,new g({color:Y.foreground,dim:!0})))}return new e({text:new P("",void 0,K)})}class Nd4 extends J4{props;constructor(J){super();this.props=J}build(J){let Z=this.props.affectedFiles,Q=Z.length>0,Y=Q?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",X=f0.of(J),K=[new e({text:new P(Y,new g({color:X.app.command,bold:!0}))}),new R0({height:1})],V=Bd4(J,Z);if(V)K.push(V),K.push(new R0({height:1}));let z=[{value:"confirm",label:Q?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return K.push(new $$({options:z,onSelect:(G)=>{if(G==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:C0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:K})}}class wd4 extends J4{props;constructor(J){super();this.props=J}build(J){let Z=this.props.affectedFiles,Q=f0.of(J),Y=[],X=Bd4(J,Z);if(X)Y.push(new e({text:new P("This will restore the following files:",new g({color:Q.app.command,bold:!0}))})),Y.push(new R0({height:1})),Y.push(X),Y.push(new R0({height:1}));let K=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new $$({options:K,onSelect:(V)=>{if(V==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:C0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class wG0 extends l0{controller;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;onDoubleAtTrigger;submitOnEnter;constructor(J){super();this.controller=J.controller,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview,this.onDoubleAtTrigger=J.onDoubleAtTrigger,this.submitOnEnter=J.submitOnEnter??!0}createState(){return new Ld4}}class Ld4 extends p0{currentShellModeStatus;imageAttachments=[];get controller(){return this.widget.controller}initState(){this.controller.addListener(this.textChangeListener);let J=YL(this.controller.text);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Z=this.widget.message.content.filter((Q)=>Q.type==="image");this.imageAttachments=Z}}dispose(){this.controller.removeListener(this.textChangeListener),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Q=YL(J)?.visibility;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=async(J)=>{let Z=await ZL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.widget.onShowImagePreview(Z,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Q,Y)=>Y!==J)})})};build(J){let Z=f0.of(J),Q=Z.colors,Y=Z.app,X=this.currentShellModeStatus?db4(Z,this.currentShellModeStatus):Y.selectedMessage,K=null,V=this.widget.message&&fD(this.widget.message);if(V)K=J41(J,V);let z=K?new n0({padding:C0.only({top:1}),child:K}):void 0,G=new BR({controller:this.controller,triggers:[new yq],bottomWidget:z,completionBuilder:this.widget.completionBuilder,onSubmitted:this.handleSubmit,theme:Q,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:Uz0(Z),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0,onDoubleAtTrigger:this.widget.onDoubleAtTrigger,submitKey:this.widget.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}}}),F=[];if(this.currentShellModeStatus===QL)F.push(new P("shell mode (incognito)",new g({color:Z.app.shellModeHidden})));else if(this.currentShellModeStatus===Wz0)F.push(new P("shell mode",new g({color:Z.app.shellMode})));else F.push(new P("esc",new g({color:Y.keybind})),new P(" to cancel",new g({color:Q.foreground,dim:!0})));return new bX0({child:new t8({decoration:{color:Q.background,border:c1.all(new g1(X,2,"solid"))},padding:C0.only({left:1,right:1}),overlays:[{child:new e({text:new P("",void 0,F)}),position:"bottom",alignment:"left"}],child:G})})}}d4();function aa(J){if(J.type==="message"){let K=J.message;if(K.role==="user"){let G=l3(K.content),F=K.content.filter((W)=>W.type==="image").length,q=(K.discoveredGuidanceFiles??[]).map((W)=>`${W.uri}|${W.lineCount}`).join("||");return`${J.id}|user|${K.interrupted?1:0}|${F}|${G}|${q}`}if(K.role==="assistant"){let G=l3(K.content),F=K.state?.type??"none",q=K.content.filter((B)=>B.type==="thinking"),W=K.content.filter((B)=>B.type==="tool_use"),U=q.map((B)=>{return`${YR(B.thinking).length}:${Sq(B)?"1":"0"}`}).join("|"),H=K.usage,D=H?`${H.inputTokens}|${H.outputTokens}|${H.cacheCreationInputTokens??""}|${H.cacheReadInputTokens??""}|${H.model??""}`:"no-usage";return`${J.id}|assistant|${F}|${q.length}|${W.length}|${G}|${U}|${D}|${K.turnElapsedMs??""}`}let z=K.content.map((G)=>G.type).join(",");return`${J.id}|info|${z}`}let Q=J.toolResult.run.status,Y=J.toolResult.userInput,X=Y?`accepted:${Y.accepted?1:0}|ask:${Y.askAnswers?Object.keys(Y.askAnswers).length:0}`:"none";return`${J.id}|tool|${Q}|${J.toolUse.id}|${X}`}function Od4(J){return(J.normalizedName??J.name)===M9}function k_3(J,Z,Q){let X=f0.maybeOf(J)?.colors??x1.of(J).colorScheme,V=Z.trimStart().startsWith("You're absolutely right"),z=new M3(`${Q}-text`),G=[];if(V)G.push(new t11({key:z,markdown:Z,defaultColor:X.foreground}));else G.push(new j3({key:z,markdown:Z}));if(G.length===1)return G[0];return new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:G})}class Z41{options;constructor(J){this.options=J}getRenderItems(){let J=[];for(let[Z,Q]of this.options.items.entries())J.push({type:"item",item:Q,sourceIndex:Z});return J}getSourceIndex(J){return J.sourceIndex}includesSourceIndex(J,Z){return J.sourceIndex===Z}getCacheIdentity(J){if(J.item.type==="message"){let Z=J.item.message;return`message:${Z.dtwMessageID??`${Z.role}:${Z.messageId}`}`}return`tool:${J.item.toolUse.id}`}getRenderSignature(J){let Z=aa(J.item),Q=this._getTaskSignatureSuffix(J);if(Q)return`${Z}|${Q}`;return Z}buildWidget(J,Z,Q){if(Z.item.type==="toolResult"&&Od4(Z.item.toolUse))return this._buildCollapsibleTaskItem(J,Z,Q);return this.buildThreadItemWidget(J,Z.item,Z.sourceIndex)}buildThreadItemWidget(J,Z,Q){let Y=new M3(`thread-item-${Z.id}`);if(Z.type==="message"){let K=Z.message;if(K.role==="user"){let W,U=(H,D)=>{this.options.onShowImagePreview(H,D,()=>{})};if(!this.options.isInSelectionMode)W=new ky({message:K,isFirstMessage:Q>0,onShowImagePreview:U});else{let H=this.options.onGetOrdinalFromUserMessageIndex(Q);if(H===null)W=new ky({message:K,isFirstMessage:Q>0,onShowImagePreview:U});else if(this.options.stateController.editingMessageOrdinal===H&&this.options.stateController.editingController)W=new wG0({controller:this.options.stateController.editingController,message:K,onSubmitted:(D,B)=>{this.options.onEditConfirmationRequest(D,B)},completionBuilder:this.options.completionBuilder,autocompleteHandle:this.options.autocompleteHandle,onShowImagePreview:this.options.onShowImagePreview,onDoubleAtTrigger:this.options.onDoubleAtTrigger,submitOnEnter:this.options.submitOnEnter});else if(this.options.stateController.selectedUserMessageOrdinal===H)W=new NG0({message:K,isFirstMessage:Q>0,showRestoreHint:this.options.showRestoreHint,isShowingRestoreConfirmation:this.options.stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this.options.stateController.isShowingEditConfirmation,affectedFiles:[...this.options.stateController.affectedFiles],pendingEditText:this.options.stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.options.onRestoreConfirm()},onRestoreCancel:()=>{this.options.onRestoreCancel()},onEditConfirm:()=>{this.options.onEditConfirm()},onEditCancel:()=>{this.options.onEditCancel()},onShowImagePreview:U});else W=new ky({message:K,isFirstMessage:Q>0,onShowImagePreview:U})}return W}if(K.role==="assistant"){let W=this._buildAssistantMessageWidget(J,K,Q,Z.id);return new d0({key:Y,child:W})}let V=K,z=[],G=this.options.onGetOrdinalFromUserMessageIndex(Q),F=this.options.isInSelectionMode&&G!==null&&this.options.stateController.selectedUserMessageOrdinal===G,q=(W,U)=>{this.options.onShowImagePreview(W,U,()=>{})};for(let W of V.content){if(W.type!=="manual_bash_invocation")continue;if(this.options.stateController.editingMessageOrdinal===G&&this.options.stateController.editingController)z.push(new wG0({controller:this.options.stateController.editingController,message:V,onSubmitted:(U,H)=>{this.options.onEditConfirmationRequest(U,H)},completionBuilder:this.options.completionBuilder,autocompleteHandle:this.options.autocompleteHandle,onShowImagePreview:this.options.onShowImagePreview,onDoubleAtTrigger:this.options.onDoubleAtTrigger,submitOnEnter:this.options.submitOnEnter}));else if(!this.options.isInSelectionMode||!F)z.push(new ky({message:V,isFirstMessage:Q>0,onShowImagePreview:q}));else z.push(new NG0({message:V,isFirstMessage:Q>0,showRestoreHint:this.options.showRestoreHint,isShowingRestoreConfirmation:this.options.stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this.options.stateController.isShowingEditConfirmation,affectedFiles:[...this.options.stateController.affectedFiles],pendingEditText:this.options.stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.options.onRestoreConfirm()},onRestoreCancel:()=>{this.options.onRestoreCancel()},onEditConfirm:()=>{this.options.onEditConfirm()},onEditCancel:()=>{this.options.onEditCancel()},onShowImagePreview:q,showEditHint:!this.options.isDTWMode}))}if(z.length===0)return new d0;if(z.length===1)return z[0];return new x0({crossAxisAlignment:"stretch",children:z})}let X=new gQ({toolUse:Z.toolUse,toolRun:Z.toolResult.run,toolProgress:this.options.toolProgressByToolUseID.get(Z.toolUse.id),userInput:Z.toolResult.userInput,subagentContent:this.options.subagentContentByParentID[Z.toolUse.id]});return new d0({key:Y,child:X})}_getTaskSignatureSuffix(J){if(J.item.type!=="toolResult"||!Od4(J.item.toolUse))return;let Z=this._isTaskCompleted(J.item.toolResult.run.status);return`task:${this.options.stateController.denseViewItemStates.get(J.item.id)??!Z?"1":"0"}`}_isTaskCompleted(J){return J!=="in-progress"&&J!=="queued"&&J!=="blocked-on-user"}_buildCollapsibleTaskItem(J,Z,Q){if(Z.item.type!=="toolResult")return this.buildThreadItemWidget(J,Z.item,Z.sourceIndex);let Y=Z.item.toolUse,X=Z.item.toolResult.run,K=na(J,Y,X),V=this._isTaskCompleted(X.status),z=this.options.stateController.denseViewItemStates.get(Z.item.id)??!V,G=new ia({toolUse:Y,toolRun:X,subagentContent:this.options.subagentContentByParentID[Y.id],hideHeader:!0});return new uq({key:new M3(`task-${Z.item.id}`),title:K,child:G,expanded:z,onChanged:(F)=>{this.options.onStateUpdate(()=>{this.options.stateController.setDenseViewItemState(Z.item.id,F),this.options.onInvalidateSourceIndex(Z.sourceIndex)})}})}_getThinkingBlockExpanded(J,Z){let Q=`${J}-${Z}`;return this.options.stateController.thinkingBlockStates.get(Q)??R7.instance.allExpanded}_toggleThinkingBlock(J,Z){return(Q)=>{let Y=`${J}-${Z}`;this.options.onStateUpdate(()=>{this.options.stateController.setThinkingBlockState(Y,Q),this.options.onInvalidateSourceIndex(J)})}}_buildThinkingBlock(J,Z,Q,Y,X){let K=Q===X,V=Y.state?.type==="streaming"&&K,z=Y.state?.type==="cancelled"&&K;return new XR({key:new M3(`thinking-${Z}-${Q}`),thinkingBlock:J,expanded:this._getThinkingBlockExpanded(Z,Q),onToggle:this._toggleThinkingBlock(Z,Q),isStreaming:V,isCancelled:z})}_buildAssistantMessageWidget(J,Z,Q,Y){let X=this.options.showThinkingBlocks?Z.content.map((U,H)=>({block:U,index:H})).filter((U)=>U.block.type==="thinking"&&Sq(U.block)):[],K=X.length>0,V=X.length>0?X.at(-1).index:-1,z=Z.content.filter((U)=>U.type==="text"&&!U.hidden),G=[];X.forEach(({block:U,index:H},D)=>{if(D>0)G.push(new R0({height:1}));G.push(this._buildThinkingBlock(U,Q,H,Z,V))});let F=l3(z);if(K&&F.trim().length>0)G.push(new R0({height:1}));if(F.trim())G.push(k_3(J,F,Y));let q=NV0(J),W=Z.usage!=null&&(Z.usage.inputTokens>0||Z.usage.outputTokens>0);if(q&&W){let H=f0.maybeOf(J)?.colors??x1.of(J).colorScheme,D=B_4(Z.usage);G.push(new n0({padding:C0.only({top:1}),child:new e({text:new P(D,new g({color:H.foreground,dim:!0}))})}))}if(G.length===0)return new d0;if(G.length===1)return G[0];return new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:G})}}class LG0 extends S3{}class OG0 extends S3{}class Q41 extends S3{}class Y41 extends S3{}class X41 extends S3{}class K41 extends S3{}class V41 extends S3{}class z41 extends S3{}function Ed4(J){return J.type==="item"&&"item"in J&&"sourceIndex"in J}function v_3(J){let Z=fD(J);if(Z)return`${Z.hidden?"$$":"$"}${Z.args.cmd}`;return l3(J.content)}class oa extends l0{items;subagentContentByParentID;toolProgressByToolUseID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onShowForkDeprecation;getAffectedFiles;hasStartedStreamingResponse=!1;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;onDoubleAtTrigger;stateController;denseView;submitOnEnter;threadViewState;isDTWMode;get userMessageIndices(){let J=[];for(let Z=0;Z<this.items.length;Z++){let Q=this.items[Z];if(Q?.type==="message"){if(Q.message.role==="user"||AW(Q.message))J.push(Z)}}return J}get navigableItemIndices(){let J=[];for(let Z=0;Z<this.items.length;Z++){let Q=this.items[Z];if(Q?.type==="message"){if(Q.message.role==="user"||AW(Q.message))J.push(Z)}else if(Q?.type==="toolResult"&&Q.toolUse.name==="chart")J.push(Z)}return J}constructor({key:J,items:Z,subagentContentByParentID:Q={},toolProgressByToolUseID:Y=new Map,controller:X,autofocus:K=!1,onNewMessage:V,showScrollbar:z=!0,onCopy:G,onMessageEditSubmit:F,onMessageRestoreSubmit:q,onShowForkDeprecation:W,getAffectedFiles:U,hasStartedStreamingResponse:H=!1,focusNode:D,onDismissFocus:B,isInSelectionMode:N=!1,isInHandoffMode:w=!1,completionBuilder:L,onShowImagePreview:O,onSelectionChanged:E,onDoubleAtTrigger:M,stateController:A,denseView:j,submitOnEnter:R=!0,threadViewState:_,isDTWMode:T=!1}){super(J?{key:J}:{});this.items=Z,this.subagentContentByParentID=Q,this.toolProgressByToolUseID=Y,this.controller=X,this.autofocus=K,this.onNewMessage=V,this.showScrollbar=z,this.onCopy=G,this.onMessageEditSubmit=F,this.onMessageRestoreSubmit=q,this.onShowForkDeprecation=W,this.getAffectedFiles=U,this.hasStartedStreamingResponse=H,this.focusNode=D,this.onDismissFocus=B,this.isInSelectionMode=N,this.isInHandoffMode=w,this.completionBuilder=L,this.onShowImagePreview=O,this.onSelectionChanged=E,this.onDoubleAtTrigger=M,this.stateController=A,this.denseView=j,this.submitOnEnter=R,this.threadViewState=_,this.isDTWMode=T}createState(){return new Md4}}class Md4 extends p0{_controller=null;_isDisposed=!1;_globalToggleListener;_denseToggleListener;_renderItems=[];_streamingIndexes=new Set;_viewportHeight=25;_renderItemCacheKeys=[];_widgetCache=new Map;_lastCostDisplayState=null;_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;_controllerUnsubscribe=null;_lastDenseViewState=null;_renderDelegate=null;get controller(){return this._controller}get _stateController(){return this.widget.stateController}get _isDenseViewEnabled(){return this.widget.denseView}_createRenderDelegate(){let J=new Z41({items:this.widget.items,toolProgressByToolUseID:this.widget.toolProgressByToolUseID,subagentContentByParentID:this.widget.subagentContentByParentID,stateController:this._stateController,isInSelectionMode:this.widget.isInSelectionMode,showRestoreHint:!!this.widget.onMessageRestoreSubmit,isDTWMode:this.widget.isDTWMode,completionBuilder:this.widget.completionBuilder,onShowImagePreview:this.widget.onShowImagePreview,onDoubleAtTrigger:this.widget.onDoubleAtTrigger,submitOnEnter:this.widget.submitOnEnter,autocompleteHandle:this._autocompleteHandle,showThinkingBlocks:!this._isDenseViewEnabled,onGetOrdinalFromUserMessageIndex:(Z)=>this.getOrdinalFromUserMessageIndex(Z),onEditConfirmationRequest:(Z,Q)=>{this.handleEditConfirmationRequest(Z,Q)},onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onStateUpdate:(Z)=>{this.setState(()=>{Z()})},onInvalidateSourceIndex:(Z)=>{this._clearCacheForSourceIndex(Z)}});if(this._isDenseViewEnabled)return new s11({items:this.widget.items,toolProgressByToolUseID:this.widget.toolProgressByToolUseID,subagentContentByParentID:this.widget.subagentContentByParentID,stateController:this._stateController,hasStartedStreamingResponse:this.widget.hasStartedStreamingResponse,threadViewState:this.widget.threadViewState,buildThreadItemWidget:(Z,Q,Y)=>J.buildThreadItemWidget(Z,Q,Y),onStateUpdate:(Z)=>{this.setState(()=>{Z()})},onInvalidateRenderItemIndex:(Z)=>{let Q=this._getCacheKeyForRenderItem(Z);this._widgetCache.delete(Q)}});return J}_getRenderDelegate(){if(!this._renderDelegate)this._renderDelegate=this._createRenderDelegate();return this._renderDelegate}dismiss(){C6.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Z){if(Z<=0)return null;if(J===null)return Z-1;if(J<=0)return 0;return J-1}_navigateDown(J,Z){if(Z<=0)return null;if(J===null)return null;if(J>=Z-1)return null;return J+1}_ordinalToIndex(J,Z){if(Z===null)return null;if(Z<0||Z>=J.length)return null;return J[Z]??null}_getUserCount(){return this.widget.navigableItemIndices.length}_updateRenderItems(){this._renderDelegate=this._createRenderDelegate(),this._renderItems=this._renderDelegate.getRenderItems(),this._renderDelegate.onRenderItemsUpdated?.(this._renderItems),this._rebuildRenderItemCacheKeys()}_getSourceIndexForRenderItem(J){return this._getRenderDelegate().getSourceIndex(J)}_rebuildRenderItemCacheKeys(){let J=new Map;this._renderItemCacheKeys=this._renderItems.map((Z)=>{let Q=this._getRenderDelegate().getCacheIdentity(Z),Y=J.get(Q)??0;return J.set(Q,Y+1),`${Q}:${Y}`})}_toolAuxiliarySignature(J,Z=this.widget.toolProgressByToolUseID,Q=this.widget.subagentContentByParentID){let Y=Z.get(J),X=Y?`${Y.status}|${Y.content}`:"none",K=BG0(Q[J]);return`progress:${X}|subagents:${K}`}_getCacheKeyForRenderItem(J){return this._renderItemCacheKeys[J]??`missing:${J}`}_clearSelectedUserMessage(){let J=this._stateController.selectedUserMessageOrdinal,Z=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Z!=null)this._clearCacheForSourceIndex(Z);this._stateController.setSelectedUserMessageOrdinal(null)})}_selectUserMessageByOrdinal(J){let Z=this._stateController.selectedUserMessageOrdinal,Q=J,Y=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null,X=this.getUserMessageIndexFromOrdinal(Q);if(Y!==null)this._clearCacheForSourceIndex(Y);if(X!==null)this._clearCacheForSourceIndex(X);if(this.setState(()=>{this._stateController.setSelectedUserMessageOrdinal(Q)}),X!==null)C6.instance.addPostFrameCallback(()=>{let K=this._getRenderIndexForSourceIndex(X);this.scrollToMessage(K??X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Z=this._stateController.editingMessageOrdinal,Q=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null,Y=J!==null?this.getUserMessageIndexFromOrdinal(J):null;if(Q!==null)this._clearCacheForSourceIndex(Q);if(Y!==null)this._clearCacheForSourceIndex(Y);if(J===null)this.setState(()=>{this._stateController.stopEditing()});else{let X=this.getUserMessageIndexFromOrdinal(J),K=X!==null?this.widget.items[X]:null,V=K?.type==="message"&&(K.message.role==="user"||K.message.role==="info")?v_3(K.message):"";this.setState(()=>{this._stateController.startEditing(J,V)})}}getUserMessageIndexFromOrdinal(J){return this.widget.navigableItemIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Q=this.widget.navigableItemIndices.indexOf(J);return Q>=0?Q:null}getLatestUserMessageOrdinal(){let J=this.widget.navigableItemIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Z=this._getUserCount(),Q=this._stateController.selectedUserMessageOrdinal,Y=J==="up"?this._navigateUp(Q,Z):this._navigateDown(Q,Z);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._stateController.editingMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._stateController.editingMessageOrdinal);if(J!=null)this._clearCacheForSourceIndex(J);return this.setState(()=>{this._stateController.stopEditing()}),C6.instance.addPostFrameCallback(()=>{this.widget.focusNode?.requestFocus()}),"handled"}else if(this._stateController.selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._stateController.stopEditing()}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this.getUserMessageIndexFromOrdinal(J),Q=Z!==null?this.widget.items[Z]:null;if(Q?.type==="message"&&AW(Q.message)&&this.widget.isDTWMode)return"handled";return this._selectEditingUserMessageByOrdinal(J),"handled"}return"ignored"};handleRestoreMessage=()=>{if(!this.widget.onMessageRestoreSubmit)return"ignored";let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this.getUserMessageIndexFromOrdinal(J);if(Z===null)return"ignored";if(Z===0)return"ignored";let Q=this.widget.items[Z];if(Q?.type==="message"&&(Q.message.role==="user"||AW(Q.message)))this.showRestoreConfirmation(Q.message,Z);return"handled"}return"ignored"};async showRestoreConfirmation(J,Z){let Q=[];if(this.widget.getAffectedFiles)try{Q=await this.widget.getAffectedFiles(J)}catch{Q=[]}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!0),this._stateController.setAffectedFiles(Q)}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let Y=this._getRenderIndexForSourceIndex(Z);this.scrollToMessage(Y??Z)})}handleRestoreConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){if(Z===0)return"ignored";let Q=this.widget.items[Z];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let Q=this._getRenderIndexForSourceIndex(Z);this.scrollToMessage(Q??Z)})}}return"handled"};handleForkMessage=()=>{if(this._stateController.selectedUserMessageOrdinal!==null&&this.widget.onShowForkDeprecation)return this.widget.onShowForkDeprecation(),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss(),"handled";return"ignored"};handleEditConfirmationRequest=async(J,Z)=>{if(J.trim()===""&&Z.length===0)return;let Q=this._stateController.editingMessageOrdinal;if(Q!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,Q);if(Y!=null){let X=this.widget.items[Y],K=[];if(this.widget.getAffectedFiles&&X?.type==="message")try{K=await this.widget.getAffectedFiles(X.message)}catch{K=[]}if(K.length===0&&X?.type==="message"&&(X.message.role==="user"||X.message.role==="info")){this.widget.onMessageEditSubmit?.(X.message,J,Z),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.stopEditing()}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!0),this._stateController.setPendingEditText(J),this._stateController.setPendingEditImageAttachments(Z),this._stateController.setAffectedFiles(K),this._stateController.stopEditing()}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let V=this._getRenderIndexForSourceIndex(Y);this.scrollToMessage(V??Y)})}}};handleEditConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal,Z=this._stateController.pendingEditText;if(J!==null&&Z!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){let Y=this.widget.items[Q];if(Y?.type==="message"&&(Y.message.role==="user"||Y.message.role==="info"))this.widget.onMessageEditSubmit?.(Y.message,Z,[...this._stateController.pendingEditImageAttachments]),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.controller.atBottom)C6.instance.addPostFrameCallback(()=>{let Q=this._getRenderIndexForSourceIndex(Z);this.scrollToMessage(Q??Z)})}}};initState(){if(super.initState(),this._lastDenseViewState=this._isDenseViewEnabled,this._updateRenderItems(),this._controller=this.widget.controller||new j5,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._stateController.clearThinkingBlockStates(),this._widgetCache.clear()})},R7.instance.addListener(this._globalToggleListener),this._denseToggleListener=()=>{this.setState(()=>{this._stateController.clearDenseViewItemStates(),this._widgetCache.clear()})},kJ.instance.addListener(this._denseToggleListener),this._controllerUnsubscribe=this._stateController.subscribe(()=>{this.setState(()=>{})}),this.widget.items.length>0)C6.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),this._lastDenseViewState!==this._isDenseViewEnabled){if(this._lastDenseViewState=this._isDenseViewEnabled,this._stateController.clearDenseViewItemStates(),this._widgetCache.clear(),!this._isDenseViewEnabled)kJ.instance.setAllExpanded(!1)}if(this._updateRenderItems(),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let X=this.getLatestUserMessageOrdinal();if(X!==null)this._selectUserMessageByOrdinal(X)}let Q=Math.min(J.items.length,this.widget.items.length);for(let X=0;X<Q;X++){let K=J.items[X],V=this.widget.items[X];if(K&&V){if(K.type!==V.type){this._clearCacheForSourceIndex(X);continue}if(aa(K)!==aa(V))this._clearCacheForSourceIndex(X)}}if(J.toolProgressByToolUseID!==this.widget.toolProgressByToolUseID||J.subagentContentByParentID!==this.widget.subagentContentByParentID)for(let[X,K]of this.widget.items.entries()){if(K?.type!=="toolResult")continue;let V=this._toolAuxiliarySignature(K.toolUse.id,J.toolProgressByToolUseID,J.subagentContentByParentID),z=this._toolAuxiliarySignature(K.toolUse.id);if(V!==z)this._clearCacheForSourceIndex(X)}this._cleanupOrphanedCacheEntries(),this._updateStreamingIndexes();for(let X of this._streamingIndexes)if(X>=this._renderItems.length)this._streamingIndexes.delete(X)}_cleanupOrphanedCacheEntries(){let J=new Set(this._renderItemCacheKeys);for(let Z of this._widgetCache.keys())if(!J.has(Z))this._widgetCache.delete(Z)}_clearCacheForSourceIndex(J){for(let[Z,Q]of this._renderItems.entries()){let Y=this._getCacheKeyForRenderItem(Z);if(this._getRenderDelegate().includesSourceIndex(Q,J))this._widgetCache.delete(Y)}}_getRenderIndexForSourceIndex(J){for(let[Z,Q]of this._renderItems.entries())if(this._getRenderDelegate().includesSourceIndex(Q,J))return Z;return null}_isMessageStreaming(J){if(!Ed4(J))return!1;if(J.item.type!=="message")return!1;let Z=J.item.message;if(Z.role!=="assistant")return!1;return Z.state.type==="streaming"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this._renderItems.length)this._streamingIndexes.delete(J);for(let J=0;J<this._renderItems.length;J++){let Z=this._renderItems[J];if(!Z)continue;let Q=this._isMessageStreaming(Z);if(Q&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Q&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Z=J.size;if(typeof Z.height==="number"&&Z.height>0)return this._viewportHeight=Z.height,Z.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)R7.instance.removeListener(this._globalToggleListener);if(this._denseToggleListener)kJ.instance.removeListener(this._denseToggleListener);if(this._controllerUnsubscribe)this._controllerUnsubscribe(),this._controllerUnsubscribe=null;if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Z=f0.of(J),Q=NV0(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Q)this._widgetCache.clear();this._lastCostDisplayState=Q;let Y=this._getTotalItemCount(J),X=[];for(let U=0;U<Y;U++)if(X.push(this._buildItemAtIndex(J,U)),U<Y-1)X.push(new R0({height:1}));let K=new T6({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new x0({key:new M3("message-list-column"),crossAxisAlignment:"start",children:X})}),z=[new n0({padding:C0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:K})];if(this.widget.showScrollbar&&this._controller){let U=new N9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack});z.push(new t6({right:1,top:0,bottom:0,child:new R0({width:1,child:U})}))}let G=new z5({children:z}),F=new p$({child:G,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),q=new Map([[LG0,new D6(this.handleNavigateUserMessageUp)],[OG0,new D6(this.handleNavigateUserMessageDown)],[Q41,new D6(this.handleEscape)],[Y41,new D6(this.handleScrollDown)],[X41,new D6(this.handleScrollUp)],[K41,new D6(this.handleEditMessage)],[V41,new D6(this.handleRestoreMessage)],[z41,new D6(this.handleForkMessage)]]),W=new Map([[D4.key("Tab"),new LG0],[D4.shift("Tab"),new OG0],[D4.key("Escape"),new Q41],[D4.key("j"),new Y41],[D4.key("k"),new X41],[D4.key("e"),new K41],[D4.key("f"),new z41]]);if(this.widget.onMessageRestoreSubmit)W.set(D4.key("r"),new V41);if(!a7())W.set(D4.key("ArrowUp"),new LG0),W.set(D4.key("ArrowDown"),new OG0);if(this.widget.focusNode)return new s4({focusNode:this.widget.focusNode,child:new A7({actions:q,child:new m$({shortcuts:W,focusNode:this.widget.focusNode,child:F})})});return F}_getTotalItemCount(J){return this._renderItems.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._stateController.isShowingRestoreConfirmation||this._stateController.isShowingEditConfirmation){let Q=this._stateController.selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}let Z=this._stateController.editingMessageOrdinal;if(Z!==null){let Q=this.getUserMessageIndexFromOrdinal(Z);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Z){let Q=this._renderItems[Z];if(!Q)return new d0;let Y=Ed4(Q)?Q.item:null,X=Y?.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),K=this._getSourceIndexForRenderItem(Q),V=this._shouldDimItem(K),z=this._isMessageStreaming(Q);if(!X&&!z){let q=`${this._getRenderDelegate().getRenderSignature(Q)}|dim:${V?1:0}`,W=this._getCacheKeyForRenderItem(Z),U=this._widgetCache.get(W);if(U&&U.sig===q)return U.widget;let H=this._getRenderDelegate().buildWidget(J,Q,Z),D=V?new oY({forceDim:!0,child:H}):H;return this._widgetCache.set(W,{sig:q,widget:D}),D}let F=this._getRenderDelegate().buildWidget(J,Q,Z);return V?new oY({forceDim:!0,child:F}):F}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Z=!1,offsetPercent:Q=0.25,edge:Y="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let K=this._getMessageRelativeOffset(J,Y);if(K===null)return!1;let V=this._getViewportHeight(),z=Math.floor(V*Q),G=K-z;if(Z)this._controller.animateTo(G,X);else this._controller.jumpTo(G);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Z=new M3("message-list-column"),Q=(Y)=>{if(Y.widget.key?.equals(Z))return Y;for(let X of Y.children){let K=Q(X);if(K)return K}return null};return Q(J)}_getMessageRelativeOffset(J,Z){let Q=this._getColumnElement();if(!Q)return null;let Y=J*2,X=Q.children[Y];if(!X?.renderObject)return null;let K=X.renderObject,V=Q.renderObject;if(!V)return null;let z=K.localToGlobal({x:0,y:0}),G=V.localToGlobal({x:0,y:0}),F=0;if(Z==="bottom")F=K.size.height;return z.y+F-G.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Z=this._getViewportHeight(),Q=this._controller?.offset??0,Y=J+Z;return{totalContentHeight:Math.max(Y,0),viewportHeight:Math.max(Z,1),scrollOffset:Math.max(Q,0)}}}class EG0{_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_pendingEditImageAttachments=[];_affectedFiles=[];_thinkingBlockStates=new Map;_denseViewItemStates=new Map;_denseViewItemTouched=new Set;_editingController=null;listeners=new Set;get selectedUserMessageOrdinal(){return this._selectedUserMessageOrdinal}setSelectedUserMessageOrdinal(J){if(this._selectedUserMessageOrdinal===J)return;this._selectedUserMessageOrdinal=J,this.notify()}get editingMessageOrdinal(){return this._editingMessageOrdinal}get isShowingRestoreConfirmation(){return this._isShowingRestoreConfirmation}setIsShowingRestoreConfirmation(J){if(this._isShowingRestoreConfirmation===J)return;this._isShowingRestoreConfirmation=J,this.notify()}get isShowingEditConfirmation(){return this._isShowingEditConfirmation}setIsShowingEditConfirmation(J){if(this._isShowingEditConfirmation===J)return;this._isShowingEditConfirmation=J,this.notify()}get pendingEditText(){return this._pendingEditText}setPendingEditText(J){if(this._pendingEditText===J)return;this._pendingEditText=J,this.notify()}get pendingEditImageAttachments(){return this._pendingEditImageAttachments}setPendingEditImageAttachments(J){this._pendingEditImageAttachments=[...J],this.notify()}get affectedFiles(){return this._affectedFiles}setAffectedFiles(J){this._affectedFiles=[...J],this.notify()}get thinkingBlockStates(){return this._thinkingBlockStates}get denseViewItemStates(){return this._denseViewItemStates}get denseViewItemTouched(){return this._denseViewItemTouched}setThinkingBlockState(J,Z){if(this._thinkingBlockStates.get(J)===Z)return;this._thinkingBlockStates.set(J,Z),this.notify()}clearThinkingBlockStates(){if(this._thinkingBlockStates.size===0)return;this._thinkingBlockStates.clear(),this.notify()}setDenseViewItemState(J,Z){if(this._denseViewItemStates.get(J)===Z)return;this._denseViewItemStates.set(J,Z),this._denseViewItemTouched.add(J),this.notify()}setDenseViewItemTouched(J){if(this._denseViewItemTouched.has(J))return;this._denseViewItemTouched.add(J),this.notify()}clearDenseViewItemStates(){if(this._denseViewItemStates.size===0)return;this._denseViewItemStates.clear(),this._denseViewItemTouched.clear(),this.notify()}get editingController(){return this._editingController}startEditing(J,Z){if(this._editingMessageOrdinal===J&&this._editingController)return;this._editingController?.dispose(),this._editingController=new r7,this._editingController.text=Z,this._editingMessageOrdinal=J,this.notify()}stopEditing(){if(this._editingMessageOrdinal===null&&!this._editingController)return;this._editingMessageOrdinal=null,this._editingController?.dispose(),this._editingController=null,this.notify()}subscribe(J){return this.listeners.add(J),()=>this.listeners.delete(J)}notify(){for(let J of[...this.listeners])J()}reset(){this._selectedUserMessageOrdinal=null,this._editingMessageOrdinal=null,this._isShowingRestoreConfirmation=!1,this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[],this._thinkingBlockStates.clear(),this._denseViewItemStates.clear(),this._denseViewItemTouched.clear(),this._editingController?.dispose(),this._editingController=null,this.notify()}}class G41 extends l0{message;onDestruct;constructor({key:J,message:Z,onDestruct:Q}){super(J?{key:J}:{});this.message=Z,this.onDestruct=Q}createState(){return new Ad4}}class Ad4 extends p0{scrollController;focusNode;viewportHeight=1;scrollListenerAttached=!1;initState(){this.scrollController=new j5,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0),this.focusNode=new G6}dispose(){this.scrollController.dispose(),this.focusNode.dispose()}formatDate(J){return new Date(J).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let K=Y.children||[];for(let V of K){if(V&&"size"in V){let G=V.size;if(typeof G?.height==="number"&&G.height>0)return G.height}let z=Z(V,X+1);if(z>0)return z}}return 0},Q=Z(J);if(Q>0)return Q;return this.viewportHeight}build(J){let Q=x1.of(J).colorScheme,X=f0.of(J).app,K=K4.of(J);if(!this.scrollListenerAttached)this.scrollController.addListener(()=>{this.updateViewportHeight(),this.setState(()=>{})}),this.scrollListenerAttached=!0;let V=new g({color:Q.primary,bold:!0}),z=new g({color:Q.foreground,dim:!0}),G=new g({color:Q.foreground}),F=new g({color:X.keybind}),q=new g({color:Q.foreground}),W=K.size.width,U=K.size.height,H=W-4,B=Math.min(20,U-4),N=Math.max(40,Math.min(60,H)),w=new n0({padding:C0.only({top:1,left:2,right:2,bottom:1}),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new X4({child:new e({text:new P(this.widget.message.title,V)})}),new X4({child:new e({text:new P(this.formatDate(this.widget.message.visibleFrom),z)})})]})}),L=new W1({crossAxisAlignment:"stretch",children:[new y1({child:new T6({autofocus:!0,controller:this.scrollController,child:new d0({constraints:new I1(N-5,N-5,0,Number.POSITIVE_INFINITY),child:new n0({padding:C0.only({left:2,right:2}),child:new e({text:new P(this.widget.message.body,G)})})})})}),new N9({controller:this.scrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let M=this.scrollController.maxScrollExtent,A=this.scrollController.offset,j=this.viewportHeight,R=M+j;return{totalContentHeight:Math.max(R,0),viewportHeight:Math.max(j,1),scrollOffset:Math.max(A,0)}}})]}),O=new n0({padding:C0.symmetric(2,1),child:new X4({child:new e({text:new P("",q,[new P("Destroy message ",q),new P("(Esc)",F)])})})}),E=new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[w,new bz({fit:"loose",child:L}),O]});return new s4({autofocus:!0,focusNode:this.focusNode,onKey:(M)=>{if(M.key==="Escape")return this.widget.onDestruct(),"handled";return"ignored"},child:new X4({child:new d0({constraints:new I1(N,N,0,B),decoration:new $6(Q.background,c1.all(new g1(Q.primary,1,"rounded"))),child:E})})})}}class F41 extends l0{request;onDismiss;constructor({request:J,onDismiss:Z}){super();this.request=J,this.onDismiss=Z}createState(){return new jd4}}class jd4 extends p0{textController;focusNode;errorMessage=null;initState(){this.textController=new r7,this.focusNode=new G6}dispose(){this.textController.dispose(),this.focusNode.dispose()}handleSubmit=()=>{let J=this.textController.text.trim();if(!J){this.setState(()=>{this.errorMessage="Please enter the callback URL or authorization code"});return}this.widget.request.resolve(J),this.widget.onDismiss()};build(J){let Q=x1.of(J).colorScheme,X=f0.of(J).app,K=K4.of(J),V=K.size.width,z=K.size.height,G=V-4,F=Math.max(50,Math.min(80,G)),q=new g({color:Q.primary,bold:!0}),W=new g({color:X.link,bold:!0}),U=new g({color:Q.foreground,dim:!0}),H=new g({color:X.keybind}),D=new g({color:X.toolError}),B=this.widget.request.serverName,N=[new e({text:new P("1. Open this URL in your browser (select to copy):",U)}),new R0({height:1}),new n0({padding:C0.only({left:3}),child:new p$({child:new e({text:new P(this.widget.request.authorizationUrl,W),selectable:!0})})}),new R0({height:1}),new e({text:new P("2. Authorize the application",U)}),new R0({height:1}),new e({text:new P("3. After redirect fails, copy the URL from your browser address bar",U)}),new R0({height:1}),new e({text:new P("4. Paste the localhost URL below:",U)})],w=[new e({text:new P(`OAuth Required: ${B}`,q)}),new R0({height:1}),...N,new R0({height:1}),new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,placeholder:"Paste callback URL or authorization code...",onSubmitted:this.handleSubmit})];if(this.errorMessage)w.push(new R0({height:1})),w.push(new e({text:new P(this.errorMessage,D)}));w.push(new R0({height:1})),w.push(new W1({children:[new e({text:new P("",void 0,[new P("Enter",H),new P(" submit · ",U),new P("Esc",H),new P(" cancel",U)])})]}));let L=new d0({constraints:new I1(F-4,F-4,0,z-6),decoration:{color:Q.background,border:c1.all(new g1(Q.primary,1,"rounded"))},padding:C0.all(2),child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:w})});return new X4({child:L})}}var y_3=30;class q41 extends l0{originX;originY;sparkleColors;durationSeconds;fps;onComplete;constructor({originX:J,originY:Z,sparkleColors:Q,durationSeconds:Y=Jh4,fps:X=y_3,onComplete:K,key:V}){super(V?{key:V}:{});this.originX=J,this.originY=Z,this.sparkleColors=Q,this.durationSeconds=Y,this.fps=X,this.onComplete=K}createState(){return new Rd4}}class Rd4 extends p0{elapsedSeconds=0;timer=null;particles=[];completed=!1;animationStartTimeMs=0;initState(){super.initState(),this.restart()}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.originX!==J.originX||this.widget.originY!==J.originY||this.widget.durationSeconds!==J.durationSeconds||this.widget.fps!==J.fps)this.restart()}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null;super.dispose()}restart(){if(this.timer)clearInterval(this.timer),this.timer=null;this.elapsedSeconds=0,this.completed=!1,this.animationStartTimeMs=performance.now();let J=Qh4(this.widget.originX,this.widget.originY);if(this.particles=Yh4(J,Zh4),this.widget.fps<=0){this.elapsedSeconds=this.widget.durationSeconds,this.complete();return}let Z=Math.max(16,Math.floor(1000/this.widget.fps));this.timer=setInterval(()=>{if(!this.mounted)return;if(this.elapsedSeconds=Math.min(this.widget.durationSeconds,(performance.now()-this.animationStartTimeMs)/1000),this.elapsedSeconds>=this.widget.durationSeconds){this.elapsedSeconds=this.widget.durationSeconds,this.setState(()=>{}),this.complete();return}this.setState(()=>{})},Z)}complete(){if(this.completed)return;if(this.completed=!0,this.timer)clearInterval(this.timer),this.timer=null;this.widget.onComplete?.()}build(J){let Z=x1.of(J),Q=this.widget.sparkleColors.length>0?this.widget.sparkleColors:[Z.colorScheme.primary,Z.colorScheme.warning];return new Id4({originX:this.widget.originX,originY:this.widget.originY,elapsedSeconds:this.elapsedSeconds,sparkleColors:Q,particles:this.particles})}}class Id4 extends x${props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new fK(this)}createRenderObject(){return new Pd4(this.props.originX,this.props.originY,this.props.elapsedSeconds,this.props.sparkleColors,this.props.particles)}updateRenderObject(J){J.update(this.props.originX,this.props.originY,this.props.elapsedSeconds,this.props.sparkleColors,this.props.particles)}}class Pd4 extends u4{_originX;_originY;_elapsedSeconds;_sparkleColors;_particles;constructor(J,Z,Q,Y,X){super();this._originX=J;this._originY=Z;this._elapsedSeconds=Q;this._sparkleColors=Y;this._particles=X}update(J,Z,Q,Y,X){this._originX=J,this._originY=Z,this._elapsedSeconds=Q,this._sparkleColors=Y,this._particles=X,this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Z=J.constrain(J.biggest.width,J.biggest.height);this.setSize(Z.width,Z.height),super.performLayout()}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,K=Math.floor(this.size.width),V=Math.floor(this.size.height),z=this._originX-Y,G=this._originY-X,F=this._sparkleColors;for(let q of this._particles){let W=Xh4(q,{elapsedSeconds:this._elapsedSeconds,originX:z,originY:G});if(!W)continue;let U=Math.round(W.x),H=Math.round(W.y);if(U<0||U>=K||H<0||H>=V)continue;let D=W.progress,B=D>0.85?".":q.glyph,N=F[q.colorIndex%F.length];if(!N)continue;if(J.setCell(Y+U,X+H,{char:B,width:1,style:{fg:N,dim:D>0.65,bold:q.kind==="burst"&&D<0.25}}),!(q.kind==="rain"&&D>0.2))continue;let L=H-1;if(L<0||L>=V)continue;J.setCell(Y+U,X+L,{char:".",width:1,style:{fg:N,dim:!0}});let O=H-2;if(O<0||O>=V)continue;J.setCell(Y+U,X+O,{char:".",width:1,style:{fg:N,dim:!0}})}}}function x_3(J,Z,Q=process.platform){if(Q==="win32"){let Y=J.replace(/\\/g,"/").toLowerCase(),X=Z.replace(/\\/g,"/").toLowerCase();return Y===X}return J===Z}class W41 extends l0{props;constructor(J){super();this.props=J}createState(){return new Cd4}}class Cd4 extends p0{filterByWorkspace=!0;cachedEntries=[];initState(){this.cachedEntries=this.computeFilteredEntries()}handleKeyEvent=(J)=>{if(J.ctrlKey&&J.key.toLowerCase()==="t"||J.altKey&&J.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.cachedEntries=this.computeFilteredEntries()}),"handled";return"ignored"};computeFilteredEntries(){let{entries:J,currentCwd:Z}=this.widget.props,Q;if(this.filterByWorkspace)Q=J.filter((K)=>K.cwd===void 0||x_3(K.cwd,Z));else Q=[...J];Q=Q.reverse();let Y=new Set,X=[];for(let K of Q){if(!Y.has(K.text))Y.add(K.text),X.push(K);if(X.length>=200)break}return X}handleAccept=(J)=>{this.widget.props.onAccept(J.text)};handleDismiss=()=>{this.widget.props.onDismiss()};build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.cachedEntries,K=this.filterByWorkspace?"Showing: current workspace":"Showing: all workspaces",V=new d0({padding:C0.symmetric(1,0),child:new W1({children:[new e({text:new P("",void 0,[new P("Alt+W/Ctrl+T",new g({color:Q.foreground})),new P(` toggle filter · ${K}`,new g({color:Q.foreground,dim:!0}))])})]})}),z=new $7({items:X,getLabel:(G)=>G.text.slice(0,60),filterItem:(G,F)=>{if(!F)return!0;return G.text.toLowerCase().includes(F.toLowerCase())},sortItems:()=>0,onAccept:this.handleAccept,onDismiss:this.handleDismiss,title:"Prompt History",emptyStateText:this.filterByWorkspace?"No history for this workspace":"No prompt history",maxRenderItems:100,footer:V,renderItem:(G,F,q,W)=>{let U=F?Y.selectionBackground:void 0,H=F?Y.selectionForeground:Q.foreground,D=80,B=G.text.replace(/\n/g," ");if(B.length>80)B=B.slice(0,79)+"…";return new d0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new e({text:new P(B,new g({color:H}))})})}});return new s4({onKey:this.handleKeyEvent,child:z,debugLabel:"PromptHistoryPicker"})}}var f_3=900;class U41 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Td4}}class Td4 extends p0{pendingInterruptQueuedMessageIDs=new Set;isInterruptArrowEmphasized=!1;interruptBlinkTimer=null;getQueuedMessageID(J){return J.queuedMessage.dtwMessageID??J.id}parseQueuedMessageID(J){let Z=s6.safeParse(J);if(!Z.success)return;return Z.data}initState(){super.initState(),this.updateInterruptBlinkAnimationState()}didUpdateWidget(J){super.didUpdateWidget(J),this.updateInterruptBlinkAnimationState()}dispose(){this.stopInterruptBlinkAnimation(),super.dispose()}build(J){let{queuedMessages:Z,title:Q="Queue"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return this.updateInterruptBlinkAnimationState(),new R0({width:0,height:0});let Y=new Set(Z.map((K)=>this.getQueuedMessageID(K)));for(let K of Z)if(K.interrupt)this.pendingInterruptQueuedMessageIDs.delete(this.getQueuedMessageID(K));for(let K of this.pendingInterruptQueuedMessageIDs)if(!Y.has(K))this.pendingInterruptQueuedMessageIDs.delete(K);this.updateInterruptBlinkAnimationState();let X=Z.map((K)=>this.buildQueueItem(K));return new d0({child:new n0({padding:C0.symmetric(1,0),child:new x0({crossAxisAlignment:"stretch",children:[new e({text:new P(Q,new g({bold:!0}))}),...X]})})})}buildQueueItem(J){let Q=f0.maybeOf(this.context)?.colors??x1.of(this.context).colorScheme,Y=this.getQueuedMessageID(J),X=J.interrupt===!0||this.pendingInterruptQueuedMessageIDs.has(Y),V=J.queuedMessage.content.filter((B)=>B.type==="text").map((B)=>B.text).join(" ").trim(),G=J.queuedMessage.content.filter((B)=>B.type==="image").length,F=V.split(`
|
|
7593
7593
|
`)[0],q=V.includes(`
|
|
7594
7594
|
`)?`${F}...`:V,W=new g({color:Q.mutedForeground,dim:X}),U=[new P(q,W)];if(G>0){let B=new g({color:Q.success});for(let N=1;N<=G;N++)U.push(new P(" ")),U.push(new P(`[${N}]`,B))}let H=this.widget.props.onRemoveQueuedMessage?new Uy({text:"x",onPressed:()=>{let B=this.parseQueuedMessageID(Y);if(!B)return;this.widget.props.onRemoveQueuedMessage?.(B)},padding:C0.symmetric(0,0),color:Q.mutedForeground}):null,D=this.widget.props.onInterruptQueuedMessage?X?new e({text:new P("↑",new g({color:Q.foreground,dim:!this.isInterruptArrowEmphasized}))}):new Uy({text:"↑",onPressed:()=>this.interruptQueuedMessage(Y),padding:C0.symmetric(0,0),color:Q.mutedForeground}):null;return new n0({padding:C0.only({bottom:0}),child:new W1({crossAxisAlignment:"start",children:[...D?[new n0({padding:C0.only({right:1}),child:D})]:[],new n0({padding:C0.only({right:1}),child:new e({text:new P("•",new g({color:Q.mutedForeground}))})}),new y1({child:new e({text:new P("",void 0,U)})}),...H?[new n0({padding:C0.only({left:1}),child:H})]:[]]})})}interruptQueuedMessage(J){if(this.pendingInterruptQueuedMessageIDs.has(J))return;let Z=this.parseQueuedMessageID(J);if(!Z)return;let Q=this.widget.props.onInterruptQueuedMessage;if(!Q)return;this.setState(()=>{this.pendingInterruptQueuedMessageIDs.add(J)}),this.updateInterruptBlinkAnimationState();try{Promise.resolve(Q(Z)).catch(()=>{this.setState(()=>{this.pendingInterruptQueuedMessageIDs.delete(J)}),this.updateInterruptBlinkAnimationState()})}catch{this.setState(()=>{this.pendingInterruptQueuedMessageIDs.delete(J)}),this.updateInterruptBlinkAnimationState()}}hasInterruptingQueuedMessages(){if(!this.widget.props.onInterruptQueuedMessage)return!1;let J=this.widget.props.queuedMessages;if(!Array.isArray(J)||J.length===0)return!1;return J.some((Z)=>Z.interrupt===!0||this.pendingInterruptQueuedMessageIDs.has(this.getQueuedMessageID(Z)))}updateInterruptBlinkAnimationState(){if(this.hasInterruptingQueuedMessages()){this.startInterruptBlinkAnimation();return}this.stopInterruptBlinkAnimation()}startInterruptBlinkAnimation(){if(this.interruptBlinkTimer)return;this.interruptBlinkTimer=setInterval(()=>{this.setState(()=>{this.isInterruptArrowEmphasized=!this.isInterruptArrowEmphasized})},f_3)}stopInterruptBlinkAnimation(){if(this.interruptBlinkTimer)clearInterval(this.interruptBlinkTimer),this.interruptBlinkTimer=null;this.isInterruptArrowEmphasized=!1}}class Sd4 extends x${color;constructor({color:J,key:Z}){super({key:Z});this.color=J}createRenderObject(){return new kd4(this.color)}updateRenderObject(J){J.color=this.color}}class kd4 extends u4{color;constructor(J){super();this.color=J}performLayout(){let J=this._lastConstraints;if(J)this.setSize(J.maxWidth,1)}paint(J,Z,Q){let Y=Math.floor(this.size.width);for(let X=0;X<Y;X++)J.setChar(Z+X,Q,"─",{fg:this.color},1)}}var u_3=24,_d4=[{left:{keys:"Ctrl+O",description:"command palette"},right:{keys:"Ctrl+R",description:"prompt history"}},{left:{keys:"$ or $$",description:"shell commands"},right:{keys:"Ctrl+V",description:"paste images"}},{left:{keys:"Shift+Enter",description:"newline"},right:{keys:"Ctrl+S",description:"switch modes"}},{left:{keys:"Alt+D",description:"toggle deep reasoning"},right:{keys:"Alt+T",description:"toggle thinking/dense view"}},{left:{keys:"Ctrl+G",description:"edit in $EDITOR"},right:{keys:"Tab/Shift+Tab",description:"navigate messages"}},{left:{keys:"@ / @@",description:"mention files/threads"},right:{keys:"?",description:"toggle this help"}}];class H41 extends J4{submitOnEnter;constructor(J={}){super(J.key?{key:J.key}:{});this.submitOnEnter=J.submitOnEnter??!0}build(J){let Q=x1.of(J).colorScheme,X=f0.of(J).app,K=new g({color:X.keybind}),V=new g({color:Q.foreground,dim:!0}),z=wH()&&!yo0,F=(this.submitOnEnter?_d4:_d4.map((W)=>W.left.keys==="Shift+Enter"?{left:{keys:"Ctrl/Cmd+Enter",description:"submit"},right:W.right}:W)).map((W)=>{let U=W.left.keys==="Shift+Enter"&&z?"Alt+Enter":W.left.keys,H=W.left.description,D=U.length+1+H.length,B=" ".repeat(Math.max(0,u_3-D)),N=W.right.keys,w=W.right.description;return new e({text:new P("",void 0,[new P(U,K),new P(" ",V),new P(H,V),new P(B+" ",V),new P(N,K),new P(" ",V),new P(w,V)])})});if(z)F.push(new R0({height:1})),F.push(new Q4({onClick:()=>b3(J,"https://ampcode.com/manual/appendix#amp-cli-tmux"),cursor:"pointer",child:new e({text:new P("",void 0,[new P("Enable ",V),new P("extended-keys",new g({color:X.command})),new P(" in tmux to use ",V),new P("Shift+Enter",K),new P(". See ",V),d5.createSpan("https://ampcode.com/manual/appendix#amp-cli-tmux","https://ampcode.com/manual/appendix#amp-cli-tmux",new g({color:X.link,underline:!0}))])})}));let q=new W1({children:[new y1({child:new Sd4({color:Q.border})})]});return new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[...F,q]})}}import{homedir as D41,platform as ra}from"node:os";import{dirname as b_3,join as sa,normalize as h_3,relative as B41,sep as g_3}from"node:path";import{fileURLToPath as jG0}from"node:url";function MG0(J){let Z=h_3(J);return ra()==="win32"?Z.toLowerCase():Z}function AG0(J,Z){return MG0(J)===MG0(Z)}function mH(J,...Z){return MG0(J).endsWith(MG0(sa(...Z)))}function N41(J,Z){let Q=D41();if(Z){let Y=B41(Z,J);if(Y&&!Y.startsWith(".."))return`./${Y}`}if(J.startsWith(Q))return J.replace(Q,"~");return J}function m_3(J){let Z=J.replace(/^\.[/\\]/,"");return Z.endsWith("/")||Z.endsWith("\\")?Z:`${Z}${g_3}`}function p_3(J,Z){let Q=D41();if(mH(J,".config","agents","skills"))return ra()==="win32"?"%USERPROFILE%\\.config\\agents\\skills\\":"~/.config/agents/skills/";if(mH(J,".config","amp","skills"))return ra()==="win32"?"%USERPROFILE%\\.config\\agents\\skills\\":"~/.config/agents/skills/";if(mH(J,".agents","skills"))return AG0(J,sa(Q,".agents","skills"))?ra()==="win32"?"%USERPROFILE%\\.agents\\skills\\":"~/.agents/skills/":".agents/skills/";if(mH(J,".claude","skills"))return AG0(J,sa(Q,".claude","skills"))?ra()==="win32"?"%USERPROFILE%\\.claude\\skills\\":"~/.claude/skills/":".claude/skills/";return m_3(N41(J,Z))}function vd4(J,Z){if(J.startsWith("builtin://"))return J.replace("builtin://","(builtin) ");if(!J.startsWith("file://"))return J;try{return N41(jG0(J),Z)}catch{return J}}function d_3(J,Z){if(J.startsWith("builtin://"))return{scope:"builtin"};if(!J.startsWith("file://"))return{scope:"global"};try{let Q=b_3(jG0(J)),Y=D41(),X=p_3(Q,Z);if(mH(Q,".config","agents","skills")||mH(Q,".config","amp","skills")||mH(Q,".claude","plugins","cache"))return{scope:"global",pathHint:X};if(mH(Q,".agents","skills"))return{scope:AG0(Q,sa(Y,".agents","skills"))?"global":"local",pathHint:X};if(mH(Q,".claude","skills"))return{scope:AG0(Q,sa(Y,".claude","skills"))?"global":"local",pathHint:X};if(Z){let K=B41(Z,Q);if(K&&!K.startsWith(".."))return{scope:"local",pathHint:X}}}catch{return{scope:"global"}}return{scope:"global"}}function c_3(J,Z){let Q=new Map;for(let Y of J){let X=d_3(Y.baseDir,Z),K=X.scope==="local"?"Local":X.scope==="global"?"Global":"Built-in",V=`${X.scope}:${X.pathHint??""}`,z=Q.get(V);if(z){z.skills.push(Y);continue}Q.set(V,{scope:X.scope,label:K,pathHint:X.pathHint,skills:[Y]})}return[...Q.values()].sort((Y,X)=>{let K={local:0,global:1,builtin:2},V=K[Y.scope]-K[X.scope];if(V!==0)return V;return(Y.pathHint??"").localeCompare(X.pathHint??"")})}function l_3(J){return J.replace(/\s+/g," ").trim()}function i_3(J){if(J.startsWith("builtin://"))return"(built-in skill)";if(!J.startsWith("file://"))return J;try{return N41(jG0(J))}catch{return J}}class w41 extends l0{skills;errors;warnings;onDismiss;onAddSkill;onDocs;onInsertPrompt;onInvokeSkill;cwd;constructor({key:J,skills:Z,errors:Q,warnings:Y,onDismiss:X,onAddSkill:K,onDocs:V,onInsertPrompt:z,onInvokeSkill:G,cwd:F}){super(J?{key:J}:{});this.skills=Z,this.errors=Q,this.warnings=Y,this.onDismiss=X,this.onAddSkill=K,this.onDocs=V,this.onInsertPrompt=z,this.onInvokeSkill=G,this.cwd=F}createState(){return new yd4}}class yd4 extends p0{listScrollController=new j5;detailScrollController=new j5;scrollAreaKey=new s2("skill-list-modal-scroll-area");focusNode=new G6;selectedSkill=null;_viewportHeight=20;initState(){super.initState(),this.listScrollController.followMode=!1,this.detailScrollController.followMode=!1}dispose(){this.focusNode.dispose(),this.listScrollController.dispose(),this.detailScrollController.dispose(),super.dispose()}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}handleKeyEvent=(J)=>{switch(J.key){case"Escape":if(this.selectedSkill)return this.setState(()=>{this.selectedSkill=null}),"handled";return this.widget.onDismiss(),"handled";case"i":if(this.selectedSkill&&this.widget.onInvokeSkill)return this.widget.onInvokeSkill(this.selectedSkill.name),this.widget.onDismiss(),"handled";return"ignored";case"a":if(!this.selectedSkill&&this.widget.onAddSkill)return this.widget.onAddSkill(),"handled";return"ignored";case"o":if(!this.selectedSkill&&this.widget.onDocs)return this.widget.onDocs(),"handled";return"ignored";default:return"ignored"}};selectSkill=(J)=>{this.setState(()=>{this.selectedSkill=J,this.detailScrollController.jumpTo(0)})};build(J){let Q=x1.of(J).colorScheme,X=f0.of(J).app,K=K4.of(J),V=new g({color:Q.primary,bold:!0}),z=new g({color:Q.secondary,bold:!0}),G=new g({color:X.command}),F=new g({color:X.command,bold:!0}),q=new g({color:Q.foreground}),W=new g({color:Q.foreground,dim:!0}),U=new g({color:Q.destructive,bold:!0}),H=new g({color:Q.destructive}),D=new g({color:Q.warning,bold:!0}),B=new g({color:X.keybind}),N=new g({color:Q.foreground}),w=new g({color:Q.foreground,dim:!0}),L=K.size.width,O=K.size.height,E=L-4,M=O-4,A=this.selectedSkill!==null,j=A?Math.max(100,Math.min(150,E)):Math.max(60,Math.min(90,E)),R=A?Math.floor(j*2/5):0,_=this.widget.skills.filter((t)=>t.baseDir.startsWith("builtin://")),T=this.widget.skills.filter((t)=>!t.baseDir.startsWith("builtin://")),u=this.widget.skills.length>0&&T.length===0&&this.widget.errors.length===0,m=[],y=T.length+_.length,k=T.length>0?`Skills (${y})`:"Skills",f=new g({color:Q.secondary}),d=new g({color:Q.secondary,dim:!0}),p=new e({text:new P("",f,[new P("(",d),new P("o",B),new P(")",d),new P("wner's manual",f)])}),h=this.widget.onDocs?new Q4({cursor:"pointer",onClick:()=>this.widget.onDocs(),child:p}):p,n=new e({text:new P("",f,[new P("(",d),new P("a",B),new P(")",d),new P("dd",f)])}),c=this.widget.onAddSkill?new Q4({cursor:"pointer",onClick:()=>this.widget.onAddSkill(),child:n}):n,a=new W1({children:[new R0({width:2}),new y1({child:new e({text:new P(k,V)})}),h,new e({text:new P(" ",N)}),c,new R0({width:2})]});if(this.widget.skills.length===0&&this.widget.errors.length===0||u){m.push(new n0({padding:C0.horizontal(2),child:new e({text:new P("Skills give the agent specialized knowledge, teach it how to use tools,",w)})})),m.push(new n0({padding:C0.horizontal(2),child:new e({text:new P("or define MCP servers to load on demand.",w)})})),m.push(new R0({height:1})),m.push(new n0({padding:C0.horizontal(2),child:new e({text:new P("Create your own:",z)})}));let t=["Create a skill for searching our production logs","Create a user skill for my preferred commit message style"];for(let $0 of t)m.push(new n0({padding:C0.horizontal(2),child:this.widget.onInsertPrompt?new Q4({cursor:"pointer",onClick:()=>{this.widget.onInsertPrompt($0)},child:new e({text:new P(` "${$0}"`,q)})}):new e({text:new P(` "${$0}"`,q)})}));m.push(new R0({height:1}))}let W0=(t,$0,F0)=>{if(t.length===0)return;m.push(new n0({padding:C0.horizontal(2),child:new e({text:new P(`${$0} `,z,F0?[new P(`${F0}
|
|
7595
7595
|
`,W)]:[])})}));for(let K0 of t){let Y0=this.selectedSkill?.name===K0.name?F:G,w0=this.widget.onInvokeSkill?new Q4({cursor:"pointer",onClick:()=>this.widget.onInvokeSkill(K0.name),child:new e({text:new P(K0.name,Y0),maxLines:1,overflow:"ellipsis"})}):new e({text:new P(K0.name,Y0),maxLines:1,overflow:"ellipsis"}),X0=K0.description?l_3(K0.description):"",N0=new Q4({cursor:"pointer",onClick:()=>this.selectSkill(K0),child:new e({text:new P(X0,q),maxLines:1,overflow:"ellipsis"})});m.push(new n0({padding:C0.horizontal(6),child:new W1({crossAxisAlignment:"start",children:[new y1({flex:1,child:w0}),new R0({width:2}),new y1({flex:2,child:N0})]})}))}m.push(new R0({height:1}))};if(T.length>0)for(let t of c_3(T,this.widget.cwd))W0(t.skills,t.label,t.pathHint);if(_.length>0)W0(_,"Built-in");if(this.widget.errors.length>0){if(this.widget.skills.length>0)m.push(new R0({height:1}));m.push(new n0({padding:C0.horizontal(2),child:new e({text:new P(`Skipped skills with errors (${this.widget.errors.length}):`,U)})})),m.push(new R0({height:1}));for(let t of this.widget.errors){let $0=t.path.split("/"),F0=$0[$0.length-2]||"unknown";if(m.push(new n0({padding:C0.horizontal(2),child:new e({text:new P(`⚠ ${F0}`,D)})})),m.push(new n0({padding:C0.only({left:4}),child:new e({text:new P(t.error,H)})})),t.hint)m.push(new n0({padding:C0.only({left:4}),child:new e({text:new P(t.hint.split(`
|
|
@@ -7605,7 +7605,7 @@ ${t.content||""}`:t.content||"",T0=[],r0=t.baseDir.startsWith("file://")?jG0(t.b
|
|
|
7605
7605
|
`),process.exit(1)}process.stdout.write(await GS3(G.result.displayText)+`
|
|
7606
7606
|
`),process.exit(0)})}hM();import{stdout as FS3}from"node:process";function qS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${MF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function rd4(J){FS3.write(`${qS3(J)}
|
|
7607
7607
|
`)}function sd4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{rd4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{rd4(Z),process.exit(0)})}var Sx3=iH.join(nZ,"logs","headless.log"),e61=iH.join(Qv,"device-id.json"),Ln4=`cli-tui-${Cn4(16).toString("hex")}`;async function kx3(){for(let J of KE)try{if((await J.listConfigs()).length>0)return J}catch(Z){C.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(oy(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){A2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7608
|
-
`)}function vx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function e7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function kn4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function yx3(J){try{return await _n4(J,"utf-8")}catch{return J}}async function $51(J,Z,Q){let Y=kn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!X51(X,S2.HARNESS_SYSTEM_PROMPT)&&!vn4(K))throw new P1("You are not allowed to do this.",1);aJ("systemPrompt",await yx3(Y))}function vn4(J){return!!(J&&Z10(J))}function X51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function J51(J){return(J.userEmail?dJ(J.userEmail):!1)||X51(J.features,S2.DTW_TUI)}function On4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function Z51(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return J51({userEmail:Z.user.email,features:Z.features})}function Q51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function xx3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function HF0(J){let Y=xx3(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 P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function En4(J){if(!e6.write(J))await Px3(e6,"drain")}var Mn4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??xK,description:`Custom settings file path (overrides the default location ${xK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Tn0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:fG.SMART.key,description:`Set the agent mode (${uG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uG().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],An4=(J)=>("deprecated"in J)&&J.deprecated===!0,fx3=(J)=>("hidden"in J)&&J.hidden===!0,ux3=(J)=>("default"in J),bx3=(J)=>("default"in J)?J.default:void 0,yn4=[{name:"toggle-skills-count",entryPoint:Po0}];function hx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(E3.unknownCommand(Q),1,V)}}async function K51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new gV(J.fileSystem),generateThreadTitle:m80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function xn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var DF0=V1.file(Sn4.homedir()),Y51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(DF0,".config");function gx3(J){return Uq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Wq4(Z);let Q=jX0(),Y=po0();if((!Q||Y||kT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(jX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function mx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Q7(J,Z,Q){let Y=Q?.deferAuth??!1;Kf1("0.0.
|
|
7608
|
+
`)}function vx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function e7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function kn4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function yx3(J){try{return await _n4(J,"utf-8")}catch{return J}}async function $51(J,Z,Q){let Y=kn4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!X51(X,S2.HARNESS_SYSTEM_PROMPT)&&!vn4(K))throw new P1("You are not allowed to do this.",1);aJ("systemPrompt",await yx3(Y))}function vn4(J){return!!(J&&Z10(J))}function X51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function J51(J){return(J.userEmail?dJ(J.userEmail):!1)||X51(J.features,S2.DTW_TUI)}function On4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function Z51(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return J51({userEmail:Z.user.email,features:Z.features})}function Q51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function xx3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function HF0(J){let Y=xx3(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 P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function En4(J){if(!e6.write(J))await Px3(e6,"drain")}var Mn4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??xK,description:`Custom settings file path (overrides the default location ${xK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Tn0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:fG.SMART.key,description:`Set the agent mode (${uG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uG().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],An4=(J)=>("deprecated"in J)&&J.deprecated===!0,fx3=(J)=>("hidden"in J)&&J.hidden===!0,ux3=(J)=>("default"in J),bx3=(J)=>("default"in J)?J.default:void 0,yn4=[{name:"toggle-skills-count",entryPoint:Po0}];function hx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(E3.unknownCommand(Q),1,V)}}async function K51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new gV(J.fileSystem),generateThreadTitle:m80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function xn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var DF0=V1.file(Sn4.homedir()),Y51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(DF0,".config");function gx3(J){return Uq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Wq4(Z);let Q=jX0(),Y=po0();if((!Q||Y||kT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(jX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function mx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Q7(J,Z,Q){let Y=Q?.deferAuth??!1;Kf1("0.0.1774932368-g0d0b3f");let X=E10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:DF0,userConfigDir:Y51});ST4(X);let K=await X.getLatest();C.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),C.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)C.info("No API key found, continuing startup with deferred auth");else{e6.write(`No API key found. Starting login flow...
|
|
7609
7609
|
`);let W0=await px3(J),r=await J.secrets.get("apiKey",J.ampURL);if(C.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await zH(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];C.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let z=j1(xX(X).pipe(T5((a)=>a!=="pending"))),G=Y?"pending":await z;if(!Y)C.info("Server status resolved",{status:"ready",isAuthenticated:o6(G),isError:hW(G),errorMessage:hW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=Vq4({configService:X}),W=new Map,U=()=>W.clear(),H=new bT0(X,J.settings.getWorkspaceRootPath()),D=Ft1({configService:X,filesystem:n8}),B=Xa1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let H0=`${a}:${W0}`,L0=W.get(H0);if(L0)return C.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;C.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let z0=(async()=>{let J0=new HE(J.secrets),G0=await J0.getClientInfo(a,W0),i=r?.scopes??G0?.scopes,o=XI4();C.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:e6.isTTY});let t;if(o)t=J.executeMode?YI4():QI4(a);let $0=new wR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??G0?.clientId,clientSecret:r?.clientSecret??G0?.clientSecret,authUrl:r?.authUrl??G0?.authUrl,tokenUrl:r?.tokenUrl??G0?.tokenUrl,scopes:i,headlessAuthHandler:t});return C.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??G0?.clientId),willUseDCR:!(r?.clientId??G0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(H0,z0),z0}}),N=hg0({configService:X,filesystem:n8,spawn:C$0}),w;if(J.executeMode){let a=await qz4({toolService:F,providers:[B,N],initialTimeout:15000});w=a.registrations;for(let[W0,r]of a.initErrors)C.warn(`${W0} provider initialization slow or failed:`,r)}else w=gg0({toolService:F,providers:[B,N]});if(Z.jetbrains)JE("JetBrains");else if(Z.ide&&dI4())JE("VS Code");else if(Z.ide&&cI4())JE("Neovim");else if(Z.ide){let a=await kx3();if(a){let W0=S10(a.ideName);if(W0)JE(W0)}}if(J.executeMode)Vf1(!0);let L,O=N$.status.pipe(D1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&af1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(Fz4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new UY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends UY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Nt1({isDevelopment:!1}),A=new gS0(M,X,{maxThreads:200});C.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=Z51(j,G),_=Boolean(R||Z.headless);if(_)C.info("DTW mode enabled: thread sync service disabled");let T=_?mx3():ft1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;N$.status.subscribe((a)=>{u=a});let m=new nA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){C.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return C.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new lo0,k=process.env.PLUGINS??"off",f=Z.headless?DT4():void 0,d=f??new wX0({configService:X}),p=d instanceof wX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=$_0({configService:X,fileSystem:n8,platform:d,internalPlugins:yn4,pluginFilter:k}),n=ea1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:n8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())C.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of w.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function px3(J){if(!J.executeMode){if(!await DX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return e6.write(`Login cancelled. Run the command again to retry.
|
|
7610
7610
|
`),!1}return await fn4(J)}async function fn4(J){let Z=Cn4(32).toString("hex"),Q=await qv(J.ampURL,Z),Y=new AbortController;try{await MV(Q,Y.signal)}catch(K){C.error("Error opening browser",{error:K})}let X=await qv(J.ampURL,Z,!1);e6.write(`If your browser does not open automatically, visit:
|
|
7611
7611
|
|
|
@@ -7613,7 +7613,7 @@ ${o0.blue.bold(X)}
|
|
|
7613
7613
|
|
|
7614
7614
|
`);try{return await aC4(J.ampURL,Z,J.secrets,Y),e6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return C.error("Login failed",{error:K}),A2.write(`
|
|
7615
7615
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7616
|
-
`),!1}}function jn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function dx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function cx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function lx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!cx3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function ix3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function nx3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function ax3(J){let Z=new uN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Uj(),process.exit(0);let N=B.originalError??B;XR4(N)}),sd4(Z,{version:"0.0.
|
|
7616
|
+
`),!1}}function jn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function dx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function cx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function lx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!cx3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function ix3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function nx3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function ax3(J){let Z=new uN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Uj(),process.exit(0);let N=B.originalError??B;XR4(N)}),sd4(Z,{version:"0.0.1774932368-g0d0b3f",buildTimestamp:"2026-03-31T04:49:57.536Z",buildType:"'release'"}),Z.addHelpText("after",gI4()),Z.configureHelp({formatHelp:mI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await m3(w);await Zf3(L)}),Z.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await m3(w);await Jf3(L,await ja0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await m3(L);await vR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await m3(w);await yR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7617
7617
|
Actions:
|
|
7618
7618
|
create Create a new DTW thread and print its ID
|
|
7619
7619
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7677,8 +7677,8 @@ ${M}
|
|
|
7677
7677
|
|
|
7678
7678
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function ox3(J){C.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new sn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:uY,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new gV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw C.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function rx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Bv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Bv()).trimEnd(),stdinInput:null}}function sx3(J,Z,Q){if(J.remote&&!Z)throw new P1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new P1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new P1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new P1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new P1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new P1("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 P1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new P1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7679
7679
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function BF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(z0,J0)=>{let G0=Number(process.hrtime.bigint()-J0)/1e6,i=VO4();C.info("Startup phase",{phase:z0,phaseMs:Math.round(G0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:z}=await rx3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;sx3({...Z,streamJson:G},J.executeMode,V),e7(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;C.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await Q7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await K51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!W&&hW(D)){let z0=ak(Error(D.error.message));if(z0.message===E3.networkOffline||z0.message===E3.networkTimeout)throw HF0(J.ampURL);throw new P1(E3.invalidAPIKey,1)}let B=o6(D)?D:null,N=B?.user.email,w=vn4(N),L=J51({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&Z51(O,B);if(!W)await $51(Q,Z,D);let M=Q51(D),A=M?.features??[],j=M?.team??null,R=BX0(Z,M);if(R instanceof Error)k3(R.message);if((J.executeMode||G)&&N8(Z.mode)&&!w)throw new P1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!QE(Z.mode,N))throw new P1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await wT4(V,z,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!dJ(N))throw new P1("Headless DTW mode is only available for Amp employees",1);let z0=await U.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new P1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new P1(`Invalid thread ID: ${J0}`,1);let G0=J0?void 0:await qf3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??G0?.threadId;if(!i)throw new P1("Failed to resolve headless thread ID",1);let o=await GI4(i);if(o.status==="already-running")await U.asyncDispose(),await zH(),process.exit(0);try{await ZI4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:G0?.ownerUserId,threadVersion:G0?.threadVersion,agentMode:G0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await zH(),process.exit(0)}let _=J.executeMode?void 0:async(z0)=>Oo(z0,"interactive"),T={threadService:U.threadService,workerDeps:H,createThread:async()=>{let z0=W?await U.serverStatusPromise:D,J0=await tQ0(J.settings,process.cwd(),Q51(z0),R);if(J0 instanceof Error)k3(J0.message);return Xe0(H,{threadMeta:J0?yz(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(z0,J0)=>{if(J0?.nonBlockingOwnershipCheck){Rn4(z0,U.configService).catch((G0)=>{if(G0 instanceof P1){if(J0.onOwnershipError){J0.onOwnershipError(G0,z0);return}GH(G0,z0);return}C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})});return}try{await Rn4(z0,U.configService)}catch(G0){if(G0 instanceof P1)throw G0;C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:GH},u=async(z0)=>{try{if(z0==="dtw")return ox3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:Ln4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return If4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof P1)throw J0;throw await GH(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")A2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7680
|
-
`),await zH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await c6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return C.info("User free tier status:",G0),G0.result;return}catch(z0){C.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new $e0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await $51(Q,Z,z0);let J0=process.hrtime.bigint(),G0=Z51(O,z0),i=o6(z0)?J51({userEmail:z0.user.email,features:z0.features}):!1;On4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new P1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await GH(z0,Z.threadId)});else F=process.hrtime.bigint(),On4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),gx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){KT4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await BR4({threadPool:f,...z0});if(await Oo(J0,"execute"),Z.archive)await c6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await $u1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)N$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=ca0("0.0.
|
|
7681
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Fa1({get:async(z)=>{if(z!==sh)return;try{let G=await _n4(e61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==sh)return;await Tn4(iH.dirname(e61),{recursive:!0}),await Cx3(e61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:yG()});zf1(Y);let X=await MI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await YT4(J.mcpConfig);X=XT4(X,z)}let K=iH.dirname(X.getSettingsFilePath());qq4(Qv,K);let V=await X.get("url","global");if(!V)V=F7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!EV(V))C.info("Targeting custom Amp server",{ampURL:V});return X=tx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:AT4(await ja0(J,X))}}function tx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function ex3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=iH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Sx3:Tn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function $f3(){KO4();let J=tx3(process.argv),Z=ex3(process.argv,J),Q=Bj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(vx3(C),C.info("Starting Amp CLI.",{version:"0.0.
|
|
7680
|
+
`),await zH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await U.configService.getLatest(),J0=ou(z0),G0=await c6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(G0.ok)return C.info("User free tier status:",G0),G0.result;return}catch(z0){C.error("Failed to fetch free tier status:",z0);return}})(),k=!J.executeMode?new $e0:null,f,d=null;if(k)f=k,d=(async()=>{let z0=W?await U.serverStatusPromise:U.serverStatus;await $51(Q,Z,z0);let J0=process.hrtime.bigint(),G0=Z51(O,z0),i=o6(z0)?J51({userEmail:z0.user.email,features:z0.features}):!1;On4({dtwEnabled:G0,hasV2TUIAccess:i});let o=await u(G0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new P1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(z0)=>{let J0=z0 instanceof Error?z0:Error(String(z0));k.setInitError(J0),await GH(z0,Z.threadId)});else F=process.hrtime.bigint(),On4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),gx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(D1(([J0,G0])=>({[J0.id]:G0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){KT4(U.mcpService,J.settings);let z0={userInput:V,stdinInput:z,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await BR4({threadPool:f,...z0});if(await Oo(J0,"execute"),Z.archive)await c6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await $u1();let z0=await VE({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let J0=z0[0];if(J0)N$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=ca0("0.0.1774932368-g0d0b3f",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Io0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let z0=await j1(f.threadHandles$);if(!z0)throw new P1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await OX0();K("runMainThread:loadSessionState",F),C.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Rj((z0)=>({...z0,launchCount:z0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Du4({codebaseContextService:U.codebaseContextService,history:new Ka0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:c6,threadPool:f,createSystemPromptDeps:async()=>xn4(U),ideClient:N$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Ln4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-31T04:49:57.536Z"},(z0)=>new we0({...z0,threadPool:z0.threadPool},(J0)=>new R41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function m3(J){if(C.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)A2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7681
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Fa1({get:async(z)=>{if(z!==sh)return;try{let G=await _n4(e61,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==sh)return;await Tn4(iH.dirname(e61),{recursive:!0}),await Cx3(e61,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:yG()});zf1(Y);let X=await MI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await YT4(J.mcpConfig);X=XT4(X,z)}let K=iH.dirname(X.getSettingsFilePath());qq4(Qv,K);let V=await X.get("url","global");if(!V)V=F7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!EV(V))C.info("Targeting custom Amp server",{ampURL:V});return X=tx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:AT4(await ja0(J,X))}}function tx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function ex3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=iH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Sx3:Tn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function $f3(){KO4();let J=tx3(process.argv),Z=ex3(process.argv,J),Q=Bj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(vx3(C),C.info("Starting Amp CLI.",{version:"0.0.1774932368-g0d0b3f",buildTimestamp:"2026-03-31T04:49:57.536Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await ax3(Q).parseAsync(process.argv)}Gq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await $f3().catch(GH)});async function Jf3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),e6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7682
7682
|
`);else if(!EV(J.ampURL))e6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7683
7683
|
`);let Y=process.env.AMP_API_KEY;if(Y)e6.write(`API key found in environment variable, storing...
|
|
7684
7684
|
`),await Z.set("apiKey",Y,J.ampURL),e6.write(`API key successfully stored.
|