@sourcegraph/amp 0.0.1764806510-g3d6586 → 0.0.1764808732-gb9c377
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 +11 -11
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -72,7 +72,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
72
72
|
`)))Y.deleted+=G-X,Y.added+=K-V,Y.changed+=Math.min(G-X,K-V);return Y}catch{return Z}}function MM0(J){if(typeof J!=="string")return{added:0,deleted:0,changed:0};return{added:J.split(`
|
|
73
73
|
`).length,deleted:0,changed:0}}function nH1(J){if(!J)return{totalFiles:0,createdFiles:0,totalAdded:0,totalRemoved:0,totalModified:0,revertedFiles:0,allReverted:!1};let Q=J.files.length,Z=J.files.filter((q)=>q.created).length,Y=J.files.filter((q)=>q.reverted).length,X=Y===Q&&Q>0,G=0,V=0,K=0;for(let q of J.files){if(q.reverted)continue;G+=q.diffStat.added,V+=q.diffStat.removed,K+=q.diffStat.modified}return{totalFiles:Q,createdFiles:Z,totalAdded:G,totalRemoved:V,totalModified:K,revertedFiles:Y,allReverted:X}}var DM0;var qy=N1(()=>{DM0=W6(NM0(),1)});function AG(){return`T-${crypto.randomUUID()}`}function OG(J){if(!J.startsWith("T-"))return!1;let Q=J.slice(2);return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Q)}function oD(){return`toolu_${crypto.randomUUID()}`}function fE(J,Q,Z=oD()){return{type:"tool_use",complete:!0,id:Z,name:J,input:Q}}function T3(J){if("complete"in J)return J.complete;return!("inputPartialJSON"in J)}function aH1(J){return J.role==="user"&&J.source?.type==="course-correction"}function LM0(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="info"){let Y=Z.content[0];if(Y?.type==="summary"&&Y?.summary.type==="message")return}if(Z?.role==="assistant"&&Z.usage){if(Z.usage.totalInputTokens===0)continue;return Z.usage}}return J["~debug"]?.lastInferenceUsage}function qY(J,Q){for(let Z of J.messages){if(Z.role!=="assistant")continue;for(let Y of Z.content)if(Y.type==="tool_use"&&Y.id===Q)return Y}return}function hE(J,Q){for(let[Z,Y]of J.messages.entries()){if(Y.role!=="assistant")continue;for(let[X,G]of Y.content.entries())if(G.type==="tool_use"&&G.id===Q)return{message:Y,messageIndex:Z,block:G,blockIndex:X}}return null}function xW(J,Q){for(let Z of J.messages){if(Z.role!=="user")continue;for(let Y of Z.content)if(Y.type==="tool_result"&&Y.toolUseID===Q)return Y}return}function kJ(J){return J.messages.filter((Q)=>Q.role==="user").flatMap((Q)=>Q.content).filter((Q)=>Q.type==="tool_result").reduce((Q,Z)=>{return Q.set(Z.toolUseID,Z),Q},new Map)}function oH1(J){if(J&&typeof J==="object"&&"threadID"in J){let Q=J.threadID;if(typeof Q==="string"&&OG(Q))return Q}return}function rH1(J){let Q=[],Z=new Map;for(let Y of J)if(Y.role==="assistant"){for(let X of Y.content)if(X.type==="tool_use"&&X.name===b2)Z.set(X.id,X)}else if(Y.role==="user"){for(let X of Y.content)if(X.type==="tool_result"){let G=Z.get(X.toolUseID);if(G){let V=X.run,K=(V.status==="in-progress"||V.status==="cancelled"||V.status==="done"||V.status==="error")&&V.progress?oH1(V.progress):void 0;if(K)Q.push({toolUseID:X.toolUseID,threadID:K,toolUse:G,toolResult:X})}}}return Q}function AM0(J,Q="Untitled"){if(J.title)return qn(J.title,300);return Q}function OM0(J){if(!J)return!1;if(J.role==="assistant")return J.state?.type==="cancelled";if(J.role==="user")return J.content.some((Q)=>Q.type==="tool_result"&&Q.run.status==="cancelled");return!1}function wM0(J){if(!J)return!1;if(J.role==="user")return J.content.some((Q)=>Q.type==="tool_result"&&Q.run.status==="rejected-by-user");return!1}function sH1(J){if(!J)return!1;return J.role==="info"}function bE(J){return J.role==="info"&&J.content.some((Q)=>Q.type==="manual_bash_invocation")}function Rn(J){if(J.role!=="info")return;return J.content.find((Q)=>Q.type==="manual_bash_invocation")}function tV4(J){return J.replace(/u([0-9A-Fa-f]{4})(\s)/gi,(Q,Z,Y)=>{try{return String.fromCodePoint(parseInt(Z,16))+Y}catch{return`u${Z}${Y}`}})}function gE(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="info"){if(Z.content.some((X)=>X.type==="summary"&&X.summary.type==="message"))break}if(Z?.role!=="assistant"||!Z.state||Z.state.type!=="complete"||Z.state.stopReason!=="tool_use")continue;for(let Y of Z.content)if(Y.type==="tool_use"&&Y.name===i5&&Y.input){let X=Y.input.todos;if(Array.isArray(X))return X;let G=Y.input.content;if(typeof G==="string")return tV4(G)}}return}function Y3(J){return J.map((Q)=>Q.type==="text"?Q.text:null).filter((Q)=>Q!==null).join(`
|
|
74
74
|
|
|
75
|
-
`)}function EM0(J){return J.content.every((Q)=>!(Q.type==="tool_result"&&!Z3(Q.run)))}function Wy(J){return J.role==="assistant"&&J.state.type==="complete"&&J.state.stopReason==="end_turn"}function g2(J,Q){return J.messages.findLast((Z)=>Z.role===Q)}function kX(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z&&"role"in Z&&Z.role==="info"){for(let Y of Z.content)if(Y.type==="summary"&&Y.summary.type==="message")return{summaryBlock:Y,index:Q}}}return}function m2(J){return J.messages.filter((Q)=>Q.role==="user"&&Q.content.some((Z)=>Z.type!=="tool_result")).length}function mE(J){let Q=0,Z=0,Y=0;return J.messages.forEach((X)=>{if(X.role!=="assistant")return;X.content.forEach((G)=>{if(G.type!=="tool_use"||!T3(G))return;let V=G.input,K=null;if(G.name==="edit_file"){if("old_str"in V&&"new_str"in V){let{old_str:q,new_str:W}=V;K=vE(q,W)}}else if((G.name==="write_file"||G.name==="create_file")&&"content"in V&&typeof V.content==="string")K=MM0(V.content);if(K)Q+=K.added,Y+=K.deleted,Z+=K.changed})}),{added:Q,changed:Z,deleted:Y}}function rD(){return DU0((J,Q,Z)=>{if(Z===0){if(Q instanceof Array)throw Error("expected first event to be a full thread");return Q}if(!(Q instanceof Array))throw Error("expected all but first event to be a patch");return DD0(J,Q)})}function Hy(J,Q){let Z=J.relationships?.filter((Y)=>Y.role==="child")??[];return Q?Z.filter((Y)=>Y.type===Q):Z}function yX(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user")return Z}return}function zy(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&Z.agentMode)return Z.agentMode}return}var y8=N1(()=>{gD();o0();MQ();CH1();M4();M4();A7();qy();Vn()});function vJ(J){if(!J)return{};return{[tH1]:J.id,[eV4]:J.agentMode??""}}var yJ="x-amp-feature",tH1="x-amp-thread-id",FZ="x-amp-message-id",eV4="x-amp-mode",IM0="X-Amp-Client-Application",PM0="X-Amp-Client-Type",TM0="X-Amp-Client-Version",RM0="X-Amp-Client-Bundle",xJ="x-amp-client-request-id";var wG=()=>{};function SM0(J){CM0=J}function uE(J){Fy=J}function _M0(J){jM0=J}function Uy(){{let J=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(J)return{type:"cli",name:"AmpSDK",version:J};let Q;if(!Fy)Q="CLI";else if(["Neovim","JetBrains"].includes(Fy))Q=Fy;else Q=`${Fy} CLI`;return{type:"cli",name:jM0?`${Q} Execute Mode`:Q,version:CM0}}return{type:"unknown",name:"unknown",version:null}}function X3(){let J=Uy(),Q={};if(Q[IM0]=J.name,Q[PM0]=J.type,Q[RM0]="cli",J.version)Q[TM0]=J.version;return Q}var JK4,fl8,CM0=null,Fy=null,jM0=!1;var UZ=N1(()=>{wG();JK4={"VS Code":{type:"vscode-derived",scheme:"vscode",marketplace:"vscode"},"VS Code Insiders":{type:"vscode-derived",scheme:"vscode-insiders",marketplace:"vscode"},"VS Code Web":{type:"vscode-derived",scheme:null,marketplace:"vscode",hideFromOnboarding:!0},Cursor:{type:"vscode-derived",scheme:"cursor",marketplace:"openvsx"},Windsurf:{type:"vscode-derived",scheme:"windsurf",marketplace:"openvsx"},VSCodium:{type:"vscode-derived",scheme:"vscodium",hideFromOnboarding:!0,marketplace:"openvsx"},CLI:{type:"cli",install:{instructions:"npm install -g @sourcegraph/amp@latest"},configure:{url:"https://www.npmjs.com/package/@sourcegraph/amp"}},JetBrains:{type:"cli",install:{instructions:"npm install -g @sourcegraph/amp@latest",label:"
|
|
75
|
+
`)}function EM0(J){return J.content.every((Q)=>!(Q.type==="tool_result"&&!Z3(Q.run)))}function Wy(J){return J.role==="assistant"&&J.state.type==="complete"&&J.state.stopReason==="end_turn"}function g2(J,Q){return J.messages.findLast((Z)=>Z.role===Q)}function kX(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z&&"role"in Z&&Z.role==="info"){for(let Y of Z.content)if(Y.type==="summary"&&Y.summary.type==="message")return{summaryBlock:Y,index:Q}}}return}function m2(J){return J.messages.filter((Q)=>Q.role==="user"&&Q.content.some((Z)=>Z.type!=="tool_result")).length}function mE(J){let Q=0,Z=0,Y=0;return J.messages.forEach((X)=>{if(X.role!=="assistant")return;X.content.forEach((G)=>{if(G.type!=="tool_use"||!T3(G))return;let V=G.input,K=null;if(G.name==="edit_file"){if("old_str"in V&&"new_str"in V){let{old_str:q,new_str:W}=V;K=vE(q,W)}}else if((G.name==="write_file"||G.name==="create_file")&&"content"in V&&typeof V.content==="string")K=MM0(V.content);if(K)Q+=K.added,Y+=K.deleted,Z+=K.changed})}),{added:Q,changed:Z,deleted:Y}}function rD(){return DU0((J,Q,Z)=>{if(Z===0){if(Q instanceof Array)throw Error("expected first event to be a full thread");return Q}if(!(Q instanceof Array))throw Error("expected all but first event to be a patch");return DD0(J,Q)})}function Hy(J,Q){let Z=J.relationships?.filter((Y)=>Y.role==="child")??[];return Q?Z.filter((Y)=>Y.type===Q):Z}function yX(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user")return Z}return}function zy(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&Z.agentMode)return Z.agentMode}return}var y8=N1(()=>{gD();o0();MQ();CH1();M4();M4();A7();qy();Vn()});function vJ(J){if(!J)return{};return{[tH1]:J.id,[eV4]:J.agentMode??""}}var yJ="x-amp-feature",tH1="x-amp-thread-id",FZ="x-amp-message-id",eV4="x-amp-mode",IM0="X-Amp-Client-Application",PM0="X-Amp-Client-Type",TM0="X-Amp-Client-Version",RM0="X-Amp-Client-Bundle",xJ="x-amp-client-request-id";var wG=()=>{};function SM0(J){CM0=J}function uE(J){Fy=J}function _M0(J){jM0=J}function Uy(){{let J=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(J)return{type:"cli",name:"AmpSDK",version:J};let Q;if(!Fy)Q="CLI";else if(["Neovim","JetBrains"].includes(Fy))Q=Fy;else Q=`${Fy} CLI`;return{type:"cli",name:jM0?`${Q} Execute Mode`:Q,version:CM0}}return{type:"unknown",name:"unknown",version:null}}function X3(){let J=Uy(),Q={};if(Q[IM0]=J.name,Q[PM0]=J.type,Q[RM0]="cli",J.version)Q[TM0]=J.version;return Q}var JK4,fl8,CM0=null,Fy=null,jM0=!1;var UZ=N1(()=>{wG();JK4={"VS Code":{type:"vscode-derived",scheme:"vscode",marketplace:"vscode"},"VS Code Insiders":{type:"vscode-derived",scheme:"vscode-insiders",marketplace:"vscode"},"VS Code Web":{type:"vscode-derived",scheme:null,marketplace:"vscode",hideFromOnboarding:!0},Cursor:{type:"vscode-derived",scheme:"cursor",marketplace:"openvsx"},Windsurf:{type:"vscode-derived",scheme:"windsurf",marketplace:"openvsx"},VSCodium:{type:"vscode-derived",scheme:"vscodium",hideFromOnboarding:!0,marketplace:"openvsx"},CLI:{type:"cli",install:{instructions:"npm install -g @sourcegraph/amp@latest"},configure:{url:"https://www.npmjs.com/package/@sourcegraph/amp"}},JetBrains:{type:"cli",install:{instructions:"npm install -g @sourcegraph/amp@latest",label:"Run the installer"},configure:{url:"https://ampcode.com/manual#jetbrains",urlLabel:"View setup guide",instructions:"amp --jetbrains",npxInstructions:"npx -y @sourcegraph/amp@latest --jetbrains",label:"Install the JetBrains plugin (supports IntelliJ, WebStorm, GoLand, etc.)",startInstructions:"amp",startLabel:"Start a thread in the current directory"}},Neovim:{type:"cli",install:{instructions:"npm install -g @sourcegraph/amp@latest",label:"Run the installer"},configure:{url:"https://ampcode.com/manual#ide",urlLabel:"View setup guide",pluginInstructions:"Install the Neovim plugin:",pluginUrl:"https://github.com/sourcegraph/amp.nvim",instructions:"amp",npxInstructions:"npx -y @sourcegraph/amp@latest",label:"Start a thread in the current directory"}},AmpSDK:{type:"cli",install:{instructions:"npm install @sourcegraph/amp-sdk"},configure:{url:"https://ampcode.com/manual/sdk",urlLabel:"View SDK documentation"},hideFromOnboarding:!0}},fl8=Object.entries(JK4).map(([J,Q])=>({name:J,...Q}))});function QK4(J){if(typeof process>"u"||!process.versions?.node)return"unknown";try{switch(J){case"darwin":{try{let{execSync:Z}=k1("node:child_process"),X=Z("/usr/bin/sw_vers -productVersion",{encoding:"utf8",timeout:3000,stdio:["ignore","pipe","ignore"]}).trim();if(X&&/^\d+\.\d+/.test(X))return X}catch{}return k1("node:os").release()}case"linux":try{let Y=k1("node:fs").readFileSync("/etc/os-release","utf8").split(`
|
|
76
76
|
`);for(let G of Y)if(G.startsWith("PRETTY_NAME=")){let V=G.match(/PRETTY_NAME="?([^"]*)"?/);if(V?.[1])return V[1]}return k1("node:os").release()}catch{return k1("node:os").release()}case"windows":try{let{execSync:Q}=k1("node:child_process"),Y=Q('systeminfo | findstr /B /C:"OS Name" /C:"OS Version"',{encoding:"utf8",timeout:5000}).split(`
|
|
77
77
|
`),X=Y.find((K)=>K.includes("OS Name")),G=Y.find((K)=>K.includes("OS Version"));if(X&&G){let K=X.split(":")[1]?.trim(),q=G.split(":")[1]?.trim();return`${K} ${q}`}return k1("node:os").release()}catch{return k1("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function RF(){if(!eH1){let J=typeof process<"u"&&process.versions?.node,Q=!J,Z="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Z="darwin";else if(process.platform==="win32")Z="windows";Y=QK4(Z),X=process.arch}else if(typeof navigator<"u"){let G=navigator.platform.toLowerCase();if(G.includes("mac")||G.includes("ios"))Z="darwin";else if(G.includes("win"))Z="windows";let V=navigator.userAgent;if(Z==="darwin"){let K=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(K?.[1])Y=K[1].replace(/_/g,".")}else if(Z==="windows"){let K=V.match(/Windows NT (\d+\.\d+)/);if(K?.[1])Y=K[1]}else{let K=V.match(/Linux.*?(\d+\.\d+)/);if(K?.[1])Y=K[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}eH1={webBrowser:Q,os:Z,osVersion:Y,cpuArchitecture:X,client:Uy().name,optionAltKeyShort:Z==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Z==="darwin"?"⌘":"⌃",ctrlCmdKey:Z==="darwin"?"⌘":"Ctrl"}}return eH1}var eH1;var By=N1(()=>{UZ()});var y7=N1(()=>{KY();LG()});function Zz1(J){}function pE(J){if(typeof J=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:Q=Zz1,onError:Z=Zz1,onRetry:Y=Zz1,onComment:X}=J,G="",V=!0,K,q="",W="";function H(L){let A=V?L.replace(/^\xEF\xBB\xBF/,""):L,[E,I]=YK4(`${G}${A}`);for(let P of E)z(P);G=I,V=!1}function z(L){if(L===""){D();return}if(L.startsWith(":")){X&&X(L.slice(L.startsWith(": ")?2:1));return}let A=L.indexOf(":");if(A!==-1){let E=L.slice(0,A),I=L[A+1]===" "?2:1,P=L.slice(A+I);U(E,P,L);return}U(L,"",L)}function U(L,A,E){switch(L){case"event":W=A;break;case"data":q=`${q}${A}
|
|
78
78
|
`;break;case"id":K=A.includes("\x00")?void 0:A;break;case"retry":/^\d+$/.test(A)?Y(parseInt(A,10)):Z(new Yz1(`Invalid \`retry\` value: "${A}"`,{type:"invalid-retry",value:A,line:E}));break;default:Z(new Yz1(`Unknown field "${L.length>20?`${L.slice(0,20)}…`:L}"`,{type:"unknown-field",field:L,value:A,line:E}));break}}function D(){q.length>0&&Q({id:K,event:W||void 0,data:q.endsWith(`
|
|
@@ -3959,15 +3959,15 @@ Actual: ${X}`)}async function PV8(J,Q,Z){let{execSync:Y}=await import("node:ch
|
|
|
3959
3959
|
${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))M+=`
|
|
3960
3960
|
|
|
3961
3961
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
3962
|
-
npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}U0();U0();async function n61(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=SV8(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return x.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function SV8(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)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}o0();function a61(J,Q){let Z=new u4,Y=Z.pipe(A8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new qK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await XR(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=EA(),W=await n61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await i61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}try{await ug(W.latestVersion,z);let U=await EB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await XR(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as Iq}from"node:process";function I96(J){let Q=new qA().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 xC1(Y.force||!1,Y.verbose||!1,"0.0.
|
|
3962
|
+
npm install -g @sourcegraph/amp`;K(Error(M))}},error:(U)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!H)H=!0,V()}})})}U0();U0();async function n61(J,Q){let Y=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=SV8(J,q),H=W<0,z,U;if(K.time){let D=K.time[J],M=K.time[q],L=Date.now();if(D)z=Math.floor((L-new Date(D).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(X){return x.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function SV8(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)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}o0();function a61(J,Q){let Z=new u4,Y=Z.pipe(A8({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new qK().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await XR(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=EA(),W=await n61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,D=0.5;if(Math.abs(U)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await i61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Z.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Z.next("update-available");return}try{await ug(W.latestVersion,z);let U=await EB(W.latestVersion),D={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")X.info("success",D),Z.next("updated");else X.warn("success with warning",D),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await XR(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}import{stderr as Iq}from"node:process";function I96(J){let Q=new qA().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 xC1(Y.force||!1,Y.verbose||!1,"0.0.1764808732-gb9c377"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new qA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await _V8(Y.targetVersion)});J.addCommand(Z)}async function _V8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Iq.write(k4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
3963
3963
|
|
|
3964
3964
|
`));try{if(!J){Iq.write(k4.blue(`Checking for updates...
|
|
3965
|
-
`));let Y=EA(),{hasUpdate:X,latestVersion:G}=await n61("0.0.
|
|
3966
|
-
`));let K=await EB("0.0.
|
|
3965
|
+
`));let Y=EA(),{hasUpdate:X,latestVersion:G}=await n61("0.0.1764808732-gb9c377",Y);if(!X){Iq.write(k4.green(`✓ Amp CLI is already up to date: ${"0.0.1764808732-gb9c377"} (${"released"} ${"2025-12-04T00:44:17.586Z"})
|
|
3966
|
+
`));let K=await EB("0.0.1764808732-gb9c377");if(K.warning)Iq.write(`
|
|
3967
3967
|
`+k4.yellow(K.warning)+`
|
|
3968
3968
|
`);process.exit(0)}if(!G)Iq.write(k4.yellow("[WARN] could not find latest version")),process.exit(0);J=G}Iq.write(k4.blue(`Updating to version ${J}...
|
|
3969
3969
|
`)),await ug(J,void 0,(Y)=>{Iq.write(k4.dim(`Running: ${Y}
|
|
3970
|
-
`))});let Q="released";Iq.write(k4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-04T00:
|
|
3970
|
+
`))});let Q="released";Iq.write(k4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-12-04T00:44:17.586Z"})
|
|
3971
3971
|
`));let Z=await EB(J);if(Z.warning)Iq.write(`
|
|
3972
3972
|
`+k4.yellow(Z.warning)+`
|
|
3973
3973
|
`);process.exit(0)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);Iq.write(k4.red.bold("Error: ")+Z+`
|
|
@@ -4599,7 +4599,7 @@ exit code: ${G}`,new J1({color:Y.foreground,dim:!0,italic:!0})));if(V)K.push(new
|
|
|
4599
4599
|
`,M),...L])})];if(H.url){let v=H.url.replace(/^https?:\/\//,"");k.push(new B7({uri:H.url,text:v,style:new J1({color:Z.secondary,underline:!0})}))}if(C)k.push(new X0({height:1})),k.push(C);let y=new X0({width:40,child:new b0({crossAxisAlignment:"start",mainAxisSize:"min",children:k})});return j4.child(new R6({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new ZS1({width:_k1,height:kk1,agentMode:this.widget.agentMode,glow:this._glow,t:A,fps:0,shockwaves:this._shockwaves,onShockwave:I,...V==="disabled"&&{seed:42}}),new X0({width:2}),y]}))}}U0();y8();M4();A7();y8();o0();function BM8(J,Q){return`${J}:${Q}`}class yk1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new Q0((Q)=>{return this.emitMainThread=(Z)=>Q.next(Z),()=>{this.emitMainThread=null}}),this.subthreadObservable=new Q0((Q)=>{return this.emitSubthread=(Z)=>Q.next(Z),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new Q0((Q)=>{return this.emitWorkerStatus=(Z)=>Q.next(Z),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Z=this.threadService.observePatches(Q).pipe(rD()).subscribe((G)=>{this.threadsMap.set(Q,G);let V=this.subthreadsMap.get(Q)||[],K=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:G,subthreads:V,workerStatus:K})});this.mainThreadSubs.set(Q,Z);let Y=J.status.subscribe((G)=>{if(this.workers.set(Q,G),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:G})});this.workerStatusSubs.set(Q,Y);let X=J.subthreads.subscribe((G)=>{this.subthreadsMap.set(Q,G);for(let V of G){let K=BM8(Q,V.toolUse.id);if(this.subthreadPatchSubs.has(K))continue;let q=this.threadService.observePatches(V.threadID).pipe(rD()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:V})});this.subthreadPatchSubs.set(K,q)}});this.subthreadsSubs.set(Q,X)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Z=this.workerStatusSubs.get(J);if(Z)Z.unsubscribe(),this.workerStatusSubs.delete(J);let Y=this.subthreadsSubs.get(J);if(Y)Y.unsubscribe(),this.subthreadsSubs.delete(J);for(let[X,G]of this.subthreadPatchSubs.entries())if(X.startsWith(`${J}:`))G.unsubscribe(),this.subthreadPatchSubs.delete(X);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new Q0((Q)=>{return this.mainThreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),subthreads:new Q0((Q)=>{return this.subthreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),workerStatus:new Q0((Q)=>{return this.workerStatusObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})})}}get threadViewStates(){let J={};for(let[Q,Z]of this.threadsMap){let Y=this.workers.get(Q);if(Y)J[Q]=iL(Z,Y)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function NM8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Z,subthread:Y}=Q,X=J.subagents[Y.threadID];if(!X){if(X={subThreadID:Z.id,parentToolID:Y.toolUse.id,taskDescription:Y.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=kJ(J.mainThread);X.isCompleted=HZ6(W,Y.toolUse.id)}}let G=DM8(Z,X.agentState),V=X.agentState===G?X:{...X,agentState:G},K={...J.tools},q=LC(Z).items.filter((W)=>W.type==="toolResult");for(let W of q)K[W.id]={id:W.id,subthreadID:Z.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[Y.threadID]:V},tools:K,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Z,subthreads:Y,workerStatus:X}=Q,G=kJ(Z),V={...J.subagents};for(let z of Y){let U=V[z.threadID];if(!U)continue;let D=HZ6(G,z.toolUse.id);V[z.threadID]={...U,isCompleted:D}}let{items:K}=LC(Z),q=iL(Z,X),W=gE({messages:Z.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:V,items:K,viewState:q,todosList:H,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=iL(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function LC(J){let Q=[],Z=new Map,Y=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Z.set(W.id,W),K)Y.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let D of U.content)if(D.type==="tool_result"&&D.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:V,message:G});break;case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Z.get(q.toolUseID)??qY(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}function HZ6(J,Q){let Z=J.get(Q);return(Z&&Z3(Z.run))??!1}function DM8(J,Q){let Z=J.messages.at(-1);if(Z?.content.some((X)=>X.type==="tool_result"&&X.run.status==="blocked-on-user"))return x.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(LC(J).items.some((X)=>X.type==="toolResult"&&X.toolResult.run.status==="in-progress")){let X=Q?.type==="running-tools"?Q.startTime:Date.now();return x.info("Subagent status: running-tools",{threadID:J.id,startTime:X,hasStartTime:!!X}),{type:"running-tools",startTime:X}}if(Z&&Z.role==="assistant"&&Z.state.type==="streaming")switch(Z.content.at(-1)?.type){case"text":return x.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return x.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let G=Q?.type==="running-tools"?Q.startTime:Date.now();return x.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}default:return x.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return x.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class xk1 extends c0{props;constructor(J){super();this.props=J}createState(){return new zZ6}}class zZ6 extends p0{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new yk1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Z=Q.mainThread.subscribe((G)=>{this.dispatch({type:"main-thread-patch",thread:G.mainThread,subthreads:G.subthreads,workerStatus:G.workerStatus})});this.subscriptions.push(Z);let Y=Q.subthreads.subscribe((G)=>{this.dispatch({type:"subthread-patch",thread:G.thread,subthread:G.subthread})});this.subscriptions.push(Y);let X=Q.workerStatus.subscribe((G)=>{this.dispatch({type:"worker-status-change",workerStatus:G.status})});this.subscriptions.push(X)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=NM8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((G)=>({toolUse:G.toolUse,toolRun:G.toolRun,subthreadID:G.subthreadID})),Q={};for(let G of Object.values(this.state.subagents)){let V=J.filter((K)=>K.subthreadID===G.subThreadID);Q[G.parentToolID]=V}let Z=(G)=>G===B5||G===i8||G===VY,Y=new Map;for(let G of this.state.items)if(G.type==="toolResult"&&Z(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=Array.from(Y.values());for(let{toolUseId:G,toolRun:V}of X){let K=[],q;if(V.status==="in-progress"||V.status==="done"||V.status==="error"||V.status==="cancelled")q=V.progress;if(q){let W=0;for(let H of q)if(H.tool_uses)for(let z of H.tool_uses){let U=`${G}:progress:${W++}`;K.push({toolUse:fE(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[G]=K}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Z)=>this.switchWorker(Z),()=>this.currentWorker,this.recentThreadIDs)}}class vk1 extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new FZ6}}class FZ6 extends p0{build(J){let Z=Y6.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new X0({width:0,height:0});let G=Y.map((V)=>this.buildTodoItem(V,Z));return new l0({child:new V6({padding:B0.symmetric(1,0),child:new b0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new y1({text:new i(X,new J1({bold:!0,color:Z.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new J1({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),G=new J1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new R6({crossAxisAlignment:"start",children:[new y1({text:new i(Z,X)}),new X0({width:1}),new a6({child:new y1({text:new i(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class fk1 extends E6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y}build(J){let Q=Y6.of(J),Z=Q.colors.primary,Y=Q.colors.foreground;return new l0({decoration:new Z8(void 0,new A4(new q4(Z,1,"rounded"),new q4(Z,1,"rounded"),void 0,new q4(Z,1,"rounded"))),child:new V6({padding:B0.horizontal(1),child:new b0({children:[new R6({crossAxisAlignment:"start",children:[new a6({child:new y1({text:new i(this.ad.content,new J1({color:Y}))})}),new X0({width:4}),new B7({uri:"https://ampcode.com/free",text:"Ad",style:new J1({color:Y,dim:!0})})]}),new R6({crossAxisAlignment:"start",children:[new FS1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:B0.horizontal(1),color:Z,reverse:!0}),new X0({width:2}),new y1({text:new i(this.ad.destinationUrlHostname,new J1({color:Y,dim:!0}))})]})]})})})}}class hk1 extends c0{props;constructor(J){super();this.props=J}createState(){return new UZ6(this.props.autofocus??!0)}}class UZ6 extends p0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=f4.sizeOf(J),Y=Math.min(60,Z.width-4),X=Z.height-4,G=[];if(this.widget.props.title)G.push(new y1({text:new i(this.widget.props.title,new J1({bold:!0,color:D1.blue}))}),new X0({height:1}));if(this.widget.props.message)G.push(new y1({text:new i(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new X0({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new y1({text:new i("Enter to copy",new J1({dim:!0}))}));return V.push(new y1({text:new i("Escape to close",new J1({dim:!0}))})),G.push(new R6({children:V.flatMap((K,q)=>q<V.length-1?[K,new X0({width:1}),new y1({text:new i("•",new J1({dim:!0}))}),new X0({width:1})]:[K]),mainAxisSize:"min"})),new j4({child:new l0({constraints:new A6(Y,Y,0,X),decoration:new Z8(D1.default(),new A4(new q4(D1.blue,1,"rounded"),new q4(D1.blue,1,"rounded"),new q4(D1.blue,1,"rounded"),new q4(D1.blue,1,"rounded"))),padding:new B0(2,2,2,2),child:new D8({autofocus:this.autofocus,onKey:Q,child:new b0({children:G,mainAxisSize:"min"})})})})}}function MM8(J){let Q=Math.floor(J/60),Z=J%60;if(Q===0)return`${Z}s`;return`${Q}:${Z.toString().padStart(2,"0")}`}function LM8(J){if(J<0.01)return"<$0.01";return`$${J.toFixed(2)}`}function AM8(J){if(J<=60)return"~ 1m";if(J<=120)return"~ 2m";if(J<=300)return"~ 5m";return"~ 10m"}function BZ6(J,Q={}){if(J.secondsRemaining===null)return null;if(J.secondsRemaining===0)return{text:"cache expired",urgency:"expired"};let Z=J.secondsRemaining<=60,Y=Q.isIdle!==!1&&Z,X=Y?MM8(J.secondsRemaining):AM8(J.secondsRemaining),G=LM8(J.potentialSavingsUSD);if(Q.isNarrow)return{text:X,urgency:Y?"warning":"normal"};if(Q.prominent&&Y)return{text:`${X} left - respond now to save up to ${G}`,urgency:"warning"};return{text:`${X} (save up to ${G})`,urgency:Y?"warning":"normal"}}class N91 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,N91.prototype)}}class D91 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,D91.prototype)}}function bk1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}nW();U0();import{spawn as OM8}from"node:child_process";import{promises as wM8}from"node:fs";function NZ6(J){return J.kind==="executable"}function DZ6(J){return J.kind==="markdown"}var Xz=50000,MZ6=300000;async function gk1(J,Q,Z,Y={}){let{timeoutMs:X=MZ6,signal:G,source:V}=Y;try{let K=await Z.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(x.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),DZ6(K))return await EM8(K,Q);else if(NZ6(K))return await IM8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return x.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function EM8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await wM8.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>Xz?Z.slice(0,Xz)+`
|
|
4600
4600
|
... (output truncated at ${Xz} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function IM8(J,Q,Z=MZ6,Y){return new Promise((X)=>{let[G,V]=PM8(J,Q);x.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Z});let K=oP0(Y),q=!1,W=setTimeout(()=>{q=!0,K.abort(),x.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),H=OM8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],U=[],D=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Xz)z.push(L);else{let A=Xz-(D-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(D+=L.length,D<=Xz)U.push(L);else{let A=Xz-(D-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),I=A;if(!L&&!A.trim()&&E.trim())I=E;else if(E.trim())I+=A?`
|
|
4601
4601
|
${E}`:E;if(D>Xz)I+=`
|
|
4602
|
-
... (output truncated at ${Xz} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function PM8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return RM8(Z,Y?[...Y]:null,X,Q);else return TM8(Z,Y?[...Y]:null,X,Q)}function TM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function RM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}U0();LG();y7();yW();NY();gG();aW();mK();y8();A7();d_();o0();var vZ6=W6(LP(),1);import{writeFile as kZ6}from"fs/promises";import yZ6 from"path";U0();NY();class mk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764806510-g3d6586"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ao(Q,this.configService)}catch(Q){x.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class xm extends c0{props;constructor(J){super();this.props=J}createState(){return new LZ6}}class LZ6 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class AZ6 extends p0{controller=new P$;focusNode=new w8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=Y6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=A4.all(new q4(Z.foreground,1,"solid")),q=new bA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new R6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Z.foreground}))})}),new a6({child:q})]}),H=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new J1({color:Y.keybind}))),z.push(new i(" to submit, ",new J1({color:Z.foreground,dim:!0})));z.push(new i("Esc",new J1({color:Y.keybind}))),z.push(new i(" to cancel",new J1({color:Z.foreground,dim:!0})));let U=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i("",void 0,z)})});return new l0({decoration:{border:K,color:D1.default()},padding:B0.all(1),child:new b0({children:[H,new X0({height:1}),W,new t9,U]})})}}class M91 extends c0{props;constructor(J){super();this.props=J}createState(){return new AZ6}}aW();class OZ6 extends p0{controller=new P$;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new w8({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=(J)=>{if(this.imageAttachments.length>=iF)return!1;let Q=ZC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],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 Q=Y6.of(J),{colors:Z,app:Y}=Q,G=f4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new sA({controller:this.controller,triggers:[new pB],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:o8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new D8({focusNode:this.focusNode,child:K}),W=new l0({constraints:new A6({maxHeight:V}),padding:B0.symmetric(1,0),child:q}),H=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=new l0({padding:B0.symmetric(1,0),child:new y1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new J1({color:Y.keybind})),new i(" again to clear input",new J1({color:Z.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new J1({color:Z.foreground,dim:!0})),new i("Enter",new J1({color:Y.keybind})),new i(" to submit, ",new J1({color:Z.foreground,dim:!0})),new i("Esc",new J1({color:Y.keybind})),new i(" to clear",new J1({color:Z.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new a6({child:W}),new X0({height:1}),z];return new l0({decoration:{border:A4.all(new q4(Z.foreground,1,"solid")),color:D1.default()},padding:B0.all(1),child:new b0({children:U})})}}class AC extends c0{props;constructor(J){super();this.props=J}createState(){return new OZ6}}import{isDeepStrictEqual as _M8}from"node:util";var CM8=/[\\/_ +.#"@[({&]/,jM8=/[\\/_ +.#"@[({&]/g,SM8=/[\s-]/,wZ6=/[\s-]/g;function A91(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=A91(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(SM8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(wZ6),M&&X>0)z*=Math.pow(0.999,M.length)}else if(CM8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match(jM8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=A91(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function L91(J){return J.toLowerCase().replace(wZ6," ")}function EZ6(J,Q){let Z=A91(J,Q,L91(J),L91(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=A91(J,K,L91(J),L91(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class OC{}class wC{}class O91{}class w91{}class IZ6 extends c0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new PZ6}}class PZ6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function kM8(J,Q){if(J==="")return{matches:!0,score:1};let Z=EZ6(Q,J);return{matches:Z>0.15,score:Z}}class bZ extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new TZ6}}class TZ6 extends p0{controller=new P$;focusNode;scrollController=new U7;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new w8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!_M8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof OC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof wC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof O91){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof w91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...kM8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;D81(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=A4.all(new q4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new bA({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new DV({shortcuts:new Map([[new K4("ArrowDown"),new OC],[new K4("ArrowUp"),new wC],[new K4("Tab"),new OC],[new K4("Tab",{shift:!0}),new wC],[new K4("n",{ctrl:!0}),new OC],[new K4("p",{ctrl:!0}),new wC],[new K4("Enter"),new O91],[new K4("Escape"),new w91]]),focusNode:this.focusNode,child:V}),q=new mQ({actions:new Map([[OC,new T8(this.invoke)],[wC,new T8(this.invoke)],[O91,new T8(this.invoke)],[w91,new T8(this.invoke)]]),child:K}),W=new R6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Z.foreground}))})}),new a6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new j4({child:new y1({text:new i(L,new J1({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new a6({child:new j4({child:new y1({text:new i(this.widget.props.emptyStateText,new J1({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,C;if(this.widget.props.renderItem)C=this.widget.props.renderItem(A,I,P,J);else{let k=I?D1.yellow:void 0,y=I?D1.black:Z.foreground;C=new l0({decoration:k?{color:k}:void 0,padding:B0.symmetric(2,0),child:new y1({text:new i(this.widget.props.getLabel(A),new J1({color:y,dim:P}))})})}return new IZ6(new G8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:C}),(k)=>{this.itemContexts[E]=k})});H=new b0({children:L,crossAxisAlignment:"start"})}let z=new a6({child:new G8({onScroll:this.handleScroll,opaque:!1,child:new S5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i(this.widget.props.title,new J1({color:D1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new l0({padding:B0.vertical(1),child:new j4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new l0({decoration:{border:X,color:D1.default()},padding:B0.symmetric(1,0),child:new b0({children:U})})}}class uk1 extends c0{createState(){return new RZ6}}class RZ6 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){return new y1({text:new i("●",new J1({color:this.isGreen?D1.green:D1.index(8),bold:!0})),maxLines:1})}}function yM8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return lY.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function pk1(J,Q,Z){return new y1({text:new i(`${J}${Q}`,new J1({color:Z})),maxLines:1})}function xM8(J,Q,Z,Y){return[pk1("+",J,Y.success),t9.horizontal(1),pk1("~",Q,Y.warning),t9.horizontal(1),pk1("-",Z,Y.destructive)]}class E91 extends E6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=yM8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=Y6.of(J),q=new V6({padding:B0.symmetric(0,1),child:new j4({child:new y1({text:new i("",new J1({color:K.colors.foreground,dim:!0}),[new i("Ctrl+T",new J1({color:D1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:K.colors.foreground,dim:!0}))])})})});return new bZ({items:G,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:q,renderItem:(H,z,U,D)=>{let M=Y6.of(D),{colors:L}=M,A=z?D1.yellow:void 0,E=z?D1.black:L.foreground,I=D1.index(8),P=($1,t)=>new X0({width:t,child:R6.end([new y1({text:new i($1,new J1({color:I}))})])}),C=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",v=new I81;if(H.depth>0){let $1=[],t=H.ancestorsAreLast.slice(1);for(let F1 of t)$1.push(new i(v.getAncestorPrefix(F1),new J1({color:v.connectorColor,dim:v.connectorDim})));let p=H.isLast?v.elbow:v.tee,e=v.getConnectorText(p);$1.push(new i(e,new J1({color:v.connectorColor,dim:v.connectorDim}))),k.push(new y1({text:new i("",void 0,$1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new J1({color:D1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new J1({color:L.foreground,dim:!0})):null;if(d)b.push(new y1({text:d}));if(C){if(C.state==="active"&&(C.interactionState==="tool-running"||C.interactionState===!1))b.push(new uk1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let $1=m.match(/^Forked\((\d+)\): /);if($1)m=m.slice($1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new y1({text:new i("[fork] ",new J1({color:D1.blue}))}))}else if(y)b.push(new y1({text:new i("[handoff] ",new J1({color:D1.index(208)}))}));if(b.push(new a6({child:new y1({text:new i(m,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let $1=z?{success:I,warning:I,destructive:I}:L;b.push(...xM8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,$1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new l0({decoration:A?{color:A}:void 0,padding:B0.symmetric(2,0),child:new R6({children:[...k,...b]})})}})}}function CZ6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class dk1 extends E6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>CZ6(X.pubDate).length));return new bZ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=Y6.of(K),{colors:W}=q,H=G?D1.yellow:void 0,z=G?D1.black:W.foreground,U=D1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:R6.end([new y1({text:new i(L,new J1({color:U}))})])});return new l0({decoration:H?{color:H}:void 0,padding:B0.symmetric(2,0),child:new R6({children:[new a6({child:new y1({text:new i(X.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new y1({text:new i(D,new J1({color:U})),maxLines:1}),new X0({width:2}),M(CZ6(X.pubDate),Z)]})})}})}}class ck1 extends E6{props;constructor(J){super();this.props=J}build(){return new j4({child:new y1({text:new i("",void 0,[new i(`Forked to new thread:
|
|
4602
|
+
... (output truncated at ${Xz} characters)`;X({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(q)L=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";X({success:!1,output:z.join(""),error:L})})})}function PM8(J,Q){let{filePath:Z,interpreter:Y,extension:X}=J;if(process.platform==="win32")return RM8(Z,Y?[...Y]:null,X,Q);else return TM8(Z,Y?[...Y]:null,X,Q)}function TM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];else return[J,Y]}function RM8(J,Q,Z,Y){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Y]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Y]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Y]];case".exe":return[J,Y];default:return[J,Y]}}U0();LG();y7();yW();NY();gG();aW();mK();y8();A7();d_();o0();var vZ6=W6(LP(),1);import{writeFile as kZ6}from"fs/promises";import yZ6 from"path";U0();NY();class mk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764808732-gb9c377"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ao(Q,this.configService)}catch(Q){x.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class xm extends c0{props;constructor(J){super();this.props=J}createState(){return new LZ6}}class LZ6 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class AZ6 extends p0{controller=new P$;focusNode=new w8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=Y6.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=A4.all(new q4(Z.foreground,1,"solid")),q=new bA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let M=D.trim();if(X&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new R6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Z.foreground}))})}),new a6({child:q})]}),H=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=[];if(V)z.push(new i("Enter",new J1({color:Y.keybind}))),z.push(new i(" to submit, ",new J1({color:Z.foreground,dim:!0})));z.push(new i("Esc",new J1({color:Y.keybind}))),z.push(new i(" to cancel",new J1({color:Z.foreground,dim:!0})));let U=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i("",void 0,z)})});return new l0({decoration:{border:K,color:D1.default()},padding:B0.all(1),child:new b0({children:[H,new X0({height:1}),W,new t9,U]})})}}class M91 extends c0{props;constructor(J){super();this.props=J}createState(){return new AZ6}}aW();class OZ6 extends p0{controller=new P$;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new w8({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=(J)=>{if(this.imageAttachments.length>=iF)return!1;let Q=ZC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],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 Q=Y6.of(J),{colors:Z,app:Y}=Q,G=f4.of(J).size.height,V=Math.max(Math.floor(G*0.5),10),K=new sA({controller:this.controller,triggers:[new pB],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(D)=>{this.widget.props.onSubmit(D.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:o8.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),q=new D8({focusNode:this.focusNode,child:K}),W=new l0({constraints:new A6({maxHeight:V}),padding:B0.symmetric(1,0),child:q}),H=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i("",void 0,[new i("Command: ",new J1({color:Z.foreground})),new i(this.widget.props.commandName,new J1({color:D1.yellow,bold:!0}))])})}),z=new l0({padding:B0.symmetric(1,0),child:new y1({text:this.isConfirmingClearInput?new i("",void 0,[new i("Esc",new J1({color:Y.keybind})),new i(" again to clear input",new J1({color:Z.foreground,dim:!0}))]):new i("",void 0,[new i("Press ",new J1({color:Z.foreground,dim:!0})),new i("Enter",new J1({color:Y.keybind})),new i(" to submit, ",new J1({color:Z.foreground,dim:!0})),new i("Esc",new J1({color:Y.keybind})),new i(" to clear",new J1({color:Z.foreground,dim:!0}))])})}),U=[H,new X0({height:1}),new a6({child:W}),new X0({height:1}),z];return new l0({decoration:{border:A4.all(new q4(Z.foreground,1,"solid")),color:D1.default()},padding:B0.all(1),child:new b0({children:U})})}}class AC extends c0{props;constructor(J){super();this.props=J}createState(){return new OZ6}}import{isDeepStrictEqual as _M8}from"node:util";var CM8=/[\\/_ +.#"@[({&]/,jM8=/[\\/_ +.#"@[({&]/g,SM8=/[\s-]/,wZ6=/[\s-]/g;function A91(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,U,D,M;while(W>=0){if(z=A91(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(SM8.test(J.charAt(W-1))){if(z*=0.9,M=J.slice(X,W-1).match(wZ6),M&&X>0)z*=Math.pow(0.999,M.length)}else if(CM8.test(J.charAt(W-1))){if(z*=0.8,D=J.slice(X,W-1).match(jM8),D&&X>0)z*=Math.pow(0.999,D.length)}else if(z*=0.3,X>0)z*=Math.pow(0.999,W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(U=A91(J,Q,Z,Y,W+1,G+2,V),U*0.1>z)z=U*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function L91(J){return J.toLowerCase().replace(wZ6," ")}function EZ6(J,Q){let Z=A91(J,Q,L91(J),L91(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=A91(J,K,L91(J),L91(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class OC{}class wC{}class O91{}class w91{}class IZ6 extends c0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new PZ6}}class PZ6 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function kM8(J,Q){if(J==="")return{matches:!0,score:1};let Z=EZ6(Q,J);return{matches:Z>0.15,score:Z}}class bZ extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new TZ6}}class TZ6 extends p0{controller=new P$;focusNode;scrollController=new U7;selectedIndex=0;itemContexts=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new w8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!_M8(J.props.items,this.widget.props.items)){this.ensureSelectedItemVisible();let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof OC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof wC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),this.ensureSelectedItemVisible(),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof O91){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof w91)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...kM8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,Y)=>this.widget.props.sortItems(Z,Y,J):(Z,Y)=>Y.score-Z.score).map((Z)=>Z.item);if(this.widget.props.maxRenderItems)return Q.slice(0,this.widget.props.maxRenderItems);return Q}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;D81(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),m8.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.widget.props.onAccept(Y)}}};build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=A4.all(new q4(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new bA({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new DV({shortcuts:new Map([[new K4("ArrowDown"),new OC],[new K4("ArrowUp"),new wC],[new K4("Tab"),new OC],[new K4("Tab",{shift:!0}),new wC],[new K4("n",{ctrl:!0}),new OC],[new K4("p",{ctrl:!0}),new wC],[new K4("Enter"),new O91],[new K4("Escape"),new w91]]),focusNode:this.focusNode,child:V}),q=new mQ({actions:new Map([[OC,new T8(this.invoke)],[wC,new T8(this.invoke)],[O91,new T8(this.invoke)],[w91,new T8(this.invoke)]]),child:K}),W=new R6({children:[new l0({decoration:{color:D1.default()},child:new y1({text:new i(">",new J1({color:Z.foreground}))})}),new a6({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let L=this.widget.props.loadingText??"Loading...";H=new X0({height:10,child:new j4({child:new y1({text:new i(L,new J1({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new a6({child:new j4({child:new y1({text:new i(this.widget.props.emptyStateText,new J1({color:Z.foreground,dim:!0}))})})});else{let L=Y.map((A,E)=>{let I=E===this.selectedIndex,P=this.widget.props.isItemDisabled?.(A)??!1,C;if(this.widget.props.renderItem)C=this.widget.props.renderItem(A,I,P,J);else{let k=I?D1.yellow:void 0,y=I?D1.black:Z.foreground;C=new l0({decoration:k?{color:k}:void 0,padding:B0.symmetric(2,0),child:new y1({text:new i(this.widget.props.getLabel(A),new J1({color:y,dim:P}))})})}return new IZ6(new G8({onClick:(k)=>this.handleItemClick(E,k.clickCount),child:C}),(k)=>{this.itemContexts[E]=k})});H=new b0({children:L,crossAxisAlignment:"start"})}let z=new a6({child:new G8({onScroll:this.handleScroll,opaque:!1,child:new S5({controller:this.scrollController,autofocus:!1,child:H})})}),U=[];if(this.widget.props.title){let L=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i(this.widget.props.title,new J1({color:D1.yellow,bold:!0}))})});U.push(L)}if(U.push(W,new X0({height:1}),z),this.controller.text!==""){let L=Y.length>0?Y[this.selectedIndex]:void 0,A=L&&this.widget.props.buildDisabledReasonWidget?.(L);if(A)U.push(new l0({padding:B0.vertical(1),child:new j4({child:A})}));else U.push(new X0({height:3}))}if(this.widget.props.footer)U.push(this.widget.props.footer);return new l0({decoration:{border:X,color:D1.default()},padding:B0.symmetric(1,0),child:new b0({children:U})})}}class uk1 extends c0{createState(){return new RZ6}}class RZ6 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){return new y1({text:new i("●",new J1({color:this.isGreen?D1.green:D1.index(8),bold:!0})),maxLines:1})}}function yM8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return lY.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function pk1(J,Q,Z){return new y1({text:new i(`${J}${Q}`,new J1({color:Z})),maxLines:1})}function xM8(J,Q,Z,Y){return[pk1("+",J,Y.success),t9.horizontal(1),pk1("~",Q,Y.warning),t9.horizontal(1),pk1("-",Z,Y.destructive)]}class E91 extends E6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((H)=>H.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((H)=>H.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=this.props.currentThreadID,X=[...Q].sort((H,z)=>{if(Y){if(H.id===Y)return-1;if(z.id===Y)return 1}let U=Z.indexOf(H.id),D=Z.indexOf(z.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),G=yM8(X),V=Math.max(0,...G.map((H)=>H.description.timeAgo.length)),K=Y6.of(J),q=new V6({padding:B0.symmetric(0,1),child:new j4({child:new y1({text:new i("",new J1({color:K.colors.foreground,dim:!0}),[new i("Ctrl+T",new J1({color:D1.blue,dim:!0})),new i(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new J1({color:K.colors.foreground,dim:!0}))])})})});return new bZ({items:G,getLabel:(H)=>H.title,onAccept:(H)=>this.props.onSelect?.(H.id),onDismiss:this.props.onDismiss,onSelectionChange:(H)=>{if(this.props.previewController){if(H)this.props.previewController.select(H.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:1000,footer:this.props.isLoading?void 0:q,renderItem:(H,z,U,D)=>{let M=Y6.of(D),{colors:L}=M,A=z?D1.yellow:void 0,E=z?D1.black:L.foreground,I=D1.index(8),P=($1,t)=>new X0({width:t,child:R6.end([new y1({text:new i($1,new J1({color:I}))})])}),C=this.props.threadViewStates[H.id],k=[],y=H.relationshipType==="handoff",v=new I81;if(H.depth>0){let $1=[],t=H.ancestorsAreLast.slice(1);for(let F1 of t)$1.push(new i(v.getAncestorPrefix(F1),new J1({color:v.connectorColor,dim:v.connectorDim})));let p=H.isLast?v.elbow:v.tee,e=v.getConnectorText(p);$1.push(new i(e,new J1({color:v.connectorColor,dim:v.connectorDim}))),k.push(new y1({text:new i("",void 0,$1)}))}let b=[],d=this.props.currentThreadID===H.id?new i("(current) ",new J1({color:D1.green})):(this.props.recentThreadIDs||[]).includes(H.id)?new i("(visited) ",new J1({color:L.foreground,dim:!0})):null;if(d)b.push(new y1({text:d}));if(C){if(C.state==="active"&&(C.interactionState==="tool-running"||C.interactionState===!1))b.push(new uk1),b.push(new X0({width:1}))}let m=H.title;if(H.relationshipType==="fork"){let $1=m.match(/^Forked\((\d+)\): /);if($1)m=m.slice($1[0].length);else while(m.startsWith("Forked: "))m=m.slice(8);b.push(new y1({text:new i("[fork] ",new J1({color:D1.blue}))}))}else if(y)b.push(new y1({text:new i("[handoff] ",new J1({color:D1.index(208)}))}));if(b.push(new a6({child:new y1({text:new i(m,new J1({color:E})),overflow:"ellipsis",maxLines:1})})),b.push(new X0({width:2})),H.diffStats&&(H.diffStats.added>0||H.diffStats.changed>0||H.diffStats.deleted>0)){let $1=z?{success:I,warning:I,destructive:I}:L;b.push(...xM8(H.diffStats.added,H.diffStats.changed,H.diffStats.deleted,$1)),b.push(new X0({width:2}))}return b.push(P(H.description.timeAgo,V)),new l0({decoration:A?{color:A}:void 0,padding:B0.symmetric(2,0),child:new R6({children:[...k,...b]})})}})}}function CZ6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class dk1 extends E6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>CZ6(X.pubDate).length));return new bZ({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=Y6.of(K),{colors:W}=q,H=G?D1.yellow:void 0,z=G?D1.black:W.foreground,U=D1.index(8),D=X.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new X0({width:A,child:R6.end([new y1({text:new i(L,new J1({color:U}))})])});return new l0({decoration:H?{color:H}:void 0,padding:B0.symmetric(2,0),child:new R6({children:[new a6({child:new y1({text:new i(X.title,new J1({color:z})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new y1({text:new i(D,new J1({color:U})),maxLines:1}),new X0({width:2}),M(CZ6(X.pubDate),Z)]})})}})}}class ck1 extends E6{props;constructor(J){super();this.props=J}build(){return new j4({child:new y1({text:new i("",void 0,[new i(`Forked to new thread:
|
|
4603
4603
|
|
|
4604
4604
|
`,new J1({color:D1.white,dim:!0})),new i(`"${this.props.newThreadTitle||"Untitled"}"`,new J1({color:D1.white}))]),textAlign:"center"})})}}U0();class jZ6 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){x.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){x.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null}buildItemsWithCreateOption(){let J=this.widget.props.currentLabels||[],Z=[...this.labels.filter((Y)=>!J.includes(Y.name))];if(this.currentQuery.trim().length>0&&!this.isLoading){let Y=this.currentQuery.trim().toLowerCase(),X=this.labels.some((V)=>V.name===Y),G=J.includes(Y);if(!X&&!G&&this.isValidLabelName(Y))Z.unshift({id:"__create__",name:Y,createdAt:"",__isCreateMarker:!0})}return Z}build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=this.currentQuery.trim().toLowerCase(),X=Y.length>0?this.getValidationError(Y):null;return new bZ({title:"Add Label",items:this.buildItemsWithCreateOption(),getLabel:(G)=>G.name,onAccept:(G)=>{this.widget.props.onSelect(G.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(G,V,K,q)=>{let W=V?D1.yellow:void 0,H=V?D1.black:Z.foreground;if("__isCreateMarker"in G&&G.__isCreateMarker)return new l0({decoration:W?{color:W}:void 0,padding:B0.symmetric(2,0),child:new y1({text:new i("",void 0,[new i("Create: ",new J1({color:H})),new i(G.name,new J1({color:H,bold:!0}))])})});return new l0({decoration:W?{color:W}:void 0,padding:B0.symmetric(2,0),child:new y1({text:new i(G.name,new J1({color:H}))})})},filterItem:(G,V)=>{let K=this.currentQuery;if(this.currentQuery=V,K!==V)this.setState();if("__isCreateMarker"in G&&G.__isCreateMarker)return!0;let W=V.trim().toLowerCase();return W.length===0||G.name.includes(W)}})}}class lk1 extends c0{props;constructor(J){super();this.props=J}createState(){return new jZ6}}class vq extends c0{props;constructor(J){super();this.props=J}createState(){return new SZ6}}class SZ6 extends p0{_spinner=new T$;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=Y6.of(J),{colors:Z}=Q,Y=A4.all(new q4(Z.foreground,1,"solid")),X=this._spinner.toBraille(),G=new y1({textAlign:"center",text:new i("",void 0,[new i(X,new J1({color:D1.yellow})),new i(" ",void 0),new i(this.widget.props.message,new J1({color:Z.foreground}))])}),K=[new a6({child:new b0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new X0({height:2,child:new l0({padding:B0.symmetric(2,0),child:new y1({text:new i("",new J1({dim:!0}),[new i("Press ",new J1({color:Z.foreground})),new i("Esc",new J1({color:Z.info})),new i(" to cancel",new J1({color:Z.foreground}))])})})}));let q=new l0({decoration:new Z8(D1.default(),Y),child:new X0({width:60,height:7,child:new b0({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new D8({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class AV extends c0{props;constructor(J){super();this.props=J}createState(){return new _Z6}}class _Z6 extends p0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof MV}build(J){let Q=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=A81(Q);return{title:W.title,type:W.type,description:W.description}})(),Y=Z.type==="error"?D1.red:D1.yellow,X=A4.all(new q4(D1.default(),1,"solid")),G=new l0({padding:B0.symmetric(1,0),child:new y1({text:new i(Z.title,new J1({color:Y,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new y1({text:new i(Z.description,new J1({color:D1.default()})),selectable:!0}),K=new a6({child:new vA({child:new l0({padding:B0.symmetric(1,0),child:V})})}),q=new l0({padding:B0.symmetric(1,0),child:new y1({text:this.widget.props.onRetry?new i("",void 0,[new i("Press ",new J1({color:D1.default(),dim:!0})),new i("R",new J1({color:D1.yellow})),new i(" to retry, ",new J1({color:D1.default(),dim:!0})),new i("Esc",new J1({color:D1.yellow})),new i(" to cancel",new J1({color:D1.default(),dim:!0}))]):new i("Press any key to close",new J1({color:D1.default(),dim:!0,italic:!0}))})});return new D8({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new l0({decoration:{border:X,color:D1.default()},padding:B0.all(1),child:new b0({mainAxisAlignment:"center",children:[G,new X0({height:1}),K,q]})})})}}class ik1 extends E6{build(){return new j4({child:new y1({text:new i("",void 0,[new i(`✓ Thread Shared
|
|
4605
4605
|
|
|
@@ -4698,7 +4698,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
4698
4698
|
`)?`${K}...`:X,W=new J1({color:D1.index(8)}),H=[new i(q,W)];if(V>0){let z=new J1({color:Z.success});for(let U=1;U<=V;U++)H.push(new i(" ")),H.push(new i(`[${U}]`,z))}return new V6({padding:B0.only({bottom:0}),child:new R6({crossAxisAlignment:"start",children:[new V6({padding:B0.only({right:1}),child:new y1({text:new i("•",new J1({color:D1.index(8)}))})}),new a6({child:new y1({text:new i("",void 0,H)})})]})})}}class Iy1 extends c0{createState(){return new _Y6}}class _Y6 extends p0{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new J1({color:D1.red}),Z=new J1({color:this._visible?D1.red:D1.transparent()});return new R6({children:[new y1({text:new i("⏺",Z)}),new X0({width:1}),new y1({text:new i("Replay",Q)})]})}}class Py1 extends E6{entry;width;constructor({key:J,entry:Q,width:Z}){super({key:J});this.entry=Q,this.width=Z}build(J){let Z=Y6.of(J).colors.mutedForeground,Y=this.entry,X=Y.authors[0]?.name||"Community";if(X.includes("@"))X=X.split("@")[0]??X;let G=" · ",V=50,K=this.truncateToWidth(Y.title,V),q=`${G}${K}`,W=Math.max(1,this.width-q.length-2),H=Y.description.replace(/\s+/g," ").trim(),z=`@${X}: ${H}`,U=this.truncateToWidth(z,W),D=new y1({text:new i(U,new J1({color:Z,dim:!0}))}),M=new y1({text:new i(q,new J1({color:Z,dim:!0}))});return new G8({onClick:()=>eJ(J,Y.link),cursor:"pointer",child:new X0({width:this.width,height:1,child:new V6({padding:B0.horizontal(1),child:new R6({children:[new a6({child:new Km(new X0({width:W,height:1,child:D}))}),M]})})})})}truncateToWidth(J,Q){if(J.length<=Q)return J;return J.slice(0,Q-1)+"…"}}o0();function lL8(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/3600000),X=Math.floor(Y/24),G=Math.floor(X/7),V=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(G<=4)return`${G}w ago`;return`${V}mo ago`}class Ty1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Z)=>{let Y=this.threadHistoryService.observeThreadList().subscribe((X)=>{Y.unsubscribe(),Z(X)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((Y)=>{if(!Q.trim())return!0;let X=Y.title?.toLowerCase()||"untitled",G=Y.id.toLowerCase(),V=Q.toLowerCase();return X.includes(V)||G.includes(V)}).map((Y)=>{let X=new Date(Y.userLastInteractedAt),G=lL8(X),V=Y.id.slice(-8),K=Y.env?.initial.trees?.[0]?.uri;return{id:Y.id,title:Y.title||"Untitled",updatedAt:new Date(Y.userLastInteractedAt).toISOString(),description:{timeAgo:G,title:Y.title||"Untitled",shortThreadID:V},diffStats:Y.summaryStats?.diffStats,workspaceURI:K,parentRelationships:Y.parentRelationships}})}}U0();y8();class Ry1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new U7;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(rD()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function kY6(J,Q){switch(J){case"update-available":return[new i("A newer Amp is available. Run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new i("Update complete, run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning})),new i(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"update-error":return[new i("Update failed, run ",new J1({color:Q.foreground,dim:!0})),new i("amp update",new J1({color:Q.warning})),new i(" to see warnings",new J1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function rL8(J){return new Promise((Q)=>{nL8("git",["branch","--show-current"],{cwd:J},(Z,Y)=>{if(Z){Q(null);return}let X=Y.trim();Q(X||null)})})}class mY6 extends c0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new xy1}}class xy1 extends p0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingContextDetailOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteShowOptions=null;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new Ry1;previewThread=null;planScrollController=(()=>{let J=new U7;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new U7;return J.followMode=!1,J})();filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new w8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new w8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedTickerQueue=[];hasSubmittedFirstMessage=!1;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;previousThreadIdForHint=null;pendingMCPServers=[];mcpTrustSubscription=null;mcpServers=[];mcpServersSubscription=null;cacheTimerState=null;cacheTimerSubscription=null;agentModeController=null;freeTierStatus=void 0;agentModePulseSeq=0;agentModeSlideProgress=null;agentModeSlideTimer=null;updateState="hidden";updateServiceSubscription=null;toastController=new OS1;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];async initThreadFeed(){let J=await H6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Z=Q.includes("localhost")||Q.includes("127.0.0.1");try{let V=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(V.ok){let K=V.result,q="user"in K?K.user:K;this.currentUserInfo={username:q.username??void 0,displayName:q.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Z&&K.team?.id!==W)return}else return}catch(V){x.debug("Failed to fetch user info for thread feed filtering",V);return}let Y="/threads.rss",X=async(V,K)=>{let q=V instanceof Request?V.url:V.toString();return n2(q,K,this.widget.dependencies.configService)},G=ca0();G.get("entries").then((V)=>{if(V){let K=this.filterEntries(V);if(this.threadFeedEntries=K,K.length>0&&!this.currentThreadFeedEntry){let q=[...K].sort((H,z)=>z.pubDate.getTime()-H.pubDate.getTime());this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue];let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}),this.threadFeedReader=new hj1(G,X,{url:Y}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(V)=>{try{let K=this.filterEntries(V);if(K.length>0){this.threadFeedEntries=[...K,...this.threadFeedEntries];let q=[...K].sort((W,H)=>H.pubDate.getTime()-W.pubDate.getTime());if(this.threadFeedTickerQueue=[...q,...this.threadFeedTickerQueue],!this.currentThreadFeedEntry){let W=this.getNextFeedEntry();if(W)this.setState(()=>{this.currentThreadFeedEntry=W})}}}catch(K){x.error("Thread feed: error in next handler",K)}},error:(V)=>{x.error("Thread feed error:",V)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Z}=this.currentUserInfo;return J.filter((Y)=>{return!Y.authors.some((X)=>{let G=X.name;if(!G)return!1;return Q&&G===Q||Z&&G===Z||Q&&G.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{let J=this.getNextFeedEntry();if(J)this.setState(()=>{this.currentThreadFeedEntry=J})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(){if(this.threadFeedTickerQueue.length>0)return this.threadFeedTickerQueue.shift();return null}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.previousThreadIdForHint=J}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Z,baseWpm:Y}=J,X=Q.messages;for(let G=0;G<X.length;G++){if(this.replayAbortController.signal.aborted)break;let V=X[G];if(!V)continue;if(G>0)await this.replaySleep(J.messageDelayMs);if(V.role==="user"&&Z){let W=V.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
4699
4699
|
`);if(W)await this.replayTypeMessage(W,Y)}if(V.role==="assistant"){let W=V.content.some((U)=>U.type==="tool_use"),H=X[G+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...V,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let D=J.thread.id;this.getMessageScrollController(D).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),V]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,V],this.textController.clear()});let K=J.thread.id;this.getMessageScrollController(K).scrollToBottom()}await this.replaySleep(J.exitDelayMs),o8.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Z=J.split(/(?<=\s)/),Y=60000/Q;for(let X of Z){if(this.replayAbortController.signal.aborted)break;if(this.looksLikePastedContent(X.trim())){await this.replaySleep(150),this.textController.text=this.textController.text+X,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{}),await this.replaySleep(300);continue}let G=Y/X.length;for(let V of X){this.textController.text=this.textController.text+V,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let K=0.8+Math.random()*0.4,q=G*K;await this.replaySleep(q)}}}looksLikePastedContent(J){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(J))return!0;if(J.startsWith("/")&&J.length>10)return!0;if(/^[a-z]:\\/i.test(J))return!0;if(/^[a-f0-9]{7,40}$/i.test(J))return!0;if(/^T-[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(J))return!0;return!1}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return this.agentModeController?.getEffectiveMode()??"smart"}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((G)=>G.type==="toolResult").filter((G)=>G.toolResult.run.status==="in-progress"||G.toolResult.run.status==="queued"),Y=J.subagentActiveTools.filter((G)=>G.toolRun.status==="in-progress"||G.toolRun.status==="queued");return[...Z,...Y].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new i(this.submitDisabledHint,new J1({color:J.foreground,dim:!0}));if(this.isExiting)return new i("Exiting...",new J1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new i("",void 0,[new i("Ctrl+C",new J1({color:Q.keybind})),new i(" again to exit",new J1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" again to clear input",new J1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new i("",void 0,[new i("Escape",new J1({color:Q.keybind})),new i(" to close help",new J1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),G=yy1(X);return new i("",void 0,[new i("Images aren't supported in ",new J1({color:J.warning,dim:!1})),new i(X,new J1({color:G})),new i(" mode.",new J1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" again to cancel",new J1({color:J.foreground,dim:!0}))]);return new i("",void 0,[new i("Esc",new J1({color:Q.keybind})),new i(" to cancel",new J1({color:J.foreground,dim:!0}))])}if(this.statusMessage)return new i(this.statusMessage,new J1({color:J.foreground,dim:!0}));let Z=kY6(this.updateState,J);if(Z)return new i("",void 0,Z);let Y=this.widget.dependencies.worker.thread;if(Y.agentMode==="plan"&&TA(Y))return new i("",void 0,[new i("Ctrl+O",new J1({color:Q.keybind})),new i(" → Execute Plan",new J1({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let X=Q.mainThread?.messages.findIndex((G)=>G===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:X}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(G){x.error("Failed to edit message:",G)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:Y}=this.widget.dependencies,X=Q.mainThread?.id;if(!X)return;let G=Q.mainThread?.messages.findIndex((V)=>V===J);if(G===void 0||G<=0)return;try{let V=await J2.getOrCreateForThread(Z,X),K=await $R(V,Y,G-1);await this.switchToExistingThread(K)}catch(V){x.error("Failed to fork thread:",V),this.showErrorMessage(`Failed to fork thread: ${V}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:Y}=this.widget.dependencies,X=Z.mainThread;if(!X)return;let G=X.messages.findIndex((V)=>V.messageId!==void 0&&V.messageId===J.messageId);if(G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),this.widget.dependencies.history.add(Q);let V=vB(Q);if(V)await Y.handle({type:"thread:truncate",fromIndex:G}),this.invokeBashCommand(V.cmd,{visibility:V.visibility});else{let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:X.agentMode},W=G===0;if(X.agentMode&&!W&&q.agentMode!==X.agentMode){x.error(`Cannot edit message: This thread uses ${X.agentMode} mode. To change mode, create a new thread.`);return}await Y.handle({type:"user:message",message:q,index:G})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){x.error("Failed to edit message:",V)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(f2)}catch(Z){return x.error("Failed to get affected files:",Z),[]}};textController=new P$;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new U7);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let Y=this.searchElementTreeByKey(J.child,Q);if(Y)return Y}if(J?.children)for(let Y of J.children){let X=this.searchElementTreeByKey(Y,Q);if(X)return X}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{this.toastController.show("Selection copied to clipboard","success",2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),Y=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(oC1(Y))}}_handleTextCopy(J){if(J&&J.length>0)this.toastController.show("Selection copied to clipboard","success",2000)}textFieldKey=new m7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Z=vB(J)?.visibility;if(Z!==this.currentShellModeStatus)this.currentShellModeStatus=Z,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),m8.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),m8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteShowOptions=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new ak1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding,this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new sk1(this.widget.dependencies.fuzzyServer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})};getCommandPaletteContext=(J)=>{let{threadState:Q,recentThreadIDs:Z}=this.widget.dependencies;if(!Q.mainThread)return null;let Y=f0.file(process.cwd()),X=T6(Y);return{recentThreadIDs:Z,currentThreadID:Q.mainThread.id,context:J,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,V,K)=>{let q=this.widget.dependencies.threadState.mainThread?.id;if(!q)throw Error("No active thread");let W=setTimeout(()=>{K.throwIfAborted()},60000);try{let H=await this.widget.dependencies.threadService.generateHandoffPrompt(q,G,V,this.widget.dependencies.configService,K);return clearTimeout(W),H}catch(H){throw clearTimeout(W),H}},handleHandoff:async(G,V)=>{let{goal:K,generatedPrompt:q,images:W}=V;if(!K&&!q)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let H=this.widget.dependencies.threadState.mainThread?.id;if(!H)return{ok:!1,error:Error("No active thread")};let z=setTimeout(()=>G.abort(new N91("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let U=await this.widget.dependencies.threadService.createHandoffThread(H,{goal:K,generatedPrompt:q,images:W},this.widget.dependencies.configService,G.signal);return clearTimeout(z),await this.switchToExistingThread(U),{ok:!0}}catch(U){if(clearTimeout(z),U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")))throw G.signal.reason;throw U}}catch(H){return x.error("Failed to create handoff thread",H),{ok:!1,error:H instanceof Error?H:Error(String(H))}}},getGuidanceFiles:async(G)=>{if(!Q.mainThread)return[];return(await Ns({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,G)).map((K)=>({uri:K.uri,type:K.type}))},openIdePicker:()=>{this.openIdePicker()},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(G)=>{this.agentModeController?.setMode(G)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let G=Q.mainThread?.id;if(!G){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let V=await this.widget.dependencies.threadService.createPlanExecutionThread(G,"smart");await this.switchToExistingThread(V)}catch(G){x.error("Failed to execute plan",G),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${G instanceof Error?G.message:String(G)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,setThreadFeedHidden:(G)=>{this.setState(()=>{this.threadFeedHidden=G})},showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features??[],showStatusMessage:(G,V=2000)=>{if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=G}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},V)}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Ty1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await rL8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Z=Date.now(),Y=`bash-${Z}-${Math.random().toString(36).substring(7)}`,X={cmd:J},G=new AbortController;this.widget.dependencies.worker.invokeBashTool(X,G.signal,Q===xB).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((q)=>q.id===Y))this.bashInvocations=this.bashInvocations.map((q)=>q.id===Y?{...q,toolRun:V}:q);else{let q={id:Y,args:X,toolRun:V,startTime:Z,abortController:G,hidden:Q===xB};this.bashInvocations=[...this.bashInvocations,q]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0})};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.agentModeController.toggle())this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};startAgentModeSlide=()=>{if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer);this.setState(()=>{this.agentModeSlideProgress=0});let J=800,Q=16,Z=Q/J;this.agentModeSlideTimer=setInterval(()=>{this.setState(()=>{if(this.agentModeSlideProgress!==null){if(this.agentModeSlideProgress=Math.min(1,this.agentModeSlideProgress+Z),this.agentModeSlideProgress>=1){if(this.agentModeSlideProgress=null,this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null}}})},Q)};handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Gy(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=iF)return!1;let Z=ZC(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Z}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleCloseMysteryModal=()=>{this.setState(()=>{this.isShowingMysteriousMessageModal=!1})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Q)=>{if(!Q.ok)x.error("Failed to destruct mysterious message",Q.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Q)=>{x.error("Failed to destruct mysterious message",Q)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Z,unlink:Y,rmdir:X,writeFile:G}=await import("node:fs/promises"),{tmpdir:V}=await import("node:os"),K=await import("node:path");try{let q=await Q(K.join(V(),"amp-edit-")),W=K.join(q,"message.amp.md");await G(W,J,"utf-8"),await UV(W);try{let H=await Z(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")x.error("Failed to read temporary file",H)}try{await Y(W),await X(q)}catch(H){x.warn("Failed to clean up temporary file",H)}}catch(q){x.error("Error opening editor:",q)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=vB(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{this.setState(()=>{})};initState(){if(mY.getInstance().interceptConsole(),this.freeTierStatus=this.widget.dependencies.freeTierStatus,this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();o8.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),o8.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),o8.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{m8.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),H6(this.widget.dependencies.configService.config).then((Z)=>{this.paletteConfig=Z,this.agentModeController=new dj1({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.widget.dependencies.sessionState??null,freeTierStatus:this.freeTierStatus?{canUseAmpFree:this.freeTierStatus.canUseAmpFree,eligible:this.freeTierStatus.eligible,workspaceAllowsAmpFree:this.freeTierStatus.workspaceAllowsAmpFree}:void 0,initialSettings:Z.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.getCurrentWorker()?.thread??this.widget.dependencies.worker.thread}),this.agentModeController.addListener(this.agentModeListener)}),this.updateGitBranch(),this.adSubscription=Dj1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{let Z=this.agentModeController?.getMode();return(Z&&d9(Z)||this.randomAd===null)&&Nj1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let Y=aL8(16).toString("hex");this.lastAdImpressionId=Y,Promise.resolve().then(() => (d91(),p91)).then(({recordAdEvent:X})=>{let G=this.widget.dependencies.worker.thread,V=G.messages[G.messages.length-1];X("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:G.id,messageId:V?.messageId,impressionId:Y,placement:"tui",matchType:Z.metadata?.matchType,matchedPatterns:Z.metadata?.matchedPatterns,candidateAdPoolCount:Z.metadata?.candidateAdPoolCount,clientRegion:Z.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Z}),m8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Z)=>{this.setState(()=>{this.pendingMCPServers=Z})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Z)=>{this.setState(()=>{this.mcpServers=Z})}),this.cacheTimerSubscription=this.widget.dependencies.worker.cacheTimer.subscribe((Z)=>{this.setState(()=>{this.cacheTimerState=Z})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let Y=this.widget.dependencies.getCurrentWorker();if(!Y){x.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Y.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),x.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),x.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.mysteriousMessageSubscription=U41(this.widget.dependencies.configService).pipe(v5((Z)=>Z!=="pending"),Q6((Z)=>B41(Z)?Z.mysteriousMessage??null:null),N4((Z,Y)=>Z?.id===Y?.id)).subscribe((Z)=>{this.setState(()=>{if(Z?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Z,Z&&!this.mysterySequenceManager)this.mysterySequenceManager=new q81(new Map([[new K81(xy1.MYSTERY_SEQUENCE),new Lm]])),this.mysteryKeyInterceptorUnsubscribe=o8.instance.addKeyInterceptor((Y)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let X=this.mysterySequenceManager.handleKeyEvent(Y);if(X.consumed){if(X.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=X.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Z)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let Y=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.cacheTimerSubscription)this.cacheTimerSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.agentModeSlideTimer)clearInterval(this.agentModeSlideTimer),this.agentModeSlideTimer=null;if(this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(oC1("")),this.shouldUseProgressBar())process.stdout.write(F56())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Y=[...J.items.filter((K)=>K.type==="toolResult").map((K)=>({toolUse:K.toolUse,toolRun:K.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((K)=>K.toolRun.status==="blocked-on-user");if(Y.length===0)return null;let X=Y[0],G=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],V=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:G}],subthreadID:X.subthreadID,reason:V}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){x.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){x.error("No tool use block found in confirmation");return}if(J==="allow-all-session")DG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(X){if(X&&X instanceof Error)this.setState(()=>{this.displayMessage=X});else x.error("Failed to write dangerouslyAllowAll setting:",X);return}if(J==="always-guarded"){let X=Q.tools[0]?.toAllow??[],G=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],V=[...X,...G];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",V,"global")}if(J==="connect-github"){let X=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await eJ(this.context,X);return}if(J==="disable-librarian"){let X=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!X.includes(VY))await this.widget.dependencies.settingsStorage.set("tools.disable",[...X,VY],"global")}let Y=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let X={type:"user:tool-input",toolUse:Z.id,value:{accepted:Y}};if(Q.subthreadID)await(await J2.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(X);else await this.widget.dependencies.worker.handle(X)}catch(X){x.error("Failed to send tool confirmation:",X)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.agentModeController?.setMode("smart"),this.setState(()=>{this.dismissedEphemeralErrorKey=null}),e61({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette({type:"normal",commandId:"handoff"});break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await UV(Q.getSettingsFilePath())}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await J2.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Z=!0}=Q;if(Z){let Y=this.widget.dependencies.worker.thread.id;if(Y!==J)this.recordNavigation(Y)}try{x.info(`[switchToExistingThread] Switching to thread: ${J}`);let Y=await this.widget.dependencies.switchToThread(J);if(x.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${Y.thread.agentMode}`),this.widget.dependencies.worker=Y,this.widget.dependencies.threadID=Y.thread.id,this.widget.dependencies.switchWorker(Y),x.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null),Y.thread.draft)if(x.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Y.thread.draft==="string")this.textController.insertText(Y.thread.draft);else{let X=Y.thread.draft.filter((K)=>K.type==="text"),G=Y.thread.draft.filter((K)=>K.type==="image"),V=X.map((K)=>K.text).join(`
|
|
4700
4700
|
`);if(V)this.textController.insertText(V);if(G.length>0)this.setState(()=>{this.imageAttachments=G})}}catch(Y){throw x.error("Failed to switch to thread:",J,Y),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Z=m2(Q.thread)===0,Y=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&Y!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let X=[{type:"text",text:J}];if(this.imageAttachments.length>0)X.push(...this.imageAttachments);if(Z)this.startAgentModeSlide();if(await Q.handle({type:"user:message",message:{content:X,agentMode:Y}}),Z)e61({agentMode:Y});this.scrollMessageViewToBottom(),this.setState(()=>{if(this.imageAttachments=[],!this.hasSubmittedFirstMessage)this.hasSubmittedFirstMessage=!0}),m8.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((Y)=>Y.type==="handoff"&&Y.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();e61({agentMode:Q}).catch((Z)=>{x.warn("Failed to save session state on exit:",Z)}).finally(()=>{o8.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=oL8();if(J===Q)return"~";if(J.startsWith(Q+gm.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(gm.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(gm.sep),"…",Q.slice(-2).join(gm.sep)].join(gm.sep)}build(J){let Q=f4.of(J),Z=Y6.of(J),Y=Z.base;this.themeColors=Y;let{colors:X,app:G}=Z;this.themeApp=G;let V=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,K=V.thread.agentMode&&d9(V.thread.agentMode),q=K&&this.randomAd!==null,W=!K&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,H=Boolean(q),{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),D=this.widget.dependencies.replayMode,M=Boolean(D),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,I=z.todosList;if(M){let u6={...D.thread,messages:this.replayDisplayedMessages};L=LC(u6).items,A=u6,E={};let c6=gE({messages:this.replayDisplayedMessages});I=Array.isArray(c6)?c6:[]}let P=A?.id,C=A,k=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(u6)=>new z91({key:new m7(`preview-message-view-${u6.id}`),items:LC(u6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:u6,focusNode:new w8({debugLabel:"PreviewFocus"})}),v=this.previewThread,b=v?v.messages.length>2000?new b0({mainAxisSize:"max",children:[new a6({child:new X0}),new V6({padding:B0.all(2),child:new j4({child:new y1({text:new i("Thread too long for preview",new J1({color:X.mutedForeground,dim:!0}))})})})]}):y(v):k?new B91({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal}):new z91({key:P?new m7(`message-view-${P}`):void 0,items:L,subagentToolsByParentID:E,controller:P?this.getMessageScrollController(P):new U7,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:C,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),d=Math.max(Math.floor(Q.size.height*0.4),12),m=this.getCurrentEphemeralError(),n=Q.size.width<40,$1=z.mainThread?LM0(z.mainThread):void 0,t=Zz(J),p=this.buildBottomWidget(m,U,X,Z,z,I,d,H,M,$1,this.cacheTimerState??void 0,Q,t),e=new R81({threadViewState:z.viewState,threadTokenUsage:$1,threadID:P??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,mcpServers:this.mcpServers,isNarrow:n,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),F1=new P81({bashInvocations:this.bashInvocations}),q1=[];if(W&&this.currentThreadFeedEntry)q1.push(new Py1({entry:this.currentThreadFeedEntry,width:Q.size.width}));let o=this.getEffectiveAgentMode(),r=this.currentShellModeStatus,l=yy1(o),W1=!r?o.length+1:0,_1=Q.capabilities.animationSupport,s=_1==="disabled"?0:_1==="slow"?30:60,u1=DK(o)?.uiHints?.fasterAnimation?3:1,j1=s>0&&this.agentModePulseSeq>0?new x9({children:[p,new g5({top:0,left:1,right:1,height:1,child:new Ay1({color:l,trigger:this.agentModePulseSeq,fps:s,speed:u1,leftOffset:W1})})]}):p;q1.push(new a6({child:b}),F1);let R0=new x9({children:[new b0({mainAxisSize:"min",children:[q?new fk1({ad:this.randomAd,onButtonClick:async()=>{let u6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (d91(),p91)).then(({recordAdEvent:B9})=>{let O4=this.widget.dependencies.worker.thread,WJ=O4.messages[O4.messages.length-1];B9("clicked",{adId:u6.id,advertiserId:u6.advertiserId,threadId:O4.id,messageId:WJ?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:u6.metadata?.matchType,matchedPatterns:u6.metadata?.matchedPatterns,candidateAdPoolCount:u6.metadata?.candidateAdPoolCount,clientRegion:u6.metadata?.clientRegion})});if(!await eJ(this.context,u6.shortDestinationUrl)){let O4=o8.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:O4,url:u6.shortDestinationUrl}})}}}):new X0({height:0}),new l0({constraints:new A6(0,Q.size.width,0,d),child:j1})]}),H?new g5({top:0,left:0,right:0,child:new dY6({userHeight:this.bottomGridUserHeight,maxHeight:d,onInitializeHeight:(u6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(u6,d)})},onDrag:(u6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(u6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let c6=Math.floor(u6.localPosition.y)-this.bottomGridDragStartY,B9=Math.max(4,this.bottomGridDragStartHeight-c6),O4=Math.min(B9,d),WJ=Math.floor(O4);if(this.bottomGridUserHeight!==WJ)this.setState(()=>{this.bottomGridUserHeight=WJ})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new X0({height:0})]});q1.push(R0,new X0({height:1,child:new V6({padding:B0.horizontal(1),child:e})}));let C1=new b0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:q1}),z1=M&&D?.showIndicator!==!1?new x9({children:[C1,new g5({top:0,left:0,child:new Iy1})]}):C1,Z1=new T8(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((c6)=>{x.error("Failed to mark message as interrupted:",c6)}),this.cancelStreamingMessage().catch((c6)=>{x.error("Failed to cancel streaming message:",c6)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return x.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.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"ignored"}),O1=new T8(()=>{return this.onExitPressed(),"handled"}),A1=new T8(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),T1=new T8(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),S1=new T8(()=>{return GJ.instance.toggleAll(),"handled"}),c1=new T8(()=>{return this.widget.dependencies.configService.getLatest().then((u6)=>{DG("internal.showCost",!(u6.settings["internal.showCost"]??!0))}),"handled"}),g1=new T8(()=>{return o8.instance.toggleFrameStatsOverlay(),"handled"}),s1=new T8(()=>{return o8.instance.tuiInstance.getScreen().markForRefresh(),m8.instance.requestFrame(),"handled"}),K0=new T8(()=>{return this.toggleAgentMode(),"handled"}),q0=new T8(()=>{let c6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(c6){let B9=Math.max(Math.floor(Q.size.height*0.4),10),O4=Q.size.height-B9;c6.animatePageUp(O4,100)}return"handled"}),k0=new T8(()=>{let c6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(c6){let B9=Math.max(Math.floor(Q.size.height*0.4),10),O4=Q.size.height-B9;c6.animatePageDown(O4,100)}return"handled"}),v6=new T8(()=>{let c6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(c6)c6.animateTo(0,100);return"handled"}),m6=new T8(()=>{let c6=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:B9}=this.widget.dependencies,O4=B9.mainThread?.id;return O4?this.getMessageScrollController(O4):null})();if(c6)c6.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),e4=new T8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:u6}=this.widget.dependencies;if(!u6.mainThread?.messages.some((B9)=>B9.role==="user"||bE(B9)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),s8=new T8((u6)=>{if(u6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),a9=new T8(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return L81().then(async(u6)=>{if(u6)try{this.handleInsertImage(u6)}finally{try{let{unlink:c6}=await import("node:fs/promises");await c6(u6)}catch{}}}),"handled"}),E0=new Map([[K4.ctrl("c"),new zm],[K4.ctrl("l"),new Dm],[K4.ctrl("o"),new B81],[K4.ctrl("v"),new Wm],[K4.alt("s"),new GC],[K4.ctrl("s"),new GC],[K4.alt("p"),new Nm],[K4.ctrl("r"),new Um],[K4.alt("d"),new Bm],[K4.ctrl("t"),new Mm],[K4.key("PageUp"),new H81],[K4.key("PageDown"),new z81],[K4.key("Home"),new F81],[K4.key("End"),new U81],[K4.key("Escape"),new Hm],[K4.ctrl("p"),new VC("previous")],[K4.ctrl("n"),new VC("next")],[K4.key("Tab"),new Am]]);if(!v3())E0.set(K4.key("ArrowUp"),new Am);if(!1)E0.set(K4.alt("c"),new Fm);let Y4=new T8(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),Y8=new T8(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),u8=new T8(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),J7=new Map([[Hm,Z1],[Dm,s1],[GC,K0],[B81,Y4],[Wm,a9],[Fm,A1],[$81,T1],[Um,S1],[Bm,c1],[Nm,g1],[Mm,Y8],[zm,O1],[H81,q0],[z81,k0],[F81,v6],[U81,m6],[Am,e4],[VC,s8],[Lm,u8]]),p8=[z1];if(this.isShowingConsoleOverlay)p8.push(new Jy1);if(this.isShowingHelp&&this.paletteConfig)p8.push(new Xy1({commands:this.getPaletteCommands().getAllCommands()}));if(this.isShowingMCPStatusModal)p8.push(new Qk1({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)p8.push(new Ey1({message:this.mysteriousMessage,onClose:this.handleCloseMysteryModal,onDestruct:this.handleDestructMysteriousMessage}));if(this.adActionModal)p8.push(new hk1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(u6)=>{let c6=this.adActionModal.url;if(u6==="copy")try{await o8.instance.tuiInstance.clipboard.writeText(c6),this.setState(()=>{this.displayMessage=new cY("Link copied to clipboard")})}catch(B9){x.error("Failed to copy to clipboard",{error:B9}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:u6}=this.widget.dependencies;p8.push(new Oy1({servers:this.pendingMCPServers,onAlwaysTrust:u6.trustAlways.bind(u6),onTrustOnce:u6.trustOnce.bind(u6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:u6.deny.bind(u6)}))}if(this.isShowingFileChangesOverlay)p8.push(new kS1({threadData:z}));if(this.isShowingCostBreakdownOverlay&&z.mainThread)p8.push(new Zy1({thread:z.mainThread}));if(this.isShowingContextDetailOverlay)p8.push(new Qy1({thread:z.mainThread??void 0,tokenUsage:$1??void 0,cacheTimerState:this.cacheTimerState??void 0,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})}}));if(this.isShowingConfirmationOverlay)p8.push(new tk1({details:this.confirmationOverlayContent}));let Q7=this.getCommandPaletteContext(J);if(Q7&&this.isShowingPalette&&this.paletteConfig)p8.push(new j4({child:new l0({constraints:A6.loose(80,20),child:new rk1({commandContext:Q7,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})})}));if(this.isShowingIdePicker)p8.push(new Gy1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let k5=new x9({children:p8});if(this.isShowingJetBrainsInstaller)return new hA({child:new mQ({actions:J7,child:new DV({shortcuts:E0,debugLabel:"jetbrains-installer-shortcuts",child:new Ly1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new eH({controller:this.toastController,child:new hA({child:new wS1({controller:this.toastController,child:new mQ({actions:J7,child:new DV({shortcuts:E0,debugLabel:"main-app-shortcuts",child:k5})})})})})}buildScrollableTodoList(J,Q,Z){return new uY6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Z})}buildBottomWidget(J,Q,Z,Y,X,G,V,K,q,W,H,z,U){if(J)return new Yy1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new ek1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new wy1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let D=E81(Y),M=this.agentModeController?.isInRestrictedFreeMode()??!1,L=new sA({key:this.textFieldKey,controller:this.textController,triggers:q?[]:[new pB],completionBuilder:q?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:q?void 0:this.onTextSubmitted,theme:Z,placeholder:q?"Press Ctrl+C to exit":M?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!M&&!this.isShowingStandalonePalette(),shellPromptRules:D,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker,clipboard:o8.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let o=this.previousThreadIdForHint;if(o)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${o} `},onDoubleAtTrigger:q?void 0:()=>{let o=this.textController.text,r=this.textController.cursorPosition,W1=o.slice(0,r).lastIndexOf("@@");this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:()=>{if(W1!==-1){let _1=this.textController.text,s=_1.slice(0,W1)+_1.slice(W1+2);this.textController.text=s,this.textController.cursorPosition=W1}},onSubmit:()=>{this.dismissPalette()},onCancel:()=>{this.dismissPalette()}})}}),A=X.mainThread?.queuedMessages??[],E=Array.isArray(G)&&G.length>0,I=Array.isArray(A)&&A.length>0,P=X.mainThread?.agentMode==="plan"&&TA(X.mainThread),C,k;if(P){if(C=new Km(new F91({thread:X.mainThread,onExecute:async()=>{let o=this.getCommandPaletteContext();if(o)await this.getPaletteCommands().execute("execute-plan",o,void 0,new AbortController)},onEdit:async()=>{try{let o=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:r}=await this.widget.dependencies.planFileManager.ensureSync(X.mainThread.id);o8.instance.tuiInstance.suspend();let{execSync:l}=await import("child_process");l(`${o} "${r}"`,{stdio:"inherit"}),o8.instance.tuiInstance.resume()}catch(o){x.error("Failed to edit plan",o),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:Y}),{clipBehavior:"antiAlias"}),I)k=new u91({queuedMessages:A});else if(E)k=this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y)}else C=I?new u91({queuedMessages:A}):void 0,k=E?this.buildScrollableTodoList(G,this.isTextfieldAndAutocompleteFocused&&!M,Y):void 0;let y=[],v=this.currentShellModeStatus;if(v)y.push({child:new y1({text:new i(v==="hidden"?"shell mode (incognito)":"shell mode",new J1({color:v==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});let d=this.connectedClientsStatus&&this.connectedClientsStatus.enabled?this.connectedClientsStatusExpanded?(this.connectedClientsStatus?.clientID?.length??7)+3:3:0,m=this.agentModeController?.getVisibleModes()??[];if(!v&&m.length>1){let o=this.previewThread,r=o?o.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),l=yy1(r),W1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,_1=m2(W1.thread)>0,s=this.agentModeSlideProgress!==null,u1,j1;if(s){u1="top-left";let C1=z.size.width-r.length-4-d;j1=Math.floor(this.agentModeSlideProgress*C1)}else if(_1)u1="top-right",j1=d;else u1="top-left",j1=void 0;if(o)y.push({child:new y1({text:new i(r,new J1({color:l}))}),position:u1,offsetX:j1});else{let R0=!_1&&!s,C1=new y1({text:new i(r,new J1({color:l}))});y.push({child:R0?new G8({child:C1,onClick:this.toggleAgentMode,cursor:"pointer"}):C1,position:u1,offsetX:j1})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let o=this.connectedClientsStatus,r=o.mode||"disconnected",l=!!o.errorMessage,W1=o.clientID||"unknown",_1,s;if(l)_1="●",s=D1.red;else if(r==="presence")_1="○",s=D1.yellow;else if(r==="connected"&&o.connected)_1="●",s=D1.green;else _1="○",s=D1.yellow;let u1=this.connectedClientsStatusExpanded?`${W1} ${_1}`:_1;y.push({child:new G8({child:new y1({text:new i(u1,new J1({color:s}))}),onClick:this.toggleConnectedClientsStatus,cursor:"pointer"}),position:"top-right",offsetX:-2})}let n=q?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:X.mainThread?.env?.initial.trees?.[0]?.uri,$1;if(n)$1=f0.parse(n).fsPath;else $1=process.cwd();let t=this.toHomeRelative($1),p=this.shorten(t),e=!q&&this.currentGitBranch?`${p} (${this.currentGitBranch})`:p;y.push({child:new y1({text:new i(e,new J1({color:Z.foreground,dim:!0}))}),position:"bottom-right"});let F1=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(m2(F1.thread)>0&&!v){let o=[],r=new J1({color:Z.foreground,dim:!0}),l=new i(" · ",r);if(U&&X.mainThread){let W1=nt(X.mainThread);if(W1>0)o.push(new i(NV(W1),r))}if(W){if(o.length>0)o.push(l);let W1=W.totalInputTokens/W.maxInputTokens,_1=Math.round(W1*100),s=Math.max(0,Math.min(_1,100)),u1=T81(W1,W.maxInputTokens),j1=r;if(u1==="danger")j1=new J1({color:Z.destructive});else if(u1==="warning")j1=new J1({color:Z.warning});else if(u1==="recommendation")j1=new J1({color:Y.app.recommendation});o.push(new i(`${s}%`,j1))}if(U&&H){let W1=X.viewState.state==="active"&&X.viewState.inferenceState==="idle",_1=BZ6(H,{isNarrow:!0,isIdle:W1});if(_1){if(o.length>0)o.push(l);let s=r;if(_1.urgency==="warning")s=new J1({color:Z.warning});o.push(new i(_1.text,s))}}if(o.length>0){let W1=new y1({text:new i("",void 0,o)});y.push({child:U?new G8({child:W1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):W1,position:"top-left"})}}return new RS1({leftChild:new a6({child:L}),rightChild1:C,rightChild2:k,maxHeight:V,overlayTexts:y,borderColor:M||!this.isTextfieldAndAutocompleteFocused?D1.index(8):void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(o)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(o,V)})},onDrag:(o)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(o.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let r=Math.floor(o.localPosition.y)-this.bottomGridDragStartY,l=Math.max(4,this.bottomGridDragStartHeight-r),W1=Math.min(l,V),_1=Math.floor(W1);if(this.bottomGridUserHeight!==_1)this.setState(()=>{this.bottomGridUserHeight=_1})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}async function vy1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)o8.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let Y=()=>null,G=!1,V=new nH(G,1000,J.inspectorPort),K=J.features?.find((A)=>A.name==="amp-connect")?.enabled??!1,q=new xk1({threadService:J.threadService,worker:J.worker,builder:(A,E,I,P,C,k)=>{if(Y=C,J.threadDependencies&&K)uj1(J.threadDependencies,J.configService,C,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((b)=>{x.error("Failed to start automatic presence:",b)});let y=C(),v={...J,worker:y,threadID:y.thread.id};return new mY6({...v,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:C,recentThreadIDs:k})}}),W=new CS1({configService:J.configService,child:q}),H=new Yk1({configService:J.configService,child:W}),z=new US1(H),U=new Y6({data:KC.fromBaseTheme(I$.default()),child:z});try{await Wj1(U,{onRootElementMounted:(A)=>{if(x.info("TUI input ready for user interaction"),G)V.start(A)}})}finally{if(G)V.stop();if(J.threadDependencies&&K){let{stopGlobalSession:A}=await Promise.resolve().then(() => (pj1(),B36));A()}}let M=Y()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;f36(L,A,J.stdout)}}function yy1(J){let Z=DK(J)?.uiHints?.secondaryColor;if(Z)return D1.rgb(Z.r,Z.g,Z.b);return sL8(J)}class uY6 extends c0{props;constructor(J){super();this.props=J}createState(){return new pY6}}class pY6 extends p0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Z,appTheme:Y}=this.widget.props;return new R6({crossAxisAlignment:"stretch",children:[new a6({child:new S5({controller:Z,autofocus:!1,child:new vk1({todos:Q})})}),new Y2({controller:Z,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:G}=Z,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let G=Y.children||[];for(let V of G){if(V&&"size"in V){let q=V.size;if(typeof q?.height==="number"&&q.height>0)return q.height}let K=Q(V,X+1);if(K>0)return K}}return 0},Z=Q(J);if(Z>0)return Z;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class dY6 extends E6{props;constructor(J){super();this.props=J}build(J){return new G8({child:new X0({height:1}),cursor:C9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function sL8(J){let Q=0;for(let X=0;X<J.length;X++){let G=J.charCodeAt(X);Q=(Q<<5)-Q+G,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],Y=Math.abs(Q)%Z.length;return D1.index(Z[Y])}qj1();try{if(process.platform==="win32")await Promise.resolve().then(() => W6(uC(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){h$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
4701
|
-
`)}var Wv1=qv1.join(mF0||qv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function MI8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function v$(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")DG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")DG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")DG("model.sonnet",Q.useSonnet)}async function zv1(J){try{await BI8(qv1.dirname(Wv1),{recursive:!0}),await NI8(Wv1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function LI8(){try{return(await NV6(Wv1,"utf-8")).trim()}catch(J){return null}}var FV6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??M$,description:`Custom settings file path (overrides the default location ${M$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${UC1})`},{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:v3(),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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:kE.SMART.key,description:`Set the agent mode (${_X().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:_X().map((J)=>J.mode)}],UV6=(J)=>("deprecated"in J)&&J.deprecated===!0,AI8=(J)=>("hidden"in J)&&J.hidden===!0,OI8=(J)=>("default"in J),wI8=(J)=>("default"in J)?J.default:void 0;function EI8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new O8(D$.unknownCommand(Z),1,V)}}var DV6=null;function LI5(){return DV6}function Ku(J){return{...J,getThreadEnvironment:C61,vfs:eR0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new rx(J.fileSystem),generateThreadTitle:sa0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Fv1=f0.file(DI8.homedir()),MV6=process.env.XDG_CONFIG_HOME?f0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(Fv1,".config");async function f$(J,Q){SM0("0.0.
|
|
4701
|
+
`)}var Wv1=qv1.join(mF0||qv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function MI8(J){process.emitWarning=function(Q,Z,Y,X){let G=typeof Q==="string"?Q:Q.message||String(Q),V=Z||"Warning",K=!1;J.warn(G,{name:V,code:Y})}}function v$(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")DG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")DG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")DG("model.sonnet",Q.useSonnet)}async function zv1(J){try{await BI8(qv1.dirname(Wv1),{recursive:!0}),await NI8(Wv1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function LI8(){try{return(await NV6(Wv1,"utf-8")).trim()}catch(J){return null}}var FV6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??M$,description:`Custom settings file path (overrides the default location ${M$})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${UC1})`},{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:v3(),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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:kE.SMART.key,description:`Set the agent mode (${_X().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:_X().map((J)=>J.mode)}],UV6=(J)=>("deprecated"in J)&&J.deprecated===!0,AI8=(J)=>("hidden"in J)&&J.hidden===!0,OI8=(J)=>("default"in J),wI8=(J)=>("default"in J)?J.default:void 0;function EI8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new O8(D$.unknownCommand(Z),1,V)}}var DV6=null;function LI5(){return DV6}function Ku(J){return{...J,getThreadEnvironment:C61,vfs:eR0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new rx(J.fileSystem),generateThreadTitle:sa0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Fv1=f0.file(DI8.homedir()),MV6=process.env.XDG_CONFIG_HOME?f0.file(process.env.XDG_CONFIG_HOME):n0.joinPath(Fv1,".config");async function f$(J,Q){SM0("0.0.1764808732-gb9c377");let Z=Qz1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([f0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Fv1,userConfigDir:MV6}),{initializeCLITelemetry:Y}=await Promise.resolve().then(() => (d91(),p91));Y(Z);let X=await Z.getLatest();x.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=Ye0({configService:Z}),K=new Map,q=()=>K.clear(),W=new NB1(Z,J.settings.getWorkspaceRootPath()),H=GR0({configService:Z,trustStore:W,createOAuthProvider:async(t,p,e)=>{let F1=`${t}:${p}`,q1=K.get(F1);if(q1)return x.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:p}),q1;x.debug("Creating OAuth provider for server",{serverName:t,serverUrl:p});let o=(async()=>{let r=new UM(J.secrets),l=await r.getClientInfo(t,p),W1=e?.scopes??l?.scopes,_1=new bU1({storage:r,serverName:t,serverUrl:p,clientId:e?.clientId??l?.clientId,clientSecret:e?.clientSecret??l?.clientSecret,scopes:W1});return x.debug("OAuth provider created",{serverName:t,serverUrl:p,hasManualClientId:!!(e?.clientId??l?.clientId),willUseDCR:!(e?.clientId??l?.clientId),scopes:W1}),_1})();return K.set(F1,o),o}}),z=R01({configService:Z,filesystem:n8,spawn:eL}),{initializeToolProviders:U,startToolProviders:D}=await Promise.resolve().then(() => (zV6(),HV6)),M;if(J.executeMode){let t=await U({toolService:G,providers:[H,z],initialTimeout:15000});M=t.registrations;for(let[p,e]of t.initErrors)x.warn(`${p} provider initialization slow or failed:`,e)}else M=D({toolService:G,providers:[H,z]});if(Q.jetbrains)uE("JetBrains");else if(Q.ide&&V96())uE("VS Code");else if(Q.ide&&K96())uE("Neovim");if(J.executeMode)_M0(!0);let L,A=$3.status.pipe(Q6((t)=>Boolean(t.connected&&t.authenticated)),N4()).subscribe((t)=>{if(t){if(!L)L=G.registerTool(rr0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode)E=new g61(process.cwd(),{},!0);else E=new class extends g61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(D5.write(`No API key found. Starting login flow...
|
|
4702
4702
|
`),!await II8(J))await OA(),process.exit(1)}let I=await Sj0({isDevelopment:!1}),P=new BP1(I,Z),C=new HP1(I,{lazy:!0}),k=new TB1(P,(t,p)=>{let e=J2.get(t);if(e)e.handle(p).catch((F1)=>{x.error("Failed to apply artifact delta",F1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,v=$e0({playNotificationSound:async(t)=>{if(y){Xe0(t);let p=Vj1(),e=Kj1();if((!p||e)&&X.settings["notifications.system.enabled"]!==!1){if(t==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(t==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:P,configService:Z});x.info("Starting Amp background services");let b=ea0({threadService:P,threadHistoryService:C,configService:Z,isExtensionDevelopment:!1}),d;$3.status.subscribe((t)=>{d=t});let m=new u$1({workspaceRoots:[f0.file(process.cwd())],getCurrentFile:()=>{if(!d?.openFile)return;try{return f0.parse(d.openFile)}catch(t){x.warn("Failed to parse current file URI",{uri:d.openFile,error:t});return}},getOpenFiles:()=>{if(!d?.visibleFiles?.length)return[];let t=d.openFile;return d.visibleFiles.filter((p)=>p!==t).map((p)=>{try{return f0.parse(p)}catch(e){return x.warn("Failed to parse visible file URI",{uri:p,error:e}),null}}).filter((p)=>p!==null)}}),n=new Hj1,$1={codebaseContextService:m,configService:Z,toolService:G,mcpService:H,trustStore:W,threadService:P,threadHistoryService:C,threadSyncService:b,planFileManager:k,threadStorage:I,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:v,fileSystem:Q.jetbrains||Q.ide?rR0:n8,terminal:n};return{...$1,async asyncDispose(){if($1.mcpService.hasAuthenticatingClients())x.info("Waiting for OAuth authentication to complete before exit..."),await $1.mcpService.waitForAuthentication();for(let t of M.values())t.dispose();await $1.mcpService.dispose(),q(),await $1.threadService.asyncDispose(),$1.configService.unsubscribe(),V(),$1.fuzzyServer.dispose(),$1.threadSyncService.dispose(),$1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function II8(J){if(!J.executeMode){if(!await gC1("Would you like to log in to Amp? [(y)es, (n)o]: "))return D5.write(`Login cancelled. Run the command again to retry.
|
|
4703
4703
|
`),!1}return await LV6(J)}async function LV6(J){let Q=UI8(32).toString("hex"),Z=await bC1(J.ampURL,Q),Y=new AbortController;try{await CW(Z,Y.signal)}catch(G){x.error("Error opening browser",{error:G})}let X=await bC1(J.ampURL,Q,!1);D5.write(`If your browser does not open automatically, visit:
|
|
4704
4704
|
|
|
@@ -4708,7 +4708,7 @@ ${k4.blue.bold(X)}
|
|
|
4708
4708
|
Login successful! You can now use the Amp CLI.
|
|
4709
4709
|
`),!0}catch(G){return x.error("Login failed",{error:G}),h$.write(`
|
|
4710
4710
|
Login failed: ${G instanceof Error?G.message:String(G)}
|
|
4711
|
-
`),!1}}function PI8(){let J=new qA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)RR(),process.exit(0);let z=H.originalError??H;Q86(z)}),J.option("-V, --version","Print the version number and exit",()=>{D5.write(`0.0.
|
|
4711
|
+
`),!1}}function PI8(){let J=new qA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)RR(),process.exit(0);let z=H.originalError??H;Q86(z)}),J.option("-V, --version","Print the version number and exit",()=>{D5.write(`0.0.1764808732-gb9c377 (released 2025-12-04T00:44:17.586Z)
|
|
4712
4712
|
`),process.exit(0)}),J.addHelpText("after",X96()),J.configureHelp({formatHelp:$96}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await nQ(U);await jI8(D)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await nQ(U);await CI8(D,await RC1(U,D.settings))});let Q=async(H,z,U)=>{Qz1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:Q0.of([f0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:Fv1,userConfigDir:MV6});let D={...z,executeMode:!1};await Hv1(D,{...H,openThreadSwitcher:!0},U)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await nQ(U);await BV6(U,D,z)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await nQ(U);await fI8(U,D,z)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await nQ(D);if(z.pick)h$.write(`${k4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
4713
4713
|
`);if(z.last||H||M.executeMode)await vI8(D,M,H,U);else await Q(D,M,U)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await nQ(D);await xI8(D,M,H,U)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),D=await nQ(U);await BV6(U,D,z)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await nQ(D);await yI8(D,M,H,U,z.support)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,D)=>{let M=D.optsWithGlobals(),L=await nQ(M);await SI8(M,L,H,z,D)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await nQ(D);await _I8(D,M,H,U)}),Z.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,U)=>{let D=U.optsWithGlobals(),M=await nQ(D);await kI8(D,M,H,z,U)}),a56(J,async(H,z)=>{let U=await nQ(z);v$(H,z);let D=await f$(U,z);return{context:U,mcpService:D.mcpService,toolService:D.toolService,toolServices:D.toolService,configService:D.configService,cleanupTerminal:RR,asyncDispose:D.asyncDispose.bind(D)}}),p96(J,async(H)=>{let z=H.optsWithGlobals();return await nQ(z)}),k96(J,async(H)=>{let z=await nQ(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{v$(U,H);let D=await f$(z,H);return{mcpService:D.mcpService,settings:z.settings,asyncDispose:D.asyncDispose.bind(D)}}}});function X(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new Dq(z,M),A=wI8(H);if(A)L.default(A);if(L.hidden=AI8(H)||UV6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of FV6)switch(H.type){case"flag":{J.addOption(X(H,`--${H.long}`)),J.addOption(X(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(X(H,`--${H.long}`,!0));break}default:{J.addOption(X(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let G=new Dq("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(G);let V=new Dq("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let K=new Dq("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(K);let q=new Dq("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let W=new Dq("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let H=new Dq("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return Q76(J),J.action(async(H,z)=>{let U=H,D=await nQ(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")D5.write(k4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
|
|
4714
4714
|
`)),process.exit(0);if(Object.keys(U).forEach((L)=>{let A=FV6.find((E)=>E.name===L);if(A&&UV6(A)&&!OI8(A))h$.write(k4.yellow(`Warning: '--${L}' flag is deprecated
|
|
@@ -4716,8 +4716,8 @@ Login failed: ${G instanceof Error?G.message:String(G)}
|
|
|
4716
4716
|
Or pipe via stdin: echo "your message" | amp --execute`);v$(Z,Q);let V=await f$(J,Q);DV6=V;let K=Ku(V),q=async(n)=>{let $1=await NV6(n,"utf-8"),t=JSON.parse($1);if(!OG(t.id))throw new O8(D$.invalidThreadId);return _51(V,{visibility:Y,agentMode:Q.mode,thread:t})},W=async(n)=>{if(!OG(n))throw new O8(D$.invalidThreadId);try{let[t,p]=await Promise.all([X5.getThreadLinkInfo({thread:n},{config:V.configService}),X5.getUserInfo({},{config:V.configService})]);if(t.ok&&p.ok){let e=t.result.creatorUserID,F1=p.result.id;if(e&&e!==F1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new O8(`Cannot resume thread created by another user.
|
|
4717
4717
|
|
|
4718
4718
|
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.`)}}catch(t){if(t instanceof O8)throw t;x.warn("Failed to validate thread ownership in CLI, allowing to open",{error:t})}let $1=await V.threadService.get(n)??void 0;return x.info(`[fetchAndStartThread] Loaded thread ${n}, agentMode: ${$1?.agentMode??"undefined"}`),_51(V,{visibility:Y,agentMode:$1?void 0:Q.mode,thread:$1})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return _51(V,{visibility:Y,agentMode:Q.mode})}catch(n){if(n instanceof O8)throw n;throw await jg(n,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return _51(V,{visibility:Y,agentMode:Q.mode})};if(Q.format==="jsonl")h$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
4719
|
-
`),await OA(),process.exit(1);if(J.executeMode&&Q.remote)await d96(X,G,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)v96(V.mcpService,J.settings),await N86(U,U.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1;if(Q.jetbrains||Q.ide){await lM0();let n=cE({jetbrainsOnly:Q.jetbrains});if(n.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(n.length===1){let $1=n[0];if($1)$3.selectConfig($1)}else D=!0}let L=a61("0.0.
|
|
4720
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await p86({...J,workspaceTrust:{current:!0,changes:l_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await y96(J.mcpConfig);Y=x96(Y,G)}let X=await Y.get("url","global");if(!X)X=GZ;if(!BF(X))x.info("Targeting custom Amp server",{ampURL:X});return Y=gU0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:c96(await RC1(J,Y))}}function TI8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function RI8(){let J=TI8(process.argv);if(i46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),MI8(x),x.info("Starting Amp CLI.",{version:"0.0.
|
|
4719
|
+
`),await OA(),process.exit(1);if(J.executeMode&&Q.remote)await d96(X,G,V.configService),await V.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)v96(V.mcpService,J.settings),await N86(U,U.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await V.asyncDispose(),process.exit(0);let D=!1,M=!1;if(Q.jetbrains||Q.ide){await lM0();let n=cE({jetbrainsOnly:Q.jetbrains});if(n.length===0){if(Q.jetbrains)M=!await V.configService.get("jetbrains.skipInstall")}else if(n.length===1){let $1=n[0];if($1)$3.selectConfig($1)}else D=!0}let L=a61("0.0.1764808732-gb9c377",V.settingsStorage),A=new Q01(V.threadStorage),E=Q0.of([f0.file(process.cwd())]),I=t$1(void 0,E),P=new o61(V.mcpService,J.settings.getWorkspaceRootPath());if(X)U.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let C=(async()=>{try{let n=await X5.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(n.ok)return x.info("User free tier status:",n),n.result}catch(n){x.error("Failed to fetch free tier status:",n)}})(),k=(async()=>{try{let n=await X5.getUserInfo({},{config:V.configService});if(n.ok)return n.result}catch(n){x.debug("Failed to fetch user workspace info:",n)}})(),[y,v]=await Promise.all([C,k]),b=v?.email,d=b&&(b.endsWith("@sourcegraph.com")||b.endsWith("@ampcode.com")||b==="auth-bypass-user@example.com"),m=await n96();x.info("Loaded session state:",m),await vy1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new k61,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,planFileManager:V.planFileManager,threadID:U.threadID,threadFuzzyIndexer:A,worker:U,workerDeps:K,configService:V.configService,internalAPIClient:X5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:$3,connectedClientsService:new _n,commandRegistry:I,mcpService:V.mcpService,mcpTrustHandler:P,showJetBrainsInstaller:M,showIdePicker:D,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:m,freeTierStatus:y,workspace:v?.team??null,features:v?.features??[],isDogfooding:d||!1,threadDependencies:V,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function nQ(J){if(J.interactive)h$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
4720
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await p86({...J,workspaceTrust:{current:!0,changes:l_},getHook:process.env.AMP_URL?(G,V)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return V()}:void 0});if(J.mcpConfig){let G=await y96(J.mcpConfig);Y=x96(Y,G)}let X=await Y.get("url","global");if(!X)X=GZ;if(!BF(X))x.info("Targeting custom Amp server",{ampURL:X});return Y=gU0(Y),{executeMode:Q,isTTY:Z,ampURL:X,settings:Y,secrets:c96(await RC1(J,Y))}}function TI8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function RI8(){let J=TI8(process.argv);if(i46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),MI8(x),x.info("Starting Amp CLI.",{version:"0.0.1764808732-gb9c377",buildTimestamp:"2025-12-04T00:44:17.586Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new O8(D$.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await PI8().parseAsync(process.argv)}XP1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await RI8().catch(jg)});async function CI8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
4721
4721
|
`);else if(!BF(J.ampURL))D5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
4722
4722
|
`);let Z=process.env.AMP_API_KEY;if(Z)D5.write(`API key found in environment variable, storing...
|
|
4723
4723
|
`),await Q.set("apiKey",Z,J.ampURL),D5.write(`API key successfully stored.
|
|
@@ -4730,7 +4730,7 @@ This thread belongs to a different user and cannot be continued for security rea
|
|
|
4730
4730
|
`);else D5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
|
|
4731
4731
|
`);process.exit(0)}async function SI8(J,Q,Z,Y,X){v$(X,J);let G=await f$(Q,J);try{let V=k51(Z);if(!V)y51(Z);let K=V,q=Y.trim();if(q.length===0)x$("Thread name cannot be empty");if(q.length>256)x$("Thread name cannot exceed 256 characters");if(!(await pC(K,G)).messages.length)x$("Cannot rename an empty thread.");let H=Ku(G);await(await J2.getOrCreateForThread(H,K)).handle({type:"title",value:q}),x.info("GOT HERE"),await G.threadSyncService.sync(),x.info("GOT THERE"),D5.write(k4.green(`✓ Thread ${K} renamed to "${q}"
|
|
4732
4732
|
`)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;x$(K)}}async function _I8(J,Q,Z,Y){v$(Y,J);let X=await f$(Q,J);try{let G=k51(Z);if(!G)y51(Z);let K=await pC(G,X),q=YR(K);D5.write(q+`
|
|
4733
|
-
`),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;x$(V)}}async function kI8(J,Q,Z,Y,X){v$(X,J);let G=await f$(Q,J);try{let V=await Uv1(Z),K=await pC(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=Ku(G),L=K.id;await G.threadStorage.set(L,K);let A=await J2.getOrCreateForThread(M,L);await A.resume();let E=J01.fromWorker(A),I=new Q01(G.threadStorage),P=Q0.of([f0.file(process.cwd())]),C=t$1(void 0,P),k=new o61(G.mcpService,Q.settings.getWorkspaceRootPath()),y=a61("0.0.
|
|
4733
|
+
`),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;x$(V)}}async function kI8(J,Q,Z,Y,X){v$(X,J);let G=await f$(Q,J);try{let V=await Uv1(Z),K=await pC(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),U=parseInt(Y.exitDelay||"3",10)*1000,D=Y.indicator!==!1,M=Ku(G),L=K.id;await G.threadStorage.set(L,K);let A=await J2.getOrCreateForThread(M,L);await A.resume();let E=J01.fromWorker(A),I=new Q01(G.threadStorage),P=Q0.of([f0.file(process.cwd())]),C=t$1(void 0,P),k=new o61(G.mcpService,Q.settings.getWorkspaceRootPath()),y=a61("0.0.1764808732-gb9c377",G.settingsStorage);await vy1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new k61,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:G.configService,internalAPIClient:X5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:$3,connectedClientsService:new _n,commandRegistry:C,mcpService:G.mcpService,mcpTrustHandler:k,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:D}}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await jg(V,Z)}}async function yI8(J,Q,Z,Y,X){v$(Y,J);let G=await f$(Q,J);try{let V=k51(Z);if(!V)y51(Z);let K=V,q=await X5.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=r61(J,W);if(!H&&!X)x$("Must specify either --visibility or --support");if(H&&X)x$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)x$(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,s61(H)),D5.write(k4.green("✓ ")+`Thread ${K} visibility changed to ${H}.
|
|
4734
4734
|
`);if(X){await pC(K,G);let z=typeof X==="string"?X:void 0;await Ij0(G.threadService,K,G.configService,z),D5.write(k4.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
|
|
4735
4735
|
`)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),x$(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function xI8(J,Q,Z,Y){v$(Y,J);let X=await f$(Q,J),G=Ku(X);try{let V=await Uv1(Z),q=(await pC(V,X)).messages.length-1,W=await J2.getOrCreateForThread(G,V),H=await $R(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await zv1(H),D5.write(`${H}
|
|
4736
4736
|
`),await X.asyncDispose(),process.exit(0)}catch(V){h$.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
|