@sourcegraph/amp 0.0.1772495978-ge2fd2b → 0.0.1772496276-ge2fd2b
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 +10 -10
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -5901,11 +5901,11 @@ ${W}`))}},error:(F)=>{if(!G)G=!0,K(Error(`Failed to spawn brew: ${F.message}`))}
|
|
|
5901
5901
|
${W}`;if(Y==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
|
|
5902
5902
|
|
|
5903
5903
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
5904
|
-
npm install -g @sourcegraph/amp`;K(Error(H))}},error:(F)=>{if(!q)q=!0,K(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!q)q=!0,V()}})})}h0();h0();nA();async function g30(J,Z){let Y=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,U=new AbortController,V=setTimeout(()=>U.abort(),5000);try{let K=await fetch(Y,{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=FX4(J,z),G=q<0,F,W;if(D.time){let H=D.time[J],B=D.time[z],w=Date.now();if(H)F=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:G,currentVersionAge:F,latestVersionAge:W}),{hasUpdate:G,latestVersion:z,currentVersion:J,currentVersionAge:F,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 tw5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function p30(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let X=await fetch(`${tw5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!X.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let Y=(await X.text()).trim();if(!Y||!/^\d+\.\d+\.\d+/.test(Y))return{hasUpdate:!1,currentVersion:J,source:"bin"};let U=FX4(J,Y),V=U<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:Y,compareResult:U,hasUpdate:V}),{hasUpdate:V,latestVersion:Y,currentVersion:J,source:"bin"}}catch(X){return P.debug("Error checking bin version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var ew5=604800000;function GX4(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>ew5)return{ageMs:Q};return null}function FX4(J,Z){let Q=(V)=>{let[K,D]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:D}},X=Q(J),Y=Q(Z),U=Math.max(X.parts.length,Y.parts.length);for(let V=0;V<U;V++){let K=X.parts[V]||0,D=Y.parts[V]||0;if(K<D)return-1;if(K>D)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.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,X=Z[2],Y=Q!==0?DF(Q):void 0;return{sha:X,age:Y}}catch{return null}}W1();function Qu0(J,Z,Q={}){let X=new Y4,Y=X.pipe(L6({shouldCountRefs:!1}));return setImmediate(async()=>{let U=new FV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await cV(V);let K=Y.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 cV(500),X.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 m30(),G=q==="binary"||q==="brew";U.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:G});let F=G?await p30(J):await g30(J,WE());if(!(F.latestVersion&&F.hasUpdate)){U.debug("no update available");return}let W=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let H=F.currentVersionAge-F.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return U.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.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())X.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ry0()){if(U.debug("non-standard binary path, showing warning"),!W())X.next("update-available-unrecognized-path");return}if(z==="warn"){if(!W())X.next("update-available");return}if(!q){if(U.debug("auto-update not supported, falling back to warn mode"),!W())X.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())X.next("update-available");return}try{await Vm(F.latestVersion,q);let H=await pW(F.latestVersion),B={from:F.currentVersion,to:F.latestVersion,...H};if(H.status==="same")U.info("success",B),X.next("updated");else U.warn("success with warning",B),X.next("updated-with-warning")}catch(H){X.next("update-error")}}catch(D){U.debug("check failed",{error:D})}finally{await cV(5000),X.next("hidden"),K.unsubscribe(),X.complete()}}),{state:Y}}nA();import{stderr as xK}from"node:process";function WX4(J){let Z=new TW().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(X)=>{await iy0(X.force||!1,X.verbose||!1,"0.0.
|
|
5904
|
+
npm install -g @sourcegraph/amp`;K(Error(H))}},error:(F)=>{if(!q)q=!0,K(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!q)q=!0,V()}})})}h0();h0();nA();async function g30(J,Z){let Y=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,U=new AbortController,V=setTimeout(()=>U.abort(),5000);try{let K=await fetch(Y,{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=FX4(J,z),G=q<0,F,W;if(D.time){let H=D.time[J],B=D.time[z],w=Date.now();if(H)F=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:G,currentVersionAge:F,latestVersionAge:W}),{hasUpdate:G,latestVersion:z,currentVersion:J,currentVersionAge:F,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 tw5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function p30(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let X=await fetch(`${tw5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!X.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let Y=(await X.text()).trim();if(!Y||!/^\d+\.\d+\.\d+/.test(Y))return{hasUpdate:!1,currentVersion:J,source:"bin"};let U=FX4(J,Y),V=U<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:Y,compareResult:U,hasUpdate:V}),{hasUpdate:V,latestVersion:Y,currentVersion:J,source:"bin"}}catch(X){return P.debug("Error checking bin version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var ew5=604800000;function GX4(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>ew5)return{ageMs:Q};return null}function FX4(J,Z){let Q=(V)=>{let[K,D]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:D}},X=Q(J),Y=Q(Z),U=Math.max(X.parts.length,Y.parts.length);for(let V=0;V<U;V++){let K=X.parts[V]||0,D=Y.parts[V]||0;if(K<D)return-1;if(K>D)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.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,X=Z[2],Y=Q!==0?DF(Q):void 0;return{sha:X,age:Y}}catch{return null}}W1();function Qu0(J,Z,Q={}){let X=new Y4,Y=X.pipe(L6({shouldCountRefs:!1}));return setImmediate(async()=>{let U=new FV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await cV(V);let K=Y.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 cV(500),X.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 m30(),G=q==="binary"||q==="brew";U.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:G});let F=G?await p30(J):await g30(J,WE());if(!(F.latestVersion&&F.hasUpdate)){U.debug("no update available");return}let W=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let H=F.currentVersionAge-F.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return U.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.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())X.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ry0()){if(U.debug("non-standard binary path, showing warning"),!W())X.next("update-available-unrecognized-path");return}if(z==="warn"){if(!W())X.next("update-available");return}if(!q){if(U.debug("auto-update not supported, falling back to warn mode"),!W())X.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())X.next("update-available");return}try{await Vm(F.latestVersion,q);let H=await pW(F.latestVersion),B={from:F.currentVersion,to:F.latestVersion,...H};if(H.status==="same")U.info("success",B),X.next("updated");else U.warn("success with warning",B),X.next("updated-with-warning")}catch(H){X.next("update-error")}}catch(D){U.debug("check failed",{error:D})}finally{await cV(5000),X.next("hidden"),K.unsubscribe(),X.complete()}}),{state:Y}}nA();import{stderr as xK}from"node:process";function WX4(J){let Z=new TW().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(X)=>{await iy0(X.force||!1,X.verbose||!1,"0.0.1772496276-ge2fd2b"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new TW("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(X)=>{await $N5(X.targetVersion)});J.addCommand(Q)}async function $N5(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.
|
|
5905
5905
|
|
|
5906
5906
|
`));try{if(!J){xK.write(Z1.blue(`Checking for updates...
|
|
5907
|
-
`));let{hasUpdate:X,latestVersion:Y}=ny0()?await p30("0.0.
|
|
5908
|
-
`));let K=await pW("0.0.
|
|
5907
|
+
`));let{hasUpdate:X,latestVersion:Y}=ny0()?await p30("0.0.1772496276-ge2fd2b"):await g30("0.0.1772496276-ge2fd2b",WE());if(!X){let U=Zu0("0.0.1772496276-ge2fd2b"),V=U?.age?`released ${U.age} ago`:`built ${DF(new Date("2026-03-03T00:10:30.790Z"))} ago`;xK.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1772496276-ge2fd2b"} (${V})
|
|
5908
|
+
`));let K=await pW("0.0.1772496276-ge2fd2b");if(K.warning)xK.write(`
|
|
5909
5909
|
`+Z1.yellow(K.warning)+`
|
|
5910
5910
|
`);process.exit(0)}if(!Y)xK.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=Y}xK.write(Z1.blue(`Updating to version ${J}...
|
|
5911
5911
|
`)),await Vm(J,void 0,(X)=>{xK.write(Z1.dim(`Running: ${X}
|
|
@@ -6229,7 +6229,7 @@ To fix: Add "amp.mcpTrustedWorkspaces": ["${Z.getWorkspaceRootPath()}"] to ${X}
|
|
|
6229
6229
|
`)}};function uN5(J){let Z={};for(let Q=0;Q<J.length;Q++){let X=J[Q];if(X&&X.startsWith("--")){let Y=X.slice(2),U=J[Q+1];if(U&&!U.startsWith("--"))Z[Y]=U,Q++}}return Z}function xN5(J){if(J.action==="ask")return 1;if(J.action==="reject")return 2;return 0}async function yX4(J){let Z=J.json?kN5:yN5;try{let Q=uN5(J.remainingArgs),X=await J.settings.get("permissions",J.scope)??[],Y=SG(X);if(!Y.success){let V={success:!1,error:"Invalid permissions configuration",details:Y.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 SM(J.toolName,Q,Y.data,J.context,ov,J.threadId,"user");if(!U.matchedEntry)U=await SM(J.toolName,Q,_M,J.context,ov,J.threadId,"built-in");Z.outputResult(J,Q,U),J.exit(xN5(U))}catch(Q){let X={success:!1,error:Q instanceof Error?Q.message:"Unknown error"};Z.outputError(J,{},X),J.exit(1)}}function uX4(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.
|
|
6230
6230
|
|
|
6231
6231
|
See ${Z1.underline("https://ampcode.com/manual#permissions")} for more details`).enablePositionalOptions();fN5(Q,Z),bN5(Q,Z),hN5(Q,Z),mN5(Q,Z)}function fN5(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,X)=>{let Y=await Z(X),U=X.optsWithGlobals();await kX4({builtinOnly:U.builtin??!1,settings:Y.settings,exit:process.exit.bind(process),json:U.json,stdout:process.stdout,scope:U.workspace?"workspace":"global"})})}function bN5(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,X,Y)=>{let U=await Z(Y),V=()=>!1;await yX4({toolName:Q,context:X.context,threadId:X.threadId,json:X.json,settings:U.settings,remainingArgs:Y.args,stdout:X.quiet?{write:V}:process.stdout,stderr:process.stderr,exit:process.exit.bind(process),scope:X.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(`
|
|
6232
|
-
`))}function hN5(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,X)=>{let Y=await Z(X);await c30({settings:Y.settings,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exit:process.exit.bind(process),resolveEditor:tP,scope:Q.workspace?"workspace":"global"})})}function mN5(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,X,Y,U)=>{let V=await Z(U);await TX4({args:U.parent?.args.slice(1)??[],settings:V.settings,stderr:process.stderr,exit:process.exit.bind(process),scope:Y.workspace?"workspace":"global"})})}h0();import{exec as gN5}from"node:child_process";import{platform as pN5}from"node:os";import{stderr as eP}from"node:process";u9();async function xX4(J,Z,Q){let U=(await(await yJ({configService:Z},Q)).messages.create({model:aV,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.
|
|
6232
|
+
`))}function hN5(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,X)=>{let Y=await Z(X);await c30({settings:Y.settings,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exit:process.exit.bind(process),resolveEditor:tP,scope:Q.workspace?"workspace":"global"})})}function mN5(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,X,Y,U)=>{let V=await Z(U);await TX4({args:U.parent?.args.slice(1)??[],settings:V.settings,stderr:process.stderr,exit:process.exit.bind(process),scope:Y.workspace?"workspace":"global"})})}h0();import{exec as gN5}from"node:child_process";import{platform as pN5}from"node:os";import{stderr as eP}from"node:process";u9();async function xX4(J,Z,Q){let U=(await(await yJ({configService:Z},Q)).messages.create({model:aV,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.1772496276-ge2fd2b";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=pN5(),Q=Z==="darwin"?"open":Z==="win32"?"start":"xdg-open";if(await new Promise((X,Y)=>{gN5(`${Q} ${JSON.stringify(J)}`,(U)=>{if(U)Y(U);else X()})}),this.showOpenedURLToast)this.showOpenedURLToast(J);else eP.write(`
|
|
6233
6233
|
Opened URL: ${J}
|
|
6234
6234
|
|
|
6235
6235
|
`)}async input(J){if(this.showInputDialog)return this.showInputDialog(J);eP.write(`
|
|
@@ -7143,7 +7143,7 @@ Ctrl-X, Y, Z to unlock`;if(F){let f=z.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7143
7143
|
`),new C("Ctrl+O",B),new C(" for ",N),new C("help",w),new C(`
|
|
7144
7144
|
|
|
7145
7145
|
|
|
7146
|
-
`,N)])}),A];if(!D&&!F&&z.url){let h=z.url.replace(/^https?:\/\//,"");_.push(new Z5({uri:z.url,text:h,style:new b({color:Q.secondary,underline:!0})}))}if(M&&!F)_.push(M);let S=new j0({width:50,child:new u0({crossAxisAlignment:"start",mainAxisSize:"min",children:_})}),y=W?new j0({width:A20,height:j20}):new Qh0({width:A20,height:j20,agentMode:this.widget.agentMode,glow:this._glow,backgroundColor:Q.background,t:q,fps:0,shockwaves:this._shockwaves,onShockwave:this.handleShockwave,onClick:this.handleOrbClick,...V==="disabled"&&{seed:42}});return n1.child(new D1({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[y,new j0({width:2}),S]}))}}class Jg0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new lB4}}class lB4 extends g0{build(J){let Q=x0.of(J).colors,{todos:X,title:Y="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new j0({width:0,height:0});let U=X.map((V)=>this.buildTodoItem(V,Q));return new c0({child:new a0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Q0({text:new C(Y,new b({bold:!0,color:Q.foreground}))}),...U]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),X=J.status==="completed",Y=new b({bold:J.status==="in-progress",color:Z.foreground,dim:X}),U=new b({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:X});return new D1({crossAxisAlignment:"start",children:[new Q0({text:new C(Q,Y)}),new j0({width:1}),new S1({child:new Q0({text:new C(J.content,U)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Zg0 extends p0{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Z,onDismiss:Q,onButtonClick:X,onImpression:Y,onAdInfoClick:U}){super({key:J});this.ad=Z,this.onDismiss=Q,this.onButtonClick=X,this.onImpression=Y,this.onAdInfoClick=U}createState(){return new iB4}}class iB4 extends g0{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Z=x0.of(J),Q=Z.colors.primary,X=Z.colors.foreground,Y=Z.colors.background,U=this.widget.ad;return new c0({decoration:new _4(Y,new f1(new y1(Q,1,"rounded"),new y1(Q,1,"rounded"),void 0,new y1(Q,1,"rounded"))),child:new a0({padding:C0.horizontal(1),child:new u0({children:[new D1({crossAxisAlignment:"start",children:[new S1({child:new Q0({text:new C(U.content,new b({color:X}))})}),new j0({width:4}),new i1({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new Q0({text:new C("Ad",new b({color:X,dim:!0}))})})]}),new D1({crossAxisAlignment:"start",children:[new vg({text:U.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:C0.horizontal(1),color:Q,reverse:!0}),new j0({width:2}),new Q0({text:new C(U.destinationUrlHostname,new b({color:X,dim:!0}))})]})]})})})}}class Qg0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new nB4(this.props.autofocus??!0)}}class nB4 extends g0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=R1.of(J).colorScheme,X=(z)=>{if(z.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(z.ctrlKey&&z.key==="c"||z.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=o1.sizeOf(J),U=Math.min(60,Y.width-4),V=Y.height-4,K=[];if(this.widget.props.title)K.push(new Q0({text:new C(this.widget.props.title,new b({bold:!0,color:Q.primary}))}),new j0({height:1}));if(this.widget.props.message)K.push(new Q0({text:new C(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new j0({height:1}));let D=[];if(this.widget.props.showCopyOption)D.push(new Q0({text:new C("Enter to copy",new b({dim:!0}))}));return D.push(new Q0({text:new C("Escape to close",new b({dim:!0}))})),K.push(new D1({children:D.flatMap((z,q)=>q<D.length-1?[z,new j0({width:1}),new Q0({text:new C("•",new b({dim:!0}))}),new j0({width:1})]:[z]),mainAxisSize:"min"})),new n1({child:new c0({constraints:new M1(U,U,0,V),decoration:new _4(Q.background,new f1(new y1(Q.primary,1,"rounded"),new y1(Q.primary,1,"rounded"),new y1(Q.primary,1,"rounded"),new y1(Q.primary,1,"rounded"))),padding:new C0(2,2,2,2),child:new S4({autofocus:this.autofocus,onKey:X,child:new u0({children:K,mainAxisSize:"min"})})})})}}class Xg0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new aB4(this.props.autofocus??!0)}}class aB4 extends g0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Z=R1.of(J).colorScheme,Q=(K)=>{if(K.key==="Enter"||K.key==="Escape"||K.ctrlKey&&K.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},X=o1.sizeOf(J),Y=Math.min(60,X.width-4),U=X.height-4,V=[];if(V.push(new Q0({text:new C("Ads make Amp Free possible",new b({bold:!0}))})),this.widget.props.provider)V.push(new j0({height:1}),new Q0({text:new C(`Ad source: ${this.widget.props.provider}`,new b({dim:!0}))}));return V.push(new j0({height:1}),new Q0({text:new C("Escape to close",new b({dim:!0}))})),new n1({child:new c0({constraints:new M1(Y,Y,0,U),decoration:new _4(Z.background,new f1(new y1(Z.primary,1,"rounded"),new y1(Z.primary,1,"rounded"),new y1(Z.primary,1,"rounded"),new y1(Z.primary,1,"rounded"))),padding:new C0(2,2,2,2),child:new S4({autofocus:this.autofocus,onKey:Q,child:new u0({children:V,mainAxisSize:"min"})})})})}}class Yg0 extends p0{manualURL;isAuthenticating;errorMessage;constructor({manualURL:J,isAuthenticating:Z,errorMessage:Q}){super();this.manualURL=J,this.isAuthenticating=Z,this.errorMessage=Q}createState(){return new oB4}}class oB4 extends g0{build(J){let Q=R1.of(J).colorScheme,X=x0.of(J),Y=o1.of(J),U=Y.size.width,V=Y.size.height,K=U-4,D=Math.max(56,Math.min(86,K)),z=new b({color:Q.primary,bold:!0}),q=new b({color:Q.foreground,dim:!0}),G=new b({color:X.app.link,bold:!0}),F=new b({color:X.app.keybind}),W=new b({color:X.app.toolError}),H=[new Q0({text:new C("Authentication Required",z)}),new j0({height:1}),new Q0({text:new C("Sign in to Amp to continue. Your pending prompt will send automatically after login.",q)}),new j0({height:1}),new Q0({text:new C("Manual login link (select to copy):",q)}),new a0({padding:C0.only({left:2,top:1}),child:new N2({child:new Q0({text:new C(this.widget.manualURL,G),selectable:!0})})})];if(this.widget.errorMessage)H.push(new j0({height:1})),H.push(new Q0({text:new C(this.widget.errorMessage,W)}));if(H.push(new j0({height:1})),H.push(new Q0({text:new C("",void 0,[new C("Enter/O",F),new C(" open browser · ",q),new C("C",F),new C(" copy link · ",q),new C("I",F),new C(" I completed login · ",q),new C("P",F),new C(" paste code · ",q),new C("Esc",F),new C(" cancel",q)])})),this.widget.isAuthenticating)H.push(new j0({height:1})),H.push(new Q0({text:new C("Waiting for login callback...",q)}));let B=new c0({constraints:new M1(D-4,D-4,0,V-6),decoration:{color:Q.background,border:f1.all(new y1(Q.primary,1,"rounded"))},padding:C0.all(2),child:new u0({crossAxisAlignment:"start",mainAxisSize:"min",children:H})});return new n1({child:B})}}h0();n9();import{execSync as Mm5}from"node:child_process";iM();GJ();O3();t7();Pw();IY();I$();TJ();NY();cO();f4();Su();Pv();W1();var uw4=L4(Gz(),1);import{writeFile as _w4}from"fs/promises";import Sw4 from"path";h0();I$();class Ug0{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.1772495978-ge2fd2b"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await ys(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 uH extends p0{props;constructor(J){super();this.props=J}createState(){return new rB4}}class rB4 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 sB4 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=x0.of(J),{colors:Q,app:X}=Z,Y=this.widget.props.isRequiredArg??!0,U=this.controller.text.trim().length>0,V=!Y||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(Y&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new D1({children:[new c0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:D})]}),q=new c0({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:X.command,bold:!0}))])})}),G=[];if(V)G.push(new C("Enter",new b({color:X.keybind}))),G.push(new C(" to submit, ",new b({color:Q.foreground,dim:!0})));G.push(new C("Esc",new b({color:X.keybind}))),G.push(new C(" to cancel",new b({color:Q.foreground,dim:!0})));let F=new c0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,G)})});return new c0({decoration:{border:K,color:Q.background},padding:C0.all(1),child:new u0({children:[q,new j0({height:1}),z,new Z3,F]})})}}class Wp extends p0{props;constructor(J){super();this.props=J}createState(){return new sB4}}import{isDeepStrictEqual as Vg0}from"node:util";var Qm5=/[\\/_ +.#"@[({&]/,Xm5=/[\\/_ +.#"@[({&]/g,Ym5=/[\s-]/,tB4=/[\s-]/g;function C20(J,Z,Q,X,Y,U,V){if(U===Z.length){if(Y===J.length)return 1;return 0.99}let K=`${Y},${U}`;if(V[K]!==void 0)return V[K];let D=X.charAt(U),z=Q.indexOf(D,Y),q=0,G,F,W,H;while(z>=0){if(G=C20(J,Z,Q,X,z+1,U+1,V),G>q){if(z===Y)G*=1;else if(Ym5.test(J.charAt(z-1))){if(G*=0.9,H=J.slice(Y,z-1).match(tB4),H&&Y>0)G*=0.999**H.length}else if(Qm5.test(J.charAt(z-1))){if(G*=0.8,W=J.slice(Y,z-1).match(Xm5),W&&Y>0)G*=0.999**W.length}else if(G*=0.3,Y>0)G*=0.999**(z-Y);if(J.charAt(z)!==Z.charAt(U))G*=0.9999}if(G<0.1&&(Q.charAt(z-1)===X.charAt(U+1)||X.charAt(U+1)===X.charAt(U)&&Q.charAt(z-1)!==X.charAt(U))){if(F=C20(J,Z,Q,X,z+1,U+2,V),F*0.1>G)G=F*0.1}if(G>q)q=G;z=Q.indexOf(D,z+1)}return V[K]=q,q}function P20(J){return J.toLowerCase().replace(tB4," ")}function eB4(J,Z){let Q=C20(J,Z,P20(J),P20(Z),0,0,{}),X=Z.trim().split(/\s+/);if(X.length>1){let Y=0,U=0;for(let K of X){let D=C20(J,K,P20(J),P20(K),0,0,{});if(D===0)return Q;Y+=D,U+=K.length}let V=Y/X.length*0.95;return Math.max(Q,V)}return Q}class zT{}class qT{}class T20{}class _20{}class $w4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Jw4}}class Jw4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}function Um5(J,Z){if(J==="")return{matches:!0,score:1};let Q=eB4(Z,J);return{matches:Q>0.15,score:Q}}class p9 extends p0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Zw4}}class Zw4 extends g0{textController;focusNode;scrollController=new r6;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)=>Vg0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Vg0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Vg0(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 zT){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 qT){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 T20){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 _20)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,X=Z.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...Um5(Q,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,U)=>this.widget.props.sortItems(Y,U,J):(Y,U)=>U.score-Y.score).map((Y)=>Y.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?X.slice(0,this.widget.props.maxRenderItems):X}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,X=Z.size.height;nC(J,{top:Q,bottom:X},{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 X=Q[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!Y){if(X)this.hasUserInteracted=!0,this.widget.props.onAccept(X,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=x0.of(J),{colors:Q}=Z,X=this.getFilteredItems(),Y=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 w2({shortcuts:new Map([[new e1("ArrowDown"),new zT],[new e1("ArrowUp"),new qT],[new e1("Tab"),new zT],[new e1("Tab",{shift:!0}),new qT],[new e1("n",{ctrl:!0}),new zT],[new e1("p",{ctrl:!0}),new qT],[new e1("Enter"),new T20],[new e1("Escape"),new _20]]),focusNode:this.focusNode,child:K}),z=new A9({actions:new Map([[zT,new o4(this.invoke)],[qT,new o4(this.invoke)],[T20,new o4(this.invoke)],[_20,new o4(this.invoke)]]),child:D}),q=new D1({children:[new c0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:z})]});this.itemContexts=[];let G;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";G=new j0({height:10,child:new n1({child:new Q0({text:new C(w,new b({color:Q.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)G=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=X.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,I;if(this.widget.props.renderItem)I=this.widget.props.renderItem(N,E,L,J);else{let M=E?Z.app.selectionBackground:void 0,A=E?Z.app.selectionForeground:Q.foreground;I=new c0({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 $w4(new i1({onClick:(M)=>this.handleItemClick(O,M.clickCount),child:I}),(M)=>{this.itemContexts[O]=M})});G=new u0({children:w,crossAxisAlignment:"start"})}let F=new i1({onScroll:this.handleScroll,opaque:!1,child:new O6({controller:this.scrollController,autofocus:!1,child:G})}),W=[];if(this.widget.props.title){let w=new c0({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=X.length>0?X[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:F}),new c0({padding:C0.only({top:1}),child:new n1({child:N??new j0({height:1})})})]})}))}else W.push(new S1({child:F}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:Y,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function Qw4(J){let Q=new Date().getTime()-J.getTime(),X=Math.floor(Q/60000),Y=Math.floor(Q/3600000),U=Math.floor(Q/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(Y<24)return`${Y}h ago`;if(U<7)return`${U}d ago`;return J.toLocaleDateString()}class Kg0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((Y,U)=>U.pubDate.getTime()-Y.pubDate.getTime()),Q=Math.max(0,...Z.map((Y)=>Qw4(Y.pubDate).length));return new p9({items:Z,getLabel:(Y)=>Y.title,onAccept:(Y)=>this.props.onSelect?.(Y),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(Y,U,V,K)=>{let D=x0.of(K),{colors:z}=D,q=D.app,G=U?q.selectionBackground:void 0,F=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 c0({decoration:G?{color:G}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new S1({child:new Q0({text:new C(Y.title,new b({color:F})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),H(Qw4(Y.pubDate),Q)]})})}})}}f4();class Dg0 extends p0{createState(){return new Xw4}}class Xw4 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=x0.of(J).colors;return new Q0({text:new C("●",new b({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Vm5=/\/threads\/(T-[^/?#\s<>]+)/i;function Km5(J){let Z=J.trim(),X=Z.match(Vm5)?.[1];if(X&&C8(X))return X;let Y=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(C8(Y))return Y;return null}function Dm5(J){let Z=new Map,Q=new Map,X=new Map,Y=[];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){X.set(V.id,K.type);let D=K.threadID,z=Q.get(D)||[];z.push(V),Q.set(D,z)}else Y.push(V)}return v90.flatten(Y,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:X.get(V.item.id)}))}function zg0(J,Z,Q){return new Q0({text:new C(`${J}${Z}`,new b({color:Q})),maxLines:1})}function zm5(J,Z,Q,X){return[zg0("+",J,X.success),Z3.horizontal(1),zg0("~",Z,X.warning),Z3.horizontal(1),zg0("-",Q,X.destructive)]}function qm5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class S20 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Yw4}}class Yw4 extends g0{spinner=new L3;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,X=this.isSwitchingThread?"Switching thread...":"Loading threads...",Y=`${this.spinner.toBraille()} ${X}`,U=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)U=U.filter((O)=>O.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],K=new Set(V),D=Z.currentThreadID,z=[...U].sort((O,E)=>{if(D){if(O.id===D)return-1;if(E.id===D)return 1}let L=V.indexOf(O.id),I=V.indexOf(E.id);if(L!==-1&&I!==-1)return L-I;if(L!==-1)return-1;if(I!==-1)return 1;return 0}),q=Dm5(z),G=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),F=x0.of(J),W=new a0({padding:C0.symmetric(0,1),child:new n1({child:new Q0({text:new C("",new b({color:F.colors.foreground,dim:!0}),[new C("Ctrl+T",new b({color:F.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new b({color:F.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=Km5(O);return B};return new p9({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!qm5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:Y,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,I)=>{let M=x0.of(I),{app:A,colors:j}=M,_=E?A.selectionBackground:void 0,S=E?A.selectionForeground:j.foreground,y=j.mutedForeground,h=($0,B0)=>new j0({width:B0,child:D1.end([new Q0({text:new C($0,new b({color:y}))})])}),f=Z.threadViewStates[O.id],k=[],x=O.relationshipType==="handoff",g=new Hg({connectorColor:j.mutedForeground});if(O.depth>0){let $0=[],B0=O.ancestorsAreLast.slice(1);for(let U0 of B0)$0.push(new C(g.getAncestorPrefix(U0),new b({color:g.connectorColor,dim:g.connectorDim})));let i=O.isLast?g.elbow:g.tee,V0=g.getConnectorText(i);$0.push(new C(V0,new b({color:g.connectorColor,dim:g.connectorDim}))),k.push(new Q0({text:new C("",void 0,$0)}))}let a=[],m=D===O.id?new C("(current) ",new b({color:j.success})):K.has(O.id)?new C("(visited) ",new b({color:j.foreground,dim:!0})):null;if(m)a.push(new Q0({text:m}));if(lR(f))a.push(new Dg0),a.push(new j0({width:1}));let l=O.title;if(O.relationshipType==="fork"){let $0=l.match(/^Forked\((\d+)\): /);if($0)l=l.slice($0[0].length);else while(l.startsWith("Forked: "))l=l.slice(8);a.push(new Q0({text:new C("[fork] ",new b({color:j.primary}))}))}else if(x)a.push(new Q0({text:new C("[handoff] ",new b({color:j.accent}))}));if(a.push(new S1({child:new Q0({text:new C(l,new b({color:S})),overflow:"ellipsis",maxLines:1})})),a.push(new j0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let $0=E?{success:y,warning:y,destructive:y}:j;a.push(...zm5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,$0)),a.push(new j0({width:2}))}return a.push(h(O.description.timeAgo,G)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...a]})})}})}}class Vw4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Kw4}}class Kw4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}var Uw4=30,Gm5=30;class GT{}class FT{}class v20{}class k20{}class qg0 extends p0{props;constructor(J){super();this.props=J}createState(){return new Dw4}}class Dw4 extends g0{highlightedIndex=0;controller=new u7;focusNode;scrollController=new r6;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,X=Z.size.height;nC(J,{top:Q,bottom:X},{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 GT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof FT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof v20){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof k20)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=x0.of(J),{colors:X,app:Y}=Q,K=o1.of(J).size.width>=Gm5+Uw4,D=f1.all(new y1(X.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new c0({padding:C0.symmetric(1,0),child:new Q0({text:new C("Select a cluster",new b({color:Y.command,bold:!0}))})}),G=new i$({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:X.foreground,border:null},maxLines:1}),F=new w2({shortcuts:new Map([[new e1("ArrowDown"),new GT],[new e1("ArrowUp"),new FT],[new e1("Tab"),new GT],[new e1("Tab",{shift:!0}),new FT],[new e1("n",{ctrl:!0}),new GT],[new e1("p",{ctrl:!0}),new FT],[new e1("Enter"),new v20],[new e1("Escape"),new k20]]),focusNode:this.focusNode,child:G}),W=new A9({actions:new Map([[GT,new o4(this.invoke)],[FT,new o4(this.invoke)],[v20,new o4(this.invoke)],[k20,new o4(this.invoke)]]),child:F}),H=new D1({children:[new c0({decoration:{color:X.background},child:new Q0({text:new C(">",new b({color:X.foreground}))})}),new S1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((I,M)=>{let A=M===this.highlightedIndex,j=Z?I.threads.some((h)=>h.id===Z):!1,_=A?Y.selectionBackground:void 0,S=A?Y.selectionForeground:X.foreground,y=[new C(I.label,new b({color:S})),new C(` (${I.threads.length})`,new b({color:S,dim:!0}))];if(j)y.push(new C(" (current)",new b({color:A?Y.selectionForeground:X.success})));return new Vw4(new i1({onClick:(h)=>this.handleItemClick(M,h.clickCount),child:new c0({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 O6({controller:this.scrollController,autofocus:!1,child:w})})}),O=z?z.threads.map((I)=>({id:I.id,title:I.title,parentID:I.parentID,updatedAt:I.updatedAt})):[],E=z?new c0({padding:C0.all(1),child:new QL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(K){let I=E?new S1({child:E}):new j0({width:Uw4});L=new D1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,I]})}else{let I=[new S1({child:new i1({onScroll:this.handleScroll,child:new O6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)I.push(new S1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:I})}return new c0({decoration:{border:D,color:X.background},padding:C0.symmetric(1,0),child:new u0({children:[q,H,new j0({height:1}),new S1({child:L})]})})}}h0();class zw4 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||[],X=this.labels.some((U)=>U.name===Z),Y=Q.includes(Z);return!X&&!Y}build(J){let Z=x0.of(J),{app:Q,colors:X}=Z,Y=this.currentQuery.trim().toLowerCase(),U=Y.length>0?this.getValidationError(Y):null,V=this.getAvailableLabels(),D=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new p9({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,G,F)=>{let W=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:X.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({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 c0({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 F=q.trim().toLowerCase();return F.length===0||z.name.includes(F)},sortItems:(z,q,G)=>{let F="__isCreateMarker"in z.item&&z.item.__isCreateMarker,W="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(F&&!W)return-1;if(!F&&W)return 1;return q.score-z.score}})}}class Gg0 extends p0{props;constructor(J){super();this.props=J}createState(){return new zw4}}class xH extends p0{props;constructor(J){super();this.props=J}createState(){return new qw4}}class qw4 extends g0{_spinner=new L3;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=x0.of(J),{colors:Q,app:X}=Z,Y=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:X.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 c0({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 c0({decoration:new _4(Q.background,Y),child:new j0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new S4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class YL extends p0{props;constructor(J){super();this.props=J}createState(){return new Gw4}}class Gw4 extends g0{scrollController=new r6;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=x0.of(J),Q=this.widget.props.message,X=(()=>{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}})(),Y=X.type==="error"?Z.app.toolError:Z.app.command,U=f1.all(new y1(Z.colors.border,1,"solid")),V=new c0({padding:C0.symmetric(1,0),child:new Q0({text:new C(X.title,new b({color:Y,bold:!0}))})}),K=this.isWidgetMessage(Q)?Q.widget:new Q0({text:new C(X.description,new b({color:Z.colors.foreground})),selectable:!0}),D=new S1({child:new N2({child:new c0({padding:C0.symmetric(1,0),child:new D1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new O6({controller:this.scrollController,autofocus:!0,child:K})}),new A8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,G=this.scrollController.offset,F=this.getViewportHeight(),W=q+F;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(G,0)}}})]})})})}),z=new c0({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 G=new b({color:Z.app.keybind}),F=new b({color:Z.colors.foreground,dim:!0});return new C("",F,[new C("Press ",F),new C("Escape",G),new C(" to close • Use ",F),new C("↑↓",G),new C(" or ",F),new C("j/k",G),new C(" to scroll",F)])}return new C("Press any key to close",new b({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new S4({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 c0({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 Fw4 extends p0{props;constructor(J){super();this.props=J}createState(){return new Ww4}}class Ww4 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=y8.default(),{colors:Q,app:X}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:X.toolSuccess};case"error":return{icon:"✗",color:X.toolError}}}build(J){let Z=x0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new Q0({text:new C("No plugins found.",new b({dim:!0}))});let X=[],Y=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(X.push(new C(`${U}/${Y} ${g4(Y,"plugin")} active`,new b({bold:!0}))),V>0||K>0)X.push(new C(` (${V} ${g4(V,"command")}, ${K} ${g4(K,"tool")})`,new b({dim:!0})));X.push(new C(`
|
|
7146
|
+
`,N)])}),A];if(!D&&!F&&z.url){let h=z.url.replace(/^https?:\/\//,"");_.push(new Z5({uri:z.url,text:h,style:new b({color:Q.secondary,underline:!0})}))}if(M&&!F)_.push(M);let S=new j0({width:50,child:new u0({crossAxisAlignment:"start",mainAxisSize:"min",children:_})}),y=W?new j0({width:A20,height:j20}):new Qh0({width:A20,height:j20,agentMode:this.widget.agentMode,glow:this._glow,backgroundColor:Q.background,t:q,fps:0,shockwaves:this._shockwaves,onShockwave:this.handleShockwave,onClick:this.handleOrbClick,...V==="disabled"&&{seed:42}});return n1.child(new D1({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[y,new j0({width:2}),S]}))}}class Jg0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new lB4}}class lB4 extends g0{build(J){let Q=x0.of(J).colors,{todos:X,title:Y="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new j0({width:0,height:0});let U=X.map((V)=>this.buildTodoItem(V,Q));return new c0({child:new a0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new Q0({text:new C(Y,new b({bold:!0,color:Q.foreground}))}),...U]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),X=J.status==="completed",Y=new b({bold:J.status==="in-progress",color:Z.foreground,dim:X}),U=new b({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:X});return new D1({crossAxisAlignment:"start",children:[new Q0({text:new C(Q,Y)}),new j0({width:1}),new S1({child:new Q0({text:new C(J.content,U)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Zg0 extends p0{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Z,onDismiss:Q,onButtonClick:X,onImpression:Y,onAdInfoClick:U}){super({key:J});this.ad=Z,this.onDismiss=Q,this.onButtonClick=X,this.onImpression=Y,this.onAdInfoClick=U}createState(){return new iB4}}class iB4 extends g0{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Z=x0.of(J),Q=Z.colors.primary,X=Z.colors.foreground,Y=Z.colors.background,U=this.widget.ad;return new c0({decoration:new _4(Y,new f1(new y1(Q,1,"rounded"),new y1(Q,1,"rounded"),void 0,new y1(Q,1,"rounded"))),child:new a0({padding:C0.horizontal(1),child:new u0({children:[new D1({crossAxisAlignment:"start",children:[new S1({child:new Q0({text:new C(U.content,new b({color:X}))})}),new j0({width:4}),new i1({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new Q0({text:new C("Ad",new b({color:X,dim:!0}))})})]}),new D1({crossAxisAlignment:"start",children:[new vg({text:U.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:C0.horizontal(1),color:Q,reverse:!0}),new j0({width:2}),new Q0({text:new C(U.destinationUrlHostname,new b({color:X,dim:!0}))})]})]})})})}}class Qg0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new nB4(this.props.autofocus??!0)}}class nB4 extends g0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=R1.of(J).colorScheme,X=(z)=>{if(z.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(z.ctrlKey&&z.key==="c"||z.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=o1.sizeOf(J),U=Math.min(60,Y.width-4),V=Y.height-4,K=[];if(this.widget.props.title)K.push(new Q0({text:new C(this.widget.props.title,new b({bold:!0,color:Q.primary}))}),new j0({height:1}));if(this.widget.props.message)K.push(new Q0({text:new C(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new j0({height:1}));let D=[];if(this.widget.props.showCopyOption)D.push(new Q0({text:new C("Enter to copy",new b({dim:!0}))}));return D.push(new Q0({text:new C("Escape to close",new b({dim:!0}))})),K.push(new D1({children:D.flatMap((z,q)=>q<D.length-1?[z,new j0({width:1}),new Q0({text:new C("•",new b({dim:!0}))}),new j0({width:1})]:[z]),mainAxisSize:"min"})),new n1({child:new c0({constraints:new M1(U,U,0,V),decoration:new _4(Q.background,new f1(new y1(Q.primary,1,"rounded"),new y1(Q.primary,1,"rounded"),new y1(Q.primary,1,"rounded"),new y1(Q.primary,1,"rounded"))),padding:new C0(2,2,2,2),child:new S4({autofocus:this.autofocus,onKey:X,child:new u0({children:K,mainAxisSize:"min"})})})})}}class Xg0 extends p0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new aB4(this.props.autofocus??!0)}}class aB4 extends g0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Z=R1.of(J).colorScheme,Q=(K)=>{if(K.key==="Enter"||K.key==="Escape"||K.ctrlKey&&K.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},X=o1.sizeOf(J),Y=Math.min(60,X.width-4),U=X.height-4,V=[];if(V.push(new Q0({text:new C("Ads make Amp Free possible",new b({bold:!0}))})),this.widget.props.provider)V.push(new j0({height:1}),new Q0({text:new C(`Ad source: ${this.widget.props.provider}`,new b({dim:!0}))}));return V.push(new j0({height:1}),new Q0({text:new C("Escape to close",new b({dim:!0}))})),new n1({child:new c0({constraints:new M1(Y,Y,0,U),decoration:new _4(Z.background,new f1(new y1(Z.primary,1,"rounded"),new y1(Z.primary,1,"rounded"),new y1(Z.primary,1,"rounded"),new y1(Z.primary,1,"rounded"))),padding:new C0(2,2,2,2),child:new S4({autofocus:this.autofocus,onKey:Q,child:new u0({children:V,mainAxisSize:"min"})})})})}}class Yg0 extends p0{manualURL;isAuthenticating;errorMessage;constructor({manualURL:J,isAuthenticating:Z,errorMessage:Q}){super();this.manualURL=J,this.isAuthenticating=Z,this.errorMessage=Q}createState(){return new oB4}}class oB4 extends g0{build(J){let Q=R1.of(J).colorScheme,X=x0.of(J),Y=o1.of(J),U=Y.size.width,V=Y.size.height,K=U-4,D=Math.max(56,Math.min(86,K)),z=new b({color:Q.primary,bold:!0}),q=new b({color:Q.foreground,dim:!0}),G=new b({color:X.app.link,bold:!0}),F=new b({color:X.app.keybind}),W=new b({color:X.app.toolError}),H=[new Q0({text:new C("Authentication Required",z)}),new j0({height:1}),new Q0({text:new C("Sign in to Amp to continue. Your pending prompt will send automatically after login.",q)}),new j0({height:1}),new Q0({text:new C("Manual login link (select to copy):",q)}),new a0({padding:C0.only({left:2,top:1}),child:new N2({child:new Q0({text:new C(this.widget.manualURL,G),selectable:!0})})})];if(this.widget.errorMessage)H.push(new j0({height:1})),H.push(new Q0({text:new C(this.widget.errorMessage,W)}));if(H.push(new j0({height:1})),H.push(new Q0({text:new C("",void 0,[new C("Enter/O",F),new C(" open browser · ",q),new C("C",F),new C(" copy link · ",q),new C("I",F),new C(" I completed login · ",q),new C("P",F),new C(" paste code · ",q),new C("Esc",F),new C(" cancel",q)])})),this.widget.isAuthenticating)H.push(new j0({height:1})),H.push(new Q0({text:new C("Waiting for login callback...",q)}));let B=new c0({constraints:new M1(D-4,D-4,0,V-6),decoration:{color:Q.background,border:f1.all(new y1(Q.primary,1,"rounded"))},padding:C0.all(2),child:new u0({crossAxisAlignment:"start",mainAxisSize:"min",children:H})});return new n1({child:B})}}h0();n9();import{execSync as Mm5}from"node:child_process";iM();GJ();O3();t7();Pw();IY();I$();TJ();NY();cO();f4();Su();Pv();W1();var uw4=L4(Gz(),1);import{writeFile as _w4}from"fs/promises";import Sw4 from"path";h0();I$();class Ug0{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.1772496276-ge2fd2b"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await ys(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 uH extends p0{props;constructor(J){super();this.props=J}createState(){return new rB4}}class rB4 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 sB4 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=x0.of(J),{colors:Q,app:X}=Z,Y=this.widget.props.isRequiredArg??!0,U=this.controller.text.trim().length>0,V=!Y||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(Y&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new D1({children:[new c0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:D})]}),q=new c0({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:X.command,bold:!0}))])})}),G=[];if(V)G.push(new C("Enter",new b({color:X.keybind}))),G.push(new C(" to submit, ",new b({color:Q.foreground,dim:!0})));G.push(new C("Esc",new b({color:X.keybind}))),G.push(new C(" to cancel",new b({color:Q.foreground,dim:!0})));let F=new c0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,G)})});return new c0({decoration:{border:K,color:Q.background},padding:C0.all(1),child:new u0({children:[q,new j0({height:1}),z,new Z3,F]})})}}class Wp extends p0{props;constructor(J){super();this.props=J}createState(){return new sB4}}import{isDeepStrictEqual as Vg0}from"node:util";var Qm5=/[\\/_ +.#"@[({&]/,Xm5=/[\\/_ +.#"@[({&]/g,Ym5=/[\s-]/,tB4=/[\s-]/g;function C20(J,Z,Q,X,Y,U,V){if(U===Z.length){if(Y===J.length)return 1;return 0.99}let K=`${Y},${U}`;if(V[K]!==void 0)return V[K];let D=X.charAt(U),z=Q.indexOf(D,Y),q=0,G,F,W,H;while(z>=0){if(G=C20(J,Z,Q,X,z+1,U+1,V),G>q){if(z===Y)G*=1;else if(Ym5.test(J.charAt(z-1))){if(G*=0.9,H=J.slice(Y,z-1).match(tB4),H&&Y>0)G*=0.999**H.length}else if(Qm5.test(J.charAt(z-1))){if(G*=0.8,W=J.slice(Y,z-1).match(Xm5),W&&Y>0)G*=0.999**W.length}else if(G*=0.3,Y>0)G*=0.999**(z-Y);if(J.charAt(z)!==Z.charAt(U))G*=0.9999}if(G<0.1&&(Q.charAt(z-1)===X.charAt(U+1)||X.charAt(U+1)===X.charAt(U)&&Q.charAt(z-1)!==X.charAt(U))){if(F=C20(J,Z,Q,X,z+1,U+2,V),F*0.1>G)G=F*0.1}if(G>q)q=G;z=Q.indexOf(D,z+1)}return V[K]=q,q}function P20(J){return J.toLowerCase().replace(tB4," ")}function eB4(J,Z){let Q=C20(J,Z,P20(J),P20(Z),0,0,{}),X=Z.trim().split(/\s+/);if(X.length>1){let Y=0,U=0;for(let K of X){let D=C20(J,K,P20(J),P20(K),0,0,{});if(D===0)return Q;Y+=D,U+=K.length}let V=Y/X.length*0.95;return Math.max(Q,V)}return Q}class zT{}class qT{}class T20{}class _20{}class $w4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Jw4}}class Jw4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}function Um5(J,Z){if(J==="")return{matches:!0,score:1};let Q=eB4(Z,J);return{matches:Q>0.15,score:Q}}class p9 extends p0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Zw4}}class Zw4 extends g0{textController;focusNode;scrollController=new r6;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)=>Vg0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Vg0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Vg0(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 zT){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 qT){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 T20){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 _20)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,X=Z.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...Um5(Q,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,U)=>this.widget.props.sortItems(Y,U,J):(Y,U)=>U.score-Y.score).map((Y)=>Y.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?X.slice(0,this.widget.props.maxRenderItems):X}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,X=Z.size.height;nC(J,{top:Q,bottom:X},{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 X=Q[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!Y){if(X)this.hasUserInteracted=!0,this.widget.props.onAccept(X,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=x0.of(J),{colors:Q}=Z,X=this.getFilteredItems(),Y=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 w2({shortcuts:new Map([[new e1("ArrowDown"),new zT],[new e1("ArrowUp"),new qT],[new e1("Tab"),new zT],[new e1("Tab",{shift:!0}),new qT],[new e1("n",{ctrl:!0}),new zT],[new e1("p",{ctrl:!0}),new qT],[new e1("Enter"),new T20],[new e1("Escape"),new _20]]),focusNode:this.focusNode,child:K}),z=new A9({actions:new Map([[zT,new o4(this.invoke)],[qT,new o4(this.invoke)],[T20,new o4(this.invoke)],[_20,new o4(this.invoke)]]),child:D}),q=new D1({children:[new c0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new S1({child:z})]});this.itemContexts=[];let G;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";G=new j0({height:10,child:new n1({child:new Q0({text:new C(w,new b({color:Q.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)G=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=X.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,I;if(this.widget.props.renderItem)I=this.widget.props.renderItem(N,E,L,J);else{let M=E?Z.app.selectionBackground:void 0,A=E?Z.app.selectionForeground:Q.foreground;I=new c0({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 $w4(new i1({onClick:(M)=>this.handleItemClick(O,M.clickCount),child:I}),(M)=>{this.itemContexts[O]=M})});G=new u0({children:w,crossAxisAlignment:"start"})}let F=new i1({onScroll:this.handleScroll,opaque:!1,child:new O6({controller:this.scrollController,autofocus:!1,child:G})}),W=[];if(this.widget.props.title){let w=new c0({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=X.length>0?X[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:F}),new c0({padding:C0.only({top:1}),child:new n1({child:N??new j0({height:1})})})]})}))}else W.push(new S1({child:F}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:Y,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function Qw4(J){let Q=new Date().getTime()-J.getTime(),X=Math.floor(Q/60000),Y=Math.floor(Q/3600000),U=Math.floor(Q/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(Y<24)return`${Y}h ago`;if(U<7)return`${U}d ago`;return J.toLocaleDateString()}class Kg0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((Y,U)=>U.pubDate.getTime()-Y.pubDate.getTime()),Q=Math.max(0,...Z.map((Y)=>Qw4(Y.pubDate).length));return new p9({items:Z,getLabel:(Y)=>Y.title,onAccept:(Y)=>this.props.onSelect?.(Y),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(Y,U,V,K)=>{let D=x0.of(K),{colors:z}=D,q=D.app,G=U?q.selectionBackground:void 0,F=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 c0({decoration:G?{color:G}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new S1({child:new Q0({text:new C(Y.title,new b({color:F})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),H(Qw4(Y.pubDate),Q)]})})}})}}f4();class Dg0 extends p0{createState(){return new Xw4}}class Xw4 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=x0.of(J).colors;return new Q0({text:new C("●",new b({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Vm5=/\/threads\/(T-[^/?#\s<>]+)/i;function Km5(J){let Z=J.trim(),X=Z.match(Vm5)?.[1];if(X&&C8(X))return X;let Y=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(C8(Y))return Y;return null}function Dm5(J){let Z=new Map,Q=new Map,X=new Map,Y=[];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){X.set(V.id,K.type);let D=K.threadID,z=Q.get(D)||[];z.push(V),Q.set(D,z)}else Y.push(V)}return v90.flatten(Y,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:X.get(V.item.id)}))}function zg0(J,Z,Q){return new Q0({text:new C(`${J}${Z}`,new b({color:Q})),maxLines:1})}function zm5(J,Z,Q,X){return[zg0("+",J,X.success),Z3.horizontal(1),zg0("~",Z,X.warning),Z3.horizontal(1),zg0("-",Q,X.destructive)]}function qm5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class S20 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Yw4}}class Yw4 extends g0{spinner=new L3;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,X=this.isSwitchingThread?"Switching thread...":"Loading threads...",Y=`${this.spinner.toBraille()} ${X}`,U=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)U=U.filter((O)=>O.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],K=new Set(V),D=Z.currentThreadID,z=[...U].sort((O,E)=>{if(D){if(O.id===D)return-1;if(E.id===D)return 1}let L=V.indexOf(O.id),I=V.indexOf(E.id);if(L!==-1&&I!==-1)return L-I;if(L!==-1)return-1;if(I!==-1)return 1;return 0}),q=Dm5(z),G=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),F=x0.of(J),W=new a0({padding:C0.symmetric(0,1),child:new n1({child:new Q0({text:new C("",new b({color:F.colors.foreground,dim:!0}),[new C("Ctrl+T",new b({color:F.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new b({color:F.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=Km5(O);return B};return new p9({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!qm5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:Y,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,I)=>{let M=x0.of(I),{app:A,colors:j}=M,_=E?A.selectionBackground:void 0,S=E?A.selectionForeground:j.foreground,y=j.mutedForeground,h=($0,B0)=>new j0({width:B0,child:D1.end([new Q0({text:new C($0,new b({color:y}))})])}),f=Z.threadViewStates[O.id],k=[],x=O.relationshipType==="handoff",g=new Hg({connectorColor:j.mutedForeground});if(O.depth>0){let $0=[],B0=O.ancestorsAreLast.slice(1);for(let U0 of B0)$0.push(new C(g.getAncestorPrefix(U0),new b({color:g.connectorColor,dim:g.connectorDim})));let i=O.isLast?g.elbow:g.tee,V0=g.getConnectorText(i);$0.push(new C(V0,new b({color:g.connectorColor,dim:g.connectorDim}))),k.push(new Q0({text:new C("",void 0,$0)}))}let a=[],m=D===O.id?new C("(current) ",new b({color:j.success})):K.has(O.id)?new C("(visited) ",new b({color:j.foreground,dim:!0})):null;if(m)a.push(new Q0({text:m}));if(lR(f))a.push(new Dg0),a.push(new j0({width:1}));let l=O.title;if(O.relationshipType==="fork"){let $0=l.match(/^Forked\((\d+)\): /);if($0)l=l.slice($0[0].length);else while(l.startsWith("Forked: "))l=l.slice(8);a.push(new Q0({text:new C("[fork] ",new b({color:j.primary}))}))}else if(x)a.push(new Q0({text:new C("[handoff] ",new b({color:j.accent}))}));if(a.push(new S1({child:new Q0({text:new C(l,new b({color:S})),overflow:"ellipsis",maxLines:1})})),a.push(new j0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let $0=E?{success:y,warning:y,destructive:y}:j;a.push(...zm5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,$0)),a.push(new j0({width:2}))}return a.push(h(O.description.timeAgo,G)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...a]})})}})}}class Vw4 extends p0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Kw4}}class Kw4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}var Uw4=30,Gm5=30;class GT{}class FT{}class v20{}class k20{}class qg0 extends p0{props;constructor(J){super();this.props=J}createState(){return new Dw4}}class Dw4 extends g0{highlightedIndex=0;controller=new u7;focusNode;scrollController=new r6;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,X=Z.size.height;nC(J,{top:Q,bottom:X},{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 GT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof FT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof v20){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof k20)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=x0.of(J),{colors:X,app:Y}=Q,K=o1.of(J).size.width>=Gm5+Uw4,D=f1.all(new y1(X.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new c0({padding:C0.symmetric(1,0),child:new Q0({text:new C("Select a cluster",new b({color:Y.command,bold:!0}))})}),G=new i$({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:X.foreground,border:null},maxLines:1}),F=new w2({shortcuts:new Map([[new e1("ArrowDown"),new GT],[new e1("ArrowUp"),new FT],[new e1("Tab"),new GT],[new e1("Tab",{shift:!0}),new FT],[new e1("n",{ctrl:!0}),new GT],[new e1("p",{ctrl:!0}),new FT],[new e1("Enter"),new v20],[new e1("Escape"),new k20]]),focusNode:this.focusNode,child:G}),W=new A9({actions:new Map([[GT,new o4(this.invoke)],[FT,new o4(this.invoke)],[v20,new o4(this.invoke)],[k20,new o4(this.invoke)]]),child:F}),H=new D1({children:[new c0({decoration:{color:X.background},child:new Q0({text:new C(">",new b({color:X.foreground}))})}),new S1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((I,M)=>{let A=M===this.highlightedIndex,j=Z?I.threads.some((h)=>h.id===Z):!1,_=A?Y.selectionBackground:void 0,S=A?Y.selectionForeground:X.foreground,y=[new C(I.label,new b({color:S})),new C(` (${I.threads.length})`,new b({color:S,dim:!0}))];if(j)y.push(new C(" (current)",new b({color:A?Y.selectionForeground:X.success})));return new Vw4(new i1({onClick:(h)=>this.handleItemClick(M,h.clickCount),child:new c0({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 O6({controller:this.scrollController,autofocus:!1,child:w})})}),O=z?z.threads.map((I)=>({id:I.id,title:I.title,parentID:I.parentID,updatedAt:I.updatedAt})):[],E=z?new c0({padding:C0.all(1),child:new QL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(K){let I=E?new S1({child:E}):new j0({width:Uw4});L=new D1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,I]})}else{let I=[new S1({child:new i1({onScroll:this.handleScroll,child:new O6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)I.push(new S1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:I})}return new c0({decoration:{border:D,color:X.background},padding:C0.symmetric(1,0),child:new u0({children:[q,H,new j0({height:1}),new S1({child:L})]})})}}h0();class zw4 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||[],X=this.labels.some((U)=>U.name===Z),Y=Q.includes(Z);return!X&&!Y}build(J){let Z=x0.of(J),{app:Q,colors:X}=Z,Y=this.currentQuery.trim().toLowerCase(),U=Y.length>0?this.getValidationError(Y):null,V=this.getAvailableLabels(),D=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new p9({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,G,F)=>{let W=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:X.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({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 c0({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 F=q.trim().toLowerCase();return F.length===0||z.name.includes(F)},sortItems:(z,q,G)=>{let F="__isCreateMarker"in z.item&&z.item.__isCreateMarker,W="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(F&&!W)return-1;if(!F&&W)return 1;return q.score-z.score}})}}class Gg0 extends p0{props;constructor(J){super();this.props=J}createState(){return new zw4}}class xH extends p0{props;constructor(J){super();this.props=J}createState(){return new qw4}}class qw4 extends g0{_spinner=new L3;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=x0.of(J),{colors:Q,app:X}=Z,Y=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:X.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 c0({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 c0({decoration:new _4(Q.background,Y),child:new j0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new S4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class YL extends p0{props;constructor(J){super();this.props=J}createState(){return new Gw4}}class Gw4 extends g0{scrollController=new r6;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=x0.of(J),Q=this.widget.props.message,X=(()=>{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}})(),Y=X.type==="error"?Z.app.toolError:Z.app.command,U=f1.all(new y1(Z.colors.border,1,"solid")),V=new c0({padding:C0.symmetric(1,0),child:new Q0({text:new C(X.title,new b({color:Y,bold:!0}))})}),K=this.isWidgetMessage(Q)?Q.widget:new Q0({text:new C(X.description,new b({color:Z.colors.foreground})),selectable:!0}),D=new S1({child:new N2({child:new c0({padding:C0.symmetric(1,0),child:new D1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new O6({controller:this.scrollController,autofocus:!0,child:K})}),new A8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,G=this.scrollController.offset,F=this.getViewportHeight(),W=q+F;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(G,0)}}})]})})})}),z=new c0({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 G=new b({color:Z.app.keybind}),F=new b({color:Z.colors.foreground,dim:!0});return new C("",F,[new C("Press ",F),new C("Escape",G),new C(" to close • Use ",F),new C("↑↓",G),new C(" or ",F),new C("j/k",G),new C(" to scroll",F)])}return new C("Press any key to close",new b({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new S4({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 c0({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 Fw4 extends p0{props;constructor(J){super();this.props=J}createState(){return new Ww4}}class Ww4 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=y8.default(),{colors:Q,app:X}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:X.toolSuccess};case"error":return{icon:"✗",color:X.toolError}}}build(J){let Z=x0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new Q0({text:new C("No plugins found.",new b({dim:!0}))});let X=[],Y=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(X.push(new C(`${U}/${Y} ${g4(Y,"plugin")} active`,new b({bold:!0}))),V>0||K>0)X.push(new C(` (${V} ${g4(V,"command")}, ${K} ${g4(K,"tool")})`,new b({dim:!0})));X.push(new C(`
|
|
7147
7147
|
|
|
7148
7148
|
`));for(let D of this.plugins){let{icon:z,color:q}=this.statusIcon(D.status),G=this.getRelativePath(D.uri.toString());if(X.push(new C(`${z} `,new b({color:q}))),X.push(new C(G,new b({bold:!0}))),X.push(new C(` ${D.status}`,new b({dim:!0}))),X.push(new C(`
|
|
7149
7149
|
`)),D.status==="active"&&D.registeredEvents.length>0)X.push(new C(" Events: ",new b({dim:!0}))),X.push(new C(D.registeredEvents.join(", "),new b({color:Q.link}))),X.push(new C(`
|
|
@@ -7282,7 +7282,7 @@ ${r.content||""}`:r.content||"",F1=[],A1=r.baseDir.startsWith("file://")?Q$0(r.b
|
|
|
7282
7282
|
`)}function XO4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,X)=>{let Y=X.optsWithGlobals(),U=await Z(Y),V=await U.settings.get("proxy"),K=LM1({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+`
|
|
7283
7283
|
`),process.exit(1)}process.stdout.write(await Jp5(D.result.displayText)+`
|
|
7284
7284
|
`),process.exit(0)})}var Li5=gp.join(NZ,"logs","headless.log"),pd0=gp.join(oP,"device-id.json");function Ii5(){return lD.some((J)=>J.listConfigs().length>0)}try{if(process.platform==="win32")await Promise.resolve().then(() => L4(vT(),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}
|
|
7285
|
-
`)}function Mi5(J){process.emitWarning=(Z,Q,X,Y)=>{let U=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",K=!1;J.warn(U,{name:V,code:X})}}function g7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")N7("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")N7("experimental.agentMode",Z.mode)}function SI4(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 Ai5(J){try{return await _I4(J,"utf-8")}catch{return J}}async function dd0(J,Z,Q){let X=SI4(J,Z);if(!X)return;let Y=L5(Q)?Q.features:[],U=L5(Q)?Q.user.email:void 0;if(!Y.some((K)=>K.name===MY.HARNESS_SYSTEM_PROMPT&&K.enabled)&&!vI4(U))throw new z4("You are not allowed to do this.",1);N7("systemPrompt",await Ai5(X))}function vI4(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function cd0(J,Z){if(typeof J==="boolean")return J;if(!L5(Z))return!1;return pQ(Z.user.email)}function ji5(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 ld0(J){let X=ji5(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 z4(`Couldn't connect to the Amp server at ${J}.`,1,X)}var jI4=[{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??CX,description:`Custom settings file path (overrides the default location ${CX})`},{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 ${VE})`},{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:LV.SMART.key,description:`Set the agent mode (${fQ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fQ().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}],RI4=(J)=>("deprecated"in J)&&J.deprecated===!0,Ri5=(J)=>("hidden"in J)&&J.hidden===!0,Pi5=(J)=>("default"in J),Ci5=(J)=>("default"in J)?J.default:void 0,kI4=[{name:"toggle-skills-count",entryPoint:Ku0}];function Ti5(J,Z){let Q=Z.args[0],X=Z.commands.map((U)=>U.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let U=X.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 z4(Y8.unknownCommand(Q),1,V)}}async function nd0(J){return{...J,getThreadEnvironment:$Q,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mY(J.fileSystem),generateThreadTitle:D00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>_J(J.configService),pluginService:J.pluginService}}var n$0=q1.file(Ei5.homedir()),id0=process.env.XDG_CONFIG_HOME?q1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(n$0,".config");function _i5(J){return n84({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){i84(Z);let Q=U80(),X=Su0();if((!Q||X||JY4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(Uq("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(Uq("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(U80()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Si5(){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 X=Q?.deferAuth??!1;WM1("0.0.
|
|
7285
|
+
`)}function Mi5(J){process.emitWarning=(Z,Q,X,Y)=>{let U=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",K=!1;J.warn(U,{name:V,code:X})}}function g7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")N7("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")N7("experimental.agentMode",Z.mode)}function SI4(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 Ai5(J){try{return await _I4(J,"utf-8")}catch{return J}}async function dd0(J,Z,Q){let X=SI4(J,Z);if(!X)return;let Y=L5(Q)?Q.features:[],U=L5(Q)?Q.user.email:void 0;if(!Y.some((K)=>K.name===MY.HARNESS_SYSTEM_PROMPT&&K.enabled)&&!vI4(U))throw new z4("You are not allowed to do this.",1);N7("systemPrompt",await Ai5(X))}function vI4(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function cd0(J,Z){if(typeof J==="boolean")return J;if(!L5(Z))return!1;return pQ(Z.user.email)}function ji5(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 ld0(J){let X=ji5(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 z4(`Couldn't connect to the Amp server at ${J}.`,1,X)}var jI4=[{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??CX,description:`Custom settings file path (overrides the default location ${CX})`},{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 ${VE})`},{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:LV.SMART.key,description:`Set the agent mode (${fQ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fQ().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}],RI4=(J)=>("deprecated"in J)&&J.deprecated===!0,Ri5=(J)=>("hidden"in J)&&J.hidden===!0,Pi5=(J)=>("default"in J),Ci5=(J)=>("default"in J)?J.default:void 0,kI4=[{name:"toggle-skills-count",entryPoint:Ku0}];function Ti5(J,Z){let Q=Z.args[0],X=Z.commands.map((U)=>U.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let U=X.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 z4(Y8.unknownCommand(Q),1,V)}}async function nd0(J){return{...J,getThreadEnvironment:$Q,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mY(J.fileSystem),generateThreadTitle:D00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>_J(J.configService),pluginService:J.pluginService}}var n$0=q1.file(Ei5.homedir()),id0=process.env.XDG_CONFIG_HOME?q1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(n$0,".config");function _i5(J){return n84({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){i84(Z);let Q=U80(),X=Su0();if((!Q||X||JY4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(Uq("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(Uq("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(U80()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Si5(){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 X=Q?.deferAuth??!1;WM1("0.0.1772496276-ge2fd2b");let Y=Lo({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([q1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:n$0,userConfigDir:id0});rX4(Y);let U=await Y.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(U.settings)});let{toolService:V,dispose:K}=g84({configService:Y}),D=new Map,z=()=>D.clear(),q=new AE0(Y,J.settings.getWorkspaceRootPath()),G=Nb1({configService:Y,filesystem:a6}),F=gk1({configService:Y,trustStore:q,skillMCPServers:G.skillMCPServers,createOAuthProvider:async(l,d,$0)=>{let B0=`${l}:${d}`,i=D.get(B0);if(i)return P.debug("Reusing existing OAuth provider for server",{serverName:l,serverUrl:d}),i;P.debug("Creating OAuth provider for server",{serverName:l,serverUrl:d});let V0=(async()=>{let U0=new UN(J.secrets),N0=await U0.getClientInfo(l,d),Y0=$0?.scopes??N0?.scopes,H0=zQ4();P.info("OAuth headless mode check",{useHeadless:H0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let c;if(H0)c=J.executeMode?DQ4():KQ4(l);let s=new dO0({storage:U0,serverName:l,serverUrl:d,clientId:$0?.clientId??N0?.clientId,clientSecret:$0?.clientSecret??N0?.clientSecret,authUrl:$0?.authUrl??N0?.authUrl,tokenUrl:$0?.tokenUrl??N0?.tokenUrl,scopes:Y0,headlessAuthHandler:c});return P.debug("OAuth provider created",{serverName:l,serverUrl:d,hasManualClientId:!!($0?.clientId??N0?.clientId),willUseDCR:!($0?.clientId??N0?.clientId),scopes:Y0,headlessMode:H0,executeMode:J.executeMode}),s})();return D.set(B0,V0),V0}}),W=LS0({configService:Y,filesystem:a6,spawn:$50}),H;if(J.executeMode){let l=await X54({toolService:V,providers:[F,W],initialTimeout:15000});H=l.registrations;for(let[d,$0]of l.initErrors)P.warn(`${d} provider initialization slow or failed:`,$0)}else H=MS0({toolService:V,providers:[F,W]});if(Z.jetbrains)fw("JetBrains");else if(Z.ide&&iQ4())fw("VS Code");else if(Z.ide&&nQ4())fw("Neovim");else if(Z.ide&&Ii5()){let l=lD.find((d)=>d.listConfigs().length>0);if(l){let d=jo(l.ideName);if(d)fw(d)}}if(J.executeMode)HM1(!0);let B,w=_8.status.pipe(B1((l)=>Boolean(l.connected&&l.authenticated&&l.ideName&&SM1(l.ideName))),I4()).subscribe((l)=>{if(l){if(!B)B=V.registerTool(Q54)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let l=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new j30(process.cwd(),{alwaysIncludePaths:l},!0)}else N=new class extends j30{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let l=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(l),P.info("API key lookup before login",{found:Boolean(l),ampURL:J.ampURL,deferAuth:X}),!l)if(X)P.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
|
|
7286
7286
|
`);let d=await vi5(J),$0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:d,storedKeyPresent:Boolean($0),ampURL:J.ampURL}),!d)await Zq(),process.exit(1);O=!0}}{let l=await Y.getLatest(),d=l.settings.url,$0=l.secrets.isSet?.[d];P.info("Config secrets state after login",{configURL:d,apiKeySet:$0?.apiKey??!1})}let E=L1(_J(Y).pipe(k5((l)=>l!=="pending"))),L=await Ab1({isDevelopment:!1}),I=X?"pending":await E;if(!X)P.info("Server status resolved",{status:"ready",isAuthenticated:L5(I),isError:KF(I),errorMessage:KF(I)?I.error.message:void 0});let M=new vM0(L,Y),A=new AI0(L,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let j=cd0(Z.dtw,I),_=Boolean(j||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let S=_?Si5():sh1({threadService:M,threadHistoryService:A,configService:Y,isExtensionDevelopment:!1}),y;_8.status.subscribe((l)=>{y=l});let h=new gH0({workspaceRoots:[q1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?ms:a6,getCurrentFile:()=>{if(!y?.openFile)return;try{return q1.parse(y.openFile)}catch(l){P.warn("Failed to parse current file URI",{uri:y.openFile,error:l});return}},getOpenFiles:()=>{if(!y?.visibleFiles?.length)return[];let l=y.openFile;return y.visibleFiles.filter((d)=>d!==l).map((d)=>{try{return q1.parse(d)}catch($0){return P.warn("Failed to parse visible file URI",{uri:d,error:$0}),null}}).filter((d)=>d!==null)}}),f=new yu0,k=process.env.PLUGINS??"off",x=new Vu0({configService:Y}),g=qI0({configService:Y,fileSystem:Z.jetbrains||Z.ide?ms:a6,platform:x,internalPlugins:kI4,pluginFilter:k}),a=hf1({pluginService:g,toolService:V}),m={codebaseContextService:h,configService:Y,toolService:V,mcpService:F,skillService:G,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?ms:a6,terminal:f,pluginService:g,pluginPlatform:x,serverStatus:I,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...m,async asyncDispose(){if(m.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await m.mcpService.waitForAuthentication();for(let l of H.values())l.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 vi5(J){if(!J.executeMode){if(!await Yu0("Would you like to log in to Amp? [(y)es, (n)o]: "))return s6.write(`Login cancelled. Run the command again to retry.
|
|
7287
7287
|
`),!1}return await yI4(J)}async function yI4(J){let Z=wi5(32).toString("hex"),Q=await sP(J.ampURL,Z),X=new AbortController;try{await EY(Q,X.signal)}catch(U){P.error("Error opening browser",{error:U})}let Y=await sP(J.ampURL,Z,!1);s6.write(`If your browser does not open automatically, visit:
|
|
7288
7288
|
|
|
@@ -7290,7 +7290,7 @@ ${Z1.blue.bold(Y)}
|
|
|
7290
7290
|
|
|
7291
7291
|
`);try{return await BX4(J.ampURL,Z,J.secrets,X),s6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(U){return P.error("Login failed",{error:U}),q7.write(`
|
|
7292
7292
|
Login failed: ${U instanceof Error?U.message:String(U)}
|
|
7293
|
-
`),!1}}function ki5(){let J=new TW().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)DE(),process.exit(0);let B=H.originalError??H;AZ4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${DF(new Date("2026-03-03T00:
|
|
7293
|
+
`),!1}}function ki5(){let J=new TW().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)DE(),process.exit(0);let B=H.originalError??H;AZ4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${DF(new Date("2026-03-03T00:10:30.790Z"))} ago`}catch{}s6.write(`0.0.1772496276-ge2fd2b (released 2026-03-03T00:10:30.790Z${B??""})
|
|
7294
7294
|
`),process.exit(0)}),J.addHelpText("after",dQ4()),J.configureHelp({formatHelp:cQ4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await M3(w);await mi5(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 M3(w);await hi5(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(),O=await M3(N);await aZ4(H??"get",O.ampURL,O.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 M3(w);await oZ4(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",`
|
|
7295
7295
|
Actions:
|
|
7296
7296
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7334,7 +7334,7 @@ See: https://ampcode.com/news/stick-a-fork-in-it
|
|
|
7334
7334
|
amp threads handoff T-xxx --goal "Continue working on the auth feature"
|
|
7335
7335
|
amp threads handoff --goal "Fix the remaining tests" # Uses last thread
|
|
7336
7336
|
|
|
7337
|
-
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(),O=await M3(N);await ni5(N,O,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(),O=await M3(N);await ci5(N,O,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(),O=await M3(N);await li5(N,O,H,w)}),k94(Q,M3,g7,c9,ad0,sH,q3),rY4(J,async(H,B)=>{let w=await M3(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:$Q,serverStatus:N.serverStatus,toolboxService:N.toolboxService,configService:N.configService,cleanupTerminal:DE,asyncDispose:N.asyncDispose.bind(N)}}),bX4(J,async(H)=>{let B=H.optsWithGlobals(),w=await M3(B);g7(H,B);let N=Lo({storage:w.settings,secretStorage:w.secrets,workspaceRoots:v0.of([q1.file(process.cwd())]),defaultAmpURL:w.ampURL,homeDir:n$0,userConfigDir:id0});return{pluginService:qI0({configService:N,fileSystem:a6,platform:{clientKind:"terminal",clientVersion:"0.0.
|
|
7337
|
+
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(),O=await M3(N);await ni5(N,O,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(),O=await M3(N);await ci5(N,O,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(),O=await M3(N);await li5(N,O,H,w)}),k94(Q,M3,g7,c9,ad0,sH,q3),rY4(J,async(H,B)=>{let w=await M3(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:$Q,serverStatus:N.serverStatus,toolboxService:N.toolboxService,configService:N.configService,cleanupTerminal:DE,asyncDispose:N.asyncDispose.bind(N)}}),bX4(J,async(H)=>{let B=H.optsWithGlobals(),w=await M3(B);g7(H,B);let N=Lo({storage:w.settings,secretStorage:w.secrets,workspaceRoots:v0.of([q1.file(process.cwd())]),defaultAmpURL:w.ampURL,homeDir:n$0,userConfigDir:id0});return{pluginService:qI0({configService:N,fileSystem:a6,platform:{clientKind:"terminal",clientVersion:"0.0.1772496276-ge2fd2b",async notify(L){P.debug("plugin notification (TUI not loaded): %s",L)},async open(L){q7.write(`
|
|
7338
7338
|
${L}
|
|
7339
7339
|
|
|
7340
7340
|
`)},async input(){return},async confirm(){return!1},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},internalPlugins:kI4,emitSessionStart:!1,pluginFilter:process.env.PLUGINS??"off"}),asyncDispose:async()=>{}}}),dX4(J,async(H)=>{let B=H.optsWithGlobals(),w=await M3(B);g7(H,B);let N=await c9(w,B);return{toolService:N.toolService,mcpService:N.mcpService,configService:N.configService,skillService:N.skillService,cleanupTerminal:DE,asyncDispose:N.asyncDispose.bind(N)}}),aX4(J,async(H)=>{let B=H.optsWithGlobals(),w=await M3(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)}}),uX4(J,async(H)=>{let B=H.optsWithGlobals();return await M3(B)}),AX4(J,async(H)=>{let B=await M3(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)}}}}),XO4(J,M3);function U(H,B,w){let O=typeof H.description==="string"?H.description:w===void 0?H.description(!0):H.description(w),E=new qU(B,O),L=Ci5(H);if(L)E.default(L);if(E.hidden=Ri5(H)||RI4(H),"choices"in H)E.choices([...H.choices]);return E}for(let H of jI4){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 qU(`--${B}`,H.description);w.hidden=!0,w.implies({[H.name]:!0}),J.addOption(w)}}let V=new qU("-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 qU("-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 qU("--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 qU("--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 qU("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let G=new qU("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(G);let F=new qU("--archive","When used with --execute, archive the thread after the command finishes.").default(!1);J.addOption(F);let W=new qU("-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 M3(w);if(Object.keys(w).forEach((O)=>{let E=jI4.find((L)=>L.name===O);if(E&&RI4(E)&&!Pi5(E))q7.write(Z1.yellow(`Warning: '--${O}' flag is deprecated
|
|
@@ -7342,8 +7342,8 @@ ${L}
|
|
|
7342
7342
|
|
|
7343
7343
|
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 yi5(J){if(!J.userEmail||!pQ(J.userEmail))throw new z4("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 Am({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:$Q,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new mY(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 ui5(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await zm()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await zm()).trimEnd(),stdinInput:null}}function xi5(J,Z,Q){if(J.remote&&!Z)throw new z4("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new z4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new z4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new z4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new z4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new z4("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 z4("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 z4("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"
|
|
7344
7344
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function a$0(J,Z,Q){let X=process.hrtime.bigint(),Y=(i,V0)=>{let U0=Number(process.hrtime.bigint()-V0)/1e6,N0=x94();P.info("Startup phase",{phase:i,phaseMs:Math.round(U0),sinceMainMs:N0===null?void 0:Math.round(N0)})},{userInput:U,stdinInput:V}=await ui5(Z),K=!!Z.streamJson||!!Z.streamJsonThinking;xi5({...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;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:z,executeMode:J.executeMode});let G=await c9(J,Z,{deferAuth:q});Y("runMainThread:createThreadDependencies",D),D=process.hrtime.bigint();let F=await nd0(G);Y("runMainThread:createWorkerDeps",D);let{serverStatus:W}=G;if(!q&&KF(W)){let i=gh(Error(W.error.message));if(i.message===Y8.networkOffline||i.message===Y8.networkTimeout)throw ld0(J.ampURL);throw new z4(Y8.invalidAPIKey,1)}let H=L5(W)?W:null,B=H?.user.email,w=H?.features??[],N=H?.workspace??null,O=vI4(B),E=!J.executeMode&&H!==null&&cd0(Z.dtw,H);if(!q)await dd0(Q,Z,W);let L=L5(W)?{...W.user,features:w,team:N??void 0}:null,I=d30(Z,L);if(I instanceof Error)q3(I.message);if((J.executeMode||K)&&R8(Z.mode)&&!O)throw new z4(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(J.executeMode&&Z.remote)await hX4(U,V,G.configService),await G.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!pQ(B))throw new z4("Headless DTW mode is only available for Amp employees",1);let i=await G.secretStorage.get("apiKey",J.ampURL);if(!i)throw new z4("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&&!C8(V0))throw new z4(`Invalid thread ID: ${V0}`,1);let U0=V0??await ai5({dependencies:G,visibility:I??void 0}),N0=await WQ4(U0);if(N0.status==="already-running")await G.asyncDispose(),await Zq(),process.exit(0);try{await VQ4({ampURL:J.ampURL,apiKey:i,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:U0,configService:G.configService,mcpService:G.mcpService,toolService:G.toolService,skillService:G.skillService,fileSystem:G.fileSystem})}finally{await N0.release(),await G.asyncDispose()}await Zq(),process.exit(0)}let M={threadService:G.threadService,workerDeps:F,createThread:async()=>{let i=await F30(J.settings,process.cwd(),L,I);if(i instanceof Error)q3(i.message);return cb0(F,{threadMeta:i?wU(i):void 0,agentMode:Z.mode,onFirstAssistantMessage:PI4})},validateThreadOwnership:async(i,V0)=>{if(V0?.nonBlockingOwnershipCheck){CI4(i,G.configService).catch((U0)=>{if(U0 instanceof z4){if(V0.onOwnershipError){V0.onOwnershipError(U0,i);return}iP(U0,i);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})});return}try{await CI4(i,G.configService)}catch(U0){if(U0 instanceof z4)throw U0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:PI4},A=async(i,V0)=>{try{if(i==="dtw")return yi5({userEmail:V0?.dtwUserEmail??B,ampURL:J.ampURL,configService:G.configService,threadService:G.threadService,mcpService:G.mcpService,toolService:G.toolService,skillService:G.skillService,fileSystem:G.fileSystem,threadId:Z.threadId});return _q4(M,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(U0){if(U0 instanceof z4)throw U0;throw await iP(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.
|
|
7345
|
-
`),await Zq(),process.exit(1);let j=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await G.configService.getLatest(),V0=lv(i),U0=await T6.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(V0)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(i){P.error("Failed to fetch free tier status:",i);return}})(),S=!J.executeMode?new bu0:null,y,h=null;if(S)y=S,h=(async()=>{let i=q?await G.serverStatusPromise:G.serverStatus;await dd0(Q,Z,i);let V0=process.hrtime.bigint(),U0=cd0(Z.dtw,i),N0=L5(i)?i.user.email:void 0,Y0=await A(U0?"dtw":"worker",{dtwUserEmail:N0});if(Y("runMainThread:createThreadPool",V0),S.attach(Y0),U){let H0=await L1(Y0.threadHandles$);if(!H0)throw new z4("No active thread is available yet.",1);await H0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(i)=>{let V0=i instanceof Error?i:Error(String(i));S.setInitError(V0),await iP(i,Z.threadId)});else D=process.hrtime.bigint(),y=await A(E?"dtw":"worker"),Y("runMainThread:createThreadPool",D);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;D=process.hrtime.bigint();let k=await G.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),_i5({configService:G.configService,threadService:G.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(t1((i)=>{if(!i)return v0.of({});return t6(i.thread$,i.threadViewState$).pipe(B1(([V0,U0])=>({[V0.id]:U0})))}))}),Y("runMainThread:createCliNotificationService",D),J.executeMode){if(CX4(G.mcpService,J.settings),!(y instanceof CC))throw new z4("Execute mode is not supported with the DTW thread pool",1);let i=y.getWorkerForExecuteMode();if(await kZ4({worker:i,threadID:i.threadID,userInput:U,stdinInput:V,dependencies:G,streamJson:K,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:O,agentMode:Z.mode,labels:Z.label}),Z.archive)await T6.archiveThread({thread:i.threadID,archived:!0},{config:G.configService});await G.asyncDispose(),process.exit(0)}let x=!1,g=!1,a=!1;if(Z.jetbrains||Z.ide){await xM1();let i=pw({jetbrainsOnly:Z.jetbrains});if(i.length===0){if(Z.jetbrains)g=!await G.configService.get("jetbrains.skipInstall")}else if(i.length===1){let V0=i[0];if(V0)_8.selectConfig(V0)}else a=!0}D=process.hrtime.bigint();let m=Qu0("0.0.
|
|
7346
|
-
`);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 X=await nk1({get:async(K)=>{if(K!==my)return;try{let D=await _I4(pd0,"utf-8");return JSON.parse(D).installationID}catch{return}},set:async(K,D)=>{if(K!==my)return;await Ni5(gp.dirname(pd0),{recursive:!0}),await Oi5(pd0,JSON.stringify({installationID:D},null,2),{mode:384})}},{clientType:"cli",platform:dQ()});BM1(X);let Y=await PQ4({...J,workspaceTrust:{current:!0,changes:Tv},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 RX4(J.mcpConfig);Y=PX4(Y,K)}let U=gp.dirname(Y.getSettingsFilePath());l84(oP,U);let V=await Y.get("url","global");if(!V)V=o9;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:Y.getSettingsFilePath(),workspaceRoot:Y.getWorkspaceRootPath()}),!hG(V))P.info("Targeting custom Amp server",{ampURL:V});return Y=YM1(Y),{executeMode:Z,isTTY:Q,ampURL:V,settings:Y,secrets:cX4(await hy0(J,Y))}}function fi5(J){let Z={};for(let Q=0;Q<J.length;Q++){let X=J[Q];if(X?.startsWith("--")){let U=X.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 bi5(){u94();let J=fi5(process.argv),Z=process.argv.includes("--headless")||process.argv.some((U)=>U.startsWith("--headless="));aJ4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Li5:void 0)});let Q=process.argv.includes("--no-color"),X=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!X&&!Y)Z1.level=0;if(Mi5(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7345
|
+
`),await Zq(),process.exit(1);let j=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await G.configService.getLatest(),V0=lv(i),U0=await T6.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(V0)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(i){P.error("Failed to fetch free tier status:",i);return}})(),S=!J.executeMode?new bu0:null,y,h=null;if(S)y=S,h=(async()=>{let i=q?await G.serverStatusPromise:G.serverStatus;await dd0(Q,Z,i);let V0=process.hrtime.bigint(),U0=cd0(Z.dtw,i),N0=L5(i)?i.user.email:void 0,Y0=await A(U0?"dtw":"worker",{dtwUserEmail:N0});if(Y("runMainThread:createThreadPool",V0),S.attach(Y0),U){let H0=await L1(Y0.threadHandles$);if(!H0)throw new z4("No active thread is available yet.",1);await H0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(i)=>{let V0=i instanceof Error?i:Error(String(i));S.setInitError(V0),await iP(i,Z.threadId)});else D=process.hrtime.bigint(),y=await A(E?"dtw":"worker"),Y("runMainThread:createThreadPool",D);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;D=process.hrtime.bigint();let k=await G.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),_i5({configService:G.configService,threadService:G.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(t1((i)=>{if(!i)return v0.of({});return t6(i.thread$,i.threadViewState$).pipe(B1(([V0,U0])=>({[V0.id]:U0})))}))}),Y("runMainThread:createCliNotificationService",D),J.executeMode){if(CX4(G.mcpService,J.settings),!(y instanceof CC))throw new z4("Execute mode is not supported with the DTW thread pool",1);let i=y.getWorkerForExecuteMode();if(await kZ4({worker:i,threadID:i.threadID,userInput:U,stdinInput:V,dependencies:G,streamJson:K,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:O,agentMode:Z.mode,labels:Z.label}),Z.archive)await T6.archiveThread({thread:i.threadID,archived:!0},{config:G.configService});await G.asyncDispose(),process.exit(0)}let x=!1,g=!1,a=!1;if(Z.jetbrains||Z.ide){await xM1();let i=pw({jetbrainsOnly:Z.jetbrains});if(i.length===0){if(Z.jetbrains)g=!await G.configService.get("jetbrains.skipInstall")}else if(i.length===1){let V0=i[0];if(V0)_8.selectConfig(V0)}else a=!0}D=process.hrtime.bigint();let m=Qu0("0.0.1772496276-ge2fd2b",G.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let l=new MI0(G.threadStorage);Y("runMainThread:createThreadFuzzyIndexer",D),D=process.hrtime.bigint();let d=new Uu0(G.mcpService,J.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),U&&J.executeMode){let i=await L1(y.threadHandles$);if(!i)throw new z4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:U}]})}D=process.hrtime.bigint();let $0=await fK();Y("runMainThread:loadSessionState",D),P.info("Loaded session state:",$0);let B0={...$0,launchCount:$0.launchCount+1};bK(B0);try{if(D=process.hrtime.bigint(),await hG4({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new Ay0,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadFuzzyIndexer:l,skillService:G.skillService,configService:G.configService,secretStorage:G.secretStorage,internalAPIClient:T6,initialServerStatus:G.serverStatus,hasAPIKeyAtStartup:G.hasAPIKeyAtStartup,ampURL:J.ampURL,threadPool:y,ideClient:_8,mcpService:G.mcpService,toolboxService:G.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:B0,freeTierStatusPromise:j,workspace:N??null,features:w,isDogfooding:O,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-03T00:10:30.790Z",pluginPlatform:G.pluginPlatform,pluginService:G.pluginService},(i)=>new Bh0({...i,threadPool:i.threadPool},(V0)=>new Wp0({...V0,threadState:V0.threadState}))),Y("runMainThread:mountApp-returned",D),h)await h}finally{}await G.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function M3(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.
|
|
7346
|
+
`);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 X=await nk1({get:async(K)=>{if(K!==my)return;try{let D=await _I4(pd0,"utf-8");return JSON.parse(D).installationID}catch{return}},set:async(K,D)=>{if(K!==my)return;await Ni5(gp.dirname(pd0),{recursive:!0}),await Oi5(pd0,JSON.stringify({installationID:D},null,2),{mode:384})}},{clientType:"cli",platform:dQ()});BM1(X);let Y=await PQ4({...J,workspaceTrust:{current:!0,changes:Tv},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 RX4(J.mcpConfig);Y=PX4(Y,K)}let U=gp.dirname(Y.getSettingsFilePath());l84(oP,U);let V=await Y.get("url","global");if(!V)V=o9;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:Y.getSettingsFilePath(),workspaceRoot:Y.getWorkspaceRootPath()}),!hG(V))P.info("Targeting custom Amp server",{ampURL:V});return Y=YM1(Y),{executeMode:Z,isTTY:Q,ampURL:V,settings:Y,secrets:cX4(await hy0(J,Y))}}function fi5(J){let Z={};for(let Q=0;Q<J.length;Q++){let X=J[Q];if(X?.startsWith("--")){let U=X.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 bi5(){u94();let J=fi5(process.argv),Z=process.argv.includes("--headless")||process.argv.some((U)=>U.startsWith("--headless="));aJ4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Li5:void 0)});let Q=process.argv.includes("--no-color"),X=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!X&&!Y)Z1.level=0;if(Mi5(P),P.info("Starting Amp CLI.",{version:"0.0.1772496276-ge2fd2b",buildTimestamp:"2026-03-03T00:10:30.790Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new z4(Y8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await ki5().parseAsync(process.argv)}d84().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await bi5().catch(iP)});async function hi5(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"),s6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7347
7347
|
`);else if(!hG(J.ampURL))s6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7348
7348
|
`);let X=process.env.AMP_API_KEY;if(X)s6.write(`API key found in environment variable, storing...
|
|
7349
7349
|
`),await Z.set("apiKey",X,J.ampURL),s6.write(`API key successfully stored.
|