@sourcegraph/amp 0.0.1772654704-g8a92ca → 0.0.1772685027-gdb1277
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 +17 -14
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -3159,9 +3159,12 @@ Guidelines:
|
|
|
3159
3159
|
- Make one post_explanation tool call per paragraph or section.
|
|
3160
3160
|
- Each post_explanation call should include markdown text in text.
|
|
3161
3161
|
- Include file and line range metadata when a paragraph maps to a specific location.
|
|
3162
|
+
- Include the relevant unified diff hunk in the diff parameter when explaining a specific change.
|
|
3163
|
+
The diff should be a valid unified diff snippet with --- and +++ headers and @@ hunk headers.
|
|
3164
|
+
Keep diff hunks focused on the specific change being discussed, not the entire file diff.
|
|
3162
3165
|
- If your understanding changes, add a later post_explanation call that corrects earlier claims.
|
|
3163
3166
|
|
|
3164
|
-
Keep each explanation concise, concrete, and grounded in the actual diff.`;function R54(J){if(typeof J!=="number")return;if(!Number.isInteger(J)||J<1)return;return J}function BZ5(J){let Z=J.text.trim();if(!Z)return;let Q=typeof J.file==="string"?J.file.trim():void 0,Y=R54(J.startLine),X=R54(J.endLine);return{text:Z,file:Q&&Q.length>0?Q:void 0,startLine:Y,endLine:X}}function wZ5(J){return{spec:{name:tO1,description:"Post one markdown explanation paragraph for the code tour, optionally with file and line range metadata.",inputSchema:{type:"object",properties:{text:{type:"string",description:"Markdown paragraph for this explanation section."},file:{type:"string",description:"Optional file path that this explanation paragraph refers to."},startLine:{type:"number",description:"Optional starting line for the referenced file range."},endLine:{type:"number",description:"Optional ending line for the referenced file range."}},required:["text"]},source:"builtin",executionProfile:{resourceKeys:()=>[]}},fn:({args:Z})=>v0.of((()=>{let Q=BZ5(Z);if(!Q)return{status:"error",error:{message:"post_explanation requires a non-empty text value"}};return J.push(Q),{status:"done",result:"Explanation posted"}})())}}function NZ5(J,Z,Q,Y){return new v0((X)=>{let U=wZ5(Y),V=Z.registerTool(U),K=new i8,D=a3["code-tour"].model?n3(a3["code-tour"].model):void 0;if(!D){V.dispose(),X.error(Error("Code tour subagent has no model defined"));return}let z=[{role:"user",content:J}],q=K.run(MY,{systemPrompt:j54,model:D,spec:a3["code-tour"]},{conversation:z,toolService:Z,env:Q}).subscribe({next:(F)=>X.next(F),error:(F)=>X.error(F),complete:()=>X.complete()});return()=>{q.unsubscribe(),V.dispose()}})}function EZ5(J,Z){switch(J.status){case"in-progress":return{status:"in-progress",progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]}))};case"done":return{status:"done",result:[...Z],progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]})),"~debug":J["~debug"]};case"error":return{status:"error",error:{message:J.message}};case"cancelled":return{status:"cancelled",reason:"Code tour was cancelled"}}}var OZ5=({args:J},Z)=>{let Q=[];return E4(async()=>{let Y=typeof J.diff_description==="string"?J.diff_description:void 0,X=typeof J.focus==="string"?J.focus:void 0;return A54({diffDescription:Y,focus:X})}).pipe(s1((Y)=>{return P.debug("Code tour subagent starting",{hasDiffDescription:typeof J.diff_description==="string",hasFocus:typeof J.focus==="string"}),NZ5(Y,Z.toolService,Z,Q)}),H1((Y)=>EZ5(Y,Q)))},P54={spec:{name:sO1,description:`Generate a guided code tour for a diff. Use this when you need an explanation of what changed and why.
|
|
3167
|
+
Keep each explanation concise, concrete, and grounded in the actual diff.`;function R54(J){if(typeof J!=="number")return;if(!Number.isInteger(J)||J<1)return;return J}function BZ5(J){let Z=J.text.trim();if(!Z)return;let Q=typeof J.file==="string"?J.file.trim():void 0,Y=R54(J.startLine),X=R54(J.endLine),U=typeof J.diff==="string"?J.diff.trim():void 0;return{text:Z,file:Q&&Q.length>0?Q:void 0,startLine:Y,endLine:X,diff:U&&U.length>0?U:void 0}}function wZ5(J){return{spec:{name:tO1,description:"Post one markdown explanation paragraph for the code tour, optionally with file and line range metadata.",inputSchema:{type:"object",properties:{text:{type:"string",description:"Markdown paragraph for this explanation section."},file:{type:"string",description:"Optional file path that this explanation paragraph refers to."},startLine:{type:"number",description:"Optional starting line for the referenced file range."},endLine:{type:"number",description:"Optional ending line for the referenced file range."},diff:{type:"string",description:"Optional unified diff hunk for this explanation. Should be a valid unified diff snippet (with --- and +++ headers and @@ hunk headers)."}},required:["text"]},source:"builtin",executionProfile:{resourceKeys:()=>[]}},fn:({args:Z})=>v0.of((()=>{let Q=BZ5(Z);if(!Q)return{status:"error",error:{message:"post_explanation requires a non-empty text value"}};return J.push(Q),{status:"done",result:"Explanation posted"}})())}}function NZ5(J,Z,Q,Y){return new v0((X)=>{let U=wZ5(Y),V=Z.registerTool(U),K=new i8,D=a3["code-tour"].model?n3(a3["code-tour"].model):void 0;if(!D){V.dispose(),X.error(Error("Code tour subagent has no model defined"));return}let z=[{role:"user",content:J}],q=K.run(MY,{systemPrompt:j54,model:D,spec:a3["code-tour"]},{conversation:z,toolService:Z,env:Q}).subscribe({next:(F)=>X.next(F),error:(F)=>X.error(F),complete:()=>X.complete()});return()=>{q.unsubscribe(),V.dispose()}})}function EZ5(J,Z){switch(J.status){case"in-progress":return{status:"in-progress",progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]}))};case"done":return{status:"done",result:[...Z],progress:J.turns.map((Q)=>({message:Q.message,tool_uses:[...Q.activeTools.values()]})),"~debug":J["~debug"]};case"error":return{status:"error",error:{message:J.message}};case"cancelled":return{status:"cancelled",reason:"Code tour was cancelled"}}}var OZ5=({args:J},Z)=>{let Q=[];return E4(async()=>{let Y=typeof J.diff_description==="string"?J.diff_description:void 0,X=typeof J.focus==="string"?J.focus:void 0;return A54({diffDescription:Y,focus:X})}).pipe(s1((Y)=>{return P.debug("Code tour subagent starting",{hasDiffDescription:typeof J.diff_description==="string",hasFocus:typeof J.focus==="string"}),NZ5(Y,Z.toolService,Z,Q)}),H1((Y)=>EZ5(Y,Q)))},P54={spec:{name:sO1,description:`Generate a guided code tour for a diff. Use this when you need an explanation of what changed and why.
|
|
3165
3168
|
|
|
3166
3169
|
If diff_description is omitted, this tool defaults to the repository's outstanding changes (staged + unstaged).
|
|
3167
3170
|
|
|
@@ -6006,11 +6009,11 @@ ${W}`))}},error:(G)=>{if(!F)F=!0,K(Error(`Failed to spawn brew: ${G.message}`))}
|
|
|
6006
6009
|
${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
|
|
6007
6010
|
|
|
6008
6011
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6009
|
-
npm install -g @sourcegraph/amp`;K(Error(H))}},error:(G)=>{if(!q)q=!0,K(Error(`Failed to spawn ${X}: ${G.message}`))},complete:()=>{if(!q)q=!0,V()}})})}h0();h0();Jj();async function m30(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,U=new AbortController,V=setTimeout(()=>U.abort(),5000);try{let K=await fetch(X,{signal:U.signal});if(!K.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let D=await K.json(),z=D.version??D["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=HY4(J,z),F=q<0,G,W;if(D.time){let H=D.time[J],B=D.time[z],w=Date.now();if(H)G=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:F,currentVersionAge:G,latestVersionAge:W}),{hasUpdate:F,latestVersion:z,currentVersion:J,currentVersionAge:G,latestVersionAge:W,source:"npm"}}catch(K){return P.debug("Error checking npm version",{error:K}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var uN5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function g30(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${uN5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let U=HY4(J,X),V=U<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:U,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var xN5=604800000;function WY4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>xN5)return{ageMs:Q};return null}function HY4(J,Z){let Q=(V)=>{let[K,D]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:D}},Y=Q(J),X=Q(Z),U=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<U;V++){let K=Y.parts[V]||0,D=X.parts[V]||0;if(K<D)return-1;if(K>D)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Zu0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?WG(Q):void 0;return{sha:Y,age:X}}catch{return null}}W1();function Qu0(J,Z,Q={}){let Y=new X4,X=Y.pipe(L6({shouldCountRefs:!1}));return setImmediate(async()=>{let U=new BV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await nV(V);let K=X.subscribe({next:(D)=>{U.debug("emit new state",D)}});try{let D=process.env.AMP_TEST_UPDATE_STATUS;if(D){U.debug("using fake update status for testing",{status:D}),await nV(500),Y.next(D);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){U.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){U.debug("checking disabled");return}let q=await h30(),F=q==="binary"||q==="brew";U.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:F});let G=F?await g30(J):await m30(J,IO());if(!(G.latestVersion&&G.hasUpdate)){U.debug("no update available");return}let W=()=>{if(G.currentVersionAge!==void 0&&G.latestVersionAge!==void 0){let H=G.currentVersionAge-G.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return U.debug("versions too close together, suppressing update warning",{currentVersionAge:G.currentVersionAge,latestVersionAge:G.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",U.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!W())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ry0()){if(U.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!W())Y.next("update-available");return}if(!q){if(U.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(U.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await qm(G.latestVersion,q);let H=await nW(G.latestVersion),B={from:G.currentVersion,to:G.latestVersion,...H};if(H.status==="same")U.info("success",B),Y.next("updated");else U.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(D){U.debug("check failed",{error:D})}finally{await nV(5000),Y.next("hidden"),K.unsubscribe(),Y.complete()}}),{state:X}}Jj();import{stderr as xK}from"node:process";function BY4(J){let Z=new yW().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 iy0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6012
|
+
npm install -g @sourcegraph/amp`;K(Error(H))}},error:(G)=>{if(!q)q=!0,K(Error(`Failed to spawn ${X}: ${G.message}`))},complete:()=>{if(!q)q=!0,V()}})})}h0();h0();Jj();async function m30(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,U=new AbortController,V=setTimeout(()=>U.abort(),5000);try{let K=await fetch(X,{signal:U.signal});if(!K.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let D=await K.json(),z=D.version??D["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=HY4(J,z),F=q<0,G,W;if(D.time){let H=D.time[J],B=D.time[z],w=Date.now();if(H)G=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:F,currentVersionAge:G,latestVersionAge:W}),{hasUpdate:F,latestVersion:z,currentVersion:J,currentVersionAge:G,latestVersionAge:W,source:"npm"}}catch(K){return P.debug("Error checking npm version",{error:K}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var uN5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function g30(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${uN5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let U=HY4(J,X),V=U<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:U,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var xN5=604800000;function WY4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>xN5)return{ageMs:Q};return null}function HY4(J,Z){let Q=(V)=>{let[K,D]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:D}},Y=Q(J),X=Q(Z),U=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<U;V++){let K=Y.parts[V]||0,D=X.parts[V]||0;if(K<D)return-1;if(K>D)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Zu0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?WG(Q):void 0;return{sha:Y,age:X}}catch{return null}}W1();function Qu0(J,Z,Q={}){let Y=new X4,X=Y.pipe(L6({shouldCountRefs:!1}));return setImmediate(async()=>{let U=new BV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await nV(V);let K=X.subscribe({next:(D)=>{U.debug("emit new state",D)}});try{let D=process.env.AMP_TEST_UPDATE_STATUS;if(D){U.debug("using fake update status for testing",{status:D}),await nV(500),Y.next(D);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){U.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){U.debug("checking disabled");return}let q=await h30(),F=q==="binary"||q==="brew";U.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:F});let G=F?await g30(J):await m30(J,IO());if(!(G.latestVersion&&G.hasUpdate)){U.debug("no update available");return}let W=()=>{if(G.currentVersionAge!==void 0&&G.latestVersionAge!==void 0){let H=G.currentVersionAge-G.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return U.debug("versions too close together, suppressing update warning",{currentVersionAge:G.currentVersionAge,latestVersionAge:G.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",U.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!W())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ry0()){if(U.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!W())Y.next("update-available");return}if(!q){if(U.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(U.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await qm(G.latestVersion,q);let H=await nW(G.latestVersion),B={from:G.currentVersion,to:G.latestVersion,...H};if(H.status==="same")U.info("success",B),Y.next("updated");else U.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(D){U.debug("check failed",{error:D})}finally{await nV(5000),Y.next("hidden"),K.unsubscribe(),Y.complete()}}),{state:X}}Jj();import{stderr as xK}from"node:process";function BY4(J){let Z=new yW().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 iy0(Y.force||!1,Y.verbose||!1,"0.0.1772685027-gdb1277"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new yW("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 fN5(Y.targetVersion)});J.addCommand(Q)}async function fN5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")xK.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6010
6013
|
|
|
6011
6014
|
`));try{if(!J){xK.write(Z1.blue(`Checking for updates...
|
|
6012
|
-
`));let{hasUpdate:Y,latestVersion:X}=ny0()?await g30("0.0.
|
|
6013
|
-
`));let K=await nW("0.0.
|
|
6015
|
+
`));let{hasUpdate:Y,latestVersion:X}=ny0()?await g30("0.0.1772685027-gdb1277"):await m30("0.0.1772685027-gdb1277",IO());if(!Y){let U=Zu0("0.0.1772685027-gdb1277"),V=U?.age?`released ${U.age} ago`:`built ${WG(new Date("2026-03-05T04:36:12.856Z"))} ago`;xK.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1772685027-gdb1277"} (${V})
|
|
6016
|
+
`));let K=await nW("0.0.1772685027-gdb1277");if(K.warning)xK.write(`
|
|
6014
6017
|
`+Z1.yellow(K.warning)+`
|
|
6015
6018
|
`);process.exit(0)}if(!X)xK.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}xK.write(Z1.blue(`Updating to version ${J}...
|
|
6016
6019
|
`)),await qm(J,void 0,(Y)=>{xK.write(Z1.dim(`Running: ${Y}
|
|
@@ -6334,7 +6337,7 @@ To fix: Add "amp.mcpTrustedWorkspaces": ["${Z.getWorkspaceRootPath()}"] to ${Y}
|
|
|
6334
6337
|
`)}};function NE5(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y&&Y.startsWith("--")){let X=Y.slice(2),U=J[Q+1];if(U&&!U.startsWith("--"))Z[X]=U,Q++}}return Z}function EE5(J){if(J.action==="ask")return 1;if(J.action==="reject")return 2;return 0}async function xY4(J){let Z=J.json?BE5:wE5;try{let Q=NE5(J.remainingArgs),Y=await J.settings.get("permissions",J.scope)??[],X=uF(Y);if(!X.success){let V={success:!1,error:"Invalid permissions configuration",details:X.error.issues.map((K)=>({path:K.path.join("."),message:K.message,code:K.code}))};Z.outputError(J,Q,V),J.exit(1);return}let U=await gM(J.toolName,Q,X.data,J.context,$k,J.threadId,"user");if(!U.matchedEntry)U=await gM(J.toolName,Q,mM,J.context,$k,J.threadId,"built-in");Z.outputResult(J,Q,U),J.exit(EE5(U))}catch(Q){let Y={success:!1,error:Q instanceof Error?Q.message:"Unknown error"};Z.outputError(J,{},Y),J.exit(1)}}function fY4(J,Z){let Q=J.command("permissions").alias("permission").summary("Manage permissions").description(`Configure and test tool permissions to control what actions the AI agent can take.
|
|
6335
6338
|
|
|
6336
6339
|
See ${Z1.underline("https://ampcode.com/manual#permissions")} for more details`).enablePositionalOptions();OE5(Q,Z),LE5(Q,Z),IE5(Q,Z),ME5(Q,Z)}function OE5(J,Z){J.command("list").alias("ls").summary("List permissions").description("List user-configured permissions.").option("--json","output as JSON").option("--builtin","output only builtin permissions").option("-w, --workspace","List workspace permissions instead of global").action(async(Q,Y)=>{let X=await Z(Y),U=Y.optsWithGlobals();await uY4({builtinOnly:U.builtin??!1,settings:X.settings,exit:process.exit.bind(process),json:U.json,stdout:process.stdout,scope:U.workspace?"workspace":"global"})})}function LE5(J,Z){J.command("test").summary("Test permissions").description("Test permissions against configured rules without running the tool.").argument("<tool-name>","Name of the tool to test").option("-c, --context <context>","Execution context (thread or subagent)").option("-t, --thread-id <id>","Thread ID for evaluation").option("--json","output as JSON").option("-q, --quiet","suppress output, only use exit status").option("-w, --workspace","Test against workspace permissions instead of global").allowUnknownOption(!0).action(async(Q,Y,X)=>{let U=await Z(X),V=()=>!1;await xY4({toolName:Q,context:Y.context,threadId:Y.threadId,json:Y.json,settings:U.settings,remainingArgs:X.args,stdout:Y.quiet?{write:V}:process.stdout,stderr:process.stderr,exit:process.exit.bind(process),scope:Y.workspace?"workspace":"global"})}).addHelpText("after",["Example: "," # Test permissions of Amp trying to use bash"," amp permissions test Bash --cmd ls"," # ...when running in a subagent"," amp permissions test --context subagent Bash --cmd ls","","See output of:",""," amp tools show","","for all tool schemas."].join(`
|
|
6337
|
-
`))}function IE5(J,Z){J.command("edit").summary("Edit permissions").description("Edit permissions interactively in your $EDITOR or from stdin.").option("-w, --workspace","Edit workspace permissions instead of global").action(async(Q,Y)=>{let X=await Z(Y);await d30({settings:X.settings,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exit:process.exit.bind(process),resolveEditor:QC,scope:Q.workspace?"workspace":"global"})})}function ME5(J,Z){J.command("add").summary("Add permission rule").description("Add a permission rule to the beginning of the list. Rules are evaluated in order, so newer rules take precedence.").argument("<action>","Permission action: allow, reject, ask, or delegate").option("--to <program>","Program to delegate decision to for delegate action").option("--context <type>","Limit to specific context (thread or subagent)").option("-w, --workspace","Add to workspace permissions instead of global").argument("<tool>",'Tool name (supports globs like "mcp__playwright__*")').allowUnknownOption(!0).action(async(Q,Y,X,U)=>{let V=await Z(U);await SY4({args:U.parent?.args.slice(1)??[],settings:V.settings,stderr:process.stderr,exit:process.exit.bind(process),scope:X.workspace?"workspace":"global"})})}h0();import{exec as AE5}from"node:child_process";import{platform as jE5}from"node:os";import{stderr as YC}from"node:process";x9();async function bY4(J,Z,Q){let U=(await(await yJ({configService:Z},Q)).messages.create({model:sV,max_tokens:300,system:"You are a classifier that answers yes/no questions. You must use the provided tool to give your answer with reasoning.",messages:[{role:"user",content:J}],tools:[{name:"answer_question",description:"Provide your answer to the yes/no question with reasoning",input_schema:{type:"object",properties:{probability_yes:{type:"number",description:'Probability that the answer is "yes", from 0 to 1. Use 0 for definitely no, 0.5 for uncertain, 1 for definitely yes.'},reasoning:{type:"string",description:"Brief (2-sentence max) explanation of why you gave this probability."}},required:["probability_yes","reasoning"]}}],tool_choice:{type:"tool",name:"answer_question"}},{headers:{"anthropic-beta":"interleaved-thinking-2025-05-14"}})).content.find((q)=>q.type==="tool_use");if(!U||U.type!=="tool_use")throw Error("Expected tool use response from Claude");let V=U.input,K=V.probability_yes??0.5,D=V.reasoning??"No reasoning provided",z;if(K>=0.8)z="yes";else if(K<0.2)z="no";else z="uncertain";return{result:z,probability:K,reason:D}}class Vu0{clientKind="terminal";clientVersion="0.0.
|
|
6340
|
+
`))}function IE5(J,Z){J.command("edit").summary("Edit permissions").description("Edit permissions interactively in your $EDITOR or from stdin.").option("-w, --workspace","Edit workspace permissions instead of global").action(async(Q,Y)=>{let X=await Z(Y);await d30({settings:X.settings,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exit:process.exit.bind(process),resolveEditor:QC,scope:Q.workspace?"workspace":"global"})})}function ME5(J,Z){J.command("add").summary("Add permission rule").description("Add a permission rule to the beginning of the list. Rules are evaluated in order, so newer rules take precedence.").argument("<action>","Permission action: allow, reject, ask, or delegate").option("--to <program>","Program to delegate decision to for delegate action").option("--context <type>","Limit to specific context (thread or subagent)").option("-w, --workspace","Add to workspace permissions instead of global").argument("<tool>",'Tool name (supports globs like "mcp__playwright__*")').allowUnknownOption(!0).action(async(Q,Y,X,U)=>{let V=await Z(U);await SY4({args:U.parent?.args.slice(1)??[],settings:V.settings,stderr:process.stderr,exit:process.exit.bind(process),scope:X.workspace?"workspace":"global"})})}h0();import{exec as AE5}from"node:child_process";import{platform as jE5}from"node:os";import{stderr as YC}from"node:process";x9();async function bY4(J,Z,Q){let U=(await(await yJ({configService:Z},Q)).messages.create({model:sV,max_tokens:300,system:"You are a classifier that answers yes/no questions. You must use the provided tool to give your answer with reasoning.",messages:[{role:"user",content:J}],tools:[{name:"answer_question",description:"Provide your answer to the yes/no question with reasoning",input_schema:{type:"object",properties:{probability_yes:{type:"number",description:'Probability that the answer is "yes", from 0 to 1. Use 0 for definitely no, 0.5 for uncertain, 1 for definitely yes.'},reasoning:{type:"string",description:"Brief (2-sentence max) explanation of why you gave this probability."}},required:["probability_yes","reasoning"]}}],tool_choice:{type:"tool",name:"answer_question"}},{headers:{"anthropic-beta":"interleaved-thinking-2025-05-14"}})).content.find((q)=>q.type==="tool_use");if(!U||U.type!=="tool_use")throw Error("Expected tool use response from Claude");let V=U.input,K=V.probability_yes??0.5,D=V.reasoning??"No reasoning provided",z;if(K>=0.8)z="yes";else if(K<0.2)z="no";else z="uncertain";return{result:z,probability:K,reason:D}}class Vu0{clientKind="terminal";clientVersion="0.0.1772685027-gdb1277";showToast=null;appendToThreadHandler=null;showOpenedURLToast=null;showInputDialog=null;showConfirmDialog=null;configService;constructor(J){this.configService=J.configService}async notify(J){if(this.showToast)this.showToast(J);else P.debug("plugin notification (TUI not loaded): %s",J)}async open(J){let Z=jE5(),Q=Z==="darwin"?"open":Z==="win32"?"start":"xdg-open";if(await new Promise((Y,X)=>{AE5(`${Q} ${JSON.stringify(J)}`,(U)=>{if(U)X(U);else Y()})}),this.showOpenedURLToast)this.showOpenedURLToast(J);else YC.write(`
|
|
6338
6341
|
Opened URL: ${J}
|
|
6339
6342
|
|
|
6340
6343
|
`)}async input(J){if(this.showInputDialog)return this.showInputDialog(J);YC.write(`
|
|
@@ -7166,7 +7169,7 @@ Ctrl-X, Y, Z to unlock`;if(G){let f=z.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7166
7169
|
`),U=[];for(let V=0;V<X.length;V++){let z=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))U.push(new C(q.slice(1,-1),new b({color:Y.app.keybind,bold:!0})));else U.push(new C(q,new b({color:Q.colorScheme.foreground})));if(V<X.length-1)U.push(new C(`
|
|
7167
7170
|
`))}return new d0({decoration:{color:Q.colorScheme.background,border:f1.all(new y1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new Q0({text:new C(void 0,void 0,U)})})})}}class zm0 extends F2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=z20}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Km0({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function ZH4(J,Z,Q,Y,X,U,V){if(U<=0)return null;switch(J){case"horizontal-bar":{let K=Q;return K>=0&&K<U?K:null}case"bar":case"stacked-bar":{let K=V?f8:0,D=Y-K;if(D<=0)return null;let z=Z-K;if(z<0||z>=D)return null;let q=Math.max(1,Math.floor(D/U)),F=Math.floor(z/q);return F>=0&&F<U?F:null}case"line":case"sparkline":case"stacked-area":{let K=V?f8:0,D=Y-K;if(D<=0)return null;let z=Math.max(0,Math.min(D-1,Z-K));if(U===1)return 0;let q=D/(U-1),F=Math.round(z/q);return Math.max(0,Math.min(U-1,F))}default:return null}}function Yb5(J,Z,Q,Y,X,U,V,K){if(X<=0||Z<0||Z>=X)return null;let D=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=U?f8:0,q=Q-z,F=Y-(U?D:0);if(q<=0||F<=0)return null;let G=Math.max(1,Math.floor(q/X)),W=z+Z*G+Math.floor(G/2),H=K>0?V/K:0,B=Math.round((1-H)*(F-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let z=U?f8:0,q=Q-z,F=Y-(U?D:0);if(q<=0||F<=0)return null;let G=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),W=K>0?V/K:0,H=Math.round((1-W)*(F-1));return{x:G,y:H}}default:return null}}function Xb5(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function Ub5(J,Z,Q,Y,X){if(Q.length<=1){let K=Y(J.value),D=J.meta?` (${J.meta})`:"";return J.label.length+2+K.length+D.length}let U=J.label.length,V=0;for(let K of Q){let D=K.points[Z];if(!D)continue;V+=D.value;let z=2+K.name.length+2+Y(D.value).length;U=Math.max(U,z)}if(X){let K=9+Y(V).length;U=Math.max(U,K)}return U}function Vb5(J,Z,Q,Y,X,U,V){let K;try{let H=R1.of(J),B=f0.of(J);K={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{K={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let D=new b({color:K.foreground,bold:!0}),z=new b({color:K.foreground}),q=new b({color:K.foreground,dim:!0}),F=[],G=new b({color:K.foreground,underline:!0}),W=(H,B)=>new C(B,G,void 0,e30(H),()=>{K8(J,H)});if(Y.length<=1){if(F.push(new C(`${Z.label}: `,D)),Z.link)F.push(W(Z.link,U(Z.value)));else F.push(new C(U(Z.value),z));if(Z.meta)F.push(new C(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";F.push(new C(`${Z.label}
|
|
7168
7171
|
`,D));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],E=N.points[Q];if(!E)continue;B+=E.value;let O=N.color??X[w%X.length]??K.foreground;if(F.push(new C("● ",new b({color:O}))),F.push(new C(`${N.name}: `,q)),E.link)F.push(W(E.link,U(E.value)));else F.push(new C(U(E.value),z));if(w<Y.length-1||H)F.push(new C(`
|
|
7169
|
-
`))}if(H)F.push(new C(" ",q)),F.push(new C("Total: ",q)),F.push(new C(U(B),z))}return new d0({decoration:{color:K.background,border:f1.all(new y1(K.border,1,"rounded"))},child:new Q0({text:new C(void 0,void 0,F)})})}h0();n9();import{execSync as ub5}from"node:child_process";ZA();FJ();O3();w7();_w();MX();L$();TJ();EX();rE();f4();xu();Sv();W1();var oH4=I4(Bz(),1);import{writeFile as cH4}from"fs/promises";import lH4 from"path";h0();L$();class qm0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1772654704-g8a92ca"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await us(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class yH extends p0{props;constructor(J){super();this.props=J}createState(){return new QH4}}class QH4 extends g0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class YH4 extends g0{controller=new u7;focusNode=new n4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,U=this.controller.text.trim().length>0,V=!X||U,K=f1.all(new y1(Q.foreground,1,"solid")),D=new i$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new D1({children:[new d0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:D})]}),q=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,[new C("Command: ",new b({color:Q.foreground})),new C(this.widget.props.commandName,new b({color:Y.command,bold:!0}))])})}),F=[];if(V)F.push(new C("Enter",new b({color:Y.keybind}))),F.push(new C(" to submit, ",new b({color:Q.foreground,dim:!0})));F.push(new C("Esc",new b({color:Y.keybind}))),F.push(new C(" to cancel",new b({color:Q.foreground,dim:!0})));let G=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,F)})});return new d0({decoration:{border:K,color:Q.background},padding:C0.all(1),child:new u0({children:[q,new j0({height:1}),z,new Z3,G]})})}}class $p extends p0{props;constructor(J){super();this.props=J}createState(){return new YH4}}import{isDeepStrictEqual as Fm0}from"node:util";var Kb5=/[\\/_ +.#"@[({&]/,Db5=/[\\/_ +.#"@[({&]/g,zb5=/[\s-]/,XH4=/[\s-]/g;function G20(J,Z,Q,Y,X,U,V){if(U===Z.length){if(X===J.length)return 1;return 0.99}let K=`${X},${U}`;if(V[K]!==void 0)return V[K];let D=Y.charAt(U),z=Q.indexOf(D,X),q=0,F,G,W,H;while(z>=0){if(F=G20(J,Z,Q,Y,z+1,U+1,V),F>q){if(z===X)F*=1;else if(zb5.test(J.charAt(z-1))){if(F*=0.9,H=J.slice(X,z-1).match(XH4),H&&X>0)F*=0.999**H.length}else if(Kb5.test(J.charAt(z-1))){if(F*=0.8,W=J.slice(X,z-1).match(Db5),W&&X>0)F*=0.999**W.length}else if(F*=0.3,X>0)F*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(U))F*=0.9999}if(F<0.1&&(Q.charAt(z-1)===Y.charAt(U+1)||Y.charAt(U+1)===Y.charAt(U)&&Q.charAt(z-1)!==Y.charAt(U))){if(G=G20(J,Z,Q,Y,z+1,U+2,V),G*0.1>F)F=G*0.1}if(F>q)q=F;z=Q.indexOf(D,z+1)}return V[K]=q,q}function F20(J){return J.toLowerCase().replace(XH4," ")}function UH4(J,Z){let Q=G20(J,Z,F20(J),F20(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,U=0;for(let K of Y){let D=G20(J,K,F20(J),F20(K),0,0,{});if(D===0)return Q;X+=D,U+=K.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class UT{}class VT{}class W20{}class H20{}class VH4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new KH4}}class KH4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}function qb5(J,Z){if(J==="")return{matches:!0,score:1};let Q=UH4(Z,J);return{matches:Q>0.15,score:Q}}class g9 extends p0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new DH4}}class DH4 extends g0{textController;focusNode;scrollController=new o6;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new u7(this.widget.props.controller?.query??""),this.focusNode=new n4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Fm0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Fm0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Fm0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof UT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof VT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof W20){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof H20)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...qb5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,U)=>this.widget.props.sortItems(X,U,J):(X,U)=>U.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;tC(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new y1(Q.foreground,1,"solid")),U=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,K=new i$({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),D=new B2({shortcuts:new Map([[new $4("ArrowDown"),new UT],[new $4("ArrowUp"),new VT],[new $4("Tab"),new UT],[new $4("Tab",{shift:!0}),new VT],[new $4("n",{ctrl:!0}),new UT],[new $4("p",{ctrl:!0}),new VT],[new $4("Enter"),new W20],[new $4("Escape"),new H20]]),focusNode:this.focusNode,child:K}),z=new j9({actions:new Map([[UT,new o4(this.invoke)],[VT,new o4(this.invoke)],[W20,new o4(this.invoke)],[H20,new o4(this.invoke)]]),child:D}),q=new D1({children:[new d0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:z})]});this.itemContexts=[];let F;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";F=new j0({height:10,child:new n1({child:new Q0({text:new C(w,new b({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)F=new S1({child:new n1({child:new Q0({text:new C(this.widget.props.emptyStateText,new b({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,I;if(this.widget.props.renderItem)I=this.widget.props.renderItem(N,O,L,J);else{let M=O?Z.app.selectionBackground:void 0,A=O?Z.app.selectionForeground:Q.foreground;I=new d0({decoration:M?{color:M}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(this.widget.props.getLabel(N),new b({color:A,dim:L}))})})}return new VH4(new i1({onClick:(M)=>this.handleItemClick(E,M.clickCount),child:I}),(M)=>{this.itemContexts[E]=M})});F=new u0({children:w,crossAxisAlignment:"start"})}let G=new i1({onScroll:this.handleScroll,opaque:!1,child:new N6({controller:this.scrollController,autofocus:!1,child:F})}),W=[];if(this.widget.props.title){let w=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C(this.widget.props.title,new b({color:Z.app.command,bold:!0}))})});W.push(w)}if(!U)W.push(q,new j0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new S1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new S1({child:G}),new d0({padding:C0.only({top:1}),child:new n1({child:N??new j0({height:1})})})]})}))}else W.push(new S1({child:G}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function zH4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),U=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(U<7)return`${U}d ago`;return J.toLocaleDateString()}class Gm0 extends c1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,U)=>U.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>zH4(X.pubDate).length));return new g9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,U,V,K)=>{let D=f0.of(K),{colors:z}=D,q=D.app,F=U?q.selectionBackground:void 0,G=U?q.selectionForeground:z.foreground,W=z.mutedForeground,H=(B,w)=>new j0({width:w,child:D1.end([new Q0({text:new C(B,new b({color:W}))})])});return new d0({decoration:F?{color:F}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new S1({child:new Q0({text:new C(X.title,new b({color:G})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),H(zH4(X.pubDate),Q)]})})}})}}f4();class Wm0 extends p0{createState(){return new qH4}}class qH4 extends g0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new Q0({text:new C("●",new b({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Fb5=/\/threads\/(T-[^/?#\s<>]+)/i;function Gb5(J){let Z=J.trim(),Y=Z.match(Fb5)?.[1];if(Y&&T8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(T8(X))return X;return null}function Wb5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let K=V.relationships.find((D)=>D.role==="child"&&Z.has(D.threadID)&&(D.type==="fork"||D.type==="handoff"));if(K){Y.set(V.id,K.type);let D=K.threadID,z=Q.get(D)||[];z.push(V),Q.set(D,z)}else X.push(V)}return v90.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function Hm0(J,Z,Q){return new Q0({text:new C(`${J}${Z}`,new b({color:Q})),maxLines:1})}function Hb5(J,Z,Q,Y){return[Hm0("+",J,Y.success),Z3.horizontal(1),Hm0("~",Z,Y.warning),Z3.horizontal(1),Hm0("-",Q,Y.destructive)]}function Bb5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class B20 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new FH4}}class FH4 extends g0{spinner=new I3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,U=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)U=U.filter((E)=>E.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],K=new Set(V),D=Z.currentThreadID,z=[...U].sort((E,O)=>{if(D){if(E.id===D)return-1;if(O.id===D)return 1}let L=V.indexOf(E.id),I=V.indexOf(O.id);if(L!==-1&&I!==-1)return L-I;if(L!==-1)return-1;if(I!==-1)return 1;return 0}),q=Wb5(z),F=Math.max(0,...q.map((E)=>E.description.timeAgo.length)),G=f0.of(J),W=new a0({padding:C0.symmetric(0,1),child:new n1({child:new Q0({text:new C("",new b({color:G.colors.foreground,dim:!0}),[new C("Ctrl+T",new b({color:G.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new b({color:G.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(E)=>{if(E!==H)H=E,B=Gb5(E);return B};return new g9({items:q,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=w(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>w(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!Bb5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(E,O,L,I)=>{let M=f0.of(I),{app:A,colors:R}=M,_=O?A.selectionBackground:void 0,S=O?A.selectionForeground:R.foreground,y=R.mutedForeground,h=(e,N0)=>new j0({width:N0,child:D1.end([new Q0({text:new C(e,new b({color:y}))})])}),f=Z.threadViewStates[E.id],k=[],x=E.relationshipType==="handoff",g=new Eg({connectorColor:R.mutedForeground});if(E.depth>0){let e=[],N0=E.ancestorsAreLast.slice(1);for(let U0 of N0)e.push(new C(g.getAncestorPrefix(U0),new b({color:g.connectorColor,dim:g.connectorDim})));let n=E.isLast?g.elbow:g.tee,V0=g.getConnectorText(n);e.push(new C(V0,new b({color:g.connectorColor,dim:g.connectorDim}))),k.push(new Q0({text:new C("",void 0,e)}))}let a=[],m=D===E.id?new C("(current) ",new b({color:R.success})):K.has(E.id)?new C("(visited) ",new b({color:R.foreground,dim:!0})):null;if(m)a.push(new Q0({text:m}));if(EE(f))a.push(new Wm0),a.push(new j0({width:1}));let i=E.title;if(E.relationshipType==="fork"){let e=i.match(/^Forked\((\d+)\): /);if(e)i=i.slice(e[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);a.push(new Q0({text:new C("[fork] ",new b({color:R.primary}))}))}else if(x)a.push(new Q0({text:new C("[handoff] ",new b({color:R.accent}))}));if(a.push(new S1({child:new Q0({text:new C(i,new b({color:S})),overflow:"ellipsis",maxLines:1})})),a.push(new j0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let e=O?{success:y,warning:y,destructive:y}:R;a.push(...Hb5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,e)),a.push(new j0({width:2}))}return a.push(h(E.description.timeAgo,F)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...a]})})}})}}function Bm0(J){return 1-(1-J)**3}function wm0(J,Z,Q){return J+(Z-J)*Q}function Jp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),U=Bm0(Y),V=Bm0(X);return{x:wm0(J.startOffset.x,J.targetOffset.x,U),y:wm0(J.startOffset.y,J.targetOffset.y,V)}}var wb5={nodeWidth:3,horizontalSpacing:3};class KT{options;constructor(J={}){this.options={...wb5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let U=0,V=(K,D)=>{let z=Z.get(K.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...K,parentID:Q.get(K.id)};if(z.length===0){Y.push({node:q,position:{x:U,y:D}});let B=U;return U+=this.options.nodeWidth+this.options.horizontalSpacing,B}let F=[];for(let B of z)F.push(V(B,D+1));let G=Math.min(...F),W=Math.max(...F),H=Math.floor((G+W)/2);return Y.push({node:q,position:{x:H,y:D}}),H};for(let K of X)V(K,0);return Y}buildTree(J){let Z=new Set(J.map((U)=>U.id)),Q=[...J].sort((U,V)=>U.id.localeCompare(V.id)),Y=new Map;for(let U of Q){if(!U.parentID||!Z.has(U.parentID)){Y.set(U.id,void 0);continue}let V=!1,K=U.parentID;while(K){if(K===U.id){V=!0;break}K=Y.get(K)}Y.set(U.id,V?void 0:U.parentID)}let X=new Map;for(let U of J){let V=Y.get(U.id);if(!X.has(V))X.set(V,[]);X.get(V).push(U)}return{childrenMap:X,resolvedParent:Y}}}var Nb5={nodeWidth:3,nodeHeight:2};class DT{options;constructor(J={}){this.options={...Nb5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let U=this.calculateConnectorLine(X.position,Y.position);Z.push({points:U,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,U=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let K=V+1;if(Y.push({x:X,y:K}),X!==U)Y.push({x:U,y:K});let D=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:U,y:D}),Y}}var Eb5={nodeWidth:3,nodeHeight:2},Ob5={x:0,y:0};class N20{options;constructor(J={}){this.options={...Eb5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Ob5,X,U,V,K){let D=K?f0.of(K):null,z=D?.colors,q=D?.app,F=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:F}))});let G=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let A=G;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new j0({width:y.position.x-S}));let h=y.node.id===Q,f=V?.(y.node.data)??!1,k=U?.activeFlashOn??!1,x=y.node.id===U?.copyFlashNodeId;_.push(this.renderNode(h,f,k,x,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new D1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(G+1)*B,I=[new j0({width:H,height:L}),new $5({left:E,top:O,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=G-M.position.y,_=E+M.position.x+this.options.nodeWidth+1,S=O+R*B+1,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new $5({left:_,top:S,child:this.renderInfoBox(A,y,z,q)}))}return new d0({padding:C0.horizontal(2),child:new $H(new D5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X,U){let V="┌─┐",K="└─┘",D=J?X?.threadGraphNodeSelected??U?.primary??U?.foreground:X?.threadGraphNode??U?.primary??U?.foreground,z=!1;if(Y)D=X?.threadGraphNodeSelected??U?.primary??D,V="┏━┓",K="┗━┛",z=!0;else if(Z&&Q)D=X?.toolSuccess??U?.primary??D,V="┏━┓",K="┗━┛";return new u0({crossAxisAlignment:"start",children:[new Q0({text:new C(V,new b({color:D,bold:z}))}),new Q0({text:new C(K,new b({color:D,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),U=Math.min(Z,Math.max(1,...X.map((G)=>G.length))),V=U+2,K="┌"+"─".repeat(V)+"┐",D="└"+"─".repeat(V)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,F=[new Q0({text:new C(K,new b({color:z}))})];for(let G of X){let W=" ".repeat(U-G.length);F.push(new Q0({text:new C("│ ",new b({color:z}),[new C(G+W,new b({color:q??z})),new C(" │",new b({color:z}))])}))}return F.push(new Q0({text:new C(D,new b({color:z}))})),new u0({crossAxisAlignment:"start",children:F})}renderConnectors(J,Z,Q,Y,X,U){let V=[],K=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let G of Z){let W=G.position.x+K;if(W>=0&&W<Y)z[W]="▲"}V.push(new Q0({text:new C(z.join(""),new b({color:D}))}));let q=Array(Y).fill(" ");for(let G of J){let W=Z.filter((E)=>E.node.parentID===G.node.id);if(W.length===0)continue;let H=G.position.x+K,B=W.map((E)=>E.position.x+K),w=Math.min(...B),N=Math.max(...B);for(let E=w;E<=N;E++)if(E>=0&&E<Y){if(E===H)if(W.length===1&&B[0]===H)q[E]="│";else if(E===w)q[E]="└";else if(E===N)q[E]="┘";else q[E]="┬";else if(B.includes(E))if(E===w)q[E]="└";else if(E===N)q[E]="┘";else q[E]="┴";else if(q[E]===" ")q[E]="─"}}V.push(new Q0({text:new C(q.join(""),new b({color:D}))}));let F=Array(Y).fill(" ");for(let G of J){if(Z.filter((B)=>B.node.parentID===G.node.id).length===0)continue;let H=G.position.x+K;if(H>=0&&H<Y)F[H]="│"}return V.push(new Q0({text:new C(F.join(""),new b({color:D}))})),V}}var Lb5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Ib5={x:0,y:0};class Nm0{options;constructor(J={}){this.options={...Lb5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Ib5,X,U,V,K){let D=K?f0.of(K):null,z=D?.colors,q=D?.app,F=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:F}))});let G=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let A=G;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new j0({width:y.position.x-S}));let h=y.node.id===Q,f=V?.(y.node.data)??!1,k=U?.activeFlashOn??!1;_.push(this.renderNode(h,f,k,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new D1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(G+1)*B,I=[new j0({width:H,height:L}),new $5({left:E,top:O,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=G-M.position.y,_=E+M.position.x+this.options.nodeWidth+1,S=O+R*B,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new $5({left:_,top:S,child:this.renderInfoBox(A,y,z)}))}return new d0({padding:C0.horizontal(2),child:new $H(new D5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X){let U=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,U="■";return new Q0({text:new C(U,new b({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,U=[];for(let V of Y)U.push(new Q0({text:new C(V,new b({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,U){let V=[],K=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let F=Z.filter((w)=>w.node.parentID===q.node.id);if(F.length===0)continue;let G=q.position.x+K,W=F.map((w)=>w.position.x+K),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===G,E=W.includes(w);if(N&&E)if(F.length===1)z[w]="│";else if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┼";else if(N)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┬";else if(E)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┴";else if(z[w]===" ")z[w]="─"}}return V.push(new Q0({text:new C(z.join(""),new b({color:D}))})),V}}class Zp extends D3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new GH4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class GH4 extends N4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class qL extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new BH4}}var WH4=400,HH4=300,Mb5=16;class BH4 extends g0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new KT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new DT;renderer=new Nm0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((D)=>D.id)),Q=new Set(this.widget.props.threads.map((D)=>D.id));if(Z.size!==Q.size||[...Z].some((D)=>!Q.has(D)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,U=this.widget.props.initialSelectedThreadID;if(X!==U&&U){let z=this.widget.props.threads.find((q)=>q.id===U);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((D)=>D.isActive),K=this.widget.props.threads.some((D)=>D.isActive);if(V!==K){if(this.stopActiveFlashTimer(),K)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:WH4,durationY:HH4};let Z=Math.max(WH4,HH4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Jp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Mb5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),U=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,K=2,D=Math.floor(this.viewportHeight/2),q=Math.floor(D/2)-V;return{x:U,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((U)=>U.node.parentID===Q.node.id);if(X.length>0){X.sort((V,K)=>V.position.x-K.position.x);let U=Math.floor(X.length/2);Y=X[U]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x<Q.position.x);if(X.length>0)X.sort((U,V)=>V.position.x-U.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x>Q.position.x);if(X.length>0)X.sort((U,V)=>U.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((F)=>F.node.id===this.selectedNodeId):null)??this.positionedNodes.find((F)=>!F.node.parentID);if(q){let F=Math.max(...this.positionedNodes.map((G)=>G.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,F)}}let X=this.widget.props.showTitle??!0,U=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+U},K=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),D=new Zp({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:K});return new _4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:D})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class NH4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new EH4}}class EH4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}var wH4=30,Ab5=30;class zT{}class qT{}class E20{}class O20{}class Em0 extends p0{props;constructor(J){super();this.props=J}createState(){return new OH4}}class OH4 extends g0{highlightedIndex=0;controller=new u7;focusNode;scrollController=new o6;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new n4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;tC(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof zT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof qT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof E20){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof O20)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,K=o1.of(J).size.width>=Ab5+wH4,D=f1.all(new y1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C("Select a cluster",new b({color:X.command,bold:!0}))})}),F=new i$({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),G=new B2({shortcuts:new Map([[new $4("ArrowDown"),new zT],[new $4("ArrowUp"),new qT],[new $4("Tab"),new zT],[new $4("Tab",{shift:!0}),new qT],[new $4("n",{ctrl:!0}),new zT],[new $4("p",{ctrl:!0}),new qT],[new $4("Enter"),new E20],[new $4("Escape"),new O20]]),focusNode:this.focusNode,child:F}),W=new j9({actions:new Map([[zT,new o4(this.invoke)],[qT,new o4(this.invoke)],[E20,new o4(this.invoke)],[O20,new o4(this.invoke)]]),child:G}),H=new D1({children:[new d0({decoration:{color:Y.background},child:new Q0({text:new C(">",new b({color:Y.foreground}))})}),new S1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((I,M)=>{let A=M===this.highlightedIndex,R=Z?I.threads.some((h)=>h.id===Z):!1,_=A?X.selectionBackground:void 0,S=A?X.selectionForeground:Y.foreground,y=[new C(I.label,new b({color:S})),new C(` (${I.threads.length})`,new b({color:S,dim:!0}))];if(R)y.push(new C(" (current)",new b({color:A?X.selectionForeground:Y.success})));return new NH4(new i1({onClick:(h)=>this.handleItemClick(M,h.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,y)})})}),(h)=>{this.itemContexts[M]=h})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new S1({child:new i1({onScroll:this.handleScroll,child:new N6({controller:this.scrollController,autofocus:!1,child:w})})}),E=z?z.threads.map((I)=>({id:I.id,title:I.title,parentID:I.parentID,updatedAt:I.updatedAt})):[],O=z?new d0({padding:C0.all(1),child:new qL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(K){let I=O?new S1({child:O}):new j0({width:wH4});L=new D1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,I]})}else{let I=[new S1({child:new i1({onScroll:this.handleScroll,child:new N6({controller:this.scrollController,autofocus:!1,child:w})})})];if(O)I.push(new S1({child:O}));L=new u0({crossAxisAlignment:"stretch",children:I})}return new d0({decoration:{border:D,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[q,H,new j0({height:1}),new S1({child:L})]})})}}class n${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!n$._instance)n$._instance=new n$;return n$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class LH4 extends g0{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){P.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){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((U)=>U.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),U=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),D=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new g9({title:"Add Label",items:D,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:U||"Type to create a new label",renderItem:(z,q,F,G)=>{let W=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,[new C("Create new label: ",new b({color:H})),new C(w,new b({color:H,bold:!0}))])})})}return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(z.name,new b({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let G=q.trim().toLowerCase();return G.length===0||z.name.includes(G)},sortItems:(z,q,F)=>{let G="__isCreateMarker"in z.item&&z.item.__isCreateMarker,W="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(G&&!W)return-1;if(!G&&W)return 1;return q.score-z.score}})}}class Om0 extends p0{props;constructor(J){super();this.props=J}createState(){return new LH4}}class uH extends p0{props;constructor(J){super();this.props=J}createState(){return new IH4}}class IH4 extends g0{_spinner=new I3;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 Z=f0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new y1(Q.foreground,1,"solid")),U=this._spinner.toBraille(),V=new Q0({textAlign:"center",text:new C("",void 0,[new C(U,new b({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new b({color:Q.foreground}))])}),D=[new S1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)D.push(new j0({height:2,child:new d0({padding:C0.symmetric(2,0),child:new Q0({text:new C("",new b({dim:!0}),[new C("Press ",new b({color:Q.foreground})),new C("Esc",new b({color:Q.info})),new C(" to cancel",new b({color:Q.foreground}))])})})}));let z=new d0({decoration:new T4(Q.background,X),child:new j0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new _4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class j8 extends p0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:V=!0,thumbColor:K,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=V,this.thumbColor=K,this.trackColor=D}createState(){return new MH4}}class MH4 extends g0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let U=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),K=Math.max(1,X*V),D=Math.max(0,Math.min(1,U.scrollOffset/(Z-Q))),z=X-K,q=Math.max(0,z*D),F=q+K;return J>=q&&J<=F}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),U=this.context.findRenderObject()?.size.height??0;if(U===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,K=Math.min(1,Q/Z),D=Math.max(1,U*K),z=U-D;if(z<=0)return;let q=Z-Q,F=z/q,G=V/F,W=Math.max(0,Math.min(q,this._dragStartOffset+G));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let K=Math.min(1,Y/Q),D=Math.max(1,V*K),z=Q-Y,q=V-D,F=Math.max(0,Math.min(1,X/(Q-Y))),G=Math.max(0,q*F),W=G+D;if(Z>=G&&Z<=W)return;if(Z<G)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new i1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?H5.POINTER:H5.DEFAULT,child:new AH4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class AH4 extends zC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:V=!0,thumbColor:K,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=V,this.thumbColor=K,this.trackColor=D}createRenderObject(){return new jH4(this)}updateRenderObject(J){J.updateWidget(this)}}class jH4 extends N4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;u4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:U}=this._calculateScrollbarMetrics();if(!U)return;let V=this._widget.trackColor,K=this._widget.thumbColor,D=["▁","▂","▃","▄","▅","▆","▇","█"],z=Y,q=Y+X;for(let F=0;F<this.size.height;F++){let G="█",W=!0;if(F===Math.floor(z)){let H=1-(z-F),B=Math.floor(H*8);G=D[B]||"█",W=!1}else if(F===Math.floor(q)){let H=1-(q-F),B=Math.floor(H*8);G=D[B]||"█"}else if(F>z&&F<q)W=!1;J.setChar(Z,Q+F,G,{fg:K,bg:V,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),U=Math.min(1,Z/J),V=Math.max(1,Y*U),K=Y-V;return{thumbStartFloat:Math.max(0,K*X),thumbSizeFloat:V,showScrollbar:!0}}}class FL extends p0{props;constructor(J){super();this.props=J}createState(){return new RH4}}class RH4 extends g0{scrollController=new o6;scrollAreaKey=new _7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof E2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{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 q=p70(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,U=f1.all(new y1(Z.colors.border,1,"solid")),V=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C(Y.title,new b({color:X,bold:!0}))})}),K=this.isWidgetMessage(Q)?Q.widget:new Q0({text:new C(Y.description,new b({color:Z.colors.foreground})),selectable:!0}),D=new S1({child:new w2({child:new d0({padding:C0.symmetric(1,0),child:new D1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:this.scrollController,autofocus:!0,child:K})}),new j8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,F=this.scrollController.offset,G=this.getViewportHeight(),W=q+G;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(F,0)}}})]})})})}),z=new d0({padding:C0.symmetric(1,0),child:new Q0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new b({color:Z.colors.foreground,dim:!0})),new C("R",new b({color:Z.app.keybind})),new C(" to retry, ",new b({color:Z.colors.foreground,dim:!0})),new C("Esc",new b({color:Z.app.keybind})),new C(" to cancel",new b({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new b({color:Z.colors.foreground,dim:!0}));if(q==="help"){let F=new b({color:Z.app.keybind}),G=new b({color:Z.colors.foreground,dim:!0});return new C("",G,[new C("Press ",G),new C("Escape",F),new C(" to close • Use ",G),new C("↑↓",F),new C(" or ",G),new C("j/k",F),new C(" to scroll",G)])}return new C("Press any key to close",new b({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new _4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new d0({decoration:{border:U,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[V,new j0({height:1}),D,z]})})})}}n9();class PH4 extends p0{props;constructor(J){super();this.props=J}createState(){return new CH4}}class CH4 extends g0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=u8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new Q0({text:new C("No plugins found.",new b({dim:!0}))});let Y=[],X=this.plugins.length,U=this.plugins.filter((D)=>D.status==="active").length,V=this.plugins.reduce((D,z)=>D+z.registeredCommands.length,0),K=this.plugins.reduce((D,z)=>D+z.registeredTools.length,0);if(Y.push(new C(`${U}/${X} ${g4(X,"plugin")} active`,new b({bold:!0}))),V>0||K>0)Y.push(new C(` (${V} ${g4(V,"command")}, ${K} ${g4(K,"tool")})`,new b({dim:!0})));Y.push(new C(`
|
|
7172
|
+
`))}if(H)F.push(new C(" ",q)),F.push(new C("Total: ",q)),F.push(new C(U(B),z))}return new d0({decoration:{color:K.background,border:f1.all(new y1(K.border,1,"rounded"))},child:new Q0({text:new C(void 0,void 0,F)})})}h0();n9();import{execSync as ub5}from"node:child_process";ZA();FJ();O3();w7();_w();MX();L$();TJ();EX();rE();f4();xu();Sv();W1();var oH4=I4(Bz(),1);import{writeFile as cH4}from"fs/promises";import lH4 from"path";h0();L$();class qm0{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1772685027-gdb1277"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await us(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class yH extends p0{props;constructor(J){super();this.props=J}createState(){return new QH4}}class QH4 extends g0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class YH4 extends g0{controller=new u7;focusNode=new n4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,U=this.controller.text.trim().length>0,V=!X||U,K=f1.all(new y1(Q.foreground,1,"solid")),D=new i$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new D1({children:[new d0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:D})]}),q=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,[new C("Command: ",new b({color:Q.foreground})),new C(this.widget.props.commandName,new b({color:Y.command,bold:!0}))])})}),F=[];if(V)F.push(new C("Enter",new b({color:Y.keybind}))),F.push(new C(" to submit, ",new b({color:Q.foreground,dim:!0})));F.push(new C("Esc",new b({color:Y.keybind}))),F.push(new C(" to cancel",new b({color:Q.foreground,dim:!0})));let G=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,F)})});return new d0({decoration:{border:K,color:Q.background},padding:C0.all(1),child:new u0({children:[q,new j0({height:1}),z,new Z3,G]})})}}class $p extends p0{props;constructor(J){super();this.props=J}createState(){return new YH4}}import{isDeepStrictEqual as Fm0}from"node:util";var Kb5=/[\\/_ +.#"@[({&]/,Db5=/[\\/_ +.#"@[({&]/g,zb5=/[\s-]/,XH4=/[\s-]/g;function G20(J,Z,Q,Y,X,U,V){if(U===Z.length){if(X===J.length)return 1;return 0.99}let K=`${X},${U}`;if(V[K]!==void 0)return V[K];let D=Y.charAt(U),z=Q.indexOf(D,X),q=0,F,G,W,H;while(z>=0){if(F=G20(J,Z,Q,Y,z+1,U+1,V),F>q){if(z===X)F*=1;else if(zb5.test(J.charAt(z-1))){if(F*=0.9,H=J.slice(X,z-1).match(XH4),H&&X>0)F*=0.999**H.length}else if(Kb5.test(J.charAt(z-1))){if(F*=0.8,W=J.slice(X,z-1).match(Db5),W&&X>0)F*=0.999**W.length}else if(F*=0.3,X>0)F*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(U))F*=0.9999}if(F<0.1&&(Q.charAt(z-1)===Y.charAt(U+1)||Y.charAt(U+1)===Y.charAt(U)&&Q.charAt(z-1)!==Y.charAt(U))){if(G=G20(J,Z,Q,Y,z+1,U+2,V),G*0.1>F)F=G*0.1}if(F>q)q=F;z=Q.indexOf(D,z+1)}return V[K]=q,q}function F20(J){return J.toLowerCase().replace(XH4," ")}function UH4(J,Z){let Q=G20(J,Z,F20(J),F20(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,U=0;for(let K of Y){let D=G20(J,K,F20(J),F20(K),0,0,{});if(D===0)return Q;X+=D,U+=K.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class UT{}class VT{}class W20{}class H20{}class VH4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new KH4}}class KH4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}function qb5(J,Z){if(J==="")return{matches:!0,score:1};let Q=UH4(Z,J);return{matches:Q>0.15,score:Q}}class g9 extends p0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new DH4}}class DH4 extends g0{textController;focusNode;scrollController=new o6;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new u7(this.widget.props.controller?.query??""),this.focusNode=new n4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Fm0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Fm0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Fm0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof UT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof VT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof W20){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof H20)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...qb5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,U)=>this.widget.props.sortItems(X,U,J):(X,U)=>U.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;tC(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new y1(Q.foreground,1,"solid")),U=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,K=new i$({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),D=new B2({shortcuts:new Map([[new $4("ArrowDown"),new UT],[new $4("ArrowUp"),new VT],[new $4("Tab"),new UT],[new $4("Tab",{shift:!0}),new VT],[new $4("n",{ctrl:!0}),new UT],[new $4("p",{ctrl:!0}),new VT],[new $4("Enter"),new W20],[new $4("Escape"),new H20]]),focusNode:this.focusNode,child:K}),z=new j9({actions:new Map([[UT,new o4(this.invoke)],[VT,new o4(this.invoke)],[W20,new o4(this.invoke)],[H20,new o4(this.invoke)]]),child:D}),q=new D1({children:[new d0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:z})]});this.itemContexts=[];let F;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";F=new j0({height:10,child:new n1({child:new Q0({text:new C(w,new b({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)F=new S1({child:new n1({child:new Q0({text:new C(this.widget.props.emptyStateText,new b({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,I;if(this.widget.props.renderItem)I=this.widget.props.renderItem(N,O,L,J);else{let M=O?Z.app.selectionBackground:void 0,A=O?Z.app.selectionForeground:Q.foreground;I=new d0({decoration:M?{color:M}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(this.widget.props.getLabel(N),new b({color:A,dim:L}))})})}return new VH4(new i1({onClick:(M)=>this.handleItemClick(E,M.clickCount),child:I}),(M)=>{this.itemContexts[E]=M})});F=new u0({children:w,crossAxisAlignment:"start"})}let G=new i1({onScroll:this.handleScroll,opaque:!1,child:new N6({controller:this.scrollController,autofocus:!1,child:F})}),W=[];if(this.widget.props.title){let w=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C(this.widget.props.title,new b({color:Z.app.command,bold:!0}))})});W.push(w)}if(!U)W.push(q,new j0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new S1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new S1({child:G}),new d0({padding:C0.only({top:1}),child:new n1({child:N??new j0({height:1})})})]})}))}else W.push(new S1({child:G}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function zH4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),U=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(U<7)return`${U}d ago`;return J.toLocaleDateString()}class Gm0 extends c1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,U)=>U.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>zH4(X.pubDate).length));return new g9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,U,V,K)=>{let D=f0.of(K),{colors:z}=D,q=D.app,F=U?q.selectionBackground:void 0,G=U?q.selectionForeground:z.foreground,W=z.mutedForeground,H=(B,w)=>new j0({width:w,child:D1.end([new Q0({text:new C(B,new b({color:W}))})])});return new d0({decoration:F?{color:F}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new S1({child:new Q0({text:new C(X.title,new b({color:G})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),H(zH4(X.pubDate),Q)]})})}})}}f4();class Wm0 extends p0{createState(){return new qH4}}class qH4 extends g0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new Q0({text:new C("●",new b({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Fb5=/\/threads\/(T-[^/?#\s<>]+)/i;function Gb5(J){let Z=J.trim(),Y=Z.match(Fb5)?.[1];if(Y&&T8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(T8(X))return X;return null}function Wb5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let K=V.relationships.find((D)=>D.role==="child"&&Z.has(D.threadID)&&(D.type==="fork"||D.type==="handoff"));if(K){Y.set(V.id,K.type);let D=K.threadID,z=Q.get(D)||[];z.push(V),Q.set(D,z)}else X.push(V)}return v90.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function Hm0(J,Z,Q){return new Q0({text:new C(`${J}${Z}`,new b({color:Q})),maxLines:1})}function Hb5(J,Z,Q,Y){return[Hm0("+",J,Y.success),Z3.horizontal(1),Hm0("~",Z,Y.warning),Z3.horizontal(1),Hm0("-",Q,Y.destructive)]}function Bb5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class B20 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new FH4}}class FH4 extends g0{spinner=new I3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,U=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)U=U.filter((E)=>E.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],K=new Set(V),D=Z.currentThreadID,z=[...U].sort((E,O)=>{if(D){if(E.id===D)return-1;if(O.id===D)return 1}let L=V.indexOf(E.id),I=V.indexOf(O.id);if(L!==-1&&I!==-1)return L-I;if(L!==-1)return-1;if(I!==-1)return 1;return 0}),q=Wb5(z),F=Math.max(0,...q.map((E)=>E.description.timeAgo.length)),G=f0.of(J),W=new a0({padding:C0.symmetric(0,1),child:new n1({child:new Q0({text:new C("",new b({color:G.colors.foreground,dim:!0}),[new C("Ctrl+T",new b({color:G.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new b({color:G.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(E)=>{if(E!==H)H=E,B=Gb5(E);return B};return new g9({items:q,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=w(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>w(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!Bb5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(E,O,L,I)=>{let M=f0.of(I),{app:A,colors:R}=M,_=O?A.selectionBackground:void 0,S=O?A.selectionForeground:R.foreground,y=R.mutedForeground,h=(e,N0)=>new j0({width:N0,child:D1.end([new Q0({text:new C(e,new b({color:y}))})])}),f=Z.threadViewStates[E.id],k=[],x=E.relationshipType==="handoff",g=new Eg({connectorColor:R.mutedForeground});if(E.depth>0){let e=[],N0=E.ancestorsAreLast.slice(1);for(let U0 of N0)e.push(new C(g.getAncestorPrefix(U0),new b({color:g.connectorColor,dim:g.connectorDim})));let n=E.isLast?g.elbow:g.tee,V0=g.getConnectorText(n);e.push(new C(V0,new b({color:g.connectorColor,dim:g.connectorDim}))),k.push(new Q0({text:new C("",void 0,e)}))}let a=[],m=D===E.id?new C("(current) ",new b({color:R.success})):K.has(E.id)?new C("(visited) ",new b({color:R.foreground,dim:!0})):null;if(m)a.push(new Q0({text:m}));if(EE(f))a.push(new Wm0),a.push(new j0({width:1}));let i=E.title;if(E.relationshipType==="fork"){let e=i.match(/^Forked\((\d+)\): /);if(e)i=i.slice(e[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);a.push(new Q0({text:new C("[fork] ",new b({color:R.primary}))}))}else if(x)a.push(new Q0({text:new C("[handoff] ",new b({color:R.accent}))}));if(a.push(new S1({child:new Q0({text:new C(i,new b({color:S})),overflow:"ellipsis",maxLines:1})})),a.push(new j0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let e=O?{success:y,warning:y,destructive:y}:R;a.push(...Hb5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,e)),a.push(new j0({width:2}))}return a.push(h(E.description.timeAgo,F)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...a]})})}})}}function Bm0(J){return 1-(1-J)**3}function wm0(J,Z,Q){return J+(Z-J)*Q}function Jp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),U=Bm0(Y),V=Bm0(X);return{x:wm0(J.startOffset.x,J.targetOffset.x,U),y:wm0(J.startOffset.y,J.targetOffset.y,V)}}var wb5={nodeWidth:3,horizontalSpacing:3};class KT{options;constructor(J={}){this.options={...wb5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let U=0,V=(K,D)=>{let z=Z.get(K.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...K,parentID:Q.get(K.id)};if(z.length===0){Y.push({node:q,position:{x:U,y:D}});let B=U;return U+=this.options.nodeWidth+this.options.horizontalSpacing,B}let F=[];for(let B of z)F.push(V(B,D+1));let G=Math.min(...F),W=Math.max(...F),H=Math.floor((G+W)/2);return Y.push({node:q,position:{x:H,y:D}}),H};for(let K of X)V(K,0);return Y}buildTree(J){let Z=new Set(J.map((U)=>U.id)),Q=[...J].sort((U,V)=>U.id.localeCompare(V.id)),Y=new Map;for(let U of Q){if(!U.parentID||!Z.has(U.parentID)){Y.set(U.id,void 0);continue}let V=!1,K=U.parentID;while(K){if(K===U.id){V=!0;break}K=Y.get(K)}Y.set(U.id,V?void 0:U.parentID)}let X=new Map;for(let U of J){let V=Y.get(U.id);if(!X.has(V))X.set(V,[]);X.get(V).push(U)}return{childrenMap:X,resolvedParent:Y}}}var Nb5={nodeWidth:3,nodeHeight:2};class DT{options;constructor(J={}){this.options={...Nb5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let U=this.calculateConnectorLine(X.position,Y.position);Z.push({points:U,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,U=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let K=V+1;if(Y.push({x:X,y:K}),X!==U)Y.push({x:U,y:K});let D=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:U,y:D}),Y}}var Eb5={nodeWidth:3,nodeHeight:2},Ob5={x:0,y:0};class N20{options;constructor(J={}){this.options={...Eb5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Ob5,X,U,V,K){let D=K?f0.of(K):null,z=D?.colors,q=D?.app,F=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:F}))});let G=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let A=G;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new j0({width:y.position.x-S}));let h=y.node.id===Q,f=V?.(y.node.data)??!1,k=U?.activeFlashOn??!1,x=y.node.id===U?.copyFlashNodeId;_.push(this.renderNode(h,f,k,x,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new D1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(G+1)*B,I=[new j0({width:H,height:L}),new $5({left:E,top:O,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=G-M.position.y,_=E+M.position.x+this.options.nodeWidth+1,S=O+R*B+1,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new $5({left:_,top:S,child:this.renderInfoBox(A,y,z,q)}))}return new d0({padding:C0.horizontal(2),child:new $H(new D5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X,U){let V="┌─┐",K="└─┘",D=J?X?.threadGraphNodeSelected??U?.primary??U?.foreground:X?.threadGraphNode??U?.primary??U?.foreground,z=!1;if(Y)D=X?.threadGraphNodeSelected??U?.primary??D,V="┏━┓",K="┗━┛",z=!0;else if(Z&&Q)D=X?.toolSuccess??U?.primary??D,V="┏━┓",K="┗━┛";return new u0({crossAxisAlignment:"start",children:[new Q0({text:new C(V,new b({color:D,bold:z}))}),new Q0({text:new C(K,new b({color:D,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),U=Math.min(Z,Math.max(1,...X.map((G)=>G.length))),V=U+2,K="┌"+"─".repeat(V)+"┐",D="└"+"─".repeat(V)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,F=[new Q0({text:new C(K,new b({color:z}))})];for(let G of X){let W=" ".repeat(U-G.length);F.push(new Q0({text:new C("│ ",new b({color:z}),[new C(G+W,new b({color:q??z})),new C(" │",new b({color:z}))])}))}return F.push(new Q0({text:new C(D,new b({color:z}))})),new u0({crossAxisAlignment:"start",children:F})}renderConnectors(J,Z,Q,Y,X,U){let V=[],K=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let G of Z){let W=G.position.x+K;if(W>=0&&W<Y)z[W]="▲"}V.push(new Q0({text:new C(z.join(""),new b({color:D}))}));let q=Array(Y).fill(" ");for(let G of J){let W=Z.filter((E)=>E.node.parentID===G.node.id);if(W.length===0)continue;let H=G.position.x+K,B=W.map((E)=>E.position.x+K),w=Math.min(...B),N=Math.max(...B);for(let E=w;E<=N;E++)if(E>=0&&E<Y){if(E===H)if(W.length===1&&B[0]===H)q[E]="│";else if(E===w)q[E]="└";else if(E===N)q[E]="┘";else q[E]="┬";else if(B.includes(E))if(E===w)q[E]="└";else if(E===N)q[E]="┘";else q[E]="┴";else if(q[E]===" ")q[E]="─"}}V.push(new Q0({text:new C(q.join(""),new b({color:D}))}));let F=Array(Y).fill(" ");for(let G of J){if(Z.filter((B)=>B.node.parentID===G.node.id).length===0)continue;let H=G.position.x+K;if(H>=0&&H<Y)F[H]="│"}return V.push(new Q0({text:new C(F.join(""),new b({color:D}))})),V}}var Lb5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Ib5={x:0,y:0};class Nm0{options;constructor(J={}){this.options={...Lb5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Ib5,X,U,V,K){let D=K?f0.of(K):null,z=D?.colors,q=D?.app,F=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:F}))});let G=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let A=G;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new j0({width:y.position.x-S}));let h=y.node.id===Q,f=V?.(y.node.data)??!1,k=U?.activeFlashOn??!1;_.push(this.renderNode(h,f,k,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new D1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(G+1)*B,I=[new j0({width:H,height:L}),new $5({left:E,top:O,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=G-M.position.y,_=E+M.position.x+this.options.nodeWidth+1,S=O+R*B,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new $5({left:_,top:S,child:this.renderInfoBox(A,y,z)}))}return new d0({padding:C0.horizontal(2),child:new $H(new D5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X){let U=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,U="■";return new Q0({text:new C(U,new b({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,U=[];for(let V of Y)U.push(new Q0({text:new C(V,new b({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,U){let V=[],K=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let F=Z.filter((w)=>w.node.parentID===q.node.id);if(F.length===0)continue;let G=q.position.x+K,W=F.map((w)=>w.position.x+K),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===G,E=W.includes(w);if(N&&E)if(F.length===1)z[w]="│";else if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┼";else if(N)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┬";else if(E)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┴";else if(z[w]===" ")z[w]="─"}}return V.push(new Q0({text:new C(z.join(""),new b({color:D}))})),V}}class Zp extends D3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new GH4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class GH4 extends N4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class qL extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new BH4}}var WH4=400,HH4=300,Mb5=16;class BH4 extends g0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new KT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new DT;renderer=new Nm0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((D)=>D.id)),Q=new Set(this.widget.props.threads.map((D)=>D.id));if(Z.size!==Q.size||[...Z].some((D)=>!Q.has(D)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,U=this.widget.props.initialSelectedThreadID;if(X!==U&&U){let z=this.widget.props.threads.find((q)=>q.id===U);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((D)=>D.isActive),K=this.widget.props.threads.some((D)=>D.isActive);if(V!==K){if(this.stopActiveFlashTimer(),K)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:WH4,durationY:HH4};let Z=Math.max(WH4,HH4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Jp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Mb5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),U=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,K=2,D=Math.floor(this.viewportHeight/2),q=Math.floor(D/2)-V;return{x:U,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((U)=>U.node.parentID===Q.node.id);if(X.length>0){X.sort((V,K)=>V.position.x-K.position.x);let U=Math.floor(X.length/2);Y=X[U]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x<Q.position.x);if(X.length>0)X.sort((U,V)=>V.position.x-U.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x>Q.position.x);if(X.length>0)X.sort((U,V)=>U.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((F)=>F.node.id===this.selectedNodeId):null)??this.positionedNodes.find((F)=>!F.node.parentID);if(q){let F=Math.max(...this.positionedNodes.map((G)=>G.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,F)}}let X=this.widget.props.showTitle??!0,U=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+U},K=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),D=new Zp({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:K});return new _4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:D})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class NH4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new EH4}}class EH4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}var wH4=30,Ab5=30;class zT{}class qT{}class E20{}class O20{}class Em0 extends p0{props;constructor(J){super();this.props=J}createState(){return new OH4}}class OH4 extends g0{highlightedIndex=0;controller=new u7;focusNode;scrollController=new o6;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new n4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;tC(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof zT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof qT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof E20){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof O20)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,K=o1.of(J).size.width>=Ab5+wH4,D=f1.all(new y1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C("Select a cluster",new b({color:X.command,bold:!0}))})}),F=new i$({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),G=new B2({shortcuts:new Map([[new $4("ArrowDown"),new zT],[new $4("ArrowUp"),new qT],[new $4("Tab"),new zT],[new $4("Tab",{shift:!0}),new qT],[new $4("n",{ctrl:!0}),new zT],[new $4("p",{ctrl:!0}),new qT],[new $4("Enter"),new E20],[new $4("Escape"),new O20]]),focusNode:this.focusNode,child:F}),W=new j9({actions:new Map([[zT,new o4(this.invoke)],[qT,new o4(this.invoke)],[E20,new o4(this.invoke)],[O20,new o4(this.invoke)]]),child:G}),H=new D1({children:[new d0({decoration:{color:Y.background},child:new Q0({text:new C(">",new b({color:Y.foreground}))})}),new S1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((I,M)=>{let A=M===this.highlightedIndex,R=Z?I.threads.some((h)=>h.id===Z):!1,_=A?X.selectionBackground:void 0,S=A?X.selectionForeground:Y.foreground,y=[new C(I.label,new b({color:S})),new C(` (${I.threads.length})`,new b({color:S,dim:!0}))];if(R)y.push(new C(" (current)",new b({color:A?X.selectionForeground:Y.success})));return new NH4(new i1({onClick:(h)=>this.handleItemClick(M,h.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,y)})})}),(h)=>{this.itemContexts[M]=h})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new S1({child:new i1({onScroll:this.handleScroll,child:new N6({controller:this.scrollController,autofocus:!1,child:w})})}),E=z?z.threads.map((I)=>({id:I.id,title:I.title,parentID:I.parentID,updatedAt:I.updatedAt})):[],O=z?new d0({padding:C0.all(1),child:new qL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(K){let I=O?new S1({child:O}):new j0({width:wH4});L=new D1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,I]})}else{let I=[new S1({child:new i1({onScroll:this.handleScroll,child:new N6({controller:this.scrollController,autofocus:!1,child:w})})})];if(O)I.push(new S1({child:O}));L=new u0({crossAxisAlignment:"stretch",children:I})}return new d0({decoration:{border:D,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[q,H,new j0({height:1}),new S1({child:L})]})})}}class n${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!n$._instance)n$._instance=new n$;return n$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class LH4 extends g0{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){P.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){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((U)=>U.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),U=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),D=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new g9({title:"Add Label",items:D,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:U||"Type to create a new label",renderItem:(z,q,F,G)=>{let W=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,[new C("Create new label: ",new b({color:H})),new C(w,new b({color:H,bold:!0}))])})})}return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(z.name,new b({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let G=q.trim().toLowerCase();return G.length===0||z.name.includes(G)},sortItems:(z,q,F)=>{let G="__isCreateMarker"in z.item&&z.item.__isCreateMarker,W="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(G&&!W)return-1;if(!G&&W)return 1;return q.score-z.score}})}}class Om0 extends p0{props;constructor(J){super();this.props=J}createState(){return new LH4}}class uH extends p0{props;constructor(J){super();this.props=J}createState(){return new IH4}}class IH4 extends g0{_spinner=new I3;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 Z=f0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new y1(Q.foreground,1,"solid")),U=this._spinner.toBraille(),V=new Q0({textAlign:"center",text:new C("",void 0,[new C(U,new b({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new b({color:Q.foreground}))])}),D=[new S1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)D.push(new j0({height:2,child:new d0({padding:C0.symmetric(2,0),child:new Q0({text:new C("",new b({dim:!0}),[new C("Press ",new b({color:Q.foreground})),new C("Esc",new b({color:Q.info})),new C(" to cancel",new b({color:Q.foreground}))])})})}));let z=new d0({decoration:new T4(Q.background,X),child:new j0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new _4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class j8 extends p0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:V=!0,thumbColor:K,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=V,this.thumbColor=K,this.trackColor=D}createState(){return new MH4}}class MH4 extends g0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let U=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),K=Math.max(1,X*V),D=Math.max(0,Math.min(1,U.scrollOffset/(Z-Q))),z=X-K,q=Math.max(0,z*D),F=q+K;return J>=q&&J<=F}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),U=this.context.findRenderObject()?.size.height??0;if(U===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,K=Math.min(1,Q/Z),D=Math.max(1,U*K),z=U-D;if(z<=0)return;let q=Z-Q,F=z/q,G=V/F,W=Math.max(0,Math.min(q,this._dragStartOffset+G));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let K=Math.min(1,Y/Q),D=Math.max(1,V*K),z=Q-Y,q=V-D,F=Math.max(0,Math.min(1,X/(Q-Y))),G=Math.max(0,q*F),W=G+D;if(Z>=G&&Z<=W)return;if(Z<G)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new i1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?H5.POINTER:H5.DEFAULT,child:new AH4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class AH4 extends zC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:V=!0,thumbColor:K,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=V,this.thumbColor=K,this.trackColor=D}createRenderObject(){return new jH4(this)}updateRenderObject(J){J.updateWidget(this)}}class jH4 extends N4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;u4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:U}=this._calculateScrollbarMetrics();if(!U)return;let V=this._widget.trackColor,K=this._widget.thumbColor,D=["▁","▂","▃","▄","▅","▆","▇","█"],z=Y,q=Y+X;for(let F=0;F<this.size.height;F++){let G="█",W=!0;if(F===Math.floor(z)){let H=1-(z-F),B=Math.floor(H*8);G=D[B]||"█",W=!1}else if(F===Math.floor(q)){let H=1-(q-F),B=Math.floor(H*8);G=D[B]||"█"}else if(F>z&&F<q)W=!1;J.setChar(Z,Q+F,G,{fg:K,bg:V,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),U=Math.min(1,Z/J),V=Math.max(1,Y*U),K=Y-V;return{thumbStartFloat:Math.max(0,K*X),thumbSizeFloat:V,showScrollbar:!0}}}class FL extends p0{props;constructor(J){super();this.props=J}createState(){return new RH4}}class RH4 extends g0{scrollController=new o6;scrollAreaKey=new _7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof E2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{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 q=p70(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,U=f1.all(new y1(Z.colors.border,1,"solid")),V=new d0({padding:C0.symmetric(1,0),child:new Q0({text:new C(Y.title,new b({color:X,bold:!0}))})}),K=this.isWidgetMessage(Q)?Q.widget:new Q0({text:new C(Y.description,new b({color:Z.colors.foreground})),selectable:!0}),D=new S1({child:new w2({child:new d0({padding:C0.symmetric(1,0),child:new D1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:this.scrollController,autofocus:!0,child:K})}),new j8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,F=this.scrollController.offset,G=this.getViewportHeight(),W=q+G;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(F,0)}}})]})})})}),z=new d0({padding:C0.symmetric(1,0),child:new Q0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new b({color:Z.colors.foreground,dim:!0})),new C("R",new b({color:Z.app.keybind})),new C(" to retry, ",new b({color:Z.colors.foreground,dim:!0})),new C("Esc",new b({color:Z.app.keybind})),new C(" to cancel",new b({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new b({color:Z.colors.foreground,dim:!0}));if(q==="help"){let F=new b({color:Z.app.keybind}),G=new b({color:Z.colors.foreground,dim:!0});return new C("",G,[new C("Press ",G),new C("Escape",F),new C(" to close • Use ",G),new C("↑↓",F),new C(" or ",G),new C("j/k",F),new C(" to scroll",G)])}return new C("Press any key to close",new b({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new _4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new d0({decoration:{border:U,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[V,new j0({height:1}),D,z]})})})}}n9();class PH4 extends p0{props;constructor(J){super();this.props=J}createState(){return new CH4}}class CH4 extends g0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=u8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new Q0({text:new C("No plugins found.",new b({dim:!0}))});let Y=[],X=this.plugins.length,U=this.plugins.filter((D)=>D.status==="active").length,V=this.plugins.reduce((D,z)=>D+z.registeredCommands.length,0),K=this.plugins.reduce((D,z)=>D+z.registeredTools.length,0);if(Y.push(new C(`${U}/${X} ${g4(X,"plugin")} active`,new b({bold:!0}))),V>0||K>0)Y.push(new C(` (${V} ${g4(V,"command")}, ${K} ${g4(K,"tool")})`,new b({dim:!0})));Y.push(new C(`
|
|
7170
7173
|
|
|
7171
7174
|
`));for(let D of this.plugins){let{icon:z,color:q}=this.statusIcon(D.status),F=this.getRelativePath(D.uri.toString());if(Y.push(new C(`${z} `,new b({color:q}))),Y.push(new C(F,new b({bold:!0}))),Y.push(new C(` ${D.status}`,new b({dim:!0}))),Y.push(new C(`
|
|
7172
7175
|
`)),D.status==="active"&&D.registeredEvents.length>0)Y.push(new C(" Events: ",new b({dim:!0}))),Y.push(new C(D.registeredEvents.join(", "),new b({color:Q.link}))),Y.push(new C(`
|
|
@@ -7380,14 +7383,14 @@ ${I0.join(`
|
|
|
7380
7383
|
---
|
|
7381
7384
|
|
|
7382
7385
|
${o.content||""}`:o.content||"",F1=[],L1=o.baseDir.startsWith("file://")?Y$0(o.baseDir):o.baseDir,K4=(o.files||[]).filter((i0)=>!i0.toLowerCase().endsWith("skill.md"));if(!$0){F1.push(new j0({height:1})),F1.push(new Q0({text:new C("─".repeat(R-4),F)})),F1.push(new j0({height:1})),F1.push(new Q0({text:new C("Files:",F)})),F1.push(new i1({cursor:"pointer",onClick:()=>{K8(J,`${o.baseDir}/SKILL.md`)},child:new Q0({text:new C(" SKILL.md",new b({color:Q.primary}))})}));for(let i0 of K4){let e0=iN4(L1,i0),j1=i0.startsWith("/")?`file://${i0}`:`${o.baseDir}/${i0}`;F1.push(new i1({cursor:"pointer",onClick:()=>{K8(J,j1)},child:new Q0({text:new C(` ${e0}`,new b({color:Q.primary}))})}))}}let D4=$0?new Q0({text:new C("SKILL.md",F)}):new i1({cursor:"pointer",onClick:()=>{K8(J,`${o.baseDir}/SKILL.md`)},child:new Q0({text:new C("SKILL.md",new b({color:Q.primary}))})}),c0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[D4,new j0({height:1}),...X1?[new Q0({text:new C(X1,q)})]:[],...F1]});B0=new d0({constraints:new A1({minWidth:R,maxWidth:R}),decoration:new T4(void 0,new f1(void 0,void 0,void 0,new y1(Q.border,1))),padding:C0.only({left:2}),child:new u0({crossAxisAlignment:"stretch",children:[H0,new j0({height:1}),new S1({child:new D1({crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:this.detailScrollController,child:c0})}),new j8({controller:this.detailScrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let i0=this.detailScrollController.maxScrollExtent,e0=this.detailScrollController.offset;return{totalContentHeight:Math.max(i0+20,0),viewportHeight:20,scrollOffset:Math.max(e0,0)}}})]})})]})})}let X0=new S1({child:new a0({padding:M?C0.only({right:1}):C0.all(0),child:new D1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:this.listScrollController,child:U0})}),new j8({controller:this.listScrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let o=this.getViewportHeight(),$0=this.listScrollController.maxScrollExtent,D0=this.listScrollController.offset;return{totalContentHeight:Math.max($0+o,0),viewportHeight:o,scrollOffset:Math.max(D0,0)}}})]})})}),W0=new n1({child:new Q0({text:new C("",N,[new C("Escape",B),new C(" to close",N)])})}),l=new S1({child:new d0({padding:C0.symmetric(1,0),child:new D1({crossAxisAlignment:"stretch",children:[X0]})})}),J0=[new S1({child:new u0({crossAxisAlignment:"stretch",children:[e,new j0({height:1}),l,new j0({height:1}),W0]})})];if(B0)J0.push(B0);let c=new D1({crossAxisAlignment:"stretch",children:J0});return new _4({autofocus:!0,focusNode:this.focusNode,onKey:this.handleKeyEvent,child:new n1({child:new d0({constraints:new A1(A,A,0,I),decoration:new T4(Q.background,f1.all(new y1(Q.primary,1,"rounded"))),child:new a0({padding:C0.all(1),child:c})})})})}}class Dp0 extends p0{props;constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends g0{_scrollController=new o6;_viewportHeight=0;getOptions(){return[{value:"remove",label:"Remove skill"},{value:"close",label:"Close"}]}handleSelect=(J)=>{if(!J){this.widget.props.onDismiss();return}switch(J){case"remove":this.widget.props.onRemove();break;case"close":this.widget.props.onDismiss();break}};dispose(){this._scrollController.dispose(),super.dispose()}build(J){let{pendingSkill:Z,skill:Q}=this.widget.props,Y=R1.of(J).colorScheme,X=f0.of(J),U=o1.sizeOf(J),V=U.width,K=U.height,D=Math.min(V-12,80),z=Math.min(K-4,30),q=16,F=z-16,G=[];if(Q?.description){if(G.push(new Q0({text:new C(Q.description,new b({color:Y.foreground}))})),G.push(new j0({height:1})),Q.content&&F>2){G.push(new Q0({text:new C("─".repeat(D-6),new b({color:Y.foreground,dim:!0}))})),G.push(new j0({height:1}));let H=Q.content.split(`
|
|
7383
|
-
`).length,B=Math.max(Math.min(H,F),3);this._viewportHeight=B;let w=new f3({markdown:Q.content}),N=new d0({constraints:new A1({maxHeight:B}),child:new D1({crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:this._scrollController,autofocus:!1,child:w})}),new j8({controller:this._scrollController,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let E=this._scrollController.maxScrollExtent,O=this._scrollController.offset,L=this._viewportHeight,I=E+L;return{totalContentHeight:Math.max(I,0),viewportHeight:Math.max(L,1),scrollOffset:Math.max(O,0)}}})]})});G.push(N),G.push(new j0({height:1}))}}else G.push(new Q0({text:new C("(Loading skill details...)",new b({color:Y.foreground,dim:!0,italic:!0}))})),G.push(new j0({height:1}));if(Z.arguments)G.push(new Q0({text:new C("",void 0,[new C("Arguments: ",new b({color:Y.foreground,dim:!0})),new C(Z.arguments,new b({color:Y.foreground}))])})),G.push(new j0({height:1}));let W=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Q0({text:new C("",void 0,[new C(Z.name,new b({bold:!0,color:Y.success,underline:!0}))])}),new j0({height:1}),...G,new k7({options:this.getOptions(),onSelect:this.handleSelect,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})]});return new _4({onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"},child:new n1({child:new $H(new d0({constraints:new A1(D,D,0,z),decoration:{color:Y.background,border:f1.all(new y1(Y.success,1,"rounded"))},padding:C0.symmetric(2,1),child:W}))})})}}function mp5(J,Z){if(J===Z)return!0;let Q=Object.keys(J),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;for(let X of Q){if(!(X in Z))return!1;if(!Object.is(J[X],Z[X]))return!1}return!0}class zp0 extends p0{stableProps;arePropsEqual;constructor({key:J,stableProps:Z,arePropsEqual:Q}){super(J?{key:J}:{});this.stableProps=Z,this.arePropsEqual=Q??mp5}createState(){return new X$0}}class X$0 extends g0{cachedChild=null;build(J){let{stableProps:Z,arePropsEqual:Q}=this.widget,Y=this.cachedChild;if(Y&&Q(Y.props,Z))return Y.widget;let X=this.widget.buildStableChild(Z);return this.cachedChild={props:Z,widget:X},X}dispose(){this.cachedChild=null}}class qp0 extends zp0{constructor(J){super({stableProps:J})}createState(){return new oN4}buildStableChild(J){let{threadID:Z,...Q}=J;return new Ip({...Q,key:Z?new s5(`message-view-${Z}`):void 0})}}class oN4 extends X$0{build(J){return super.build(J)}}W1();function gp5(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),U=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(U<=4)return`${U}w ago`;return`${V}mo ago`}class Fp0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList(Z).subscribe((U)=>{X.unsubscribe(),Y(U)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadHistoryService.observeHistory().pipe(H1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let U=X.title?.toLowerCase()||"untitled",V=X.id.toLowerCase(),K=Z.toLowerCase();return U.includes(K)||V.includes(K)}).map((X)=>{let U=new Date(X.userLastInteractedAt),V=gp5(U),K=X.id.slice(-8),D=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:V,title:X.title||"Untitled",shortThreadID:K},diffStats:X.summaryStats?.diffStats,workspaceURI:D,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}h0();f4();f4();function rN4(J){let Z=nI1(J),Q=Array.from(Z.entries()).map(([U,V])=>({path:U,diffStats:V})),X=t7(J)?.totalInputTokens??0;return{filesAffected:Q,totalTokens:X}}class Gp0{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new o6;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){P.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Z=await this.threadService.get(J);if(Z){if(this.currentId===J)this.current=Z,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 Z=this.listeners.indexOf(J);if(Z!==-1)this.listeners.splice(Z,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Z=rN4(this.current);return this.statsCache.set(this.current.id,{stats:Z,version:this.current.v}),Z}clearStatsCache(){this.statsCache.clear()}dispose(){this.cancelTimerAndSubscription(),this.clearStatsCache(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){P.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(Go()).subscribe((Z)=>{if(this.currentId===J)this.current=Z,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)}}class Wp0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new sN4}}class sN4 extends g0{build(J){let Q=f0.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new j0({width:0,height:0});let U=Y.map((V)=>this.buildTodoItem(V,Q));return new d0({child:new a0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Q0({text:new C(X,new b({bold:!0,color:Q.foreground}))}),...U]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),Y=J.status==="completed",X=new b({bold:J.status==="in-progress",color:Z.foreground,dim:Y}),U=new b({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:Y});return new D1({crossAxisAlignment:"start",children:[new Q0({text:new C(Q,X)}),new j0({width:1}),new S1({child:new Q0({text:new C(J.content,U)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}function tN4(J,Z){switch(J){case"update-available":return[new C("A newer Amp is available. Run ",new b({color:Z.foreground,dim:!0})),new C("amp update",new b({color:Z.warning}))];case"update-available-unrecognized-path":return[new C("A newer Amp is available.",new b({color:Z.foreground,dim:!0}))];case"update-available-brew":return[new C("A newer Amp is available. Run ",new b({color:Z.foreground,dim:!0})),new C("brew upgrade ampcode",new b({color:Z.warning}))];case"updated":return null;case"updated-with-warning":return[new C("Update complete, run ",new b({color:Z.foreground,dim:!0})),new C("amp update",new b({color:Z.warning})),new C(" to see warnings",new b({color:Z.foreground,dim:!0}))];case"update-error":return[new C("Update failed, run ",new b({color:Z.foreground,dim:!0})),new C("amp update",new b({color:Z.warning})),new C(" to see warnings",new b({color:Z.foreground,dim:!0}))];case"hidden":return null}}async function rp5(J){return new Promise((Z)=>{pp5("git",["branch","--show-current"],{cwd:J},(Q,Y)=>{if(Q){Z(null);return}let X=Y.trim();Z(X||null)})})}class Hp0 extends p0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new U$0}}class U$0 extends g0{debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";lastThreadStatusDebugSignature=null;themeColors=null;themeApp=null;ideStatus=null;randomAd=null;adSubscription=null;adsDisabledBySetting=!1;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingShortcutsHelp=!1;isShowingContextAnalyzeModal=!1;isShowingSkillListModal=!1;skillListData=null;shortcutsHintUsed=!1;deepReasoningEffort="medium";anthropicSpeed=void 0;deepReasoningEffortSubscription=null;anthropicSpeedSubscription=null;sessionState=UC;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;lastInferenceState=void 0;elapsedTimeTimer=null;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;skillListSubscription=null;skillWarningsSubscription=null;skillErrorsSubscription=null;availableSkillCount=0;availableSkillCountReady=!1;showSkillsCountInPromptBar=!0;showSkillsCountInPromptBarSubscription=null;skillWarningCount=0;skillErrorCount=0;pendingApprovals=[];pendingApprovalsSubscription=null;submitOnEnter=!0;submitOnEnterSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;isShowingPromptHistoryPicker=!1;paletteShowOptions=null;paletteOnThreadMentionSelected=null;threadsForPicker=[];parentThreadTitles=new Map;parentThreadTitleLoadsInFlight=new Set;clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Gp0;previewThread=null;todoScrollController=(()=>{let J=new o6;return J.followMode=!1,J})();contextAnalyzeDeps=null;openContextAnalyzeModal=()=>{this.widget.dependencies.createSystemPromptDeps().then((J)=>{this.contextAnalyzeDeps=J,this.setState(()=>{this.isShowingContextAnalyzeModal=!0})})};filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new n4({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new n4({debugLabel:"AutocompleteFocus"});autocompleteFocusNodeListener=null;isTextfieldAndAutocompleteFocused=!1;hasReplayedEarlyInput=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreview=null;fileImagePreviewPath=null;painterImagePreview=null;painterSaveDialog=null;messageViewController=new Q$0;previewMessageViewController=new Q$0;handleMainMessageViewCopy=(J,Z)=>{this._handleTextCopy(J,Z)};handleMainMessageViewDismissFocus=()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()};messageViewControllerUnsubscribe=null;lastEditingMessageOrdinal=null;skillPreview=null;cachedSkillForPreview=null;adActionModal=null;adInfoModal=null;adModalStack=[];newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;parentThreadLinkAnchor=new ig;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null,countdownSeconds:null};isInQueueMode=!1;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;pendingAuthLogin=null;authStatus="pending";authStatusSubscription=null;authModalKeyInterceptorUnsubscribe=null;isCreatingAuthLoginSession=!1;queuedPromptAfterAuth=null;pendingInputDialog=null;pendingConfirmDialog=null;mcpServers=[];mcpServersSubscription=null;pluginInfos=[];pluginInfosSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1,isDailyGrantEnabled:!1};agentModePulseSeq=0;updateState="hidden";updateServiceSubscription=null;toastController=new D90;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];isShowingForkDeprecationModal=!1;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];splashOrbExplosion=null;splashOrbExplosionSeq=0;freeTierStatusSubscription=null;allConnectedThreadActivityStatusesSubscription=null;allConnectedThreadActivityStatuses={};threadTitlesSubscription=null;threadTitles={};pendingNavigationSubscription=null;pluginCommands=[];pluginCommandsSubscription=null;async initNewsFeed(){let J=async(Q)=>{return W8(Q,void 0,this.widget.dependencies.configService)},Z=cb1();this.newsFeedReader=new bh0(Z,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Q)=>{if(Q.length>0)this.setState(()=>{this.newsFeedEntries=[...Q,...this.newsFeedEntries]})},error:(Q)=>{P.error("News feed error:",Q)}})}bringAdModalToFront(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J),this.adModalStack.push(J)}removeAdModalFromStack(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J)}getTopAdModal(){for(let J=this.adModalStack.length-1;J>=0;J--){let Z=this.adModalStack[J];if(Z==="adAction"&&this.adActionModal)return Z;if(Z==="adInfo"&&this.adInfoModal)return Z}return null}dismissTopAdModal(){let J=this.getTopAdModal();if(!J)return!1;return this.setState(()=>{if(J==="adAction")this.adActionModal=null;if(J==="adInfo")this.adInfoModal=null;this.removeAdModalFromStack(J)}),!0}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};onThreadSwitch(){this.handoffController?.resetUIState(),this.exitQueueMode(),this.isMessageViewInSelectionMode=!1,this.imagePreview=null}canInterruptQueuedInference(){let{threadPool:J,threadState:Z}=this.widget.dependencies,Q=(Z.mainThread?.queuedMessages?.length??0)>0;return J.queueOnSubmitByDefault&&Q&&EE(Z.viewState)}startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.recordNavigation(J);await this.widget.dependencies.threadPool.createThread(),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J??null})};canChangeAgentModeInPromptEditor(){return(this.messageViewController.editingMessageOrdinal===0||this.handoffState.isInHandoffMode)&&!this.handoffState.isGeneratingHandoff}getEffectiveAgentMode(){if(!this.agentModeController)return"smart";return(this.canChangeAgentModeInPromptEditor()?this.agentModeController.getMode():null)??this.agentModeController.getEffectiveMode()}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(J.viewState.interactionState==="handoff")return!0;if(Boolean(J.viewState.inferenceState==="running"))return!0;return J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued").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 Z=this.themeApp;if(!Z)return null;if(this.submitDisabledHint)return new C(this.submitDisabledHint,new b({color:J.foreground,dim:!0}));if(this.isExiting)return new C("Exiting...",new b({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C("",void 0,[new C("Ctrl+C",new b({color:Z.keybind})),new C(" again to exit",new b({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C("",void 0,[new C("Esc",new b({color:Z.keybind})),new C(" again to clear input",new b({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C("",void 0,[new C("Escape",new b({color:Z.keybind})),new C(" to close help",new b({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let z=this.getEffectiveAgentMode(),q=Qg(z);return new C("",void 0,[new C("Images aren't supported in ",new b({color:J.warning,dim:!1})),new C(z,new b({color:q})),new C(" mode.",new b({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new C("",void 0,[new C("Esc",new b({color:Z.keybind})),new C(" again to cancel",new b({color:J.foreground,dim:!0}))]);if(this.canInterruptQueuedInference())return new C("",void 0,[new C("Enter",new b({color:Z.keybind})),new C(" to interrupt",new b({color:J.foreground,dim:!0}))]);return new C("",void 0,[new C("Esc",new b({color:Z.keybind})),new C(" to cancel",new b({color:J.foreground,dim:!0}))])}let{threadState:Q}=this.widget.dependencies;if(this.statusMessage){if(this.debugThreadViewState)P.info("[tui-ui] footer status override",{source:"statusMessage",statusMessage:this.statusMessage,inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C(this.statusMessage,new b({color:J.foreground,dim:!0}))}let Y=tN4(this.updateState,J);if(Y){if(this.debugThreadViewState)P.info("[tui-ui] footer status override",{source:"updateState",inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C("",void 0,Y)}let X=this.getCurrentConfirmation(),U=$E4(Q),V=new tg({threadViewState:Q.viewState,tokenUsage:U,thread:Q.mainThread??void 0,waitingForConfirmation:!!X,showingEphemeralError:Boolean(Q.viewState.state==="active"&&Q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),K=sg(V);if(this.debugThreadViewState){let z=JSON.stringify({inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0,interactionState:Q.viewState.interactionState,statusType:K.type});if(z!==this.lastThreadStatusDebugSignature)this.lastThreadStatusDebugSignature=z,P.info("[tui-ui] footer thread status",JSON.parse(z))}let D=!this.shortcutsHintUsed||this.sessionState.launchCount<10;if(K.type==="none"&&!this.isShowingShortcutsHelp&&this.textController.text===""&&D)return new C("",void 0,[new C("?",new b({color:Z.keybind})),new C(" for shortcuts",new b({color:J.foreground,dim:!0}))]);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Z=Dk(J).filter((V)=>V.type==="fork"||V.type==="handoff");if(Z.length===0)return null;let Q=Z[0],Y=Q.threadID,X=this.threadsForPicker.find((V)=>V.id===Y);if(!X?.title)this.ensureParentThreadTitleLoaded(Y);let U=X?.title??this.parentThreadTitles.get(Y)??Y.slice(-8);return{type:Q.type==="handoff"?"handoff":"fork",title:U,threadID:Y}}ensureParentThreadTitleLoaded(J){if(this.parentThreadTitles.has(J)||this.parentThreadTitleLoadsInFlight.has(J))return;this.parentThreadTitleLoadsInFlight.add(J),this.widget.dependencies.threadService.getPrimitiveProperty(J,"title").then((Z)=>{if(!this.mounted||!Z)return;this.setState(()=>{this.parentThreadTitles.set(J,Z)})}).catch((Z)=>{P.debug("Failed to load parent thread title",{threadID:J,error:Z})}).finally(()=>{this.parentThreadTitleLoadsInFlight.delete(J)})}getThreadClusterForMinimap=(J)=>{let Z=this.clustersForPicker.find((Q)=>Q.threads.some((Y)=>Y.id===J));if(!Z||Z.threads.length<2)return null;return Z.threads.map((Q)=>({id:Q.id,title:Q.title,parentID:Q.parentID,updatedAt:Q.updatedAt,isActive:this.isThreadActivelyWorking(Q.id)}))};getCurrentThreadClusterForMinimap=()=>{let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;return this.getThreadClusterForMinimap(J.id)};enrichClustersWithActiveState=(J)=>{return J.map((Z)=>({...Z,threads:Z.threads.map((Q)=>({...Q,isActive:this.isThreadActivelyWorking(Q.id)}))}))};areRecordValuesEqual(J,Z){if(J===Z)return!0;let Q=Object.entries(J),Y=Object.entries(Z);if(Q.length!==Y.length)return!1;for(let[X,U]of Q){if(!Object.hasOwn(Z,X))return!1;if(!Object.is(U,Z[X]))return!1}return!0}getThreadViewStatesSnapshot(){let J={...this.allConnectedThreadActivityStatuses},Z=this.widget.dependencies.threadState.mainThread;if(Z)J[Z.id]=this.widget.dependencies.threadState.viewState;return J}isThreadActivelyWorking(J){return EE(this.allConnectedThreadActivityStatuses[J])}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Z,activeThreadHandle:Q}=this.widget.dependencies;if(!Z.mainThread?.id)return;if(!Q.restoreMessage)return;let X=Z.mainThread?.messages.findIndex((U)=>U===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Q.cancelTurn(),await Q.restoreMessage(X),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(U){P.error("Failed to edit message:",U)}};showForkDeprecationMessage=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!0})};dismissForkDeprecationModal=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!1})};handleMessageEditSubmit=async(J,Z,Q)=>{let{threadState:Y,activeThreadHandle:X}=this.widget.dependencies,U=Y.mainThread;if(!U)return;let V=U.messages.findIndex((z)=>z.messageId!==void 0&&z.messageId===J.messageId);if(V===-1)return;let K=V===0,D=K?this.agentModeController?.getMode()??U.agentMode??this.getEffectiveAgentMode():U.agentMode;if(this.shouldRequireAuthForPromptSubmit()){this.showSubmitDisabledHint("Sign in required before editing and resubmitting messages"),this.ensureAuthLoginSession();return}try{this.cancelBashInvocations(),await X.cancelTurn(),this.widget.dependencies.history.add(Z,process.cwd());let z=PH(Z);if(z&&X.invokeBashTool)await X.editMessage(V),this.invokeBashCommand(z.cmd,{visibility:z.visibility});else{let q=[{type:"text",text:Z}];if(Q.length>0)q.push(...Q);let F=D;if(U.agentMode&&!K&&F!==U.agentMode){P.error(`Cannot edit message: This thread uses ${U.agentMode} mode. To change mode, create a new thread.`);return}await X.sendMessage({content:q,agentMode:F,editIndex:V})}this.scrollMessageViewToBottom()}catch(z){P.error("Failed to edit message:",z)}};getAffectedFiles=async(J)=>{let{activeThreadHandle:Z,threadState:Q}=this.widget.dependencies;try{let Y=Q.mainThread;if(!Y)return[];let X=Y.messages.findIndex((V)=>V===J);if(X===-1)return[];return(await Z.getFilesAffectedByTruncation(X)).map(S9)}catch(Y){return P.error("Failed to get affected files:",Y),[]}};textController=new u7;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new o6);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.id;if(!Z)return;this.getMessageScrollController(Z).scrollToBottom()}_handleSelectionChanged=(J)=>{this.setState(()=>{})};updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.title;if(Z!==this.currentTitle){this.currentTitle=Z;let Q=process.cwd().replace(process.env.HOME||"","~"),Y=Z?`amp - ${Z} - ${Q}`:"";process.stdout.write(Ou0(Y))}}_handleTextCopy(J,Z){if(J&&J.length>0){let Q=Z?"Selection copied to clipboard":"Failed to copy selection to clipboard",Y=Z?"success":"error";this.toastController.show(Q,Y,2000)}}textFieldKey=new s5("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="")this.textController.resetScrollOffset();if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear(),this.toastController.show("Use [[Ctrl-O]] to open the command palette","warning");return}let Z=PH(J),Q=J===""&&this.bottomGridUserHeight!==void 0,Y=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?void 0:Z?.visibility;this.setState(()=>{if(this.currentShellModeStatus=Y,Q)this.bottomGridUserHeight=void 0})};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}),q6.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Z)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Z)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Z){await this.widget.dependencies.ideClient.start(J,!0,Z)}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}),q6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};handleDoubleAtTrigger=(J)=>{let{text:Z,cursorPosition:Q}=J,X=Z.slice(0,Q).lastIndexOf("@@"),U=J!==this.textController;if(P.info("[handleDoubleAtTrigger] called",{isEditingPreviousMessage:U,text:Z,cursor:Q,atAtIndex:X}),U)this.setState(()=>{this.paletteOnThreadMentionSelected=(V)=>{let K=this.messageViewController.editingController;if(!K){P.warn("[paletteOnThreadMentionSelected] no editing controller found");return}this.insertThreadMention(K,V)}});else this.setState(()=>{this.paletteOnThreadMentionSelected=null});this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:U?void 0:()=>{if(X!==-1){let V=J.text,K=V.slice(0,X)+V.slice(X+2);J.text=K,J.cursorPosition=X}},onSubmit:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()},onCancel:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()}})};insertThreadMention(J,Z){let{text:Q,cursorPosition:Y}=J,U=Q.slice(0,Y).lastIndexOf("@@");if(U!==-1){let V=Q.slice(Y),K=V.length===0,D=`@${Z}${K?" ":""}`,z=Q.slice(0,U)+D+V,q=U+D.length;J.text=z,J.cursorPosition=q}else J.insertText(`@${Z} `)}showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;let Z=!this.isShowingPalette;if(this.setState(()=>{if(this.isShowingPalette=Z,this.paletteShowOptions=Z?J??null:null,!Z)this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),Z)this.loadThreadsForPicker();else this.unloadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new _m0(this.widget.dependencies.configService,(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 km0(this.widget.dependencies.fuzzyServer);return this.completionBuilder}unloadThreadsForPicker(){if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe(),this.threadLoadSubscription=null;this.threadPreviewController.clearStatsCache(),this.widget.dependencies.threadHistoryService.resetCache()}dismissPalette=()=>{if(this.isExiting)return;this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),this.unloadThreadsForPicker()};lastRootContext;getCommandPaletteContext=(J)=>{let{threadState:Z,recentThreadIDs:Q}=this.widget.dependencies;if(!Z.mainThread)return null;let Y=J??this.lastRootContext;if(!Y)return null;let X=V1.file(process.cwd()),U=p1(X);return{recentThreadIDs:Q,currentThreadID:Z.mainThread.id,contextFallback:Y,context:J,threadPool:this.widget.dependencies.threadPool,createSystemPromptDeps:this.widget.dependencies.createSystemPromptDeps,activeThreadHandle:this.widget.dependencies.activeThreadHandle,editorState:this.textController,isProcessing:this.isProcessing(),thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let V=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),V},setImageAttachments:(V)=>{this.setState(()=>{this.imageAttachments=V})},editorDispatch:(V)=>{switch(V.type){case"set-input":this.textController.clear(),this.textController.insertText(V.input);break;case"set-input-with-cursor":this.textController.clear(),this.textController.insertText(V.input),this.textController.cursorPosition=V.cursorPosition;break;case"insert-text":this.textController.insertText(V.text);break;case"clear":this.textController.clear();break}},submitMessage:(V)=>{this.onTextSubmitted(V)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},openContextAnalyze:()=>{this.openContextAnalyzeModal()},openSkillList:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,createThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.freeTierStatus.canUseAmpFree,isDailyGrantEnabled:this.freeTierStatus.isDailyGrantEnabled,switchToThread:async(V)=>{await this.switchToExistingThread(V),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null});return},handleHandoff:async(V,K)=>{let{goal:D,images:z}=K;if(!D)return{ok:!1,error:Error("Goal is required")};try{let q=this.widget.dependencies.threadState.mainThread;if(!q)return{ok:!1,error:Error("No active thread")};let F=setTimeout(()=>V.abort(new $T("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let G=await this.widget.dependencies.threadPool.createHandoff(q.id,{goal:D,images:z,agentMode:q.agentMode,queuedMessages:q.queuedMessages?[...q.queuedMessages]:void 0,signal:V.signal});return clearTimeout(F),await this.switchToExistingThread(G),{ok:!0}}catch(G){if(clearTimeout(F),G instanceof Error&&(G.name==="AbortError"||G.message.includes("aborted")))throw V.signal.reason;throw G}}catch(q){return P.error("Failed to create handoff thread",{error:q}),{ok:!1,error:q instanceof Error?q:Error(String(q))}}},getGuidanceFiles:(V)=>{return this.widget.dependencies.activeThreadHandle.getGuidanceFiles(V)},openIdePicker:()=>{this.openIdePicker()},openPromptHistoryPicker:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!0})},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(V)=>{this.agentModeController?.setMode(V)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.enrichClustersWithActiveState(this.clustersForPicker),previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:U,threadViewStates:this.getThreadViewStatesSnapshot(),newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features,showStatusMessage:(V,K=2000)=>{this.showStatusMessage(V,K)},showToast:(V,K="success",D)=>{this.toastController.show(V,K,D)},getThemeName:()=>PF4(Y).themeName,isMessageViewInteractionActive:this.isMessageViewInSelectionMode||this.messageViewController.editingMessageOrdinal!==null,enterHandoffMode:this.enterHandoffMode,isInHandoffMode:this.handoffState.isInHandoffMode,enterQueueMode:this.enterQueueMode,submitQueue:this.submitQueue,isInQueueMode:this.isInQueueMode,addPendingSkill:(V)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill(V)},onThreadMentionSelected:this.paletteOnThreadMentionSelected??void 0,canChangeAgentModeInPromptEditor:()=>this.canChangeAgentModeInPromptEditor(),pluginCommands:this.pluginCommands,executePluginCommand:this.widget.dependencies.pluginService?(V,K,D)=>this.widget.dependencies.pluginService.commands.execute(V,K,{threadID:D}):void 0,reloadPlugins:this.widget.dependencies.pluginService?()=>this.widget.dependencies.pluginService.reload():void 0,pluginService:this.widget.dependencies.pluginService}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Fp0(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("",{includeArchived:!0}).subscribe({next:(Z)=>{this.setState(()=>{this.threadsForPicker=Z,this.clustersForPicker=dH4(Z),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await rp5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Z)=>Z.id!==J)})};invokeBashCommand=(J,{visibility:Z})=>{if(!this.widget.dependencies.activeThreadHandle.invokeBashTool)return;let Q=Date.now(),Y=`bash-${Q}-${Math.random().toString(36).substring(7)}`,X={cmd:J},U=new AbortController;this.widget.dependencies.activeThreadHandle.invokeBashTool(X,{hidden:Z===RH,abortController:U}).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((D)=>D.id===Y))this.bashInvocations=this.bashInvocations.map((D)=>D.id===Y?{...D,toolRun:V}:D);else{let D={id:Y,args:X,toolRun:V,startTime:Q,abortController:U,hidden:Z===RH};this.bashInvocations=[...this.bashInvocations,D]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Z)=>Z.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=gF4(()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(Z.ok)this.setState(()=>{this.threadCostInfo=Z.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J)=>{let Z=this.lastInferenceState==="running",Q=J==="running",Y=J==="idle"&&Z,X=Q&&!Z;if(Y)this.fetchThreadCostInfo();if(X)this.startElapsedTimeTimer();else if(Z&&!Q)this.stopElapsedTimeTimer();this.lastInferenceState=J};startElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)return;this.elapsedTimeTimer=setInterval(()=>{let J=this.widget.dependencies.threadState.viewState;if(!(J.state==="active"&&J.inferenceState==="running")){this.stopElapsedTimeTimer();return}this.setState(()=>{})},1000)};stopElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)clearInterval(this.elapsedTimeTimer),this.elapsedTimeTimer=null};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.handoffState.isGeneratingHandoff)return;let J=this.canChangeAgentModeInPromptEditor();if(this.agentModeController.toggle(J))this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};handleMessageViewControllerUpdate=()=>{let J=this.messageViewController.editingMessageOrdinal;if(J===this.lastEditingMessageOrdinal)return;if(this.lastEditingMessageOrdinal===0&&J!==0){let Y=this.agentModeController;if(!Y){this.lastEditingMessageOrdinal=J,this.setState(()=>{});return}if(Y.getMode()!==null)Y.setMode(null)}this.lastEditingMessageOrdinal=J,this.setState(()=>{})};showStatusMessage(J,Z=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=J}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},Z)}toggleDeepReasoningEffort=()=>{if(this.getEffectiveAgentMode()!=="deep"){this.showStatusMessage("Deep reasoning effort is only available in deep mode");return}let Z=this.widget.dependencies.threadState.mainThread;if(!Z)return;if(Y8(Z)>0){this.showStatusMessage("Deep reasoning effort can only be toggled before the first message");return}let Q=this.deepReasoningEffort==="medium"?"high":this.deepReasoningEffort==="high"?"xhigh":"medium";this.deepReasoningEffort=Q,E7("internal.deepReasoningEffort",Q),this.showStatusMessage(`Deep reasoning effort: ${Q}`),this.setState(()=>{this.agentModePulseSeq++})};formatAgentModeLabel(J){if(J!=="deep")return J;if(this.deepReasoningEffort==="high")return"deep²";if(this.deepReasoningEffort==="xhigh")return"deep³";return"deep"}handleInsertImage=async(J)=>{let Z=this.getEffectiveAgentMode();if(!tv(Z)){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>=cM)return!1;let Q=await sC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Q}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.setState(()=>{this.imagePreview={image:Z,index:J,onRemove:()=>{let Q=this.imageAttachments.indexOf(Z);if(Q!==-1)this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,X)=>X!==Q),this.imagePreview=null})}}})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreview=null})};handleShowFileImagePreview=(J)=>{this.setState(()=>{this.fileImagePreviewPath=J})};handleFileImagePreviewDismiss=()=>{this.setState(()=>{this.fileImagePreviewPath=null})};handleShowPainterImagePreview=(J,Z)=>{this.setState(()=>{this.painterImagePreview={image:J,filePath:Z}})};handlePainterImagePreviewDismiss=()=>{this.setState(()=>{this.painterImagePreview=null})};handleShowPainterSaveDialog=(J,Z)=>{this.setState(()=>{this.painterSaveDialog={image:J,filePath:Z}})};handlePainterSaveDialogDismiss=()=>{this.setState(()=>{this.painterSaveDialog=null})};handleSkillClick=(J)=>{let Z=this.pendingSkills[J];if(Z)this.setState(()=>{this.cachedSkillForPreview=null,this.skillPreview={skillIndex:J,onRemove:()=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(Z.name),this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})}}}),this.widget.dependencies.skillService.getSkills().then((Q)=>{let Y=Q.find((X)=>X.name===Z.name)??null;if(this.skillPreview!==null)this.setState(()=>{this.cachedSkillForPreview=Y})})};handleSkillPreviewDismiss=()=>{this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})};handleShowEditingImagePreview=(J,Z,Q)=>{this.setState(()=>{this.imagePreview={image:J,index:Z,onRemove:Q}})};handleImagePreviewRemove=()=>{if(this.imagePreview)this.imagePreview.onRemove(),this.setState(()=>{this.imagePreview=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleSplashOrbExplode=(J)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:J.x,originY:J.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(!Z.ok)P.error("Failed to destruct mysterious message",Z.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Z)=>{P.error("Failed to destruct mysterious message",Z)})};exitMessageViewInteraction=()=>{this.messageViewController.setSelectedUserMessageOrdinal(null),this.messageViewController.setIsShowingRestoreConfirmation(!1),this.messageViewController.setIsShowingEditConfirmation(!1),this.messageViewController.setPendingEditText(null),this.messageViewController.setPendingEditImageAttachments([]),this.messageViewController.setAffectedFiles([]),this.messageViewController.stopEditing(),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),this.scrollMessageViewToBottom(),q6.instance.addPostFrameCallback(()=>{if(!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};enterHandoffMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.handoffController?.enter()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Z=this.imageAttachments;if(this.resetHistory(),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Q=await this.handoffController.submit(J,Z,this.agentModeController?.getMode()??null);if(!Q.ok&&Q.error.message!=="Cancelled")this.displayMessage=Q.error,this.setState(()=>{});else if(Q.ok)this.setState(()=>{this.imageAttachments=[]}),setTimeout(()=>{this.handoffController?.startCountdown(()=>{this.autoSubmitHandoffDraft()})},0)};autoSubmitHandoffDraft=async()=>{let J=this.textController.text;if(J.trim())this.textController.clear(),await this.sendUserMessage(J)};enterQueueMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.setState(()=>{this.isInQueueMode=!0})};exitQueueMode=()=>{this.setState(()=>{this.isInQueueMode=!1})};submitQueue=(J)=>{this.exitMessageViewInteraction();let{threadState:Z}=this.widget.dependencies;if((Z.mainThread?.queuedMessages?.length??0)>=Y00){this.toastController.show(`Queue is full (max ${Y00} messages)`,"error",3000);return}let Y=this.imageAttachments;this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),this.textController.clear();let X=[{type:"text",text:J}];if(Y.length>0)X.push(...Y);this.widget.dependencies.activeThreadHandle.queueMessage(X),this.exitQueueMode()};isAuthRequiredStatus(J){if(!GG(J))return!1;let Z=J.error.message.toLowerCase();return Z.includes("user not found")||Z.includes("auth-required")||Z.includes("unauthorized")||Z.includes("forbidden")||Z.includes("401")||Z.includes("403")||Z.includes("api key")||Z.includes("access token")}shouldRequireAuthForPromptSubmit(){if(!this.widget.dependencies.hasAPIKeyAtStartup&&!T5(this.authStatus))return!0;return this.isAuthRequiredStatus(this.authStatus)&&!T5(this.authStatus)}queuePromptUntilAuthenticated(J,Z=[...this.imageAttachments],Q){if(this.queuedPromptAfterAuth={text:J,images:Z},Q?.clearInput??!0)this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),this.setState(()=>{this.imageAttachments=[]});this.showStatusMessage("Sign in required. Prompt queued and will send after login.",2500),this.ensureAuthLoginSession()}ensureAuthLoginSession=async()=>{if(this.pendingAuthLogin||this.isCreatingAuthLoginSession||T5(this.authStatus))return;this.isCreatingAuthLoginSession=!0;try{let J=eN4(32).toString("hex"),Z=await ZC(this.widget.dependencies.ampURL,J),Q=await ZC(this.widget.dependencies.ampURL,J,!1),Y=new AbortController;this.setState(()=>{this.pendingAuthLogin={authToken:J,browserURL:Z,manualURL:Q,abortController:Y,isOpeningBrowser:!1,isAuthenticating:!0,errorMessage:null}}),EY4(this.widget.dependencies.ampURL,J,this.widget.dependencies.secretStorage,Y).then(()=>{this.showStatusMessage("Login successful",2000),this.checkAuthStatusAfterLogin()}).catch((X)=>{if(Y.signal.aborted)return;let U=X instanceof Error?X.message:"Login failed. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=U,this.pendingAuthLogin.isAuthenticating=!1})})}catch(J){let Z=J instanceof Error?J.message:"Unable to start login flow. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin){this.displayMessage=Error(Z);return}this.pendingAuthLogin.errorMessage=Z,this.pendingAuthLogin.isAuthenticating=!1})}finally{this.isCreatingAuthLoginSession=!1}};openAuthLoginBrowser=async()=>{if(!this.pendingAuthLogin)return;let J=this.pendingAuthLogin.browserURL,Z=this.pendingAuthLogin.abortController;this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!0,this.pendingAuthLogin.errorMessage=null});try{await LX(J,Z.signal)}catch(Q){let Y=Q instanceof Error?Q.message:"Unable to open browser. Copy the manual link.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=Y})}finally{this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!1})}};copyAuthLoginLink=async()=>{let J=this.pendingAuthLogin?.manualURL;if(!J)return;try{await a4.instance.tuiInstance.clipboard.writeText(J),this.showStatusMessage("Login link copied to clipboard",2000)}catch(Z){P.error("Failed to copy login link",{error:Z}),this.showStatusMessage("Failed to copy login link",2000)}};checkAuthStatusAfterLogin=async()=>{try{let J=await this.widget.dependencies.configService.getLatest(),Z=rv(J),Q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(Z)});if(!Q.ok){this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Still waiting for login confirmation. Finish login in your browser, then press I again."});return}this.setState(()=>{this.authStatus={user:Q.result,features:Q.result.features,workspace:Q.result.team,mysteriousMessage:Q.result.mysteriousMessage},this.pendingAuthLogin=null}),await this.maybeResumeQueuedPromptAfterAuth()}catch(J){P.error("Failed to verify login state",{error:J}),this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Unable to verify login yet. Press I again in a moment."})}};cancelAuthLoginSession=()=>{if(this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("Authentication cancelled"));this.setState(()=>{this.pendingAuthLogin=null})};maybeResumeQueuedPromptAfterAuth=async()=>{if(!T5(this.authStatus))return;let J=this.queuedPromptAfterAuth;if(!J)return;this.queuedPromptAfterAuth=null,await this.proceedWithUserMessage(J.text,J.images)};handleAuthModalKey=(J)=>{if(!this.pendingAuthLogin||this.pendingInputDialog)return!1;let Z=J.key.length===1?J.key.toLowerCase():J.key;if(Z==="Enter"||Z==="o")return this.openAuthLoginBrowser(),!0;if(Z==="c")return this.copyAuthLoginLink(),!0;if(Z==="i")return this.checkAuthStatusAfterLogin(),!0;if(Z==="p")return this.promptForAuthLoginCode(),!0;return!1};promptForAuthLoginCode=async()=>{if(!this.pendingAuthLogin)return;let{authToken:J,abortController:Z}=this.pendingAuthLogin,Q=await new Promise((Y)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:{title:"Paste Login Code",helpText:"Paste the login code from the browser page. This is not your API key.",submitButtonText:"Verify"},resolve:Y}})});if(!Q||!this.pendingAuthLogin)return;try{let{accessToken:Y}=Yu0(Q,J);await this.widget.dependencies.secretStorage.set("apiKey",Y,this.widget.dependencies.ampURL),Z.abort(Error("Authentication completed from pasted code")),this.showStatusMessage("Login code accepted",2000),await this.checkAuthStatusAfterLogin()}catch(Y){let X=Y instanceof Error?Y.message:"Invalid login code.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=X,this.pendingAuthLogin.isAuthenticating=!1})}};openInEditor=async(J)=>{try{let Z=await dp5(XD.join(op5(),"amp-edit-")),Q=XD.join(Z,"message.amp.md");await np5(Q,J,"utf-8"),await yY(Q);try{let Y=await cp5(Q,"utf-8");this.textController.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await ip5(Q),await lp5(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.error("Error opening editor:",Z)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0){if(!this.canInterruptQueuedInference())return;try{await this.cancelStreamingMessage();return}catch(Y){P.error("Failed to cancel inference for queued submit",Y)}return}let Z=J.trim();if(Z===":q"){this.widget.dependencies.setExitNotice?.("Vim reflex detected. Exiting politely."),await this.exitApplication();return}if(Z==="exit"||Z==="quit"){await this.exitApplication();return}if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}if(this.isInQueueMode){this.submitQueue(J);return}let Q=PH(J);if(Q&&this.widget.dependencies.activeThreadHandle.invokeBashTool)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,process.cwd()),this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory();return}if(this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J);return}this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{let J=this.agentModeController?.getMode(),Z=this.canChangeAgentModeInPromptEditor(),Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=!Z&&J!==null&&Y8(Q)>0&&Q.agentMode!==J;if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(!Z&&J&&J!==this.sessionState.agentMode)this.persistAgentMode(J);if(Y)this.agentModeController?.setMode(null);this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};initState(){if(QQ.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new mh0({getActiveThreadHandle:()=>this.widget.dependencies.activeThreadHandle,getThreadPool:()=>this.widget.dependencies.threadPool,switchToThread:(Y)=>{return this.textController.clear(),this.switchToExistingThread(Y)}}),this.handoffController.addListener(this.handoffListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();if(a4.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),a4.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),a4.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.authStatus=this.widget.dependencies.initialServerStatus,this.authStatusSubscription=_J(this.widget.dependencies.configService).subscribe((Y)=>{if(this.setState(()=>{if(this.authStatus=Y,T5(Y))this.pendingAuthLogin=null}),T5(Y)){this.maybeResumeQueuedPromptAfterAuth();return}if(this.isAuthRequiredStatus(Y))this.ensureAuthLoginSession()}),this.authModalKeyInterceptorUnsubscribe=a4.instance.addKeyInterceptor((Y)=>this.handleAuthModalKey(Y)),!this.widget.dependencies.hasAPIKeyAtStartup)this.ensureAuthLoginSession();this.autocompleteFocusNodeListener=(Y)=>{q6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})},"TuiUIState.autocompleteFocusNodeListener")},this.autocompleteFocusNode.addListener(this.autocompleteFocusNodeListener),this.sessionState=this.widget.dependencies.sessionState??UC,this.shortcutsHintUsed=this.sessionState.shortcutsHintUsed,this.messageViewControllerUnsubscribe??=this.messageViewController.subscribe(this.handleMessageViewControllerUpdate),Promise.all([this.widget.dependencies.freeTierStatusPromise??Promise.resolve(void 0),I1(this.widget.dependencies.configService.config)]).then(([Y,X])=>{if(Y)this.freeTierStatus=Y;this.paletteConfig=X;let U=X.settings["internal.deepReasoningEffort"]??"medium",V=X.settings["anthropic.speed"];this.showSkillsCountInPromptBar=X.settings["internal.cli.showSkillsCountInPromptBar"]!==!1,this.adsDisabledBySetting=X.settings.newAdsDisplay===!0,this.deepReasoningEffort=U,this.anthropicSpeed=V,E7("internal.deepReasoningEffort",U),this.deepReasoningEffortSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings["internal.deepReasoningEffort"]===D.settings["internal.deepReasoningEffort"])).subscribe(({settings:K})=>{let D=K["internal.deepReasoningEffort"]??"medium";if(D!==this.deepReasoningEffort)this.deepReasoningEffort=D,E7("internal.deepReasoningEffort",D),this.setState(()=>{this.agentModePulseSeq++})}),this.anthropicSpeedSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings["anthropic.speed"]===D.settings["anthropic.speed"])).subscribe(({settings:K})=>{let D=K["anthropic.speed"];if(D!==this.anthropicSpeed)this.anthropicSpeed=D,this.setState(()=>{this.agentModePulseSeq++})}),this.showSkillsCountInPromptBarSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings["internal.cli.showSkillsCountInPromptBar"]===D.settings["internal.cli.showSkillsCountInPromptBar"])).subscribe(({settings:K})=>{let D=K["internal.cli.showSkillsCountInPromptBar"]!==!1;if(D!==this.showSkillsCountInPromptBar)this.setState(()=>{this.showSkillsCountInPromptBar=D})}),this.submitOnEnter=X.settings.submitOnEnter??!0,this.submitOnEnterSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings.submitOnEnter===D.settings.submitOnEnter)).subscribe(({settings:K})=>{let D=K.submitOnEnter??!0;if(D!==this.submitOnEnter)this.setState(()=>{this.submitOnEnter=D})}),this.agentModeController=new hh0({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.sessionState,freeTierStatus:this.freeTierStatus,workspace:this.widget.dependencies.workspace??null,initialSettings:X.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.threadState.mainThread}),this.agentModeController.addListener(this.agentModeListener),this.scheduleAdSubscriptionWithIdeReadiness(),this.setState(()=>{})}),this.updateGitBranch(),this.allConnectedThreadActivityStatusesSubscription=this.widget.dependencies.threadPool.allConnectedThreadActivityStatuses$.subscribe((Y)=>{if(this.areRecordValuesEqual(this.allConnectedThreadActivityStatuses,Y))return;this.setState(()=>{this.allConnectedThreadActivityStatuses=Y})}),this.threadTitlesSubscription=this.widget.dependencies.threadPool.threadTitles$.subscribe((Y)=>{if(this.areRecordValuesEqual(this.threadTitles,Y))return;this.setState(()=>{this.threadTitles=Y})}),this.pendingNavigationSubscription=this.widget.dependencies.threadPool.threadHandles$.pipe(s1((Y)=>Y?Y.thread$:v0.of(null))).subscribe((Y)=>{this.checkForPendingNavigation();let X=Y?.id;if(this.threadCostInfoThreadID!==X){if(this.threadCostInfo=void 0,this.threadCostInfoThreadID=X,X&&Y8(Y)>0)this.fetchThreadCostInfo()}let U=Y?this.widget.dependencies.threadState.viewState:void 0;this.maybeRefetchThreadCostInfo(U?.state==="active"?U.inferenceState:void 0)}),this.freeTierStatusSubscription=Tr1(async()=>{let Y=await this.widget.dependencies.configService.getLatest(),X=rv(Y),U=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(X)});if(!U.ok)throw U.error;return U.result}).subscribe({next:(Y)=>{if(Y){let X=this.freeTierStatus.canUseAmpFree;if(this.setState(()=>{this.freeTierStatus=Y}),Y.canUseAmpFree!==X)if(Y.canUseAmpFree){if(!this.adSubscription&&!this.adsDisabledBySetting)this.scheduleAdSubscriptionWithIdeReadiness()}else this.unsubscribeFromAds()}},error:(Y)=>{P.debug("Failed to fetch free tier status",Y)}});let{mcpTrustHandler:J}=this.widget.dependencies;if(this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),uy0((Y)=>{this.setState(()=>{this.pendingOAuthRequest=Y})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Y)=>{this.setState(()=>{this.mcpServers=Y})}),this.pendingSkillsSubscription=this.widget.dependencies.activeThreadHandle.pendingSkills$.subscribe((Y)=>{this.setState(()=>{this.pendingSkills=Y})}),this.widget.dependencies.pluginService){let Y=this.widget.dependencies.pluginService;this.pluginCommandsSubscription=qJ(Y.plugins,Y.commands.changed).subscribe(()=>{let X=Y.commands.list();this.setState(()=>{this.pluginCommands=X})}),this.pluginInfosSubscription=Y.plugins.subscribe((X)=>{this.setState(()=>{this.pluginInfos=X})})}this.skillListSubscription=this.widget.dependencies.skillService.skills.subscribe((Y)=>{let X=Y.filter((U)=>!U.baseDir.startsWith("builtin://")).length;this.setState(()=>{this.availableSkillCount=X,this.availableSkillCountReady=!0})}),this.skillWarningsSubscription=this.widget.dependencies.skillService.skillWarnings.subscribe((Y)=>{this.setState(()=>{this.skillWarningCount=Y.length})}),this.skillErrorsSubscription=this.widget.dependencies.skillService.skillErrors.subscribe((Y)=>{this.setState(()=>{this.skillErrorCount=Y.length})}),this.pendingApprovalsSubscription=this.widget.dependencies.activeThreadHandle.pendingApprovals$.subscribe((Y)=>{this.setState(()=>{this.pendingApprovals=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{let X=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=Y}),!X&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription&&!this.adsDisabledBySetting)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{if(!this.widget.dependencies.threadState.mainThread){P.warn("No active thread found to handle IDE message");return}await new Promise((U)=>setTimeout(U,50)),await this.widget.dependencies.activeThreadHandle.sendMessage({content:[{type:"text",text:Y}]}),P.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),P.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.mysteriousMessageSubscription=_J(this.widget.dependencies.configService).pipe(k5((Y)=>Y!=="pending"),H1((Y)=>T5(Y)?Y.mysteriousMessage??null:null),M4((Y,X)=>Y?.id===X?.id)).subscribe((Y)=>{this.setState(()=>{if(Y?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Y,Y&&!this.mysterySequenceManager)this.mysterySequenceManager=new l90(new Map([[new c90(U$0.MYSTERY_SEQUENCE),new yg]])),this.mysteryKeyInterceptorUnsubscribe=a4.instance.addKeyInterceptor((X)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let U=this.mysterySequenceManager.handleKeyEvent(X);if(U.consumed){if(U.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=U.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Y)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),a4.instance.addKeyInterceptor((Y)=>{if(Y.key==="?"){if(this.textController.text===""&&this.textController.cursorPosition===0&&!this.isShowingHelp&&!this.isShowingPalette&&this.isTextfieldAndAutocompleteFocused){if(this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!this.shortcutsHintUsed)this.shortcutsHintUsed=!0,this.sessionState={...this.sessionState,shortcutsHintUsed:!0},bK(this.sessionState);return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),Y.key==="Escape")return!0;return!1}return!1}),this.updateTerminalTitle();let Z=this.widget.dependencies.ideClient.getSelectedConfig();if(Z)this.connectToSelectedIde(Z,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();let Q=this.widget.dependencies.threadState.mainThread;if(!Q){this.initNewsFeed();return}if(Q.autoSubmitDraft&&Q.draft&&Q.messages.length===0)setTimeout(()=>this.autoSubmitInitialDraft(Q),100);this.initNewsFeed()}autoSubmitInitialDraft(J){let Z=typeof J.draft==="string"?J.draft:J.draft?.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
7384
|
-
`)??"",Q=Array.isArray(J.draft)?J.draft.filter((Y)=>Y.type==="image"):[];if(Z.trim()||Q.length>0){if(P.info("Auto-submitting initial handoff draft",{name:"handoff",threadID:J.id,hasDraftText:!!Z.trim(),draftImageCount:Q.length}),this.textController.clear(),Q.length>0)this.setState(()=>{this.imageAttachments=Q});this.proceedWithUserMessage(Z.trim())}}checkForPendingNavigation(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread;if(!Z?.pendingNavigation)return;let Q=Z.pendingNavigation;this.widget.dependencies.activeThreadHandle.clearPendingNavigation().catch(()=>{return}),P.info("Pending navigation detected, navigating to new thread",{name:"handoff",fromThreadID:Z.id,targetThreadID:Q}),this.handleHandoffNavigation(Q)}handleHandoffNavigation=async(J)=>{try{await this.switchToExistingThread(J);let Z=this.widget.dependencies.threadState.mainThread;if(!Z){P.error("Failed to get new thread after handoff navigation");return}if(Z.autoSubmitDraft&&Z.draft&&Z.messages.length===0){let{text:Q,images:Y}=mI1(Z.draft);if(Q.trim()||Y.length>0){if(P.info("Auto-submitting handoff draft",{name:"handoff",threadID:J,hasDraftText:!!Q.trim(),draftImageCount:Y.length}),this.textController.clear(),Y.length>0)this.setState(()=>{this.imageAttachments=[...Y]});await this.proceedWithUserMessage(Q.trim()),this.setState(()=>{this.imageAttachments=[]})}}}catch(Z){P.error("Failed to handle handoff navigation",{name:"handoff",newThreadID:J,error:Z})}};dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.messageViewControllerUnsubscribe)this.messageViewControllerUnsubscribe(),this.messageViewControllerUnsubscribe=null;if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.freeTierStatusSubscription)this.freeTierStatusSubscription.unsubscribe();if(this.allConnectedThreadActivityStatusesSubscription)this.allConnectedThreadActivityStatusesSubscription.unsubscribe();if(this.threadTitlesSubscription)this.threadTitlesSubscription.unsubscribe();if(this.pendingNavigationSubscription)this.pendingNavigationSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.authStatusSubscription)this.authStatusSubscription.unsubscribe(),this.authStatusSubscription=null;if(uy0(null),this.authModalKeyInterceptorUnsubscribe?.(),this.authModalKeyInterceptorUnsubscribe=null,this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("TUI disposed")),this.pendingAuthLogin=null;if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.pluginCommandsSubscription)this.pluginCommandsSubscription.unsubscribe();if(this.pluginInfosSubscription)this.pluginInfosSubscription.unsubscribe();if(this.skillListSubscription)this.skillListSubscription.unsubscribe();if(this.skillWarningsSubscription)this.skillWarningsSubscription.unsubscribe();if(this.skillErrorsSubscription)this.skillErrorsSubscription.unsubscribe();if(this.pendingApprovalsSubscription)this.pendingApprovalsSubscription.unsubscribe();if(this.unloadThreadsForPicker(),this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.deepReasoningEffortSubscription)this.deepReasoningEffortSubscription.unsubscribe(),this.deepReasoningEffortSubscription=null;if(this.anthropicSpeedSubscription)this.anthropicSpeedSubscription.unsubscribe(),this.anthropicSpeedSubscription=null;if(this.submitOnEnterSubscription)this.submitOnEnterSubscription.unsubscribe(),this.submitOnEnterSubscription=null;if(this.showSkillsCountInPromptBarSubscription)this.showSkillsCountInPromptBarSubscription.unsubscribe(),this.showSkillsCountInPromptBarSubscription=null;if(this.stopElapsedTimeTimer(),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;if(this.autocompleteFocusNodeListener)this.autocompleteFocusNode.removeListener(this.autocompleteFocusNodeListener),this.autocompleteFocusNodeListener=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Ou0("")),this.shouldUseProgressBar())process.stdout.write(IX4())}getCurrentConfirmation(){if(this.pendingApprovals.length>0){let J=this.pendingApprovals[0];return{type:"tool-use",tools:[{useBlock:{type:"tool_use",id:J.toolUseId,name:J.toolName,complete:!0,input:J.args},toAllow:J.toAllow??[]}],subthreadID:void 0,reason:J.reason??`Tool requires approval: ${J.toolName}`,isSubagent:J.context==="subagent",subagentToolName:J.subagentToolName}}return null}shouldUseProgressBar(){return!1}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},U$0.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}unsubscribeFromAds(){if(this.adSubscription)this.adSubscription.unsubscribe(),this.adSubscription=null;if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;this.setState(()=>{this.randomAd=null})}subscribeToAds(){if(this.adSubscription)return;if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;this.adSubscription=Nh0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>wh0(this.lastUserInteractionTime),this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.threadState.mainThread??void 0).subscribe({next:(J)=>{this.setState(()=>{this.randomAd=J}),q6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Z=this.getCurrentConfirmation();if(!Z||Z.type!=="tool-use"){P.error("No current tool confirmation found");return}let Q=Z.tools[0]?.useBlock;if(!Q){P.error("No tool use block found in confirmation");return}if(J?.type==="deny-with-feedback"){let{feedback:U}=J;try{if(this.pendingApprovals.find((K)=>K.toolUseId===Q.id))await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,U.trim()||void 0);else await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,U.trim()||void 0)}catch(V){P.error("Failed to send deny with feedback:",V)}return}let Y=J?.type==="simple"?J.value:null;if(Y==="allow-all-session")E7("dangerouslyAllowAll",!0);if(Y==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(U){if(U&&U instanceof Error)this.setState(()=>{this.displayMessage=U});else P.error("Failed to write dangerouslyAllowAll setting:",U);return}if(Y==="always-guarded"){let U=Z.tools[0]?.toAllow??[],V=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],K=[...U,...V];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",K,"global")}if(Y==="connect-github"){let U=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await K8(this.context,U);return}if(Y==="disable-librarian"){let U=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!U.includes(BZ))await this.widget.dependencies.settingsStorage.set("tools.disable",[...U,BZ],"global")}let X=Y!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(Y);try{await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,X)}catch(U){P.error("Failed to send tool confirmation:",U)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Z=J.viewState;if(Z.state!=="active"||!Z.ephemeralError)return null;return Z.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let{activeThreadHandle:Z}=this.widget.dependencies;switch(J){case"retry":await Z.retryTurn();break;case"dismiss":Z.dismissEphemeralError();break;case"new-thread":Z.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"handoff":Z.dismissEphemeralError(),this.enterHandoffMode();break;case"add-credits":{let Q=new URL("/pay",this.widget.dependencies.ampURL);await K8(this.context,Q),this.showStatusMessage("Payment page opened. After paying, choose Retry.");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Z}=this.widget.dependencies;await J.deny();try{await yY(Z.getSettingsFilePath())}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await this.widget.dependencies.activeThreadHandle.cancelStreaming()};switchToExistingThread=async(J,Z={})=>{let{recordInNavigationHistory:Q=!0}=Z,Y=Date.now(),X=this.widget.dependencies.threadState.mainThread?.id;if(Q&&X&&X!==J)this.recordNavigation(X);try{P.info(`[switchToExistingThread] Switching to thread: ${J}`);let U=Date.now();await this.widget.dependencies.threadPool.switchThread(J),P.info(`[switchToExistingThread] switchToThread resolved in ${Date.now()-U}ms`);let V=await this.widget.dependencies.threadService.get(J)??this.widget.dependencies.threadState.mainThread;if(!V||V.id!==J)throw Error("No active thread after switch");P.info(`[switchToExistingThread] Got thread ${J}, thread.agentMode: ${V.agentMode}`),P.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null);let K=Date.now();if(this.onThreadSwitch(),P.info(`[switchToExistingThread] onThreadSwitch completed in ${Date.now()-K}ms`),this.persistLastThreadId(J),V.draft&&Y8(V)===0)if(this.textController.clear(),typeof V.draft==="string")this.textController.insertText(V.draft);else{let D=V.draft.filter((F)=>F.type==="text"),z=V.draft.filter((F)=>F.type==="image"),q=D.map((F)=>F.text).join(`
|
|
7385
|
-
`);if(q)this.textController.insertText(q);if(z.length>0)this.setState(()=>{this.imageAttachments=z})}P.info(`[switchToExistingThread] Completed in ${Date.now()-Y}ms`)}catch(U){throw P.error("Failed to switch to thread",{threadId:J,error:U}),Error(`Failed to switch to thread: ${J}`,{cause:U})}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J,Z)=>{if(this.cancelBashInvocations(),this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J,Z??[...this.imageAttachments],{clearInput:Z===void 0});return}this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J,process.cwd());let Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=Y8(Q)===0,X=this.getEffectiveAgentMode();if(Q.agentMode&&!Y&&X!==Q.agentMode){await this.showErrorMessage(`This thread uses ${Q.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let U=Z??this.imageAttachments,V=[{type:"text",text:J}];if(U.length>0)V.push(...U);if(await this.widget.dependencies.activeThreadHandle.sendMessage({content:V,agentMode:X}),this.persistLastThreadId(Q.id),Y)this.persistAgentMode(X);if(this.scrollMessageViewToBottom(),!Z)this.setState(()=>{this.imageAttachments=[]});q6.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&&J.messages.length===0){if(J.relationships?.find((Q)=>Q.type==="handoff"&&Q.role==="child"))await this.widget.dependencies.threadPool.deleteThread?.(J.id).catch(()=>{})}a4.instance.stop()};async persistAgentMode(J){let Q={...await fK(),agentMode:J};this.sessionState=Q,await bK(Q)}async persistLastThreadId(J){let Q={...await fK(),lastThreadId:J};this.sessionState=Q,await bK(Q)}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 Z=ap5();if(J===Z)return"~";if(J.startsWith(Z+XD.sep))return"~"+J.slice(Z.length);return J}shorten(J){let Z=J.split(XD.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(XD.sep),"…",Z.slice(-2).join(XD.sep)].join(XD.sep)}buildDisplayText(J,Z,Q,Y){let X=Z?` (${Z})`:"",U=J+X;if(r5(U,Y)<=Q)return U;let V=J.split(XD.sep);if(V.length>2){let D=[V[0],"…",V[V.length-1]].join(XD.sep)+X;if(r5(D,Y)<=Q)return D}return jO(U,Q,Y)}build(J){this.lastRootContext=J;let Z=this.widget.dependencies.pluginPlatform;if(Z&&!Z.showToast){let o0=this.toastController;Z.showToast=(w1)=>o0.show(w1,"success")}if(Z&&!Z.showOpenedURLToast){let o0=this.toastController;Z.showOpenedURLToast=(w1)=>o0.show(`Opened URL: ${w1}`,"success",8000)}if(Z&&!Z.appendToThreadHandler){let o0=this.widget.dependencies;Z.appendToThreadHandler=async(w1)=>{for(let O1 of w1)await o0.activeThreadHandle.queueMessage([{type:"text",text:O1.content}])}}if(Z&&!Z.showInputDialog)Z.showInputDialog=(o0)=>{return new Promise((w1)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:o0,resolve:w1}})})};if(Z&&!Z.showConfirmDialog)Z.showConfirmDialog=(o0)=>{return new Promise((w1)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingConfirmDialog={options:o0,resolve:w1}})})};let Q=o1.of(J),Y=f0.of(J),X=Y.base;this.themeColors=X;let{colors:U,app:V}=Y;this.themeApp=V;let K=this.widget.dependencies.threadState.mainThread,D=K?.agentMode&&P8(K.agentMode),z=this.freeTierStatus.isDailyGrantEnabled,q=!this.adsDisabledBySetting&&(D||z)&&this.randomAd!==null,F=Boolean(q),{threadState:G}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=G.items,B=G.mainThread||void 0,w=G.subagentToolsByParentID,N=G.todosList,E=B?.id,O=B,L=this.isTranscriptEmpty(),I=(o0)=>new Ip({key:new s5(`preview-message-view-${o0.id}`),items:Fq(o0).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:o0,denseView:o0.agentMode==="deep",focusNode:new n4({debugLabel:"PreviewFocus"}),onShowImagePreview:()=>{},stateController:this.previewMessageViewController,submitOnEnter:this.submitOnEnter}),M=this.previewThread,A=M?M.messages.length>2000?new u0({mainAxisSize:"max",children:[new S1({child:new j0}),new a0({padding:C0.all(2),child:new n1({child:new Q0({text:new C("Thread too long for preview",new b({color:U.mutedForeground,dim:!0}))})})})]}):I(M):L?new V20({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,onOrbExplode:this.handleSplashOrbExplode}):new qp0({threadID:E,items:H,subagentToolsByParentID:w,controller:E?this.getMessageScrollController(E):new o6,autofocus:!1,onCopy:this.handleMainMessageViewCopy,thread:O,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:!this.widget.dependencies.activeThreadHandle.restoreMessage?void 0:this.handleMessageRestoreSubmit,onShowForkDeprecation:this.showForkDeprecationMessage,getAffectedFiles:this.getAffectedFiles,denseView:O?.agentMode==="deep",focusNode:this.messageViewFocusNode,onDismissFocus:this.handleMainMessageViewDismissFocus,isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:this.getCompletionBuilder(),onShowImagePreview:this.handleShowEditingImagePreview,onSelectionChanged:this._handleSelectionChanged,onDoubleAtTrigger:this.handleDoubleAtTrigger,stateController:this.messageViewController,submitOnEnter:this.submitOnEnter,threadViewState:G.viewState}),R=Math.max(Math.floor(Q.size.height*0.4),12),_=this.getCurrentEphemeralError(),S=Q.size.width<40,y=$E4(G),h=a90(J),f=this.buildBottomWidget(_,W,U,Y,G,N,R,F,y,Q,h),k=new J20({threadViewState:G.viewState,threadTokenUsage:y,threadID:E??null,thread:G.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,plugins:this.pluginInfos,isNarrow:S,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(G.viewState.state==="active"&&G.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),x=new l70({bashInvocations:this.bashInvocations}),g=[],a=WY4(this.widget.dependencies.buildTimestamp);if(a){let o0=TO0(a.ageMs,{verbose:!0});g.push(new d0({decoration:new T4(U.destructive),child:new a0({padding:C0.horizontal(1),child:new Q0({text:new C("",new b({color:U.foreground,bold:!0}),[new C(`Your Amp version is ${o0} old — run `),new C("amp update",new b({color:U.warning})),new C(" or see ampcode.com/manual")]),textAlign:"center"})})}))}g.push(new S1({child:A}),x);let m=new D5({children:[new u0({mainAxisSize:"min",children:[q?new Zm0({ad:this.randomAd,onImpression:(o0)=>{if(!o0.advertiserId){P.warn("[ad-telemetry] Skipping impression due to missing advertiserId",{adId:o0.id});return}let w1=o0.impressionId??eN4(16).toString("hex");this.lastAdImpressionId=w1;let O1=this.widget.dependencies.threadState.mainThread;if(!O1)return;let L4=O1.messages[O1.messages.length-1],h4=Date.now();zN("viewed",{adId:o0.id,advertiserId:o0.advertiserId,threadId:O1.id,messageId:L4?.messageId,impressionId:w1,placement:"tui",matchType:o0.metadata?.matchType,matchedPatterns:o0.metadata?.matchedPatterns,candidateAdPoolCount:o0.metadata?.candidateAdPoolCount,clientRegion:o0.metadata?.clientRegion,tokenProvided:!!o0.impressionToken,campaignId:o0.metadata?.campaignId,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType,relevance:o0.metadata?.relevance}),zN("impressionStarted",{adId:o0.id,advertiserId:o0.advertiserId,impressionId:w1,placement:"tui",providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType}),this.widget.dependencies.internalAPIClient.recordAdImpression({adId:o0.id,impressionToken:o0.impressionToken,impressionId:w1,externalImpressionUrl:o0.externalImpressionUrl},{config:this.widget.dependencies.configService}).then((l5)=>{if(!l5.ok)throw Error(`recordAdImpression failed: ${l5.error.code??"unknown"}`);let p7=Math.round(Date.now()-h4);zN("impressionRecorded",{adId:o0.id,advertiserId:o0.advertiserId,impressionId:w1,placement:"tui",durationMs:p7,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType})}).catch((l5)=>{let p7=Math.round(Date.now()-h4);zN("impressionFailed",{adId:o0.id,advertiserId:o0.advertiserId,impressionId:w1,errorMessage:l5 instanceof Error?l5.message:String(l5),errorType:"error",placement:"tui",durationMs:p7,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType})})},onButtonClick:async()=>{let o0=this.randomAd;if(this.lastAdImpressionId&&o0.advertiserId){let L4=this.widget.dependencies.threadState.mainThread;if(!L4)return;let h4=L4.messages[L4.messages.length-1];zN("clicked",{adId:o0.id,advertiserId:o0.advertiserId,threadId:L4.id,messageId:h4?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:o0.metadata?.matchType,matchedPatterns:o0.metadata?.matchedPatterns,candidateAdPoolCount:o0.metadata?.candidateAdPoolCount,clientRegion:o0.metadata?.clientRegion,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType})}let O1=a4.instance.tuiInstance.clipboard.isOsc52Supported();if(S30())this.setState(()=>{this.adActionModal={showCopyOption:!1,url:o0.shortDestinationUrl,title:o0.buttonLabel},this.bringAdModalToFront("adAction")});else if(!await K8(this.context,o0.shortDestinationUrl))this.setState(()=>{this.adActionModal={showCopyOption:O1,url:o0.shortDestinationUrl},this.bringAdModalToFront("adAction")})},onAdInfoClick:()=>{this.setState(()=>{this.adInfoModal={provider:this.randomAd?.metadata?.provider},this.bringAdModalToFront("adInfo")})}}):new j0({height:0}),new d0({constraints:new A1(0,Q.size.width,0,R),child:f})]}),F?new $5({top:0,left:0,right:0,child:new QE4({userHeight:this.bottomGridUserHeight,maxHeight:R,onInitializeHeight:(o0)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(o0,R)})},onDrag:(o0)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(o0.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let w1=Math.floor(o0.localPosition.y)-this.bottomGridDragStartY,O1=Math.max(4,this.bottomGridDragStartHeight-w1),L4=Math.min(O1,R),h4=Math.floor(L4);if(this.bottomGridUserHeight!==h4)this.setState(()=>{this.bottomGridUserHeight=h4})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new j0({height:0})]}),i=this.getParentThreadInfo();if(i){let o0=i.type==="handoff"?V.handoffMode:U.primary,w1=40,O1=K5(i.title),L4=O1.length>40?O1.slice(0,39).join("")+"…":i.title;g.push(new lg({link:this.parentThreadLinkAnchor,child:new dm0({type:i.type,title:L4,threadID:i.threadID,labelColor:o0,mutedColor:U.mutedForeground,foregroundColor:U.foreground,onNavigate:(h4)=>this.switchToExistingThread(h4)})}))}g.push(m,new j0({height:1,child:new a0({padding:C0.horizontal(1),child:k})}));let d=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:g}),e=new d0({constraints:A1.tight(Q.size.width,Q.size.height),decoration:new T4(U.background),child:d}),N0=new o4(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingAuthLogin)return this.cancelAuthLoginSession(),"handled";if(this.pendingOAuthRequest){let w1=this.pendingOAuthRequest;return this.setState(()=>{this.pendingOAuthRequest=null}),w1.reject(Error("OAuth authorization cancelled")),"handled"}if(this.isShowingPromptHistoryPicker)return this.setState(()=>{this.isShowingPromptHistoryPicker=!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.isShowingContextAnalyzeModal)return this.setState(()=>{this.isShowingContextAnalyzeModal=!1}),"handled";if(this.isShowingSkillListModal)return this.setState(()=>{this.isShowingSkillListModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!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.dismissTopAdModal())return"handled";if(this.handoffState.countdownSeconds!==null)return this.handoffController?.stopCountdown(),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.isInQueueMode)return this.exitQueueMode(),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let w1=this.handoffController.getPendingPrompt(),O1=this.imageAttachments;return this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((L4)=>{if(L4&&w1)this.textController.text=w1,this.handoffController?.clearPendingPrompt();if(L4&&O1.length>0)this.setState(()=>{this.imageAttachments=O1})}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.cancelStreamingMessage().catch((w1)=>{P.error("Failed to cancel streaming message:",w1)}),this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return P.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.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread))return this.handoffController.startAbortConfirmation(),"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"}),n=new o4(()=>{return this.onExitPressed(),"handled"}),V0=new o4(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),U0=new o4(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),B0=new o4(()=>{if(p9.instance.toggleAll(),G.mainThread?.agentMode==="deep")n$.instance.toggleAll();return"handled"}),X0=new o4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return this.setState(()=>{this.isShowingPromptHistoryPicker=!0}),"handled"}),W0=new o4(()=>{return a4.instance.toggleFrameStatsOverlay(),"handled"}),l=new o4(()=>{return a4.instance.tuiInstance.getScreen().markForRefresh(),q6.instance.requestFrame(),"handled"}),r=new o4(()=>{return this.toggleAgentMode(),"handled"}),J0=new o4(()=>{return this.toggleDeepReasoningEffort(),"handled"}),c=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageUp(L4,100)}return"handled"}),o=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageDown(L4,100)}return"handled"}),$0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageUp(Math.floor(L4/2),100)}return"handled"}),D0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageDown(Math.floor(L4/2),100)}return"handled"}),q0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1)w1.animateTo(0,100);return"handled"}),A0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1)w1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),H0=new o4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";if(this.isInQueueMode)return"ignored";let{threadState:o0}=this.widget.dependencies;if(!o0.mainThread?.messages.some((O1)=>O1.role==="user"||mF(O1)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),I0=new o4((o0)=>{if(o0.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),_0=new o4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return g70().then(async(o0)=>{if(o0)await this.handleInsertImage(o0)}),"handled"}),X1=new Map([[$4.ctrl("c"),new Pg],[$4.ctrl("l"),new Sg],[$4.ctrl("o"),new b70],[$4.ctrl("v"),new jg],[$4.alt("s"),new yC],[$4.ctrl("s"),new yC],[$4.alt("p"),new _g],[$4.ctrl("r"),new ug],[$4.alt("t"),new Tg],[$4.ctrl("t"),new kg],[$4.key("PageUp"),new v70],[$4.key("PageDown"),new k70],[$4.alt("k"),new y70],[$4.alt("j"),new u70],[$4.key("Home"),new x70],[$4.key("End"),new f70],[$4.key("Escape"),new Rg],[$4.ctrl("p"),new uC("previous")],[$4.ctrl("n"),new uC("next")],[$4.key("Tab"),new cg]]);if(X1.set($4.alt("d"),new vg),!m9())X1.set($4.key("ArrowUp"),new cg);if(!1)X1.set($4.alt("c"),new Cg);let L1=new o4(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),K4=new o4(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),D4=new o4(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),c0=new Map([[Rg,N0],[Sg,l],[yC,r],[vg,J0],[b70,L1],[jg,_0],[Cg,V0],[d90,U0],[Tg,B0],[_g,W0],[kg,K4],[ug,X0],[Pg,n],[v70,c],[k70,o],[y70,$0],[u70,D0],[x70,q0],[f70,A0],[cg,H0],[uC,I0],[yg,D4]]),i0=[e];if(this.splashOrbExplosion){let o0=Qg(this.getEffectiveAgentMode());i0.push(new Yp0({key:new s5(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,sparkleColors:[o0,U.warning],onComplete:this.handleSplashOrbExplosionComplete}))}if(this.isShowingConsoleOverlay)i0.push(new fm0);if(this.isShowingHelp&&this.paletteConfig)i0.push(new cm0({commands:this.getPaletteCommands().getAllCommands(),submitOnEnter:this.submitOnEnter}));if(this.isShowingContextAnalyzeModal){let{configService:o0}=this.widget.dependencies,w1=this.contextAnalyzeDeps;if(w1){let O1={configService:o0,agentModeOverride:this.getEffectiveAgentMode(),buildSystemPromptDeps:w1};i0.push(new bm0({deps:O1,thread:this.widget.dependencies.threadState.mainThread,onDismiss:()=>{this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null})}}))}else this.setState(()=>{this.isShowingContextAnalyzeModal=!1})}if(this.isShowingSkillListModal&&!this.isShowingPalette)Promise.all([this.widget.dependencies.skillService.getSkills(),this.widget.dependencies.skillService.getSkillErrors(),this.widget.dependencies.skillService.getSkillWarnings()]).then(([o0,w1,O1])=>{if(this.isShowingSkillListModal&&this.mounted)this.skillListData={skills:o0,errors:w1,warnings:O1},this.setState()}),i0.push(new Kp0({skills:this.skillListData?.skills??[],errors:this.skillListData?.errors??[],warnings:this.skillListData?.warnings??[],cwd:process.cwd(),onDismiss:()=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null})},onAddSkill:()=>{this.showCommandPalette({type:"standalone",commandId:"skill-add",onSubmit:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.isShowingSkillListModal=!1,this.skillListData=null})},onCancel:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})}})},onDocs:()=>{LX("https://ampcode.com/manual#agent-skills")},onInsertPrompt:(o0)=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null,this.textController.text=o0})},onInvokeSkill:(o0)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill({name:o0})}}));if(this.isShowingMCPStatusModal)i0.push(new Dg0({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingPromptHistoryPicker)i0.push(new Xp0({entries:this.widget.dependencies.history.getAll(),currentCwd:process.cwd(),onAccept:(o0)=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1,this.textController.text=o0,this.textController.cursorPosition=o0.length})},onDismiss:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)i0.push(new Zp0({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.isShowingForkDeprecationModal)i0.push(new gm0({onDismiss:this.dismissForkDeprecationModal}));for(let o0=0;o0<this.adModalStack.length;o0++){let w1=this.adModalStack[o0],O1=o0===this.adModalStack.length-1;if(w1==="adAction"&&this.adActionModal)i0.push(new Qm0({key:new s5(`ad-action-modal-${O1?"top":"back"}`),title:this.adActionModal.title??"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(L4)=>{let h4=this.adActionModal.url;if(L4==="copy")try{await a4.instance.tuiInstance.clipboard.writeText(h4),this.setState(()=>{this.displayMessage=new J$("Link copied to clipboard")})}catch(l5){P.error("Failed to copy to clipboard",{error:l5}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null,this.removeAdModalFromStack("adAction")})}}));if(w1==="adInfo"&&this.adInfoModal)i0.push(new Ym0({key:new s5(`ad-info-modal-${O1?"top":"back"}`),provider:this.adInfoModal.provider,onClose:()=>{this.setState(()=>{this.adInfoModal=null,this.removeAdModalFromStack("adInfo")})}}))}if(this.pendingMCPServers.length>0){let{mcpTrustHandler:o0}=this.widget.dependencies;i0.push(new zg0({servers:this.pendingMCPServers,onAlwaysTrust:o0.trustAlways.bind(o0),onTrustOnce:o0.trustOnce.bind(o0),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:o0.deny.bind(o0)}))}if(this.pendingAuthLogin)i0.push(new Xm0({manualURL:this.pendingAuthLogin.manualURL,isAuthenticating:this.pendingAuthLogin.isAuthenticating||this.pendingAuthLogin.isOpeningBrowser,errorMessage:this.pendingAuthLogin.errorMessage}));if(this.pendingOAuthRequest)i0.push(new Qp0({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.pendingInputDialog){let o0=this.pendingInputDialog;i0.push(new am0({options:o0.options,onSubmit:(w1)=>{this.setState(()=>{this.pendingInputDialog=null}),o0.resolve(w1)},onCancel:()=>{this.setState(()=>{this.pendingInputDialog=null}),o0.resolve(void 0)}}))}if(this.pendingConfirmDialog){let o0=this.pendingConfirmDialog;i0.push(new ym0({options:o0.options,onConfirm:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),o0.resolve(!0)},onCancel:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),o0.resolve(!1)}}))}if(this.isShowingFileChangesOverlay)i0.push(new lh0({threadData:G}));if(this.isShowingContextDetailOverlay){let o0=this.threadCostInfo?.costBreakdownURL;i0.push(new hm0({tokenUsage:y??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:o0?()=>{K8(J,o0)}:void 0}))}if(this.isShowingConfirmationOverlay)i0.push(new um0({details:this.confirmationOverlayContent}));if(this.imagePreview!==null)i0.push(new n1({child:new nm0({image:this.imagePreview.image,imageIndex:this.imagePreview.index,onDismiss:this.handleImagePreviewDismiss,onRemove:this.handleImagePreviewRemove})}));if(this.fileImagePreviewPath!==null)i0.push(new n1({child:new Ng({filePath:this.fileImagePreviewPath,onDismiss:this.handleFileImagePreviewDismiss})}));if(this.painterImagePreview!==null)i0.push(new n1({child:new Ng({filePath:this.painterImagePreview.filePath,onDismiss:this.handlePainterImagePreviewDismiss})}));if(this.painterSaveDialog!==null)i0.push(new n1({child:new Ng({filePath:this.painterSaveDialog.filePath,imageBlock:this.painterSaveDialog.image,onDismiss:this.handlePainterSaveDialogDismiss})}));if(this.skillPreview!==null){let o0=this.pendingSkills[this.skillPreview.skillIndex];if(o0)i0.push(new n1({child:new Dp0({pendingSkill:o0,skill:this.cachedSkillForPreview,onDismiss:this.handleSkillPreviewDismiss,onRemove:this.skillPreview.onRemove})}))}let e0=this.getCommandPaletteContext(J);if(e0&&this.isShowingPalette&&this.paletteConfig)i0.push(new n1({child:new vm0({commandContext:e0,mainThread:G.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)i0.push(new im0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let j1=new D5({children:i0});if(this.isShowingJetBrainsInstaller)return new KL({child:new j9({actions:c0,child:new B2({shortcuts:X1,debugLabel:"jetbrains-installer-shortcuts",child:new Vg0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let r1=this.widget.dependencies.threadState.mainThread?.id,j4=1+(this.bottomGridUserHeight??5)+1,v4=!this.isShowingPalette&&!this.isShowingIdePicker;return new NT({switchToThread:(o0)=>this.switchToExistingThread(o0),child:new QD({threadViewStates:this.getThreadViewStatesSnapshot(),threadTitles:this.threadTitles,threadSummaries:this.threadsForPicker,child:new pm0({getThreadCluster:this.getCurrentThreadClusterForMinimap,parentThreadID:i?.threadID,anchorLink:i?this.parentThreadLinkAnchor:void 0,bottomOffset:j4,enabled:v4,child:new JT({onShowImagePreview:this.handleShowFileImagePreview,child:new ZT({onShowImagePreview:this.handleShowPainterImagePreview,onShowSaveDialog:this.handleShowPainterSaveDialog,child:new uY({controller:this.toastController,child:new KL({child:new ug0({getThreadCluster:this.getThreadClusterForMinimap,currentThreadID:r1,enabled:v4,child:new kH({enabled:v4,child:new z90({controller:this.toastController,child:new j9({actions:c0,child:new B2({shortcuts:X1,debugLabel:"main-app-shortcuts",child:j1})})})})})})})})})})})})}buildScrollableTodoList(J,Z,Q){return new JE4({todos:J,enabled:Z,controller:this.todoScrollController,appTheme:Q})}buildBottomWidget(J,Z,Q,Y,X,U,V,K,D,z,q){if(J)return new mm0({error:J,options:{ampURL:this.widget.dependencies.ampURL,freeTierEnabled:this.freeTierStatus.canUseAmpFree},onResponse:this.handleEphemeralErrorResponse});if(Z){if(this.displayMessage)this.handleDisplayMessageDismiss();return new xm0({confirmationRequest:Z,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new qg0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let F=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?[]:c70(Y),G=this.agentModeController?.isInRestrictedFreeMode()??!1,W=this.isTextfieldAndAutocompleteFocused&&!G&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff;if(W&&!this.hasReplayedEarlyInput){this.hasReplayedEarlyInput=!0;let c=a4.instance.tuiInstance.getEarlyInputText();if(c)this.textController.insertText(c)}let H=this.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}},B=new Lp({key:this.textFieldKey,controller:this.textController,triggers:[new pH],completionBuilder:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:this.onTextSubmitted,submitKey:H,theme:Q,placeholder:G?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:W,shellPromptRules:F,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker&&!this.isShowingSkillListModal,clipboard:a4.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let c=this.previousThreadIdForHint;if(c)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${c} `},onDoubleAtTrigger:(c)=>{this.handleDoubleAtTrigger(c)},pendingSkills:this.pendingSkills,onClearPendingSkill:(c)=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(c)},popSkill:()=>{let c=this.pendingSkills[this.pendingSkills.length-1];if(c)this.widget.dependencies.activeThreadHandle.removePendingSkill(c.name)},onSkillClick:this.handleSkillClick,topWidget:this.isShowingShortcutsHelp?new Vp0({submitOnEnter:this.submitOnEnter}):void 0}),w=X.mainThread?.queuedMessages??[],N=Array.isArray(U)&&U.length>0,O=Array.isArray(w)&&w.length>0?new Up0({queuedMessages:w}):void 0,L=N?this.buildScrollableTodoList(U,this.isTextfieldAndAutocompleteFocused&&!G,Y):void 0,I=[],M=null,A=0,R=z.capabilities.emojiWidth,_=this.widget.dependencies.threadPool,S=_.isDTWMode?.()===!0,y=S?_.getTransportConnectionState?.():void 0;if(S&&y!==void 0)I.push({child:new Q0({text:new C(`(dtw: ${y})`,new b({color:Q.mutedForeground,dim:!0}))}),position:"top-left"});let h=this.currentShellModeStatus;if(h)I.push({child:new Q0({text:new C(h==="hidden"?"shell mode (incognito)":"shell mode",new b({color:h==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let c=new b({color:Y.app.handoffMode}),o=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new C("",void 0,[new C("handoff ",c),new C(this.handoffState.spinner.toBraille(),c)]):new C("handoff (submit a goal for the new thread)",c);if(I.push({child:new Q0({text:o}),position:"top-left"}),this.handoffState.isGeneratingHandoff){let $0=new b({color:Q.foreground,dim:!0});I.push({child:new Q0({text:new C("",void 0,[new C("Esc",new b({color:Y.app.keybind})),new C(" to cancel",$0)])}),position:"bottom-left"}),A=r5("Esc to cancel",R)}}if(this.handoffState.countdownSeconds!==null){let c=new b({color:Q.foreground,dim:!0}),o=`Auto-submitting in ${this.handoffState.countdownSeconds}s`,$0=this.handoffState.countdownSeconds<10?1:0;I.push({child:new a0({padding:C0.only({right:$0}),child:new Q0({text:new C(o,new b({color:Y.app.handoffMode}))})}),position:"bottom-left"}),I.push({child:new Q0({text:new C("",void 0,[new C("type",new b({color:Y.app.keybind})),new C(" to edit",c)])}),position:"bottom-left"}),A=r5("Auto-submitting in 10s",R)+2+r5("type to edit",R)}if(this.isInQueueMode){let c=new b({color:Y.app.queueMode});I.push({child:new Q0({text:new C("queue",c)}),position:"top-left"})}let f=this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread)??null,k=z.capabilities.animationSupport,x=k==="disabled"?0:k==="slow"?30:60,g=this.getEffectiveAgentMode(),a=Qg(g),m=null,i=this.agentModeController?.getVisibleModes()??[];if(!h&&!this.isInQueueMode&&i.length>1){let c=this.previewThread,o=this.agentModeController?.getMode(),$0=c?c.agentMode??this.getEffectiveAgentMode():this.handoffState.isGeneratingHandoff&&o?o:this.getEffectiveAgentMode(),D0=this.formatAgentModeLabel($0),q0=$0==="smart"&&this.anthropicSpeed==="fast",A0=q0?"smart+fast(6x$)":D0,H0=Qg($0),I0=c??this.widget.dependencies.threadState.mainThread,_0=I0?Y8(I0)>0:!1,X1="top-right";if(c){m=r5(A0,R);let F1=q0?new C("",void 0,[new C("smart",new b({color:H0})),new C("+fast(6x$)",new b({color:Q.warning}))]):new C(D0,new b({color:H0}));I.push({child:new Q0({text:F1}),position:"top-right"})}else{let F1=!_0&&!this.handoffState.isGeneratingHandoff,L1=this.handoffState.isGeneratingHandoff,K4=new b({color:H0,dim:L1}),D4=new Q0({text:q0?new C("",void 0,[new C("smart",K4),new C("+fast(6x$)",new b({color:Q.warning,dim:L1}))]):new C(D0,K4)}),c0=r5(A0,R),e0=[F1?new i1({child:D4,onClick:()=>this.toggleAgentMode(),cursor:"pointer"}):D4];if(m=c0,this.showSkillsCountInPromptBar){let j1=this.availableSkillCountReady?this.availableSkillCount:this.widget.dependencies.skillService.listInstalled().length,r1=this.skillWarningCount>0||this.skillErrorCount>0,j4=`${r1?"⚠ ":""}${j1} ${g4(j1,"skill")}`,v4=2,o0=r5(j4,R);m+=2+o0;let w1=new b({color:r1?Q.warning:Q.foreground,dim:!r1});e0.push(new j0({width:2}),new i1({child:new Q0({text:new C(j4,w1)}),onClick:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},cursor:"pointer"}))}I.push({child:new D1({mainAxisSize:"min",children:e0}),position:"top-right"})}}if(x>0&&this.agentModePulseSeq>0&&!h&&!this.isInQueueMode&&!f&&i.length>1){let o=S2(g)?.uiHints?.fasterAnimation?3:1,$0=(m??0)+1,D0=$0>0?2+$0:1;M=new $5({top:0,left:1,right:D0,height:1,child:new Kg0({color:a,backgroundColor:Q.background,trigger:this.agentModePulseSeq,fps:x,speed:o,trail:5,leftOffset:0,direction:"right-to-left"})})}if(f&&this.handoffState.countdownSeconds===null){let c=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";I.push({child:new Q0({text:new C("",void 0,[new C("Esc",new b({color:Y.app.keybind})),new C(c,new b({color:Q.foreground,dim:!0})),new C("handoff",new b({color:Y.app.handoffMode}))])}),position:"bottom-left"}),A=r5(`Esc${c}handoff`,R)}if(!f&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")I.push({child:new Q0({text:new C("",void 0,[new C("press ",new b({color:Q.foreground,dim:!0})),new C("enter",new b({color:Y.app.keybind})),new C(" to reference the previous thread",new b({color:Q.foreground,dim:!0}))])}),position:"bottom-left"}),A=r5("press enter to reference the previous thread",R);let n=X.mainThread?.env?.initial.trees?.[0]?.uri,V0;if(n)V0=V1.parse(n).fsPath;else V0=process.cwd();let U0=this.toHomeRelative(V0),B0=this.shorten(U0),X0=A>0?z.size.width-A-6:z.size.width-4,W0=this.buildDisplayText(B0,this.currentGitBranch||void 0,X0,R);I.push({child:new Q0({text:new C(W0,new b({color:Q.foreground,dim:!0}))}),position:"bottom-right"});let l=this.previewThread,r=this.widget.dependencies.threadState.mainThread;if((r?Y8(r)>0:!1)&&!h&&!this.handoffState.isInHandoffMode&&!l){let c=[],o=new b({color:Q.foreground,dim:!0}),$0=new C(" · ",o);if(D){let I0=D.totalInputTokens/D.maxInputTokens,_0=Math.round(I0*100),X1=Math.max(0,Math.min(_0,100)),F1=$20(I0,D.maxInputTokens),L1=o;if(F1==="danger")L1=new b({color:Q.destructive});else if(F1==="warning")L1=new b({color:Q.warning});else if(F1==="recommendation")L1=new b({color:Y.app.recommendation});if(c.length>0)c.push($0);if(D.maxInputTokens>=1000){let K4=Math.round(D.maxInputTokens/1000);c.push(new C(`${X1}% of ${K4}k`,L1))}else c.push(new C(`${X1}%`,L1))}if(q&&this.threadCostInfo){let I0=j20(this.threadCostInfo,{colors:{foreground:Q.foreground},dim:!0});if(I0.length>0){if(c.length>0)c.push($0);c.push(...I0)}}let D0=X.viewState,q0=D0.state==="active"?D0.turnStartTime:void 0,A0=D0.state==="active"?D0.turnElapsedMs:void 0,H0=null;if(X.mainThread?.agentMode==="deep"){let I0=q0?Date.now()-q0:A0;if(I0!==void 0){let _0=Uy1(I0);H0=new Q0({text:new C(_0,o)})}}if(c.length>0||H0){let I0=[];if(c.length>0){let _0=new Q0({text:new C("",void 0,c)});I0.push(q?new i1({child:_0,onClick:this.showContextDetailOverlay,cursor:"pointer"}):_0)}if(H0){if(c.length>0)I0.push(new Q0({text:new C(" · ",o)}));I0.push(H0)}I.push({child:new D1({mainAxisSize:"min",children:I0}),position:"top-left"})}}return new Um0({leftChild:new S1({child:B}),rightChild1:O,rightChild2:L,maxHeight:V,overlayTexts:I,overlayLayer:M,backgroundColor:Q.background,borderColor:G||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?Q.border:void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(c)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(c,V)})},onDrag:(c)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(c.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let o=Math.floor(c.localPosition.y)-this.bottomGridDragStartY,$0=Math.max(4,this.bottomGridDragStartHeight-o),D0=Math.min($0,V),q0=Math.floor(D0);if(this.bottomGridUserHeight!==q0)this.setState(()=>{this.bottomGridUserHeight=q0})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}function $E4(J){return J.resolvedTokenUsage}class JE4 extends p0{props;constructor(J){super();this.props=J}createState(){return new ZE4}}class ZE4 extends g0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Z,controller:Q,appTheme:Y}=this.widget.props;return new D1({crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:Q,autofocus:!1,child:new Wp0({todos:Z})})}),new j8({controller:Q,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:U}=Q,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(U,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 Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let U=Y.children||[];for(let V of U){if(V&&"size"in V){let D=V.size;if(typeof D?.height==="number"&&D.height>0)return D.height}let K=Z(V,X+1);if(K>0)return K}}return 0},Q=Z(J);if(Q>0)return Q;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class QE4 extends c1{props;constructor(J){super();this.props=J}build(J){return new i1({child:new j0({height:1}),cursor:H5.NS_RESIZE,onDrag:(Z)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Z)},onRelease:this.props.onRelease})}}function XE4(J){let Z=J.split(`
|
|
7386
|
+
`).length,B=Math.max(Math.min(H,F),3);this._viewportHeight=B;let w=new f3({markdown:Q.content}),N=new d0({constraints:new A1({maxHeight:B}),child:new D1({crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:this._scrollController,autofocus:!1,child:w})}),new j8({controller:this._scrollController,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let E=this._scrollController.maxScrollExtent,O=this._scrollController.offset,L=this._viewportHeight,I=E+L;return{totalContentHeight:Math.max(I,0),viewportHeight:Math.max(L,1),scrollOffset:Math.max(O,0)}}})]})});G.push(N),G.push(new j0({height:1}))}}else G.push(new Q0({text:new C("(Loading skill details...)",new b({color:Y.foreground,dim:!0,italic:!0}))})),G.push(new j0({height:1}));if(Z.arguments)G.push(new Q0({text:new C("",void 0,[new C("Arguments: ",new b({color:Y.foreground,dim:!0})),new C(Z.arguments,new b({color:Y.foreground}))])})),G.push(new j0({height:1}));let W=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Q0({text:new C("",void 0,[new C(Z.name,new b({bold:!0,color:Y.success,underline:!0}))])}),new j0({height:1}),...G,new k7({options:this.getOptions(),onSelect:this.handleSelect,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})]});return new _4({onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"},child:new n1({child:new $H(new d0({constraints:new A1(D,D,0,z),decoration:{color:Y.background,border:f1.all(new y1(Y.success,1,"rounded"))},padding:C0.symmetric(2,1),child:W}))})})}}function mp5(J,Z){if(J===Z)return!0;let Q=Object.keys(J),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;for(let X of Q){if(!(X in Z))return!1;if(!Object.is(J[X],Z[X]))return!1}return!0}class zp0 extends p0{stableProps;arePropsEqual;constructor({key:J,stableProps:Z,arePropsEqual:Q}){super(J?{key:J}:{});this.stableProps=Z,this.arePropsEqual=Q??mp5}createState(){return new X$0}}class X$0 extends g0{cachedChild=null;build(J){let{stableProps:Z,arePropsEqual:Q}=this.widget,Y=this.cachedChild;if(Y&&Q(Y.props,Z))return Y.widget;let X=this.widget.buildStableChild(Z);return this.cachedChild={props:Z,widget:X},X}dispose(){this.cachedChild=null}}class qp0 extends zp0{constructor(J){super({stableProps:J})}createState(){return new oN4}buildStableChild(J){let{threadID:Z,...Q}=J;return new Ip({...Q,key:Z?new s5(`message-view-${Z}`):void 0})}}class oN4 extends X$0{build(J){return super.build(J)}}W1();function gp5(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),U=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(U<=4)return`${U}w ago`;return`${V}mo ago`}class Fp0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList(Z).subscribe((U)=>{X.unsubscribe(),Y(U)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadHistoryService.observeHistory().pipe(H1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let U=X.title?.toLowerCase()||"untitled",V=X.id.toLowerCase(),K=Z.toLowerCase();return U.includes(K)||V.includes(K)}).map((X)=>{let U=new Date(X.userLastInteractedAt),V=gp5(U),K=X.id.slice(-8),D=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:V,title:X.title||"Untitled",shortThreadID:K},diffStats:X.summaryStats?.diffStats,workspaceURI:D,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}h0();f4();f4();function rN4(J){let Z=nI1(J),Q=Array.from(Z.entries()).map(([U,V])=>({path:U,diffStats:V})),X=t7(J)?.totalInputTokens??0;return{filesAffected:Q,totalTokens:X}}class Gp0{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new o6;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){P.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Z=await this.threadService.get(J);if(Z){if(this.currentId===J)this.current=Z,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 Z=this.listeners.indexOf(J);if(Z!==-1)this.listeners.splice(Z,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Z=rN4(this.current);return this.statsCache.set(this.current.id,{stats:Z,version:this.current.v}),Z}clearStatsCache(){this.statsCache.clear()}dispose(){this.cancelTimerAndSubscription(),this.clearStatsCache(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){P.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(Go()).subscribe((Z)=>{if(this.currentId===J)this.current=Z,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)}}class Wp0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new sN4}}class sN4 extends g0{build(J){let Q=f0.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new j0({width:0,height:0});let U=Y.map((V)=>this.buildTodoItem(V,Q));return new d0({child:new a0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Q0({text:new C(X,new b({bold:!0,color:Q.foreground}))}),...U]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),Y=J.status==="completed",X=new b({bold:J.status==="in-progress",color:Z.foreground,dim:Y}),U=new b({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:Y});return new D1({crossAxisAlignment:"start",children:[new Q0({text:new C(Q,X)}),new j0({width:1}),new S1({child:new Q0({text:new C(J.content,U)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}function tN4(J,Z){switch(J){case"update-available":return[new C("A newer Amp is available. Run ",new b({color:Z.foreground,dim:!0})),new C("amp update",new b({color:Z.warning}))];case"update-available-unrecognized-path":return[new C("A newer Amp is available.",new b({color:Z.foreground,dim:!0}))];case"update-available-brew":return[new C("A newer Amp is available. Run ",new b({color:Z.foreground,dim:!0})),new C("brew upgrade ampcode",new b({color:Z.warning}))];case"updated":return null;case"updated-with-warning":return[new C("Update complete, run ",new b({color:Z.foreground,dim:!0})),new C("amp update",new b({color:Z.warning})),new C(" to see warnings",new b({color:Z.foreground,dim:!0}))];case"update-error":return[new C("Update failed, run ",new b({color:Z.foreground,dim:!0})),new C("amp update",new b({color:Z.warning})),new C(" to see warnings",new b({color:Z.foreground,dim:!0}))];case"hidden":return null}}async function rp5(J){return new Promise((Z)=>{pp5("git",["branch","--show-current"],{cwd:J},(Q,Y)=>{if(Q){Z(null);return}let X=Y.trim();Z(X||null)})})}class Hp0 extends p0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new U$0}}class U$0 extends g0{debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";lastThreadStatusDebugSignature=null;themeColors=null;themeApp=null;ideStatus=null;randomAd=null;adSubscription=null;adsDisabledBySetting=!1;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingShortcutsHelp=!1;isShowingContextAnalyzeModal=!1;isShowingSkillListModal=!1;skillListData=null;shortcutsHintUsed=!1;deepReasoningEffort="medium";anthropicSpeed=void 0;deepReasoningEffortSubscription=null;anthropicSpeedSubscription=null;sessionState=UC;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;lastInferenceState=void 0;elapsedTimeTimer=null;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;skillListSubscription=null;skillWarningsSubscription=null;skillErrorsSubscription=null;availableSkillCount=0;availableSkillCountReady=!1;showSkillsCountInPromptBar=!0;showSkillsCountInPromptBarSubscription=null;skillWarningCount=0;skillErrorCount=0;pendingApprovals=[];pendingApprovalsSubscription=null;submitOnEnter=!0;submitOnEnterSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;isShowingPromptHistoryPicker=!1;paletteShowOptions=null;paletteOnThreadMentionSelected=null;threadsForPicker=[];parentThreadTitles=new Map;parentThreadTitleLoadsInFlight=new Set;clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Gp0;previewThread=null;todoScrollController=(()=>{let J=new o6;return J.followMode=!1,J})();contextAnalyzeDeps=null;openContextAnalyzeModal=()=>{this.widget.dependencies.createSystemPromptDeps().then((J)=>{this.contextAnalyzeDeps=J,this.setState(()=>{this.isShowingContextAnalyzeModal=!0})})};filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new n4({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new n4({debugLabel:"AutocompleteFocus"});autocompleteFocusNodeListener=null;isTextfieldAndAutocompleteFocused=!1;hasReplayedEarlyInput=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreview=null;fileImagePreviewPath=null;painterImagePreview=null;painterSaveDialog=null;messageViewController=new Q$0;previewMessageViewController=new Q$0;handleMainMessageViewCopy=(J,Z)=>{this._handleTextCopy(J,Z)};handleMainMessageViewDismissFocus=()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()};messageViewControllerUnsubscribe=null;lastEditingMessageOrdinal=null;skillPreview=null;cachedSkillForPreview=null;adActionModal=null;adInfoModal=null;adModalStack=[];newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;parentThreadLinkAnchor=new ig;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null,countdownSeconds:null};isInQueueMode=!1;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;pendingAuthLogin=null;authStatus="pending";authStatusSubscription=null;authModalKeyInterceptorUnsubscribe=null;isCreatingAuthLoginSession=!1;queuedPromptAfterAuth=null;pendingInputDialog=null;pendingConfirmDialog=null;mcpServers=[];mcpServersSubscription=null;pluginInfos=[];pluginInfosSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1,isDailyGrantEnabled:!1};agentModePulseSeq=0;updateState="hidden";updateServiceSubscription=null;toastController=new D90;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];isShowingForkDeprecationModal=!1;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];splashOrbExplosion=null;splashOrbExplosionSeq=0;freeTierStatusSubscription=null;allConnectedThreadActivityStatusesSubscription=null;allConnectedThreadActivityStatuses={};threadTitlesSubscription=null;threadTitles={};pendingNavigationSubscription=null;pluginCommands=[];pluginCommandsSubscription=null;async initNewsFeed(){let J=async(Q)=>{return W8(Q,void 0,this.widget.dependencies.configService)},Z=cb1();this.newsFeedReader=new bh0(Z,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Q)=>{if(Q.length>0)this.setState(()=>{this.newsFeedEntries=[...Q,...this.newsFeedEntries]})},error:(Q)=>{P.error("News feed error:",Q)}})}bringAdModalToFront(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J),this.adModalStack.push(J)}removeAdModalFromStack(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J)}getTopAdModal(){for(let J=this.adModalStack.length-1;J>=0;J--){let Z=this.adModalStack[J];if(Z==="adAction"&&this.adActionModal)return Z;if(Z==="adInfo"&&this.adInfoModal)return Z}return null}dismissTopAdModal(){let J=this.getTopAdModal();if(!J)return!1;return this.setState(()=>{if(J==="adAction")this.adActionModal=null;if(J==="adInfo")this.adInfoModal=null;this.removeAdModalFromStack(J)}),!0}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};onThreadSwitch(){this.handoffController?.resetUIState(),this.exitQueueMode(),this.isMessageViewInSelectionMode=!1,this.imagePreview=null}canInterruptQueuedInference(){let{threadPool:J,threadState:Z}=this.widget.dependencies,Q=(Z.mainThread?.queuedMessages?.length??0)>0;return J.queueOnSubmitByDefault&&Q&&EE(Z.viewState)}startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.recordNavigation(J);await this.widget.dependencies.threadPool.createThread(),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J??null})};canChangeAgentModeInPromptEditor(){return(this.messageViewController.editingMessageOrdinal===0||this.handoffState.isInHandoffMode)&&!this.handoffState.isGeneratingHandoff}getEffectiveAgentMode(){if(!this.agentModeController)return"smart";return(this.canChangeAgentModeInPromptEditor()?this.agentModeController.getMode():null)??this.agentModeController.getEffectiveMode()}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(J.viewState.interactionState==="handoff")return!0;if(Boolean(J.viewState.inferenceState==="running"))return!0;return J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued").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 Z=this.themeApp;if(!Z)return null;if(this.submitDisabledHint)return new C(this.submitDisabledHint,new b({color:J.foreground,dim:!0}));if(this.isExiting)return new C("Exiting...",new b({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C("",void 0,[new C("Ctrl+C",new b({color:Z.keybind})),new C(" again to exit",new b({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C("",void 0,[new C("Esc",new b({color:Z.keybind})),new C(" again to clear input",new b({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C("",void 0,[new C("Escape",new b({color:Z.keybind})),new C(" to close help",new b({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let z=this.getEffectiveAgentMode(),q=Qg(z);return new C("",void 0,[new C("Images aren't supported in ",new b({color:J.warning,dim:!1})),new C(z,new b({color:q})),new C(" mode.",new b({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new C("",void 0,[new C("Esc",new b({color:Z.keybind})),new C(" again to cancel",new b({color:J.foreground,dim:!0}))]);if(this.canInterruptQueuedInference())return new C("",void 0,[new C("Enter",new b({color:Z.keybind})),new C(" to interrupt",new b({color:J.foreground,dim:!0}))]);return new C("",void 0,[new C("Esc",new b({color:Z.keybind})),new C(" to cancel",new b({color:J.foreground,dim:!0}))])}let{threadState:Q}=this.widget.dependencies;if(this.statusMessage){if(this.debugThreadViewState)P.info("[tui-ui] footer status override",{source:"statusMessage",statusMessage:this.statusMessage,inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C(this.statusMessage,new b({color:J.foreground,dim:!0}))}let Y=tN4(this.updateState,J);if(Y){if(this.debugThreadViewState)P.info("[tui-ui] footer status override",{source:"updateState",inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C("",void 0,Y)}let X=this.getCurrentConfirmation(),U=$E4(Q),V=new tg({threadViewState:Q.viewState,tokenUsage:U,thread:Q.mainThread??void 0,waitingForConfirmation:!!X,showingEphemeralError:Boolean(Q.viewState.state==="active"&&Q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),K=sg(V);if(this.debugThreadViewState){let z=JSON.stringify({inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0,interactionState:Q.viewState.interactionState,statusType:K.type});if(z!==this.lastThreadStatusDebugSignature)this.lastThreadStatusDebugSignature=z,P.info("[tui-ui] footer thread status",JSON.parse(z))}let D=!this.shortcutsHintUsed||this.sessionState.launchCount<10;if(K.type==="none"&&!this.isShowingShortcutsHelp&&this.textController.text===""&&D)return new C("",void 0,[new C("?",new b({color:Z.keybind})),new C(" for shortcuts",new b({color:J.foreground,dim:!0}))]);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Z=Dk(J).filter((V)=>V.type==="fork"||V.type==="handoff");if(Z.length===0)return null;let Q=Z[0],Y=Q.threadID,X=this.threadsForPicker.find((V)=>V.id===Y);if(!X?.title)this.ensureParentThreadTitleLoaded(Y);let U=X?.title??this.parentThreadTitles.get(Y)??Y.slice(-8);return{type:Q.type==="handoff"?"handoff":"fork",title:U,threadID:Y}}ensureParentThreadTitleLoaded(J){if(this.parentThreadTitles.has(J)||this.parentThreadTitleLoadsInFlight.has(J))return;this.parentThreadTitleLoadsInFlight.add(J),this.widget.dependencies.threadService.getPrimitiveProperty(J,"title").then((Z)=>{if(!this.mounted||!Z)return;this.setState(()=>{this.parentThreadTitles.set(J,Z)})}).catch((Z)=>{P.debug("Failed to load parent thread title",{threadID:J,error:Z})}).finally(()=>{this.parentThreadTitleLoadsInFlight.delete(J)})}getThreadClusterForMinimap=(J)=>{let Z=this.clustersForPicker.find((Q)=>Q.threads.some((Y)=>Y.id===J));if(!Z||Z.threads.length<2)return null;return Z.threads.map((Q)=>({id:Q.id,title:Q.title,parentID:Q.parentID,updatedAt:Q.updatedAt,isActive:this.isThreadActivelyWorking(Q.id)}))};getCurrentThreadClusterForMinimap=()=>{let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;return this.getThreadClusterForMinimap(J.id)};enrichClustersWithActiveState=(J)=>{return J.map((Z)=>({...Z,threads:Z.threads.map((Q)=>({...Q,isActive:this.isThreadActivelyWorking(Q.id)}))}))};areRecordValuesEqual(J,Z){if(J===Z)return!0;let Q=Object.entries(J),Y=Object.entries(Z);if(Q.length!==Y.length)return!1;for(let[X,U]of Q){if(!Object.hasOwn(Z,X))return!1;if(!Object.is(U,Z[X]))return!1}return!0}getThreadViewStatesSnapshot(){let J={...this.allConnectedThreadActivityStatuses},Z=this.widget.dependencies.threadState.mainThread;if(Z)J[Z.id]=this.widget.dependencies.threadState.viewState;return J}isThreadActivelyWorking(J){return EE(this.allConnectedThreadActivityStatuses[J])}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Z,activeThreadHandle:Q}=this.widget.dependencies;if(!Z.mainThread?.id)return;if(!Q.restoreMessage)return;let X=Z.mainThread?.messages.findIndex((U)=>U===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Q.cancelTurn(),await Q.restoreMessage(X),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(U){P.error("Failed to edit message:",U)}};showForkDeprecationMessage=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!0})};dismissForkDeprecationModal=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!1})};handleMessageEditSubmit=async(J,Z,Q)=>{let{threadState:Y,activeThreadHandle:X}=this.widget.dependencies,U=Y.mainThread;if(!U)return;let V=U.messages.findIndex((z)=>z.messageId!==void 0&&z.messageId===J.messageId);if(V===-1)return;let K=V===0,D=K?this.agentModeController?.getMode()??U.agentMode??this.getEffectiveAgentMode():U.agentMode;if(this.shouldRequireAuthForPromptSubmit()){this.showSubmitDisabledHint("Sign in required before editing and resubmitting messages"),this.ensureAuthLoginSession();return}try{this.cancelBashInvocations(),await X.cancelTurn(),this.widget.dependencies.history.add(Z,process.cwd());let z=PH(Z);if(z&&X.invokeBashTool)await X.editMessage(V),this.invokeBashCommand(z.cmd,{visibility:z.visibility});else{let q=[{type:"text",text:Z}];if(Q.length>0)q.push(...Q);let F=D;if(U.agentMode&&!K&&F!==U.agentMode){P.error(`Cannot edit message: This thread uses ${U.agentMode} mode. To change mode, create a new thread.`);return}await X.sendMessage({content:q,agentMode:F,editIndex:V})}this.scrollMessageViewToBottom()}catch(z){P.error("Failed to edit message:",z)}};getAffectedFiles=async(J)=>{let{activeThreadHandle:Z,threadState:Q}=this.widget.dependencies;try{let Y=Q.mainThread;if(!Y)return[];let X=Y.messages.findIndex((V)=>V===J);if(X===-1)return[];return(await Z.getFilesAffectedByTruncation(X)).map(S9)}catch(Y){return P.error("Failed to get affected files:",Y),[]}};textController=new u7;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new o6);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.id;if(!Z)return;this.getMessageScrollController(Z).scrollToBottom()}_handleSelectionChanged=(J)=>{this.setState(()=>{})};updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.title;if(Z!==this.currentTitle){this.currentTitle=Z;let Q=process.cwd().replace(process.env.HOME||"","~"),Y=Z?`amp - ${Z} - ${Q}`:"";process.stdout.write(Ou0(Y))}}_handleTextCopy(J,Z){if(J&&J.length>0){let Q=Z?"Selection copied to clipboard":"Failed to copy selection to clipboard",Y=Z?"success":"error";this.toastController.show(Q,Y,2000)}}textFieldKey=new s5("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="")this.textController.resetScrollOffset();if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear(),this.toastController.show("Use [[Ctrl-O]] to open the command palette","warning");return}let Z=PH(J),Q=J===""&&this.bottomGridUserHeight!==void 0,Y=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?void 0:Z?.visibility;this.setState(()=>{if(this.currentShellModeStatus=Y,Q)this.bottomGridUserHeight=void 0})};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}),q6.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Z)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Z)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Y}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Z){await this.widget.dependencies.ideClient.start(J,!0,Z)}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}),q6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};handleDoubleAtTrigger=(J)=>{let{text:Z,cursorPosition:Q}=J,X=Z.slice(0,Q).lastIndexOf("@@"),U=J!==this.textController;if(P.info("[handleDoubleAtTrigger] called",{isEditingPreviousMessage:U,text:Z,cursor:Q,atAtIndex:X}),U)this.setState(()=>{this.paletteOnThreadMentionSelected=(V)=>{let K=this.messageViewController.editingController;if(!K){P.warn("[paletteOnThreadMentionSelected] no editing controller found");return}this.insertThreadMention(K,V)}});else this.setState(()=>{this.paletteOnThreadMentionSelected=null});this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:U?void 0:()=>{if(X!==-1){let V=J.text,K=V.slice(0,X)+V.slice(X+2);J.text=K,J.cursorPosition=X}},onSubmit:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()},onCancel:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()}})};insertThreadMention(J,Z){let{text:Q,cursorPosition:Y}=J,U=Q.slice(0,Y).lastIndexOf("@@");if(U!==-1){let V=Q.slice(Y),K=V.length===0,D=`@${Z}${K?" ":""}`,z=Q.slice(0,U)+D+V,q=U+D.length;J.text=z,J.cursorPosition=q}else J.insertText(`@${Z} `)}showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;let Z=!this.isShowingPalette;if(this.setState(()=>{if(this.isShowingPalette=Z,this.paletteShowOptions=Z?J??null:null,!Z)this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),Z)this.loadThreadsForPicker();else this.unloadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new _m0(this.widget.dependencies.configService,(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 km0(this.widget.dependencies.fuzzyServer);return this.completionBuilder}unloadThreadsForPicker(){if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe(),this.threadLoadSubscription=null;this.threadPreviewController.clearStatsCache(),this.widget.dependencies.threadHistoryService.resetCache()}dismissPalette=()=>{if(this.isExiting)return;this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),this.unloadThreadsForPicker()};lastRootContext;getCommandPaletteContext=(J)=>{let{threadState:Z,recentThreadIDs:Q}=this.widget.dependencies;if(!Z.mainThread)return null;let Y=J??this.lastRootContext;if(!Y)return null;let X=V1.file(process.cwd()),U=p1(X);return{recentThreadIDs:Q,currentThreadID:Z.mainThread.id,contextFallback:Y,context:J,threadPool:this.widget.dependencies.threadPool,createSystemPromptDeps:this.widget.dependencies.createSystemPromptDeps,activeThreadHandle:this.widget.dependencies.activeThreadHandle,editorState:this.textController,isProcessing:this.isProcessing(),thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let V=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),V},setImageAttachments:(V)=>{this.setState(()=>{this.imageAttachments=V})},editorDispatch:(V)=>{switch(V.type){case"set-input":this.textController.clear(),this.textController.insertText(V.input);break;case"set-input-with-cursor":this.textController.clear(),this.textController.insertText(V.input),this.textController.cursorPosition=V.cursorPosition;break;case"insert-text":this.textController.insertText(V.text);break;case"clear":this.textController.clear();break}},submitMessage:(V)=>{this.onTextSubmitted(V).catch((K)=>{this.handleSubmitFlowError(K)})},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},openContextAnalyze:()=>{this.openContextAnalyzeModal()},openSkillList:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,createThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.freeTierStatus.canUseAmpFree,isDailyGrantEnabled:this.freeTierStatus.isDailyGrantEnabled,switchToThread:async(V)=>{await this.switchToExistingThread(V),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null});return},handleHandoff:async(V,K)=>{let{goal:D,images:z}=K;if(!D)return{ok:!1,error:Error("Goal is required")};try{let q=this.widget.dependencies.threadState.mainThread;if(!q)return{ok:!1,error:Error("No active thread")};let F=setTimeout(()=>V.abort(new $T("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let G=await this.widget.dependencies.threadPool.createHandoff(q.id,{goal:D,images:z,agentMode:q.agentMode,queuedMessages:q.queuedMessages?[...q.queuedMessages]:void 0,signal:V.signal});return clearTimeout(F),await this.switchToExistingThread(G),{ok:!0}}catch(G){if(clearTimeout(F),G instanceof Error&&(G.name==="AbortError"||G.message.includes("aborted")))throw V.signal.reason;throw G}}catch(q){return P.error("Failed to create handoff thread",{error:q}),{ok:!1,error:q instanceof Error?q:Error(String(q))}}},getGuidanceFiles:(V)=>{return this.widget.dependencies.activeThreadHandle.getGuidanceFiles(V)},openIdePicker:()=>{this.openIdePicker()},openPromptHistoryPicker:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!0})},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(V)=>{this.agentModeController?.setMode(V)},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.enrichClustersWithActiveState(this.clustersForPicker),previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:U,threadViewStates:this.getThreadViewStatesSnapshot(),newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:this.widget.dependencies.features,showStatusMessage:(V,K=2000)=>{this.showStatusMessage(V,K)},showToast:(V,K="success",D)=>{this.toastController.show(V,K,D)},getThemeName:()=>PF4(Y).themeName,isMessageViewInteractionActive:this.isMessageViewInSelectionMode||this.messageViewController.editingMessageOrdinal!==null,enterHandoffMode:this.enterHandoffMode,isInHandoffMode:this.handoffState.isInHandoffMode,enterQueueMode:this.enterQueueMode,submitQueue:this.submitQueue,isInQueueMode:this.isInQueueMode,addPendingSkill:(V)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill(V)},onThreadMentionSelected:this.paletteOnThreadMentionSelected??void 0,canChangeAgentModeInPromptEditor:()=>this.canChangeAgentModeInPromptEditor(),pluginCommands:this.pluginCommands,executePluginCommand:this.widget.dependencies.pluginService?(V,K,D)=>this.widget.dependencies.pluginService.commands.execute(V,K,{threadID:D}):void 0,reloadPlugins:this.widget.dependencies.pluginService?()=>this.widget.dependencies.pluginService.reload():void 0,pluginService:this.widget.dependencies.pluginService}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Fp0(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("",{includeArchived:!0}).subscribe({next:(Z)=>{this.setState(()=>{this.threadsForPicker=Z,this.clustersForPicker=dH4(Z),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await rp5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Z)=>Z.id!==J)})};invokeBashCommand=(J,{visibility:Z})=>{if(!this.widget.dependencies.activeThreadHandle.invokeBashTool)return;let Q=Date.now(),Y=`bash-${Q}-${Math.random().toString(36).substring(7)}`,X={cmd:J},U=new AbortController;this.widget.dependencies.activeThreadHandle.invokeBashTool(X,{hidden:Z===RH,abortController:U}).subscribe({next:(V)=>{this.setState(()=>{if(this.bashInvocations.find((D)=>D.id===Y))this.bashInvocations=this.bashInvocations.map((D)=>D.id===Y?{...D,toolRun:V}:D);else{let D={id:Y,args:X,toolRun:V,startTime:Q,abortController:U,hidden:Z===RH};this.bashInvocations=[...this.bashInvocations,D]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Z)=>Z.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=gF4(()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(Z.ok)this.setState(()=>{this.threadCostInfo=Z.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J)=>{let Z=this.lastInferenceState==="running",Q=J==="running",Y=J==="idle"&&Z,X=Q&&!Z;if(Y)this.fetchThreadCostInfo();if(X)this.startElapsedTimeTimer();else if(Z&&!Q)this.stopElapsedTimeTimer();this.lastInferenceState=J};startElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)return;this.elapsedTimeTimer=setInterval(()=>{let J=this.widget.dependencies.threadState.viewState;if(!(J.state==="active"&&J.inferenceState==="running")){this.stopElapsedTimeTimer();return}this.setState(()=>{})},1000)};stopElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)clearInterval(this.elapsedTimeTimer),this.elapsedTimeTimer=null};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.handoffState.isGeneratingHandoff)return;let J=this.canChangeAgentModeInPromptEditor();if(this.agentModeController.toggle(J))this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};handleMessageViewControllerUpdate=()=>{let J=this.messageViewController.editingMessageOrdinal;if(J===this.lastEditingMessageOrdinal)return;if(this.lastEditingMessageOrdinal===0&&J!==0){let Y=this.agentModeController;if(!Y){this.lastEditingMessageOrdinal=J,this.setState(()=>{});return}if(Y.getMode()!==null)Y.setMode(null)}this.lastEditingMessageOrdinal=J,this.setState(()=>{})};showStatusMessage(J,Z=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=J}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},Z)}toggleDeepReasoningEffort=()=>{if(this.getEffectiveAgentMode()!=="deep"){this.showStatusMessage("Deep reasoning effort is only available in deep mode");return}let Z=this.widget.dependencies.threadState.mainThread;if(!Z)return;if(Y8(Z)>0){this.showStatusMessage("Deep reasoning effort can only be toggled before the first message");return}let Q=this.deepReasoningEffort==="medium"?"high":this.deepReasoningEffort==="high"?"xhigh":"medium";this.deepReasoningEffort=Q,E7("internal.deepReasoningEffort",Q),this.showStatusMessage(`Deep reasoning effort: ${Q}`),this.setState(()=>{this.agentModePulseSeq++})};formatAgentModeLabel(J){if(J!=="deep")return J;if(this.deepReasoningEffort==="high")return"deep²";if(this.deepReasoningEffort==="xhigh")return"deep³";return"deep"}handleInsertImage=async(J)=>{let Z=this.getEffectiveAgentMode();if(!tv(Z)){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>=cM)return!1;let Q=await sC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Q}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.setState(()=>{this.imagePreview={image:Z,index:J,onRemove:()=>{let Q=this.imageAttachments.indexOf(Z);if(Q!==-1)this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,X)=>X!==Q),this.imagePreview=null})}}})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreview=null})};handleShowFileImagePreview=(J)=>{this.setState(()=>{this.fileImagePreviewPath=J})};handleFileImagePreviewDismiss=()=>{this.setState(()=>{this.fileImagePreviewPath=null})};handleShowPainterImagePreview=(J,Z)=>{this.setState(()=>{this.painterImagePreview={image:J,filePath:Z}})};handlePainterImagePreviewDismiss=()=>{this.setState(()=>{this.painterImagePreview=null})};handleShowPainterSaveDialog=(J,Z)=>{this.setState(()=>{this.painterSaveDialog={image:J,filePath:Z}})};handlePainterSaveDialogDismiss=()=>{this.setState(()=>{this.painterSaveDialog=null})};handleSkillClick=(J)=>{let Z=this.pendingSkills[J];if(Z)this.setState(()=>{this.cachedSkillForPreview=null,this.skillPreview={skillIndex:J,onRemove:()=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(Z.name),this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})}}}),this.widget.dependencies.skillService.getSkills().then((Q)=>{let Y=Q.find((X)=>X.name===Z.name)??null;if(this.skillPreview!==null)this.setState(()=>{this.cachedSkillForPreview=Y})})};handleSkillPreviewDismiss=()=>{this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})};handleShowEditingImagePreview=(J,Z,Q)=>{this.setState(()=>{this.imagePreview={image:J,index:Z,onRemove:Q}})};handleImagePreviewRemove=()=>{if(this.imagePreview)this.imagePreview.onRemove(),this.setState(()=>{this.imagePreview=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleSplashOrbExplode=(J)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:J.x,originY:J.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(!Z.ok)P.error("Failed to destruct mysterious message",Z.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Z)=>{P.error("Failed to destruct mysterious message",Z)})};exitMessageViewInteraction=()=>{this.messageViewController.setSelectedUserMessageOrdinal(null),this.messageViewController.setIsShowingRestoreConfirmation(!1),this.messageViewController.setIsShowingEditConfirmation(!1),this.messageViewController.setPendingEditText(null),this.messageViewController.setPendingEditImageAttachments([]),this.messageViewController.setAffectedFiles([]),this.messageViewController.stopEditing(),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),this.scrollMessageViewToBottom(),q6.instance.addPostFrameCallback(()=>{if(!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};enterHandoffMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.handoffController?.enter()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Z=this.imageAttachments;if(this.resetHistory(),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Q=await this.handoffController.submit(J,Z,this.agentModeController?.getMode()??null);if(!Q.ok&&Q.error.message!=="Cancelled")this.displayMessage=Q.error,this.setState(()=>{});else if(Q.ok)this.setState(()=>{this.imageAttachments=[]}),setTimeout(()=>{this.handoffController?.startCountdown(()=>{this.autoSubmitHandoffDraft().catch((Y)=>{this.handleSubmitFlowError(Y)})})},0)};autoSubmitHandoffDraft=async()=>{let J=this.textController.text;if(J.trim())this.textController.clear(),await this.sendUserMessage(J)};enterQueueMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.setState(()=>{this.isInQueueMode=!0})};exitQueueMode=()=>{this.setState(()=>{this.isInQueueMode=!1})};submitQueue=(J)=>{this.exitMessageViewInteraction();let{threadState:Z}=this.widget.dependencies;if((Z.mainThread?.queuedMessages?.length??0)>=Y00){this.toastController.show(`Queue is full (max ${Y00} messages)`,"error",3000);return}let Y=this.imageAttachments;this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),this.textController.clear();let X=[{type:"text",text:J}];if(Y.length>0)X.push(...Y);this.widget.dependencies.activeThreadHandle.queueMessage(X),this.exitQueueMode()};isAuthRequiredStatus(J){if(!GG(J))return!1;let Z=J.error.message.toLowerCase();return Z.includes("user not found")||Z.includes("auth-required")||Z.includes("unauthorized")||Z.includes("forbidden")||Z.includes("401")||Z.includes("403")||Z.includes("api key")||Z.includes("access token")}shouldRequireAuthForPromptSubmit(){if(!this.widget.dependencies.hasAPIKeyAtStartup&&!T5(this.authStatus))return!0;return this.isAuthRequiredStatus(this.authStatus)&&!T5(this.authStatus)}queuePromptUntilAuthenticated(J,Z=[...this.imageAttachments],Q){if(this.queuedPromptAfterAuth={text:J,images:Z},Q?.clearInput??!0)this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),this.setState(()=>{this.imageAttachments=[]});this.showStatusMessage("Sign in required. Prompt queued and will send after login.",2500),this.ensureAuthLoginSession()}ensureAuthLoginSession=async()=>{if(this.pendingAuthLogin||this.isCreatingAuthLoginSession||T5(this.authStatus))return;this.isCreatingAuthLoginSession=!0;try{let J=eN4(32).toString("hex"),Z=await ZC(this.widget.dependencies.ampURL,J),Q=await ZC(this.widget.dependencies.ampURL,J,!1),Y=new AbortController;this.setState(()=>{this.pendingAuthLogin={authToken:J,browserURL:Z,manualURL:Q,abortController:Y,isOpeningBrowser:!1,isAuthenticating:!0,errorMessage:null}}),EY4(this.widget.dependencies.ampURL,J,this.widget.dependencies.secretStorage,Y).then(()=>{this.showStatusMessage("Login successful",2000),this.checkAuthStatusAfterLogin()}).catch((X)=>{if(Y.signal.aborted)return;let U=X instanceof Error?X.message:"Login failed. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=U,this.pendingAuthLogin.isAuthenticating=!1})})}catch(J){let Z=J instanceof Error?J.message:"Unable to start login flow. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin){this.displayMessage=Error(Z);return}this.pendingAuthLogin.errorMessage=Z,this.pendingAuthLogin.isAuthenticating=!1})}finally{this.isCreatingAuthLoginSession=!1}};openAuthLoginBrowser=async()=>{if(!this.pendingAuthLogin)return;let J=this.pendingAuthLogin.browserURL,Z=this.pendingAuthLogin.abortController;this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!0,this.pendingAuthLogin.errorMessage=null});try{await LX(J,Z.signal)}catch(Q){let Y=Q instanceof Error?Q.message:"Unable to open browser. Copy the manual link.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=Y})}finally{this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!1})}};copyAuthLoginLink=async()=>{let J=this.pendingAuthLogin?.manualURL;if(!J)return;try{await a4.instance.tuiInstance.clipboard.writeText(J),this.showStatusMessage("Login link copied to clipboard",2000)}catch(Z){P.error("Failed to copy login link",{error:Z}),this.showStatusMessage("Failed to copy login link",2000)}};checkAuthStatusAfterLogin=async()=>{try{let J=await this.widget.dependencies.configService.getLatest(),Z=rv(J),Q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(Z)});if(!Q.ok){this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Still waiting for login confirmation. Finish login in your browser, then press I again."});return}this.setState(()=>{this.authStatus={user:Q.result,features:Q.result.features,workspace:Q.result.team,mysteriousMessage:Q.result.mysteriousMessage},this.pendingAuthLogin=null}),await this.maybeResumeQueuedPromptAfterAuth()}catch(J){P.error("Failed to verify login state",{error:J}),this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Unable to verify login yet. Press I again in a moment."})}};cancelAuthLoginSession=()=>{if(this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("Authentication cancelled"));this.setState(()=>{this.pendingAuthLogin=null})};maybeResumeQueuedPromptAfterAuth=async()=>{if(!T5(this.authStatus))return;let J=this.queuedPromptAfterAuth;if(!J)return;this.queuedPromptAfterAuth=null,await this.proceedWithUserMessage(J.text,J.images)};handleAuthModalKey=(J)=>{if(!this.pendingAuthLogin||this.pendingInputDialog)return!1;let Z=J.key.length===1?J.key.toLowerCase():J.key;if(Z==="Enter"||Z==="o")return this.openAuthLoginBrowser(),!0;if(Z==="c")return this.copyAuthLoginLink(),!0;if(Z==="i")return this.checkAuthStatusAfterLogin(),!0;if(Z==="p")return this.promptForAuthLoginCode(),!0;return!1};promptForAuthLoginCode=async()=>{if(!this.pendingAuthLogin)return;let{authToken:J,abortController:Z}=this.pendingAuthLogin,Q=await new Promise((Y)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:{title:"Paste Login Code",helpText:"Paste the login code from the browser page. This is not your API key.",submitButtonText:"Verify"},resolve:Y}})});if(!Q||!this.pendingAuthLogin)return;try{let{accessToken:Y}=Yu0(Q,J);await this.widget.dependencies.secretStorage.set("apiKey",Y,this.widget.dependencies.ampURL),Z.abort(Error("Authentication completed from pasted code")),this.showStatusMessage("Login code accepted",2000),await this.checkAuthStatusAfterLogin()}catch(Y){let X=Y instanceof Error?Y.message:"Invalid login code.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=X,this.pendingAuthLogin.isAuthenticating=!1})}};openInEditor=async(J)=>{try{let Z=await dp5(XD.join(op5(),"amp-edit-")),Q=XD.join(Z,"message.amp.md");await np5(Q,J,"utf-8"),await yY(Q);try{let Y=await cp5(Q,"utf-8");this.textController.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await ip5(Q),await lp5(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.error("Error opening editor:",Z)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0){if(!this.canInterruptQueuedInference())return;try{await this.cancelStreamingMessage();return}catch(Y){P.error("Failed to cancel inference for queued submit",Y)}return}let Z=J.trim();if(Z===":q"){this.widget.dependencies.setExitNotice?.("Vim reflex detected. Exiting politely."),await this.exitApplication();return}if(Z==="exit"||Z==="quit"){await this.exitApplication();return}if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}if(this.isInQueueMode){this.submitQueue(J);return}let Q=PH(J);if(Q&&this.widget.dependencies.activeThreadHandle.invokeBashTool)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,process.cwd()),this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory();return}if(this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J);return}this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{let J=this.agentModeController?.getMode(),Z=this.canChangeAgentModeInPromptEditor(),Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=!Z&&J!==null&&Y8(Q)>0&&Q.agentMode!==J;if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(!Z&&J&&J!==this.sessionState.agentMode)this.persistAgentMode(J);if(Y)this.agentModeController?.setMode(null);this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};initState(){if(QQ.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new mh0({getActiveThreadHandle:()=>this.widget.dependencies.activeThreadHandle,getThreadPool:()=>this.widget.dependencies.threadPool,switchToThread:(Y)=>{return this.textController.clear(),this.switchToExistingThread(Y)}}),this.handoffController.addListener(this.handoffListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();if(a4.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),a4.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),a4.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.authStatus=this.widget.dependencies.initialServerStatus,this.authStatusSubscription=_J(this.widget.dependencies.configService).subscribe((Y)=>{if(this.setState(()=>{if(this.authStatus=Y,T5(Y))this.pendingAuthLogin=null}),T5(Y)){this.maybeResumeQueuedPromptAfterAuth();return}if(this.isAuthRequiredStatus(Y))this.ensureAuthLoginSession()}),this.authModalKeyInterceptorUnsubscribe=a4.instance.addKeyInterceptor((Y)=>this.handleAuthModalKey(Y)),!this.widget.dependencies.hasAPIKeyAtStartup)this.ensureAuthLoginSession();this.autocompleteFocusNodeListener=(Y)=>{q6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})},"TuiUIState.autocompleteFocusNodeListener")},this.autocompleteFocusNode.addListener(this.autocompleteFocusNodeListener),this.sessionState=this.widget.dependencies.sessionState??UC,this.shortcutsHintUsed=this.sessionState.shortcutsHintUsed,this.messageViewControllerUnsubscribe??=this.messageViewController.subscribe(this.handleMessageViewControllerUpdate),Promise.all([this.widget.dependencies.freeTierStatusPromise??Promise.resolve(void 0),I1(this.widget.dependencies.configService.config)]).then(([Y,X])=>{if(Y)this.freeTierStatus=Y;this.paletteConfig=X;let U=X.settings["internal.deepReasoningEffort"]??"medium",V=X.settings["anthropic.speed"];this.showSkillsCountInPromptBar=X.settings["internal.cli.showSkillsCountInPromptBar"]!==!1,this.adsDisabledBySetting=X.settings.newAdsDisplay===!0,this.deepReasoningEffort=U,this.anthropicSpeed=V,E7("internal.deepReasoningEffort",U),this.deepReasoningEffortSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings["internal.deepReasoningEffort"]===D.settings["internal.deepReasoningEffort"])).subscribe(({settings:K})=>{let D=K["internal.deepReasoningEffort"]??"medium";if(D!==this.deepReasoningEffort)this.deepReasoningEffort=D,E7("internal.deepReasoningEffort",D),this.setState(()=>{this.agentModePulseSeq++})}),this.anthropicSpeedSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings["anthropic.speed"]===D.settings["anthropic.speed"])).subscribe(({settings:K})=>{let D=K["anthropic.speed"];if(D!==this.anthropicSpeed)this.anthropicSpeed=D,this.setState(()=>{this.agentModePulseSeq++})}),this.showSkillsCountInPromptBarSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings["internal.cli.showSkillsCountInPromptBar"]===D.settings["internal.cli.showSkillsCountInPromptBar"])).subscribe(({settings:K})=>{let D=K["internal.cli.showSkillsCountInPromptBar"]!==!1;if(D!==this.showSkillsCountInPromptBar)this.setState(()=>{this.showSkillsCountInPromptBar=D})}),this.submitOnEnter=X.settings.submitOnEnter??!0,this.submitOnEnterSubscription=this.widget.dependencies.configService.config.pipe(H1((K)=>({settings:K.settings})),M4((K,D)=>K.settings.submitOnEnter===D.settings.submitOnEnter)).subscribe(({settings:K})=>{let D=K.submitOnEnter??!0;if(D!==this.submitOnEnter)this.setState(()=>{this.submitOnEnter=D})}),this.agentModeController=new hh0({initialCliMode:this.widget.dependencies.initialAgentMode,sessionState:this.sessionState,freeTierStatus:this.freeTierStatus,workspace:this.widget.dependencies.workspace??null,initialSettings:X.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.threadState.mainThread}),this.agentModeController.addListener(this.agentModeListener),this.scheduleAdSubscriptionWithIdeReadiness(),this.setState(()=>{})}),this.updateGitBranch(),this.allConnectedThreadActivityStatusesSubscription=this.widget.dependencies.threadPool.allConnectedThreadActivityStatuses$.subscribe((Y)=>{if(this.areRecordValuesEqual(this.allConnectedThreadActivityStatuses,Y))return;this.setState(()=>{this.allConnectedThreadActivityStatuses=Y})}),this.threadTitlesSubscription=this.widget.dependencies.threadPool.threadTitles$.subscribe((Y)=>{if(this.areRecordValuesEqual(this.threadTitles,Y))return;this.setState(()=>{this.threadTitles=Y})}),this.pendingNavigationSubscription=this.widget.dependencies.threadPool.threadHandles$.pipe(s1((Y)=>Y?Y.thread$:v0.of(null))).subscribe((Y)=>{this.checkForPendingNavigation();let X=Y?.id;if(this.threadCostInfoThreadID!==X){if(this.threadCostInfo=void 0,this.threadCostInfoThreadID=X,X&&Y8(Y)>0)this.fetchThreadCostInfo()}let U=Y?this.widget.dependencies.threadState.viewState:void 0;this.maybeRefetchThreadCostInfo(U?.state==="active"?U.inferenceState:void 0)}),this.freeTierStatusSubscription=Tr1(async()=>{let Y=await this.widget.dependencies.configService.getLatest(),X=rv(Y),U=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(X)});if(!U.ok)throw U.error;return U.result}).subscribe({next:(Y)=>{if(Y){let X=this.freeTierStatus.canUseAmpFree;if(this.setState(()=>{this.freeTierStatus=Y}),Y.canUseAmpFree!==X)if(Y.canUseAmpFree){if(!this.adSubscription&&!this.adsDisabledBySetting)this.scheduleAdSubscriptionWithIdeReadiness()}else this.unsubscribeFromAds()}},error:(Y)=>{P.debug("Failed to fetch free tier status",Y)}});let{mcpTrustHandler:J}=this.widget.dependencies;if(this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),uy0((Y)=>{this.setState(()=>{this.pendingOAuthRequest=Y})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((Y)=>{this.setState(()=>{this.mcpServers=Y})}),this.pendingSkillsSubscription=this.widget.dependencies.activeThreadHandle.pendingSkills$.subscribe((Y)=>{this.setState(()=>{this.pendingSkills=Y})}),this.widget.dependencies.pluginService){let Y=this.widget.dependencies.pluginService;this.pluginCommandsSubscription=qJ(Y.plugins,Y.commands.changed).subscribe(()=>{let X=Y.commands.list();this.setState(()=>{this.pluginCommands=X})}),this.pluginInfosSubscription=Y.plugins.subscribe((X)=>{this.setState(()=>{this.pluginInfos=X})})}this.skillListSubscription=this.widget.dependencies.skillService.skills.subscribe((Y)=>{let X=Y.filter((U)=>!U.baseDir.startsWith("builtin://")).length;this.setState(()=>{this.availableSkillCount=X,this.availableSkillCountReady=!0})}),this.skillWarningsSubscription=this.widget.dependencies.skillService.skillWarnings.subscribe((Y)=>{this.setState(()=>{this.skillWarningCount=Y.length})}),this.skillErrorsSubscription=this.widget.dependencies.skillService.skillErrors.subscribe((Y)=>{this.setState(()=>{this.skillErrorCount=Y.length})}),this.pendingApprovalsSubscription=this.widget.dependencies.activeThreadHandle.pendingApprovals$.subscribe((Y)=>{this.setState(()=>{this.pendingApprovals=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{let X=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=Y}),!X&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription&&!this.adsDisabledBySetting)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{try{if(!this.widget.dependencies.threadState.mainThread){P.warn("No active thread found to handle IDE message");return}await new Promise((U)=>setTimeout(U,50)),await this.widget.dependencies.activeThreadHandle.sendMessage({content:[{type:"text",text:Y}]}),P.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}catch(X){this.handleSubmitFlowError(X)}}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),P.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.mysteriousMessageSubscription=_J(this.widget.dependencies.configService).pipe(k5((Y)=>Y!=="pending"),H1((Y)=>T5(Y)?Y.mysteriousMessage??null:null),M4((Y,X)=>Y?.id===X?.id)).subscribe((Y)=>{this.setState(()=>{if(Y?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=Y,Y&&!this.mysterySequenceManager)this.mysterySequenceManager=new l90(new Map([[new c90(U$0.MYSTERY_SEQUENCE),new yg]])),this.mysteryKeyInterceptorUnsubscribe=a4.instance.addKeyInterceptor((X)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let U=this.mysterySequenceManager.handleKeyEvent(X);if(U.consumed){if(U.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=U.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!Y)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),a4.instance.addKeyInterceptor((Y)=>{if(Y.key==="?"){if(this.textController.text===""&&this.textController.cursorPosition===0&&!this.isShowingHelp&&!this.isShowingPalette&&this.isTextfieldAndAutocompleteFocused){if(this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!this.shortcutsHintUsed)this.shortcutsHintUsed=!0,this.sessionState={...this.sessionState,shortcutsHintUsed:!0},bK(this.sessionState);return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),Y.key==="Escape")return!0;return!1}return!1}),this.updateTerminalTitle();let Z=this.widget.dependencies.ideClient.getSelectedConfig();if(Z)this.connectToSelectedIde(Z,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();let Q=this.widget.dependencies.threadState.mainThread;if(!Q){this.initNewsFeed();return}if(Q.autoSubmitDraft&&Q.draft&&Q.messages.length===0)setTimeout(()=>this.autoSubmitInitialDraft(Q),100);this.initNewsFeed()}autoSubmitInitialDraft(J){let Z=typeof J.draft==="string"?J.draft:J.draft?.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
|
|
7387
|
+
`)??"",Q=Array.isArray(J.draft)?J.draft.filter((Y)=>Y.type==="image"):[];if(Z.trim()||Q.length>0){if(P.info("Auto-submitting initial handoff draft",{name:"handoff",threadID:J.id,hasDraftText:!!Z.trim(),draftImageCount:Q.length}),this.textController.clear(),Q.length>0)this.setState(()=>{this.imageAttachments=Q});this.proceedWithUserMessage(Z.trim()).catch((Y)=>{this.handleSubmitFlowError(Y)})}}handleSubmitFlowError(J){P.error("Failed to submit prompt message",J);let Z=J instanceof Error?J.message:String(J);this.showErrorMessage(Z)}checkForPendingNavigation(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread;if(!Z?.pendingNavigation)return;let Q=Z.pendingNavigation;this.widget.dependencies.activeThreadHandle.clearPendingNavigation().catch(()=>{return}),P.info("Pending navigation detected, navigating to new thread",{name:"handoff",fromThreadID:Z.id,targetThreadID:Q}),this.handleHandoffNavigation(Q)}handleHandoffNavigation=async(J)=>{try{await this.switchToExistingThread(J);let Z=this.widget.dependencies.threadState.mainThread;if(!Z){P.error("Failed to get new thread after handoff navigation");return}if(Z.autoSubmitDraft&&Z.draft&&Z.messages.length===0){let{text:Q,images:Y}=mI1(Z.draft);if(Q.trim()||Y.length>0){if(P.info("Auto-submitting handoff draft",{name:"handoff",threadID:J,hasDraftText:!!Q.trim(),draftImageCount:Y.length}),this.textController.clear(),Y.length>0)this.setState(()=>{this.imageAttachments=[...Y]});await this.proceedWithUserMessage(Q.trim()),this.setState(()=>{this.imageAttachments=[]})}}}catch(Z){P.error("Failed to handle handoff navigation",{name:"handoff",newThreadID:J,error:Z})}};dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.messageViewControllerUnsubscribe)this.messageViewControllerUnsubscribe(),this.messageViewControllerUnsubscribe=null;if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.freeTierStatusSubscription)this.freeTierStatusSubscription.unsubscribe();if(this.allConnectedThreadActivityStatusesSubscription)this.allConnectedThreadActivityStatusesSubscription.unsubscribe();if(this.threadTitlesSubscription)this.threadTitlesSubscription.unsubscribe();if(this.pendingNavigationSubscription)this.pendingNavigationSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.authStatusSubscription)this.authStatusSubscription.unsubscribe(),this.authStatusSubscription=null;if(uy0(null),this.authModalKeyInterceptorUnsubscribe?.(),this.authModalKeyInterceptorUnsubscribe=null,this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("TUI disposed")),this.pendingAuthLogin=null;if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.pluginCommandsSubscription)this.pluginCommandsSubscription.unsubscribe();if(this.pluginInfosSubscription)this.pluginInfosSubscription.unsubscribe();if(this.skillListSubscription)this.skillListSubscription.unsubscribe();if(this.skillWarningsSubscription)this.skillWarningsSubscription.unsubscribe();if(this.skillErrorsSubscription)this.skillErrorsSubscription.unsubscribe();if(this.pendingApprovalsSubscription)this.pendingApprovalsSubscription.unsubscribe();if(this.unloadThreadsForPicker(),this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.deepReasoningEffortSubscription)this.deepReasoningEffortSubscription.unsubscribe(),this.deepReasoningEffortSubscription=null;if(this.anthropicSpeedSubscription)this.anthropicSpeedSubscription.unsubscribe(),this.anthropicSpeedSubscription=null;if(this.submitOnEnterSubscription)this.submitOnEnterSubscription.unsubscribe(),this.submitOnEnterSubscription=null;if(this.showSkillsCountInPromptBarSubscription)this.showSkillsCountInPromptBarSubscription.unsubscribe(),this.showSkillsCountInPromptBarSubscription=null;if(this.stopElapsedTimeTimer(),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;if(this.autocompleteFocusNodeListener)this.autocompleteFocusNode.removeListener(this.autocompleteFocusNodeListener),this.autocompleteFocusNodeListener=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Ou0("")),this.shouldUseProgressBar())process.stdout.write(IX4())}getCurrentConfirmation(){if(this.pendingApprovals.length>0){let J=this.pendingApprovals[0];return{type:"tool-use",tools:[{useBlock:{type:"tool_use",id:J.toolUseId,name:J.toolName,complete:!0,input:J.args},toAllow:J.toAllow??[]}],subthreadID:void 0,reason:J.reason??`Tool requires approval: ${J.toolName}`,isSubagent:J.context==="subagent",subagentToolName:J.subagentToolName}}return null}shouldUseProgressBar(){return!1}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},U$0.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}unsubscribeFromAds(){if(this.adSubscription)this.adSubscription.unsubscribe(),this.adSubscription=null;if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;this.setState(()=>{this.randomAd=null})}subscribeToAds(){if(this.adSubscription)return;if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;this.adSubscription=Nh0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>wh0(this.lastUserInteractionTime),this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.threadState.mainThread??void 0).subscribe({next:(J)=>{this.setState(()=>{this.randomAd=J}),q6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Z=this.getCurrentConfirmation();if(!Z||Z.type!=="tool-use"){P.error("No current tool confirmation found");return}let Q=Z.tools[0]?.useBlock;if(!Q){P.error("No tool use block found in confirmation");return}if(J?.type==="deny-with-feedback"){let{feedback:U}=J;try{if(this.pendingApprovals.find((K)=>K.toolUseId===Q.id))await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,U.trim()||void 0);else await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,U.trim()||void 0)}catch(V){P.error("Failed to send deny with feedback:",V)}return}let Y=J?.type==="simple"?J.value:null;if(Y==="allow-all-session")E7("dangerouslyAllowAll",!0);if(Y==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(U){if(U&&U instanceof Error)this.setState(()=>{this.displayMessage=U});else P.error("Failed to write dangerouslyAllowAll setting:",U);return}if(Y==="always-guarded"){let U=Z.tools[0]?.toAllow??[],V=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],K=[...U,...V];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",K,"global")}if(Y==="connect-github"){let U=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();await K8(this.context,U);return}if(Y==="disable-librarian"){let U=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!U.includes(BZ))await this.widget.dependencies.settingsStorage.set("tools.disable",[...U,BZ],"global")}let X=Y!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(Y);try{await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,X)}catch(U){P.error("Failed to send tool confirmation:",U)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Z=J.viewState;if(Z.state!=="active"||!Z.ephemeralError)return null;return Z.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let{activeThreadHandle:Z}=this.widget.dependencies;switch(J){case"retry":await Z.retryTurn();break;case"dismiss":Z.dismissEphemeralError();break;case"new-thread":Z.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"handoff":Z.dismissEphemeralError(),this.enterHandoffMode();break;case"add-credits":{let Q=new URL("/pay",this.widget.dependencies.ampURL);await K8(this.context,Q),this.showStatusMessage("Payment page opened. After paying, choose Retry.");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Z}=this.widget.dependencies;await J.deny();try{await yY(Z.getSettingsFilePath())}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await this.widget.dependencies.activeThreadHandle.cancelStreaming()};switchToExistingThread=async(J,Z={})=>{let{recordInNavigationHistory:Q=!0}=Z,Y=Date.now(),X=this.widget.dependencies.threadState.mainThread?.id;if(Q&&X&&X!==J)this.recordNavigation(X);try{P.info(`[switchToExistingThread] Switching to thread: ${J}`);let U=Date.now();await this.widget.dependencies.threadPool.switchThread(J),P.info(`[switchToExistingThread] switchToThread resolved in ${Date.now()-U}ms`);let V=await this.widget.dependencies.threadService.get(J)??this.widget.dependencies.threadState.mainThread;if(!V||V.id!==J)throw Error("No active thread after switch");P.info(`[switchToExistingThread] Got thread ${J}, thread.agentMode: ${V.agentMode}`),P.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null);let K=Date.now();if(this.onThreadSwitch(),P.info(`[switchToExistingThread] onThreadSwitch completed in ${Date.now()-K}ms`),this.persistLastThreadId(J),V.draft&&Y8(V)===0)if(this.textController.clear(),typeof V.draft==="string")this.textController.insertText(V.draft);else{let D=V.draft.filter((F)=>F.type==="text"),z=V.draft.filter((F)=>F.type==="image"),q=D.map((F)=>F.text).join(`
|
|
7388
|
+
`);if(q)this.textController.insertText(q);if(z.length>0)this.setState(()=>{this.imageAttachments=z})}P.info(`[switchToExistingThread] Completed in ${Date.now()-Y}ms`)}catch(U){throw P.error("Failed to switch to thread",{threadId:J,error:U}),Error(`Failed to switch to thread: ${J}`,{cause:U})}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J,Z)=>{if(this.cancelBashInvocations(),this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J,Z??[...this.imageAttachments],{clearInput:Z===void 0});return}this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J,process.cwd());let Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=Y8(Q)===0,X=this.getEffectiveAgentMode();if(Q.agentMode&&!Y&&X!==Q.agentMode){await this.showErrorMessage(`This thread uses ${Q.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let U=Z??this.imageAttachments,V=[{type:"text",text:J}];if(U.length>0)V.push(...U);if(await this.widget.dependencies.activeThreadHandle.sendMessage({content:V,agentMode:X}),this.persistLastThreadId(Q.id),Y)this.persistAgentMode(X);if(this.scrollMessageViewToBottom(),!Z)this.setState(()=>{this.imageAttachments=[]});q6.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&&J.messages.length===0){if(J.relationships?.find((Q)=>Q.type==="handoff"&&Q.role==="child"))await this.widget.dependencies.threadPool.deleteThread?.(J.id).catch(()=>{})}a4.instance.stop()};async persistAgentMode(J){let Q={...await fK(),agentMode:J};this.sessionState=Q,await bK(Q)}async persistLastThreadId(J){let Q={...await fK(),lastThreadId:J};this.sessionState=Q,await bK(Q)}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 Z=ap5();if(J===Z)return"~";if(J.startsWith(Z+XD.sep))return"~"+J.slice(Z.length);return J}shorten(J){let Z=J.split(XD.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(XD.sep),"…",Z.slice(-2).join(XD.sep)].join(XD.sep)}buildDisplayText(J,Z,Q,Y){let X=Z?` (${Z})`:"",U=J+X;if(r5(U,Y)<=Q)return U;let V=J.split(XD.sep);if(V.length>2){let D=[V[0],"…",V[V.length-1]].join(XD.sep)+X;if(r5(D,Y)<=Q)return D}return jO(U,Q,Y)}build(J){this.lastRootContext=J;let Z=this.widget.dependencies.pluginPlatform;if(Z&&!Z.showToast){let o0=this.toastController;Z.showToast=(w1)=>o0.show(w1,"success")}if(Z&&!Z.showOpenedURLToast){let o0=this.toastController;Z.showOpenedURLToast=(w1)=>o0.show(`Opened URL: ${w1}`,"success",8000)}if(Z&&!Z.appendToThreadHandler){let o0=this.widget.dependencies;Z.appendToThreadHandler=async(w1)=>{for(let O1 of w1)await o0.activeThreadHandle.queueMessage([{type:"text",text:O1.content}])}}if(Z&&!Z.showInputDialog)Z.showInputDialog=(o0)=>{return new Promise((w1)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:o0,resolve:w1}})})};if(Z&&!Z.showConfirmDialog)Z.showConfirmDialog=(o0)=>{return new Promise((w1)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingConfirmDialog={options:o0,resolve:w1}})})};let Q=o1.of(J),Y=f0.of(J),X=Y.base;this.themeColors=X;let{colors:U,app:V}=Y;this.themeApp=V;let K=this.widget.dependencies.threadState.mainThread,D=K?.agentMode&&P8(K.agentMode),z=this.freeTierStatus.isDailyGrantEnabled,q=!this.adsDisabledBySetting&&(D||z)&&this.randomAd!==null,F=Boolean(q),{threadState:G}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=G.items,B=G.mainThread||void 0,w=G.subagentToolsByParentID,N=G.todosList,E=B?.id,O=B,L=this.isTranscriptEmpty(),I=(o0)=>new Ip({key:new s5(`preview-message-view-${o0.id}`),items:Fq(o0).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:o0,denseView:o0.agentMode==="deep",focusNode:new n4({debugLabel:"PreviewFocus"}),onShowImagePreview:()=>{},stateController:this.previewMessageViewController,submitOnEnter:this.submitOnEnter}),M=this.previewThread,A=M?M.messages.length>2000?new u0({mainAxisSize:"max",children:[new S1({child:new j0}),new a0({padding:C0.all(2),child:new n1({child:new Q0({text:new C("Thread too long for preview",new b({color:U.mutedForeground,dim:!0}))})})})]}):I(M):L?new V20({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,onOrbExplode:this.handleSplashOrbExplode}):new qp0({threadID:E,items:H,subagentToolsByParentID:w,controller:E?this.getMessageScrollController(E):new o6,autofocus:!1,onCopy:this.handleMainMessageViewCopy,thread:O,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:!this.widget.dependencies.activeThreadHandle.restoreMessage?void 0:this.handleMessageRestoreSubmit,onShowForkDeprecation:this.showForkDeprecationMessage,getAffectedFiles:this.getAffectedFiles,denseView:O?.agentMode==="deep",focusNode:this.messageViewFocusNode,onDismissFocus:this.handleMainMessageViewDismissFocus,isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:this.getCompletionBuilder(),onShowImagePreview:this.handleShowEditingImagePreview,onSelectionChanged:this._handleSelectionChanged,onDoubleAtTrigger:this.handleDoubleAtTrigger,stateController:this.messageViewController,submitOnEnter:this.submitOnEnter,threadViewState:G.viewState}),R=Math.max(Math.floor(Q.size.height*0.4),12),_=this.getCurrentEphemeralError(),S=Q.size.width<40,y=$E4(G),h=a90(J),f=this.buildBottomWidget(_,W,U,Y,G,N,R,F,y,Q,h),k=new J20({threadViewState:G.viewState,threadTokenUsage:y,threadID:E??null,thread:G.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,plugins:this.pluginInfos,isNarrow:S,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(G.viewState.state==="active"&&G.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),x=new l70({bashInvocations:this.bashInvocations}),g=[],a=WY4(this.widget.dependencies.buildTimestamp);if(a){let o0=TO0(a.ageMs,{verbose:!0});g.push(new d0({decoration:new T4(U.destructive),child:new a0({padding:C0.horizontal(1),child:new Q0({text:new C("",new b({color:U.foreground,bold:!0}),[new C(`Your Amp version is ${o0} old — run `),new C("amp update",new b({color:U.warning})),new C(" or see ampcode.com/manual")]),textAlign:"center"})})}))}g.push(new S1({child:A}),x);let m=new D5({children:[new u0({mainAxisSize:"min",children:[q?new Zm0({ad:this.randomAd,onImpression:(o0)=>{if(!o0.advertiserId){P.warn("[ad-telemetry] Skipping impression due to missing advertiserId",{adId:o0.id});return}let w1=o0.impressionId??eN4(16).toString("hex");this.lastAdImpressionId=w1;let O1=this.widget.dependencies.threadState.mainThread;if(!O1)return;let L4=O1.messages[O1.messages.length-1],h4=Date.now();zN("viewed",{adId:o0.id,advertiserId:o0.advertiserId,threadId:O1.id,messageId:L4?.messageId,impressionId:w1,placement:"tui",matchType:o0.metadata?.matchType,matchedPatterns:o0.metadata?.matchedPatterns,candidateAdPoolCount:o0.metadata?.candidateAdPoolCount,clientRegion:o0.metadata?.clientRegion,tokenProvided:!!o0.impressionToken,campaignId:o0.metadata?.campaignId,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType,relevance:o0.metadata?.relevance}),zN("impressionStarted",{adId:o0.id,advertiserId:o0.advertiserId,impressionId:w1,placement:"tui",providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType}),this.widget.dependencies.internalAPIClient.recordAdImpression({adId:o0.id,impressionToken:o0.impressionToken,impressionId:w1,externalImpressionUrl:o0.externalImpressionUrl},{config:this.widget.dependencies.configService}).then((l5)=>{if(!l5.ok)throw Error(`recordAdImpression failed: ${l5.error.code??"unknown"}`);let p7=Math.round(Date.now()-h4);zN("impressionRecorded",{adId:o0.id,advertiserId:o0.advertiserId,impressionId:w1,placement:"tui",durationMs:p7,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType})}).catch((l5)=>{let p7=Math.round(Date.now()-h4);zN("impressionFailed",{adId:o0.id,advertiserId:o0.advertiserId,impressionId:w1,errorMessage:l5 instanceof Error?l5.message:String(l5),errorType:"error",placement:"tui",durationMs:p7,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType})})},onButtonClick:async()=>{let o0=this.randomAd;if(this.lastAdImpressionId&&o0.advertiserId){let L4=this.widget.dependencies.threadState.mainThread;if(!L4)return;let h4=L4.messages[L4.messages.length-1];zN("clicked",{adId:o0.id,advertiserId:o0.advertiserId,threadId:L4.id,messageId:h4?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:o0.metadata?.matchType,matchedPatterns:o0.metadata?.matchedPatterns,candidateAdPoolCount:o0.metadata?.candidateAdPoolCount,clientRegion:o0.metadata?.clientRegion,providerId:o0.metadata?.providerId,providerType:o0.metadata?.providerType})}let O1=a4.instance.tuiInstance.clipboard.isOsc52Supported();if(S30())this.setState(()=>{this.adActionModal={showCopyOption:!1,url:o0.shortDestinationUrl,title:o0.buttonLabel},this.bringAdModalToFront("adAction")});else if(!await K8(this.context,o0.shortDestinationUrl))this.setState(()=>{this.adActionModal={showCopyOption:O1,url:o0.shortDestinationUrl},this.bringAdModalToFront("adAction")})},onAdInfoClick:()=>{this.setState(()=>{this.adInfoModal={provider:this.randomAd?.metadata?.provider},this.bringAdModalToFront("adInfo")})}}):new j0({height:0}),new d0({constraints:new A1(0,Q.size.width,0,R),child:f})]}),F?new $5({top:0,left:0,right:0,child:new QE4({userHeight:this.bottomGridUserHeight,maxHeight:R,onInitializeHeight:(o0)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(o0,R)})},onDrag:(o0)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(o0.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let w1=Math.floor(o0.localPosition.y)-this.bottomGridDragStartY,O1=Math.max(4,this.bottomGridDragStartHeight-w1),L4=Math.min(O1,R),h4=Math.floor(L4);if(this.bottomGridUserHeight!==h4)this.setState(()=>{this.bottomGridUserHeight=h4})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new j0({height:0})]}),i=this.getParentThreadInfo();if(i){let o0=i.type==="handoff"?V.handoffMode:U.primary,w1=40,O1=K5(i.title),L4=O1.length>40?O1.slice(0,39).join("")+"…":i.title;g.push(new lg({link:this.parentThreadLinkAnchor,child:new dm0({type:i.type,title:L4,threadID:i.threadID,labelColor:o0,mutedColor:U.mutedForeground,foregroundColor:U.foreground,onNavigate:(h4)=>this.switchToExistingThread(h4)})}))}g.push(m,new j0({height:1,child:new a0({padding:C0.horizontal(1),child:k})}));let d=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:g}),e=new d0({constraints:A1.tight(Q.size.width,Q.size.height),decoration:new T4(U.background),child:d}),N0=new o4(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingAuthLogin)return this.cancelAuthLoginSession(),"handled";if(this.pendingOAuthRequest){let w1=this.pendingOAuthRequest;return this.setState(()=>{this.pendingOAuthRequest=null}),w1.reject(Error("OAuth authorization cancelled")),"handled"}if(this.isShowingPromptHistoryPicker)return this.setState(()=>{this.isShowingPromptHistoryPicker=!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.isShowingContextAnalyzeModal)return this.setState(()=>{this.isShowingContextAnalyzeModal=!1}),"handled";if(this.isShowingSkillListModal)return this.setState(()=>{this.isShowingSkillListModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!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.dismissTopAdModal())return"handled";if(this.handoffState.countdownSeconds!==null)return this.handoffController?.stopCountdown(),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.isInQueueMode)return this.exitQueueMode(),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let w1=this.handoffController.getPendingPrompt(),O1=this.imageAttachments;return this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((L4)=>{if(L4&&w1)this.textController.text=w1,this.handoffController?.clearPendingPrompt();if(L4&&O1.length>0)this.setState(()=>{this.imageAttachments=O1})}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.cancelStreamingMessage().catch((w1)=>{P.error("Failed to cancel streaming message:",w1)}),this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return P.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.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread))return this.handoffController.startAbortConfirmation(),"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"}),n=new o4(()=>{return this.onExitPressed(),"handled"}),V0=new o4(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),U0=new o4(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),B0=new o4(()=>{if(p9.instance.toggleAll(),G.mainThread?.agentMode==="deep")n$.instance.toggleAll();return"handled"}),X0=new o4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return this.setState(()=>{this.isShowingPromptHistoryPicker=!0}),"handled"}),W0=new o4(()=>{return a4.instance.toggleFrameStatsOverlay(),"handled"}),l=new o4(()=>{return a4.instance.tuiInstance.getScreen().markForRefresh(),q6.instance.requestFrame(),"handled"}),r=new o4(()=>{return this.toggleAgentMode(),"handled"}),J0=new o4(()=>{return this.toggleDeepReasoningEffort(),"handled"}),c=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageUp(L4,100)}return"handled"}),o=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageDown(L4,100)}return"handled"}),$0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageUp(Math.floor(L4/2),100)}return"handled"}),D0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1){let O1=Math.max(Math.floor(Q.size.height*0.4),10),L4=Q.size.height-O1;w1.animatePageDown(Math.floor(L4/2),100)}return"handled"}),q0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1)w1.animateTo(0,100);return"handled"}),A0=new o4(()=>{let w1=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:O1}=this.widget.dependencies,L4=O1.mainThread?.id;return L4?this.getMessageScrollController(L4):null})();if(w1)w1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),H0=new o4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";if(this.isInQueueMode)return"ignored";let{threadState:o0}=this.widget.dependencies;if(!o0.mainThread?.messages.some((O1)=>O1.role==="user"||mF(O1)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),I0=new o4((o0)=>{if(o0.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),_0=new o4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return g70().then(async(o0)=>{if(o0)await this.handleInsertImage(o0)}),"handled"}),X1=new Map([[$4.ctrl("c"),new Pg],[$4.ctrl("l"),new Sg],[$4.ctrl("o"),new b70],[$4.ctrl("v"),new jg],[$4.alt("s"),new yC],[$4.ctrl("s"),new yC],[$4.alt("p"),new _g],[$4.ctrl("r"),new ug],[$4.alt("t"),new Tg],[$4.ctrl("t"),new kg],[$4.key("PageUp"),new v70],[$4.key("PageDown"),new k70],[$4.alt("k"),new y70],[$4.alt("j"),new u70],[$4.key("Home"),new x70],[$4.key("End"),new f70],[$4.key("Escape"),new Rg],[$4.ctrl("p"),new uC("previous")],[$4.ctrl("n"),new uC("next")],[$4.key("Tab"),new cg]]);if(X1.set($4.alt("d"),new vg),!m9())X1.set($4.key("ArrowUp"),new cg);if(!1)X1.set($4.alt("c"),new Cg);let L1=new o4(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),K4=new o4(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),D4=new o4(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),c0=new Map([[Rg,N0],[Sg,l],[yC,r],[vg,J0],[b70,L1],[jg,_0],[Cg,V0],[d90,U0],[Tg,B0],[_g,W0],[kg,K4],[ug,X0],[Pg,n],[v70,c],[k70,o],[y70,$0],[u70,D0],[x70,q0],[f70,A0],[cg,H0],[uC,I0],[yg,D4]]),i0=[e];if(this.splashOrbExplosion){let o0=Qg(this.getEffectiveAgentMode());i0.push(new Yp0({key:new s5(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,sparkleColors:[o0,U.warning],onComplete:this.handleSplashOrbExplosionComplete}))}if(this.isShowingConsoleOverlay)i0.push(new fm0);if(this.isShowingHelp&&this.paletteConfig)i0.push(new cm0({commands:this.getPaletteCommands().getAllCommands(),submitOnEnter:this.submitOnEnter}));if(this.isShowingContextAnalyzeModal){let{configService:o0}=this.widget.dependencies,w1=this.contextAnalyzeDeps;if(w1){let O1={configService:o0,agentModeOverride:this.getEffectiveAgentMode(),buildSystemPromptDeps:w1};i0.push(new bm0({deps:O1,thread:this.widget.dependencies.threadState.mainThread,onDismiss:()=>{this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null})}}))}else this.setState(()=>{this.isShowingContextAnalyzeModal=!1})}if(this.isShowingSkillListModal&&!this.isShowingPalette)Promise.all([this.widget.dependencies.skillService.getSkills(),this.widget.dependencies.skillService.getSkillErrors(),this.widget.dependencies.skillService.getSkillWarnings()]).then(([o0,w1,O1])=>{if(this.isShowingSkillListModal&&this.mounted)this.skillListData={skills:o0,errors:w1,warnings:O1},this.setState()}),i0.push(new Kp0({skills:this.skillListData?.skills??[],errors:this.skillListData?.errors??[],warnings:this.skillListData?.warnings??[],cwd:process.cwd(),onDismiss:()=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null})},onAddSkill:()=>{this.showCommandPalette({type:"standalone",commandId:"skill-add",onSubmit:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.isShowingSkillListModal=!1,this.skillListData=null})},onCancel:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})}})},onDocs:()=>{LX("https://ampcode.com/manual#agent-skills")},onInsertPrompt:(o0)=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null,this.textController.text=o0})},onInvokeSkill:(o0)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill({name:o0})}}));if(this.isShowingMCPStatusModal)i0.push(new Dg0({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingPromptHistoryPicker)i0.push(new Xp0({entries:this.widget.dependencies.history.getAll(),currentCwd:process.cwd(),onAccept:(o0)=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1,this.textController.text=o0,this.textController.cursorPosition=o0.length})},onDismiss:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)i0.push(new Zp0({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.isShowingForkDeprecationModal)i0.push(new gm0({onDismiss:this.dismissForkDeprecationModal}));for(let o0=0;o0<this.adModalStack.length;o0++){let w1=this.adModalStack[o0],O1=o0===this.adModalStack.length-1;if(w1==="adAction"&&this.adActionModal)i0.push(new Qm0({key:new s5(`ad-action-modal-${O1?"top":"back"}`),title:this.adActionModal.title??"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(L4)=>{let h4=this.adActionModal.url;if(L4==="copy")try{await a4.instance.tuiInstance.clipboard.writeText(h4),this.setState(()=>{this.displayMessage=new J$("Link copied to clipboard")})}catch(l5){P.error("Failed to copy to clipboard",{error:l5}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null,this.removeAdModalFromStack("adAction")})}}));if(w1==="adInfo"&&this.adInfoModal)i0.push(new Ym0({key:new s5(`ad-info-modal-${O1?"top":"back"}`),provider:this.adInfoModal.provider,onClose:()=>{this.setState(()=>{this.adInfoModal=null,this.removeAdModalFromStack("adInfo")})}}))}if(this.pendingMCPServers.length>0){let{mcpTrustHandler:o0}=this.widget.dependencies;i0.push(new zg0({servers:this.pendingMCPServers,onAlwaysTrust:o0.trustAlways.bind(o0),onTrustOnce:o0.trustOnce.bind(o0),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:o0.deny.bind(o0)}))}if(this.pendingAuthLogin)i0.push(new Xm0({manualURL:this.pendingAuthLogin.manualURL,isAuthenticating:this.pendingAuthLogin.isAuthenticating||this.pendingAuthLogin.isOpeningBrowser,errorMessage:this.pendingAuthLogin.errorMessage}));if(this.pendingOAuthRequest)i0.push(new Qp0({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.pendingInputDialog){let o0=this.pendingInputDialog;i0.push(new am0({options:o0.options,onSubmit:(w1)=>{this.setState(()=>{this.pendingInputDialog=null}),o0.resolve(w1)},onCancel:()=>{this.setState(()=>{this.pendingInputDialog=null}),o0.resolve(void 0)}}))}if(this.pendingConfirmDialog){let o0=this.pendingConfirmDialog;i0.push(new ym0({options:o0.options,onConfirm:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),o0.resolve(!0)},onCancel:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),o0.resolve(!1)}}))}if(this.isShowingFileChangesOverlay)i0.push(new lh0({threadData:G}));if(this.isShowingContextDetailOverlay){let o0=this.threadCostInfo?.costBreakdownURL;i0.push(new hm0({tokenUsage:y??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:o0?()=>{K8(J,o0)}:void 0}))}if(this.isShowingConfirmationOverlay)i0.push(new um0({details:this.confirmationOverlayContent}));if(this.imagePreview!==null)i0.push(new n1({child:new nm0({image:this.imagePreview.image,imageIndex:this.imagePreview.index,onDismiss:this.handleImagePreviewDismiss,onRemove:this.handleImagePreviewRemove})}));if(this.fileImagePreviewPath!==null)i0.push(new n1({child:new Ng({filePath:this.fileImagePreviewPath,onDismiss:this.handleFileImagePreviewDismiss})}));if(this.painterImagePreview!==null)i0.push(new n1({child:new Ng({filePath:this.painterImagePreview.filePath,onDismiss:this.handlePainterImagePreviewDismiss})}));if(this.painterSaveDialog!==null)i0.push(new n1({child:new Ng({filePath:this.painterSaveDialog.filePath,imageBlock:this.painterSaveDialog.image,onDismiss:this.handlePainterSaveDialogDismiss})}));if(this.skillPreview!==null){let o0=this.pendingSkills[this.skillPreview.skillIndex];if(o0)i0.push(new n1({child:new Dp0({pendingSkill:o0,skill:this.cachedSkillForPreview,onDismiss:this.handleSkillPreviewDismiss,onRemove:this.skillPreview.onRemove})}))}let e0=this.getCommandPaletteContext(J);if(e0&&this.isShowingPalette&&this.paletteConfig)i0.push(new n1({child:new vm0({commandContext:e0,mainThread:G.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)i0.push(new im0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let j1=new D5({children:i0});if(this.isShowingJetBrainsInstaller)return new KL({child:new j9({actions:c0,child:new B2({shortcuts:X1,debugLabel:"jetbrains-installer-shortcuts",child:new Vg0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let r1=this.widget.dependencies.threadState.mainThread?.id,j4=1+(this.bottomGridUserHeight??5)+1,v4=!this.isShowingPalette&&!this.isShowingIdePicker;return new NT({switchToThread:(o0)=>this.switchToExistingThread(o0),child:new QD({threadViewStates:this.getThreadViewStatesSnapshot(),threadTitles:this.threadTitles,threadSummaries:this.threadsForPicker,child:new pm0({getThreadCluster:this.getCurrentThreadClusterForMinimap,parentThreadID:i?.threadID,anchorLink:i?this.parentThreadLinkAnchor:void 0,bottomOffset:j4,enabled:v4,child:new JT({onShowImagePreview:this.handleShowFileImagePreview,child:new ZT({onShowImagePreview:this.handleShowPainterImagePreview,onShowSaveDialog:this.handleShowPainterSaveDialog,child:new uY({controller:this.toastController,child:new KL({child:new ug0({getThreadCluster:this.getThreadClusterForMinimap,currentThreadID:r1,enabled:v4,child:new kH({enabled:v4,child:new z90({controller:this.toastController,child:new j9({actions:c0,child:new B2({shortcuts:X1,debugLabel:"main-app-shortcuts",child:j1})})})})})})})})})})})})}buildScrollableTodoList(J,Z,Q){return new JE4({todos:J,enabled:Z,controller:this.todoScrollController,appTheme:Q})}buildBottomWidget(J,Z,Q,Y,X,U,V,K,D,z,q){if(J)return new mm0({error:J,options:{ampURL:this.widget.dependencies.ampURL,freeTierEnabled:this.freeTierStatus.canUseAmpFree},onResponse:this.handleEphemeralErrorResponse});if(Z){if(this.displayMessage)this.handleDisplayMessageDismiss();return new xm0({confirmationRequest:Z,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new qg0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let F=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?[]:c70(Y),G=this.agentModeController?.isInRestrictedFreeMode()??!1,W=this.isTextfieldAndAutocompleteFocused&&!G&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff;if(W&&!this.hasReplayedEarlyInput){this.hasReplayedEarlyInput=!0;let c=a4.instance.tuiInstance.getEarlyInputText();if(c)this.textController.insertText(c)}let H=this.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}},B=new Lp({key:this.textFieldKey,controller:this.textController,triggers:[new pH],completionBuilder:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:(c)=>{this.onTextSubmitted(c).catch((o)=>{this.handleSubmitFlowError(o)})},submitKey:H,theme:Q,placeholder:G?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:W,shellPromptRules:F,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker&&!this.isShowingSkillListModal,clipboard:a4.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let c=this.previousThreadIdForHint;if(c)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${c} `},onDoubleAtTrigger:(c)=>{this.handleDoubleAtTrigger(c)},pendingSkills:this.pendingSkills,onClearPendingSkill:(c)=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(c)},popSkill:()=>{let c=this.pendingSkills[this.pendingSkills.length-1];if(c)this.widget.dependencies.activeThreadHandle.removePendingSkill(c.name)},onSkillClick:this.handleSkillClick,topWidget:this.isShowingShortcutsHelp?new Vp0({submitOnEnter:this.submitOnEnter}):void 0}),w=X.mainThread?.queuedMessages??[],N=Array.isArray(U)&&U.length>0,O=Array.isArray(w)&&w.length>0?new Up0({queuedMessages:w}):void 0,L=N?this.buildScrollableTodoList(U,this.isTextfieldAndAutocompleteFocused&&!G,Y):void 0,I=[],M=null,A=0,R=z.capabilities.emojiWidth,_=this.widget.dependencies.threadPool,S=_.isDTWMode?.()===!0,y=S?_.getTransportConnectionState?.():void 0;if(S&&y!==void 0)I.push({child:new Q0({text:new C(`(dtw: ${y})`,new b({color:Q.mutedForeground,dim:!0}))}),position:"top-left"});let h=this.currentShellModeStatus;if(h)I.push({child:new Q0({text:new C(h==="hidden"?"shell mode (incognito)":"shell mode",new b({color:h==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let c=new b({color:Y.app.handoffMode}),o=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new C("",void 0,[new C("handoff ",c),new C(this.handoffState.spinner.toBraille(),c)]):new C("handoff (submit a goal for the new thread)",c);if(I.push({child:new Q0({text:o}),position:"top-left"}),this.handoffState.isGeneratingHandoff){let $0=new b({color:Q.foreground,dim:!0});I.push({child:new Q0({text:new C("",void 0,[new C("Esc",new b({color:Y.app.keybind})),new C(" to cancel",$0)])}),position:"bottom-left"}),A=r5("Esc to cancel",R)}}if(this.handoffState.countdownSeconds!==null){let c=new b({color:Q.foreground,dim:!0}),o=`Auto-submitting in ${this.handoffState.countdownSeconds}s`,$0=this.handoffState.countdownSeconds<10?1:0;I.push({child:new a0({padding:C0.only({right:$0}),child:new Q0({text:new C(o,new b({color:Y.app.handoffMode}))})}),position:"bottom-left"}),I.push({child:new Q0({text:new C("",void 0,[new C("type",new b({color:Y.app.keybind})),new C(" to edit",c)])}),position:"bottom-left"}),A=r5("Auto-submitting in 10s",R)+2+r5("type to edit",R)}if(this.isInQueueMode){let c=new b({color:Y.app.queueMode});I.push({child:new Q0({text:new C("queue",c)}),position:"top-left"})}let f=this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread)??null,k=z.capabilities.animationSupport,x=k==="disabled"?0:k==="slow"?30:60,g=this.getEffectiveAgentMode(),a=Qg(g),m=null,i=this.agentModeController?.getVisibleModes()??[];if(!h&&!this.isInQueueMode&&i.length>1){let c=this.previewThread,o=this.agentModeController?.getMode(),$0=c?c.agentMode??this.getEffectiveAgentMode():this.handoffState.isGeneratingHandoff&&o?o:this.getEffectiveAgentMode(),D0=this.formatAgentModeLabel($0),q0=$0==="smart"&&this.anthropicSpeed==="fast",A0=q0?"smart+fast(6x$)":D0,H0=Qg($0),I0=c??this.widget.dependencies.threadState.mainThread,_0=I0?Y8(I0)>0:!1,X1="top-right";if(c){m=r5(A0,R);let F1=q0?new C("",void 0,[new C("smart",new b({color:H0})),new C("+fast(6x$)",new b({color:Q.warning}))]):new C(D0,new b({color:H0}));I.push({child:new Q0({text:F1}),position:"top-right"})}else{let F1=!_0&&!this.handoffState.isGeneratingHandoff,L1=this.handoffState.isGeneratingHandoff,K4=new b({color:H0,dim:L1}),D4=new Q0({text:q0?new C("",void 0,[new C("smart",K4),new C("+fast(6x$)",new b({color:Q.warning,dim:L1}))]):new C(D0,K4)}),c0=r5(A0,R),e0=[F1?new i1({child:D4,onClick:()=>this.toggleAgentMode(),cursor:"pointer"}):D4];if(m=c0,this.showSkillsCountInPromptBar){let j1=this.availableSkillCountReady?this.availableSkillCount:this.widget.dependencies.skillService.listInstalled().length,r1=this.skillWarningCount>0||this.skillErrorCount>0,j4=`${r1?"⚠ ":""}${j1} ${g4(j1,"skill")}`,v4=2,o0=r5(j4,R);m+=2+o0;let w1=new b({color:r1?Q.warning:Q.foreground,dim:!r1});e0.push(new j0({width:2}),new i1({child:new Q0({text:new C(j4,w1)}),onClick:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},cursor:"pointer"}))}I.push({child:new D1({mainAxisSize:"min",children:e0}),position:"top-right"})}}if(x>0&&this.agentModePulseSeq>0&&!h&&!this.isInQueueMode&&!f&&i.length>1){let o=S2(g)?.uiHints?.fasterAnimation?3:1,$0=(m??0)+1,D0=$0>0?2+$0:1;M=new $5({top:0,left:1,right:D0,height:1,child:new Kg0({color:a,backgroundColor:Q.background,trigger:this.agentModePulseSeq,fps:x,speed:o,trail:5,leftOffset:0,direction:"right-to-left"})})}if(f&&this.handoffState.countdownSeconds===null){let c=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";I.push({child:new Q0({text:new C("",void 0,[new C("Esc",new b({color:Y.app.keybind})),new C(c,new b({color:Q.foreground,dim:!0})),new C("handoff",new b({color:Y.app.handoffMode}))])}),position:"bottom-left"}),A=r5(`Esc${c}handoff`,R)}if(!f&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")I.push({child:new Q0({text:new C("",void 0,[new C("press ",new b({color:Q.foreground,dim:!0})),new C("enter",new b({color:Y.app.keybind})),new C(" to reference the previous thread",new b({color:Q.foreground,dim:!0}))])}),position:"bottom-left"}),A=r5("press enter to reference the previous thread",R);let n=X.mainThread?.env?.initial.trees?.[0]?.uri,V0;if(n)V0=V1.parse(n).fsPath;else V0=process.cwd();let U0=this.toHomeRelative(V0),B0=this.shorten(U0),X0=A>0?z.size.width-A-6:z.size.width-4,W0=this.buildDisplayText(B0,this.currentGitBranch||void 0,X0,R);I.push({child:new Q0({text:new C(W0,new b({color:Q.foreground,dim:!0}))}),position:"bottom-right"});let l=this.previewThread,r=this.widget.dependencies.threadState.mainThread;if((r?Y8(r)>0:!1)&&!h&&!this.handoffState.isInHandoffMode&&!l){let c=[],o=new b({color:Q.foreground,dim:!0}),$0=new C(" · ",o);if(D){let I0=D.totalInputTokens/D.maxInputTokens,_0=Math.round(I0*100),X1=Math.max(0,Math.min(_0,100)),F1=$20(I0,D.maxInputTokens),L1=o;if(F1==="danger")L1=new b({color:Q.destructive});else if(F1==="warning")L1=new b({color:Q.warning});else if(F1==="recommendation")L1=new b({color:Y.app.recommendation});if(c.length>0)c.push($0);if(D.maxInputTokens>=1000){let K4=Math.round(D.maxInputTokens/1000);c.push(new C(`${X1}% of ${K4}k`,L1))}else c.push(new C(`${X1}%`,L1))}if(q&&this.threadCostInfo){let I0=j20(this.threadCostInfo,{colors:{foreground:Q.foreground},dim:!0});if(I0.length>0){if(c.length>0)c.push($0);c.push(...I0)}}let D0=X.viewState,q0=D0.state==="active"?D0.turnStartTime:void 0,A0=D0.state==="active"?D0.turnElapsedMs:void 0,H0=null;if(X.mainThread?.agentMode==="deep"){let I0=q0?Date.now()-q0:A0;if(I0!==void 0){let _0=Uy1(I0);H0=new Q0({text:new C(_0,o)})}}if(c.length>0||H0){let I0=[];if(c.length>0){let _0=new Q0({text:new C("",void 0,c)});I0.push(q?new i1({child:_0,onClick:this.showContextDetailOverlay,cursor:"pointer"}):_0)}if(H0){if(c.length>0)I0.push(new Q0({text:new C(" · ",o)}));I0.push(H0)}I.push({child:new D1({mainAxisSize:"min",children:I0}),position:"top-left"})}}return new Um0({leftChild:new S1({child:B}),rightChild1:O,rightChild2:L,maxHeight:V,overlayTexts:I,overlayLayer:M,backgroundColor:Q.background,borderColor:G||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?Q.border:void 0,hasBanner:K,userHeight:this.bottomGridUserHeight,onInitializeHeight:(c)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(c,V)})},onDrag:(c)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(c.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let o=Math.floor(c.localPosition.y)-this.bottomGridDragStartY,$0=Math.max(4,this.bottomGridDragStartHeight-o),D0=Math.min($0,V),q0=Math.floor(D0);if(this.bottomGridUserHeight!==q0)this.setState(()=>{this.bottomGridUserHeight=q0})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!K})}}function $E4(J){return J.resolvedTokenUsage}class JE4 extends p0{props;constructor(J){super();this.props=J}createState(){return new ZE4}}class ZE4 extends g0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Z,controller:Q,appTheme:Y}=this.widget.props;return new D1({crossAxisAlignment:"stretch",children:[new S1({child:new N6({controller:Q,autofocus:!1,child:new Wp0({todos:Z})})}),new j8({controller:Q,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:U}=Q,V=this.viewportHeight,K=X+V;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(V,1),scrollOffset:Math.max(U,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 Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let U=Y.children||[];for(let V of U){if(V&&"size"in V){let D=V.size;if(typeof D?.height==="number"&&D.height>0)return D.height}let K=Z(V,X+1);if(K>0)return K}}return 0},Q=Z(J);if(Q>0)return Q;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class QE4 extends c1{props;constructor(J){super();this.props=J}build(J){return new i1({child:new j0({height:1}),cursor:H5.NS_RESIZE,onDrag:(Z)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Z)},onRelease:this.props.onRelease})}}function XE4(J){let Z=J.split(`
|
|
7386
7389
|
`);try{return Z.map((Q)=>{let Y=Q.indexOf(":");if(Y===-1)return{label:"",content:YE4(Q)};let X=Q.slice(0,Y+1),U=Q.slice(Y+1);return{label:X,content:YE4(U)}})}catch(Q){return Z.map((Y)=>({label:"",content:[{type:"text",text:Y}]}))}}function YE4(J){let Z=[],Q=/(\+?\$[\d,.]+(?:\/\$[\d,.]+)?(?:\/hour)?)|(\busage paid\b|\bpaid\b)|(\s-\s(?=https?:\/\/))|((https?:\/\/)[^\s]+)|([^$\s][^\s]*)/gi,Y,X=0;while((Y=Q.exec(J))!==null){if(Y.index>X){let q=J.slice(X,Y.index);if(q)Z.push({type:"text",text:q})}let[U,V,K,D,z]=Y;if(V)Z.push({type:"amount",text:V});else if(K)Z.push({type:"paid",text:K});else if(D);else if(z)Z.push({type:"url",text:z});else{let q=U.replace(/\s+\)/g,")");Z.push({type:"text",text:q})}X=Q.lastIndex}if(X<J.length){let U=J.slice(X);if(U)Z.push({type:"text",text:U})}return Z}TJ();async function sp5(J){return XE4(J).map((Z)=>{let Q=Z.content.map((Y)=>{switch(Y.type){case"amount":case"paid":return Z1.bold.green(Y.text);case"url":return Z1.dim(" - ")+Z1.blue.underline(Y.text);default:return Z1.dim(Y.text)}}).join("");if(Z.label)return Z1.bold(Z.label)+Q;return Q}).join(`
|
|
7387
7390
|
`)}function UE4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),U=await Z(X),V=await U.settings.get("proxy"),K=MM1({settings:{url:U.ampURL,proxy:V},secrets:{getToken:(z,q)=>U.secrets.get(z,q)}}),D=await T6.userDisplayBalanceInfo({},{config:K});if(!D.ok){if(D.error.code==="auth-required")process.stderr.write(Z1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Z1.red("Error: ")+D.error.message+`
|
|
7388
7391
|
`),process.exit(1)}process.stdout.write(await sp5(D.result.displayText)+`
|
|
7389
7392
|
`),process.exit(0)})}var wn5=lp.join(NZ,"logs","headless.log"),dd0=lp.join($C,"device-id.json");function Nn5(){return oD.some((J)=>J.listConfigs().length>0)}try{if(process.platform==="win32")await Promise.resolve().then(() => I4(fT(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){q7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7390
|
-
`)}function En5(J){process.emitWarning=(Z,Q,Y,X)=>{let U=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",K=!1;J.warn(U,{name:V,code:Y})}}function g7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")E7("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")E7("experimental.agentMode",Z.mode)}function kI4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function On5(J){try{return await vI4(J,"utf-8")}catch{return J}}async function cd0(J,Z,Q){let Y=kI4(J,Z);if(!Y)return;let X=T5(Q)?Q.features:[],U=T5(Q)?Q.user.email:void 0;if(!X.some((K)=>K.name===AX.HARNESS_SYSTEM_PROMPT&&K.enabled)&&!yI4(U))throw new F4("You are not allowed to do this.",1);E7("systemPrompt",await On5(Y))}function yI4(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function ld0(J,Z){if(typeof J==="boolean")return J;if(!T5(Z))return!1;return pQ(Z.user.email)}function id0(J){if(!T5(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ln5(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function nd0(J){let Y=Ln5(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new F4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var PI4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??TY,description:`Custom settings file path (overrides the default location ${TY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${WO})`},{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:m9(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:AV.SMART.key,description:`Set the agent mode (${xQ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:xQ().map((J)=>J.mode).concat("large","deep")},{name:"dtw",long:"dtw",type:"flag",description:"Use the DTW-backed thread provider in the TUI (experimental)",hidden:!0,aliases:["deliver-me-to-agg"]},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],CI4=(J)=>("deprecated"in J)&&J.deprecated===!0,In5=(J)=>("hidden"in J)&&J.hidden===!0,Mn5=(J)=>("default"in J),An5=(J)=>("default"in J)?J.default:void 0,uI4=[{name:"toggle-skills-count",entryPoint:Ku0}];function jn5(J,Z){let Q=Z.args[0],Y=Z.commands.map((U)=>U.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let U=Y.filter((K)=>Q.includes(K)||K.includes(Q)),V="Run amp --help for a list of available commands.";if(U.length>0)V=`Did you mean: ${U.join(", ")}? Or run amp --help for all commands.`;throw new F4(V8.unknownCommand(Q),1,V)}}async function od0(J){return{...J,getThreadEnvironment:x$,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new pX(J.fileSystem),generateThreadTitle:F00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>_J(J.configService),pluginService:J.pluginService}}function xI4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:x$,filesystem:J.fileSystem,threadService:J.threadService}}var a$0=V1.file(Bn5.homedir()),ad0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(a$0,".config");function Rn5(J){return r84({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){o84(Z);let Q=U80(),Y=_u0();if((!Q||Y||QX4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(Dq("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(Dq("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(U80()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Pn5(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function c9(J,Z,Q){let Y=Q?.deferAuth??!1;BM1("0.0.
|
|
7393
|
+
`)}function En5(J){process.emitWarning=(Z,Q,Y,X)=>{let U=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",K=!1;J.warn(U,{name:V,code:Y})}}function g7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")E7("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")E7("experimental.agentMode",Z.mode)}function kI4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function On5(J){try{return await vI4(J,"utf-8")}catch{return J}}async function cd0(J,Z,Q){let Y=kI4(J,Z);if(!Y)return;let X=T5(Q)?Q.features:[],U=T5(Q)?Q.user.email:void 0;if(!X.some((K)=>K.name===AX.HARNESS_SYSTEM_PROMPT&&K.enabled)&&!yI4(U))throw new F4("You are not allowed to do this.",1);E7("systemPrompt",await On5(Y))}function yI4(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function ld0(J,Z){if(typeof J==="boolean")return J;if(!T5(Z))return!1;return pQ(Z.user.email)}function id0(J){if(!T5(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Ln5(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function nd0(J){let Y=Ln5(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new F4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var PI4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??TY,description:`Custom settings file path (overrides the default location ${TY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${WO})`},{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:m9(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:AV.SMART.key,description:`Set the agent mode (${xQ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:xQ().map((J)=>J.mode).concat("large","deep")},{name:"dtw",long:"dtw",type:"flag",description:"Use the DTW-backed thread provider in the TUI (experimental)",hidden:!0,aliases:["deliver-me-to-agg"]},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],CI4=(J)=>("deprecated"in J)&&J.deprecated===!0,In5=(J)=>("hidden"in J)&&J.hidden===!0,Mn5=(J)=>("default"in J),An5=(J)=>("default"in J)?J.default:void 0,uI4=[{name:"toggle-skills-count",entryPoint:Ku0}];function jn5(J,Z){let Q=Z.args[0],Y=Z.commands.map((U)=>U.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let U=Y.filter((K)=>Q.includes(K)||K.includes(Q)),V="Run amp --help for a list of available commands.";if(U.length>0)V=`Did you mean: ${U.join(", ")}? Or run amp --help for all commands.`;throw new F4(V8.unknownCommand(Q),1,V)}}async function od0(J){return{...J,getThreadEnvironment:x$,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new pX(J.fileSystem),generateThreadTitle:F00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>_J(J.configService),pluginService:J.pluginService}}function xI4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:x$,filesystem:J.fileSystem,threadService:J.threadService}}var a$0=V1.file(Bn5.homedir()),ad0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(a$0,".config");function Rn5(J){return r84({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){o84(Z);let Q=U80(),Y=_u0();if((!Q||Y||QX4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(Dq("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(Dq("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(U80()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Pn5(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function c9(J,Z,Q){let Y=Q?.deferAuth??!1;BM1("0.0.1772685027-gdb1277");let X=Mo({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([V1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:a$0,userConfigDir:ad0});tY4(X);let U=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(U.settings)});let{toolService:V,dispose:K}=c84({configService:X}),D=new Map,z=()=>D.clear(),q=new CO0(X,J.settings.getWorkspaceRootPath()),F=kb1({configService:X,filesystem:t6}),G=Zy1({configService:X,trustStore:q,skillMCPServers:F.skillMCPServers,createOAuthProvider:async(i,d,e)=>{let N0=`${i}:${d}`,n=D.get(N0);if(n)return P.debug("Reusing existing OAuth provider for server",{serverName:i,serverUrl:d}),n;P.debug("Creating OAuth provider for server",{serverName:i,serverUrl:d});let V0=(async()=>{let U0=new qN(J.secrets),B0=await U0.getClientInfo(i,d),X0=e?.scopes??B0?.scopes,W0=FQ4();P.info("OAuth headless mode check",{useHeadless:W0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:r6.isTTY});let l;if(W0)l=J.executeMode?qQ4():zQ4(i);let r=new nE0({storage:U0,serverName:i,serverUrl:d,clientId:e?.clientId??B0?.clientId,clientSecret:e?.clientSecret??B0?.clientSecret,authUrl:e?.authUrl??B0?.authUrl,tokenUrl:e?.tokenUrl??B0?.tokenUrl,scopes:X0,headlessAuthHandler:l});return P.debug("OAuth provider created",{serverName:i,serverUrl:d,hasManualClientId:!!(e?.clientId??B0?.clientId),willUseDCR:!(e?.clientId??B0?.clientId),scopes:X0,headlessMode:W0,executeMode:J.executeMode}),r})();return D.set(N0,V0),V0}}),W=LS0({configService:X,filesystem:t6,spawn:e60}),H;if(J.executeMode){let i=await Q54({toolService:V,providers:[G,W],initialTimeout:15000});H=i.registrations;for(let[d,e]of i.initErrors)P.warn(`${d} provider initialization slow or failed:`,e)}else H=MS0({toolService:V,providers:[G,W]});if(Z.jetbrains)mw("JetBrains");else if(Z.ide&&aQ4())mw("VS Code");else if(Z.ide&&oQ4())mw("Neovim");else if(Z.ide&&Nn5()){let i=oD.find((d)=>d.listConfigs().length>0);if(i){let d=lw(i.ideName);if(d)mw(d)}}if(J.executeMode)wM1(!0);let B,w=S8.status.pipe(H1((i)=>Boolean(i.connected&&i.authenticated&&i.ideName&&lM1(i.ideName))),M4()).subscribe((i)=>{if(i){if(!B)B=V.registerTool(Z54)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let i=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new A30(process.cwd(),{alwaysIncludePaths:i},!0)}else N=new class extends A30{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let E=!1;{let i=await J.secrets.get("apiKey",J.ampURL);if(E=Boolean(i),P.info("API key lookup before login",{found:Boolean(i),ampURL:J.ampURL,deferAuth:Y}),!i)if(Y)P.info("No API key found, continuing startup with deferred auth");else{r6.write(`No API key found. Starting login flow...
|
|
7391
7394
|
`);let d=await Cn5(J),e=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:d,storedKeyPresent:Boolean(e),ampURL:J.ampURL}),!d)await Xq(),process.exit(1);E=!0}}{let i=await X.getLatest(),d=i.settings.url,e=i.secrets.isSet?.[d];P.info("Config secrets state after login",{configURL:d,apiKeySet:e?.apiKey??!1})}let O=I1(_J(X).pipe(k5((i)=>i!=="pending"))),L=await hb1({isDevelopment:!1}),I=Y?"pending":await O;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:T5(I),isError:GG(I),errorMessage:GG(I)?I.error.message:void 0});let M=new uM0(L,X),A=new PI0(L,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=ld0(Z.dtw,I),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let S=_?Pn5():qm1({threadService:M,threadHistoryService:A,configService:X,isExtensionDevelopment:!1}),y;S8.status.subscribe((i)=>{y=i});let h=new dH0({workspaceRoots:[V1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?gs:t6,getCurrentFile:()=>{if(!y?.openFile)return;try{return V1.parse(y.openFile)}catch(i){P.warn("Failed to parse current file URI",{uri:y.openFile,error:i});return}},getOpenFiles:()=>{if(!y?.visibleFiles?.length)return[];let i=y.openFile;return y.visibleFiles.filter((d)=>d!==i).map((d)=>{try{return V1.parse(d)}catch(e){return P.warn("Failed to parse visible file URI",{uri:d,error:e}),null}}).filter((d)=>d!==null)}}),f=new ku0,k=process.env.PLUGINS??"off",x=new Vu0({configService:X}),g=HI0({configService:X,fileSystem:Z.jetbrains||Z.ide?gs:t6,platform:x,internalPlugins:uI4,pluginFilter:k}),a=$b1({pluginService:g,toolService:V}),m={codebaseContextService:h,configService:X,toolService:V,mcpService:G,skillService:F,toolboxService:W,trustStore:q,threadService:M,threadHistoryService:A,threadSyncService:S,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?gs:t6,terminal:f,pluginService:g,pluginPlatform:x,serverStatus:I,serverStatusPromise:O,hasAPIKeyAtStartup:E};return{...m,async asyncDispose(){if(m.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await m.mcpService.waitForAuthentication();for(let i of H.values())i.dispose();await m.mcpService.dispose(),z(),await m.threadService.asyncDispose(),m.configService.unsubscribe(),K(),m.fuzzyServer.dispose(),m.threadSyncService.dispose(),m.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),a.dispose(),m.pluginService.dispose()}}}async function Cn5(J){if(!J.executeMode){if(!await Xu0("Would you like to log in to Amp? [(y)es, (n)o]: "))return r6.write(`Login cancelled. Run the command again to retry.
|
|
7392
7395
|
`),!1}return await fI4(J)}async function fI4(J){let Z=Gn5(32).toString("hex"),Q=await ZC(J.ampURL,Z),Y=new AbortController;try{await LX(Q,Y.signal)}catch(U){P.error("Error opening browser",{error:U})}let X=await ZC(J.ampURL,Z,!1);r6.write(`If your browser does not open automatically, visit:
|
|
7393
7396
|
|
|
@@ -7395,7 +7398,7 @@ ${Z1.blue.bold(X)}
|
|
|
7395
7398
|
|
|
7396
7399
|
`);try{return await NY4(J.ampURL,Z,J.secrets,Y),r6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(U){return P.error("Login failed",{error:U}),q7.write(`
|
|
7397
7400
|
Login failed: ${U instanceof Error?U.message:String(U)}
|
|
7398
|
-
`),!1}}function Tn5(){let J=new yW().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)BO(),process.exit(0);let B=H.originalError??H;PZ4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${WG(new Date("2026-03-
|
|
7401
|
+
`),!1}}function Tn5(){let J=new yW().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)BO(),process.exit(0);let B=H.originalError??H;PZ4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${WG(new Date("2026-03-05T04:36:12.856Z"))} ago`}catch{}r6.write(`0.0.1772685027-gdb1277 (released 2026-03-05T04:36:12.856Z${B??""})
|
|
7399
7402
|
`),process.exit(0)}),J.addHelpText("after",lQ4()),J.configureHelp({formatHelp:iQ4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await A3(w);await xn5(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await A3(w);await un5(N,await hy0(w,N.settings))}),J.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await sZ4(H??"get",E.ampURL,E.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let w=B.optsWithGlobals(),N=await A3(w);await tZ4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7400
7403
|
Actions:
|
|
7401
7404
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7439,7 +7442,7 @@ See: https://ampcode.com/news/stick-a-fork-in-it
|
|
|
7439
7442
|
amp threads handoff T-xxx --goal "Continue working on the auth feature"
|
|
7440
7443
|
amp threads handoff --goal "Fix the remaining tests" # Uses last thread
|
|
7441
7444
|
|
|
7442
|
-
By default, opens the new thread in the TUI. Use --print to just print the thread ID.`).option("-g, --goal <goal>","Goal/prompt for the handoff (alternative to stdin)").option("-p, --print","Print the thread ID instead of opening the TUI").action(async(H,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await dn5(N,E,H??null,B.goal,!B.print,w)}),Q.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,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await mn5(N,E,H,w)}),Q.command("export <threadId>",{hidden:!0}).summary("Export a thread as JSON").description("Export a thread as JSON. This outputs the full thread payload.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await gn5(N,E,H,w)}),x94(Q,A3,g7,c9,rd0,JB,q3),sX4(J,async(H,B)=>{let w=await A3(B);g7(H,B);let N=await c9(w,B);return{context:w,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,skillService:N.skillService,threadService:N.threadService,fileSystem:N.fileSystem,getThreadEnvironment:x$,serverStatus:N.serverStatus,toolboxService:N.toolboxService,configService:N.configService,cleanupTerminal:BO,asyncDispose:N.asyncDispose.bind(N)}}),mY4(J,async(H)=>{let B=H.optsWithGlobals(),w=await A3(B);g7(H,B);let N=Mo({storage:w.settings,secretStorage:w.secrets,workspaceRoots:v0.of([V1.file(process.cwd())]),defaultAmpURL:w.ampURL,homeDir:a$0,userConfigDir:ad0});return{pluginService:HI0({configService:N,fileSystem:t6,platform:{clientKind:"terminal",clientVersion:"0.0.
|
|
7445
|
+
By default, opens the new thread in the TUI. Use --print to just print the thread ID.`).option("-g, --goal <goal>","Goal/prompt for the handoff (alternative to stdin)").option("-p, --print","Print the thread ID instead of opening the TUI").action(async(H,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await dn5(N,E,H??null,B.goal,!B.print,w)}),Q.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,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await mn5(N,E,H,w)}),Q.command("export <threadId>",{hidden:!0}).summary("Export a thread as JSON").description("Export a thread as JSON. This outputs the full thread payload.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),E=await A3(N);await gn5(N,E,H,w)}),x94(Q,A3,g7,c9,rd0,JB,q3),sX4(J,async(H,B)=>{let w=await A3(B);g7(H,B);let N=await c9(w,B);return{context:w,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,skillService:N.skillService,threadService:N.threadService,fileSystem:N.fileSystem,getThreadEnvironment:x$,serverStatus:N.serverStatus,toolboxService:N.toolboxService,configService:N.configService,cleanupTerminal:BO,asyncDispose:N.asyncDispose.bind(N)}}),mY4(J,async(H)=>{let B=H.optsWithGlobals(),w=await A3(B);g7(H,B);let N=Mo({storage:w.settings,secretStorage:w.secrets,workspaceRoots:v0.of([V1.file(process.cwd())]),defaultAmpURL:w.ampURL,homeDir:a$0,userConfigDir:ad0});return{pluginService:HI0({configService:N,fileSystem:t6,platform:{clientKind:"terminal",clientVersion:"0.0.1772685027-gdb1277",async notify(L){P.debug("plugin notification (TUI not loaded): %s",L)},async open(L){q7.write(`
|
|
7443
7446
|
${L}
|
|
7444
7447
|
|
|
7445
7448
|
`)},async input(){return},async confirm(){return!1},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},internalPlugins:uI4,emitSessionStart:!1,pluginFilter:process.env.PLUGINS??"off"}),asyncDispose:async()=>{}}}),lY4(J,async(H)=>{let B=H.optsWithGlobals(),w=await A3(B);g7(H,B);let N=await c9(w,B);return{toolService:N.toolService,mcpService:N.mcpService,configService:N.configService,skillService:N.skillService,cleanupTerminal:BO,asyncDispose:N.asyncDispose.bind(N)}}),rY4(J,async(H)=>{let B=H.optsWithGlobals(),w=await A3(B);g7(H,B);let N=await c9(w,B);return{settings:w.settings,configService:N.configService,skillService:N.skillService,asyncDispose:N.asyncDispose.bind(N)}}),fY4(J,async(H)=>{let B=H.optsWithGlobals();return await A3(B)}),RY4(J,async(H)=>{let B=await A3(H);return{settings:B.settings,secretStorage:B.secrets,getThreadDeps:async(w)=>{g7(w,H);let N=await c9(B,H);return{mcpService:N.mcpService,settings:B.settings,asyncDispose:N.asyncDispose.bind(N)}}}}),UE4(J,A3);function U(H,B,w){let E=typeof H.description==="string"?H.description:w===void 0?H.description(!0):H.description(w),O=new WU(B,E),L=An5(H);if(L)O.default(L);if(O.hidden=In5(H)||CI4(H),"choices"in H)O.choices([...H.choices]);return O}for(let H of PI4){switch(H.type){case"flag":{J.addOption(U(H,`--${H.long}`)),J.addOption(U(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(U(H,`--${H.long}`,!0));break}case"optional-option":{J.addOption(U(H,`${"short"in H?`-${H.short}, `:""}--${H.long} [value]`));break}default:{J.addOption(U(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}if("aliases"in H&&H.aliases)for(let B of H.aliases){let w=new WU(`--${B}`,H.description);w.hidden=!0,w.implies({[H.name]:!0}),J.addOption(w)}}let V=new WU("-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(V);let K=new WU("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);J.addOption(K);let D=new WU("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(D);let z=new WU("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);J.addOption(z);let q=new WU("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let F=new WU("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(F);let G=new WU("--archive","When used with --execute, archive the thread after the command finishes.").default(!1);J.addOption(G);let W=new WU("-l, --label <label>","When used with --execute, add a label to the thread. Can be used multiple times.").argParser((H,B)=>{if(B===void 0)return[H];return[...B,H]});return J.addOption(W),J.action(async(H,B)=>{let w=H,N=await A3(w);if(Object.keys(w).forEach((E)=>{let O=PI4.find((L)=>L.name===E);if(O&&CI4(O)&&!Mn5(O))q7.write(Z1.yellow(`Warning: '--${E}' flag is deprecated
|
|
@@ -7447,8 +7450,8 @@ ${L}
|
|
|
7447
7450
|
|
|
7448
7451
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function _n5(J){if(!J.userEmail||!pQ(J.userEmail))throw new F4("DTW TUI mode is only available for Amp employees",1);P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Cm({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:x$,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new pX(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function Sn5(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Wm()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Wm()).trimEnd(),stdinInput:null}}function vn5(J,Z,Q){if(J.remote&&!Z)throw new F4("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new F4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new F4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new F4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new F4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new F4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new F4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new F4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7449
7452
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function o$0(J,Z,Q){let Y=process.hrtime.bigint(),X=(n,V0)=>{let U0=Number(process.hrtime.bigint()-V0)/1e6,B0=h94();P.info("Startup phase",{phase:n,phaseMs:Math.round(U0),sinceMainMs:B0===null?void 0:Math.round(B0)})},{userInput:U,stdinInput:V}=await Sn5(Z),K=!!Z.streamJson||!!Z.streamJsonThinking;vn5({...Z,streamJson:K},J.executeMode,U),g7(Q,Z);let D=process.hrtime.bigint(),z=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&z;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:z,executeMode:J.executeMode,headless:Boolean(Z.headless)});let F=await c9(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",D),D=process.hrtime.bigint();let G=await od0(F);X("runMainThread:createWorkerDeps",D);let{serverStatus:W}=F;if(!q&&GG(W)){let n=lh(Error(W.error.message));if(n.message===V8.networkOffline||n.message===V8.networkTimeout)throw nd0(J.ampURL);throw new F4(V8.invalidAPIKey,1)}let H=T5(W)?W:null,B=H?.user.email,w=yI4(B),N=!J.executeMode&&H!==null&&ld0(Z.dtw,H);if(!q)await cd0(Q,Z,W);let E=id0(W),O=E?.features??[],L=E?.team??null,I=p30(Z,E);if(I instanceof Error)q3(I.message);if((J.executeMode||K)&&P8(Z.mode)&&!w)throw new F4(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(J.executeMode&&Z.remote)await gY4(U,V,F.configService),await F.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!pQ(B))throw new F4("Headless DTW mode is only available for Amp employees",1);let n=await F.secretStorage.get("apiKey",J.ampURL);if(!n)throw new F4("API key required for headless mode. Please run `amp login` first.",1);let V0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(V0&&!T8(V0))throw new F4(`Invalid thread ID: ${V0}`,1);let U0=V0??await cn5({dependencies:F,visibility:I??void 0}),B0=await BQ4(U0);if(B0.status==="already-running")await F.asyncDispose(),await Xq(),process.exit(0);try{await DQ4({ampURL:J.ampURL,apiKey:n,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:U0,configService:F.configService,mcpService:F.mcpService,toolService:F.toolService,skillService:F.skillService,fileSystem:F.fileSystem})}finally{await B0.release(),await F.asyncDispose()}await Xq(),process.exit(0)}let M={threadService:F.threadService,workerDeps:G,createThread:async()=>{let n=q?await F.serverStatusPromise:W,V0=await F30(J.settings,process.cwd(),id0(n),I);if(V0 instanceof Error)q3(V0.message);return db0(G,{threadMeta:V0?OU(V0):void 0,agentMode:Z.mode,onFirstAssistantMessage:TI4})},validateThreadOwnership:async(n,V0)=>{if(V0?.nonBlockingOwnershipCheck){_I4(n,F.configService).catch((U0)=>{if(U0 instanceof F4){if(V0.onOwnershipError){V0.onOwnershipError(U0,n);return}sP(U0,n);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})});return}try{await _I4(n,F.configService)}catch(U0){if(U0 instanceof F4)throw U0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:TI4},A=async(n,V0)=>{try{if(n==="dtw")return _n5({userEmail:V0?.dtwUserEmail??B,ampURL:J.ampURL,configService:F.configService,threadService:F.threadService,mcpService:F.mcpService,toolService:F.toolService,skillService:F.skillService,fileSystem:F.fileSystem,threadId:Z.threadId});return Sq4(M,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(U0){if(U0 instanceof F4)throw U0;throw await sP(U0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")q7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7450
|
-
`),await Xq(),process.exit(1);let R=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let n=await F.configService.getLatest(),V0=rv(n),U0=await T6.getUserFreeTierStatus({},{config:F.configService,signal:AbortSignal.timeout(V0)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(n){P.error("Failed to fetch free tier status:",n);return}})(),S=!J.executeMode?new fu0:null,y,h=null;if(S)y=S,h=(async()=>{let n=q?await F.serverStatusPromise:F.serverStatus;await cd0(Q,Z,n);let V0=process.hrtime.bigint(),U0=ld0(Z.dtw,n),B0=T5(n)?n.user.email:void 0,X0=await A(U0?"dtw":"worker",{dtwUserEmail:B0});if(X("runMainThread:createThreadPool",V0),S.attach(X0),U){let W0=await I1(X0.threadHandles$);if(!W0)throw new F4("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(n)=>{let V0=n instanceof Error?n:Error(String(n));S.setInitError(V0),await sP(n,Z.threadId)});else D=process.hrtime.bigint(),y=await A(N?"dtw":"worker"),X("runMainThread:createThreadPool",D);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;D=process.hrtime.bigint();let k=await F.configService.getLatest();if(X("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Rn5({configService:F.configService,threadService:F.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(s1((n)=>{if(!n)return v0.of({});return s6(n.thread$,n.threadViewState$).pipe(H1(([V0,U0])=>({[V0.id]:U0})))}))}),X("runMainThread:createCliNotificationService",D),J.executeMode){if(_Y4(F.mcpService,J.settings),!(y instanceof kC))throw new F4("Execute mode is not supported with the DTW thread pool",1);let n=y.getWorkerForExecuteMode();if(await xZ4({worker:n,threadID:n.threadID,userInput:U,stdinInput:V,dependencies:F,streamJson:K,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label}),Z.archive)await T6.archiveThread({thread:n.threadID,archived:!0},{config:F.configService});await F.asyncDispose(),process.exit(0)}let x=!1,g=!1,a=!1;if(Z.jetbrains||Z.ide){await sM1();let n=nw({jetbrainsOnly:Z.jetbrains});if(n.length===0){if(Z.jetbrains)g=!await F.configService.get("jetbrains.skipInstall")}else if(n.length===1){let V0=n[0];if(V0)S8.selectConfig(V0)}else a=!0}D=process.hrtime.bigint();let m=Qu0("0.0.
|
|
7451
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Ky1({get:async(K)=>{if(K!==ly)return;try{let D=await vI4(dd0,"utf-8");return JSON.parse(D).installationID}catch{return}},set:async(K,D)=>{if(K!==ly)return;await Wn5(lp.dirname(dd0),{recursive:!0}),await Hn5(dd0,JSON.stringify({installationID:D},null,2),{mode:384})}},{clientType:"cli",platform:dQ()});NM1(Y);let X=await TQ4({...J,workspaceTrust:{current:!0,changes:kv},getHook:process.env.AMP_URL?(K,D)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return D()}:void 0});if(J.mcpConfig){let K=await CY4(J.mcpConfig);X=TY4(X,K)}let U=lp.dirname(X.getSettingsFilePath());a84($C,U);let V=await X.get("url","global");if(!V)V=o9;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!dF(V))P.info("Targeting custom Amp server",{ampURL:V});return X=VM1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:iY4(await hy0(J,X))}}function kn5(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let U=Y.slice(2).replace(/-([a-z])/g,(K,D)=>D.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[U]=V,Q++}}return Z}async function yn5(){b94();let J=kn5(process.argv),Z=process.argv.includes("--headless")||process.argv.some((U)=>U.startsWith("--headless="));sJ4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?wn5:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(En5(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7453
|
+
`),await Xq(),process.exit(1);let R=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let n=await F.configService.getLatest(),V0=rv(n),U0=await T6.getUserFreeTierStatus({},{config:F.configService,signal:AbortSignal.timeout(V0)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(n){P.error("Failed to fetch free tier status:",n);return}})(),S=!J.executeMode?new fu0:null,y,h=null;if(S)y=S,h=(async()=>{let n=q?await F.serverStatusPromise:F.serverStatus;await cd0(Q,Z,n);let V0=process.hrtime.bigint(),U0=ld0(Z.dtw,n),B0=T5(n)?n.user.email:void 0,X0=await A(U0?"dtw":"worker",{dtwUserEmail:B0});if(X("runMainThread:createThreadPool",V0),S.attach(X0),U){let W0=await I1(X0.threadHandles$);if(!W0)throw new F4("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(n)=>{let V0=n instanceof Error?n:Error(String(n));S.setInitError(V0),await sP(n,Z.threadId)});else D=process.hrtime.bigint(),y=await A(N?"dtw":"worker"),X("runMainThread:createThreadPool",D);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;D=process.hrtime.bigint();let k=await F.configService.getLatest();if(X("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Rn5({configService:F.configService,threadService:F.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(s1((n)=>{if(!n)return v0.of({});return s6(n.thread$,n.threadViewState$).pipe(H1(([V0,U0])=>({[V0.id]:U0})))}))}),X("runMainThread:createCliNotificationService",D),J.executeMode){if(_Y4(F.mcpService,J.settings),!(y instanceof kC))throw new F4("Execute mode is not supported with the DTW thread pool",1);let n=y.getWorkerForExecuteMode();if(await xZ4({worker:n,threadID:n.threadID,userInput:U,stdinInput:V,dependencies:F,streamJson:K,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label}),Z.archive)await T6.archiveThread({thread:n.threadID,archived:!0},{config:F.configService});await F.asyncDispose(),process.exit(0)}let x=!1,g=!1,a=!1;if(Z.jetbrains||Z.ide){await sM1();let n=nw({jetbrainsOnly:Z.jetbrains});if(n.length===0){if(Z.jetbrains)g=!await F.configService.get("jetbrains.skipInstall")}else if(n.length===1){let V0=n[0];if(V0)S8.selectConfig(V0)}else a=!0}D=process.hrtime.bigint();let m=Qu0("0.0.1772685027-gdb1277",F.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let i=new RI0(F.threadStorage);X("runMainThread:createThreadFuzzyIndexer",D),D=process.hrtime.bigint();let d=new Uu0(F.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",D),U&&J.executeMode){let n=await I1(y.threadHandles$);if(!n)throw new F4("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:U}]})}D=process.hrtime.bigint();let e=await fK();X("runMainThread:loadSessionState",D),P.info("Loaded session state:",e);let N0={...e,launchCount:e.launchCount+1};bK(N0);try{if(D=process.hrtime.bigint(),await bF4({codebaseContextService:F.codebaseContextService,stdout:process.stdout,history:new Ay0,fuzzyServer:F.fuzzyServer,settingsStorage:F.settingsStorage,threadService:F.threadService,threadHistoryService:F.threadHistoryService,threadFuzzyIndexer:i,skillService:F.skillService,configService:F.configService,secretStorage:F.secretStorage,internalAPIClient:T6,initialServerStatus:F.serverStatus,hasAPIKeyAtStartup:F.hasAPIKeyAtStartup,ampURL:J.ampURL,threadPool:y,createSystemPromptDeps:async()=>xI4(F),ideClient:S8,mcpService:F.mcpService,toolboxService:F.toolboxService,mcpTrustHandler:d,showJetBrainsInstaller:g,showIdePicker:x,showIdePickerHint:a,openThreadSwitcher:Z.openThreadSwitcher,updateService:m,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:N0,freeTierStatusPromise:R,workspace:L??null,features:O,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-05T04:36:12.856Z",pluginPlatform:F.pluginPlatform,pluginService:F.pluginService},(n)=>new Bh0({...n,threadPool:n.threadPool},(V0)=>new Hp0({...V0,threadState:V0.threadState}))),X("runMainThread:mountApp-returned",D),h)await h}finally{}await F.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function A3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)q7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7454
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Ky1({get:async(K)=>{if(K!==ly)return;try{let D=await vI4(dd0,"utf-8");return JSON.parse(D).installationID}catch{return}},set:async(K,D)=>{if(K!==ly)return;await Wn5(lp.dirname(dd0),{recursive:!0}),await Hn5(dd0,JSON.stringify({installationID:D},null,2),{mode:384})}},{clientType:"cli",platform:dQ()});NM1(Y);let X=await TQ4({...J,workspaceTrust:{current:!0,changes:kv},getHook:process.env.AMP_URL?(K,D)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return D()}:void 0});if(J.mcpConfig){let K=await CY4(J.mcpConfig);X=TY4(X,K)}let U=lp.dirname(X.getSettingsFilePath());a84($C,U);let V=await X.get("url","global");if(!V)V=o9;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!dF(V))P.info("Targeting custom Amp server",{ampURL:V});return X=VM1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:iY4(await hy0(J,X))}}function kn5(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let U=Y.slice(2).replace(/-([a-z])/g,(K,D)=>D.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[U]=V,Q++}}return Z}async function yn5(){b94();let J=kn5(process.argv),Z=process.argv.includes("--headless")||process.argv.some((U)=>U.startsWith("--headless="));sJ4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?wn5:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(En5(P),P.info("Starting Amp CLI.",{version:"0.0.1772685027-gdb1277",buildTimestamp:"2026-03-05T04:36:12.856Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new F4(V8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Tn5().parseAsync(process.argv)}i84().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await yn5().catch(sP)});async function un5(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),r6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7452
7455
|
`);else if(!dF(J.ampURL))r6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7453
7456
|
`);let Y=process.env.AMP_API_KEY;if(Y)r6.write(`API key found in environment variable, storing...
|
|
7454
7457
|
`),await Z.set("apiKey",Y,J.ampURL),r6.write(`API key successfully stored.
|