@sourcegraph/amp 0.0.1772502119-g224ee4 → 0.0.1772503238-g61db4a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. 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.1772502119-g224ee4"),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.
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.1772503238-g61db4a"),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.1772502119-g224ee4"):await g30("0.0.1772502119-g224ee4",WE());if(!X){let U=Zu0("0.0.1772502119-g224ee4"),V=U?.age?`released ${U.age} ago`:`built ${DF(new Date("2026-03-03T01:47:49.598Z"))} ago`;xK.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1772502119-g224ee4"} (${V})
5908
- `));let K=await pW("0.0.1772502119-g224ee4");if(K.warning)xK.write(`
5907
+ `));let{hasUpdate:X,latestVersion:Y}=ny0()?await p30("0.0.1772503238-g61db4a"):await g30("0.0.1772503238-g61db4a",WE());if(!X){let U=Zu0("0.0.1772503238-g61db4a"),V=U?.age?`released ${U.age} ago`:`built ${DF(new Date("2026-03-03T02:06:20.819Z"))} ago`;xK.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1772503238-g61db4a"} (${V})
5908
+ `));let K=await pW("0.0.1772503238-g61db4a");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.1772502119-g224ee4";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(`
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.1772503238-g61db4a";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(`
@@ -6633,7 +6633,7 @@ Available parameters:`),q.push(JL5(Z));return q.join(`
6633
6633
  See https://ampcode.com/manual#toolboxes`);return Z[0]||pM}function rY4(J,Z){let Q=J.command("tools").alias("tool").description("Tool management commands");return UL5(Q,Z),VL5(Q,Z),KL5(Q,Z),DL5(Q,Z),Q}function UL5(J,Z){J.command("list").alias("ls").description("List all active tools (including MCP tools)").option("--inspect","Include full tool schemas and the effective system prompt").option("--json","output as a single JSON array").option("--mode <mode>","filter tools by agent mode (default: smart)","smart").action(async(Q,X)=>{let Y=X.optsWithGlobals(),U=await Z(X,Y),V=Y.sp||Y.systemPrompt;if(Y.inspect&&V){let D=L5(U.serverStatus)?U.serverStatus.features.some((G)=>G.name===MY.HARNESS_SYSTEM_PROMPT&&G.enabled):!1,z=L5(U.serverStatus)?U.serverStatus.user.email:void 0;if(!D&&!(z&&pQ(z)))process.stderr.write(`You are not allowed to do this.
6634
6634
  `),await U.asyncDispose(),U.cleanupTerminal(),process.exit(1);let q=await XL5(V,"utf-8").catch(()=>V);N7("systemPrompt",q)}let K=0;await mY4({json:Y.json,inspect:Y.inspect,isTTY:U.context.isTTY,mode:Y.mode,toolService:U.toolService,configService:U.configService,mcpService:U.mcpService,skillService:U.skillService,threadService:U.threadService,fileSystem:U.fileSystem,getThreadEnvironment:U.getThreadEnvironment,serverStatus:U.serverStatus,toolboxService:U.toolboxService,stderr:process.stderr,stdout:process.stdout,exit:(D)=>{K=D}}),await U.asyncDispose(),U.cleanupTerminal(),process.exit(K)})}function VL5(J,Z){J.command("show").argument("<tool>","The tool for which to show details").description("Show details about an active tool").option("--json","output as a single JSON object").option("--mode <mode>","filter tools by agent mode (default: smart)","smart").action(async(Q,X,Y)=>{let U=Y.optsWithGlobals(),V=await Z(Y,U),K=0,D=V.toolService;await cY4({toolName:Q,json:U.json,isTTY:V.context.isTTY,mode:U.mode,toolService:D,mcpService:V.mcpService,stdout:process.stdout,exit:(z)=>{K=z}}),await V.asyncDispose(),V.cleanupTerminal(),process.exit(K)})}function KL5(J,Z){J.command("make").argument("<tool-name>","A descriptive name like run-tests or build-project").description("Sets up a skeleton tool in your toolbox").option("--force","Overwrite an existing tool if it already exists").option("--bun","Create a Bun/TypeScript tool (default)").option("--zsh","Create a Zsh shell script tool").option("--bash","Create a Bash shell script tool").action(async(Q,X,Y)=>{let U="bun";if(X.zsh)U="zsh";else if(X.bash)U="bash";else if(X.bun)U="bun";try{let V=YL5();await dY4({fs:pY4,toolName:Q,toolboxDir:V,force:X.force,language:U,stdout:process.stdout,exit:process.exit})}catch(V){process.stdout.write(`${V instanceof Error?V.message:String(V)}
6635
6635
  `),process.exit(1)}})}function DL5(J,Z){let Q=[Z1.bold("Examples:"),""," # invoke the Read tool for README.md and the first ten lines"," amp tools use Read --path $PWD/README.md --read_range 0 --read_range 10",""," # invoke web_search with JSON input",` amp tools use web_search <<<'{"query":"Svelte 5"}'`,""," # invoke a toolbox tool"," amp tools use tb__run_test --workspace server","",`Use ${Z1.green("amp tools list")} to get a list of all tools available in this environment.`,"",`Use ${Z1.green("amp tools show <tool-name>")} to see the schema of a tool.`].join(`
6636
- `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Q).option("--only <field>","Extract only the specified field from the result").option("--stream","Stream updates as they arrive instead of waiting for completion").allowUnknownOption(!0).allowExcessArguments(!0).action(async(X,Y,U)=>{let V=U.optsWithGlobals(),K=await Z(U,V),D=0,z=U.args.slice(1),q;if(aY4()){let G=[];for await(let F of process.stdin)G.push(F);q=Buffer.concat(G).toString("utf-8").trim()}await iY4({toolName:X,rawArgs:z,stdinInput:q,only:Y.only,stream:Y.stream,threadDeps:K,stdout:process.stdout,stderr:process.stderr,exit:(G)=>{D=G}}),await K.asyncDispose(),K.cleanupTerminal(),process.exit(D)})}f4();W1();function K80(J){return{get thread$(){return J.thread$},get threadViewState$(){return J.threadViewState$},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},sendMessage:J.sendMessage,editMessage:J.editMessage,restoreMessage:J.restoreMessage,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}function zL5(J){return{id:J,created:Date.now(),v:0,messages:[]}}class bu0{placeholderThreadID;recentThreadIDsSubject=new B4([]);threadTitlesSubject=new B4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new B4({});attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=J8()){this.placeholderThreadID=J;let Z=new B4(zL5(this.placeholderThreadID)),Q=new B4(qK(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new B4(K80({thread$:Z,threadViewState$:Q,pendingApprovals$:new B4([]),pendingSkills$:new B4([]),sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),editMessage:async(X)=>(await this.waitForActiveHandle()).editMessage(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},resolveApproval:async(X,Y,U)=>(await this.waitForActiveHandle()).resolveApproval(X,Y,U),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,Y)=>{this.readyResolve=X,this.readyReject=Y})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return"disconnected";return this.attachedPool.getTransportConnectionState()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J,this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Z)=>this.recentThreadIDsSubject.next(Z)),J.threadTitles$.subscribe((Z)=>this.threadTitlesSubject.next(Z)),J.allConnectedThreadActivityStatuses$.subscribe((Z)=>this.allConnectedThreadActivityStatusesSubject.next(Z)),J.threadHandles$.subscribe((Z)=>{if(Z)this.threadHandlesSubject.next(Z)})],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async createSystemPromptDeps(){return(await this.waitForAttach()).createSystemPromptDeps()}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return L1(J.threadHandles$.pipe(k5((Z)=>Z!==null)))}}h0();s60();MC0();W1();h0();I$();W1();async function z80(J,Z,Q){let X=await F8("/api/durable-thread-workers",tY4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J?{threadId:J}:{})},Q),Z);if(!X.ok)throw Error(`Failed to create DTW thread: ${X.status} ${await X.text()}`);let Y=await X.json();if(!Y.threadId||!Y.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");return{threadId:Y.threadId,wsToken:Y.wsToken}}async function qL5(J,Z,Q){let X=await F8(`/api/threads/${J}`,tY4(void 0,Q),Z);if(!X.ok)throw Error(`Failed to fetch thread snapshot: ${X.status} ${await X.text()}`);return await X.json()}function tY4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function D80(J){let Z=l2.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=l2.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function GL5(J){let Z=[],Q=new Set;for(let[X,Y]of J.messages.entries()){let U=D80(Y);if(U)Q.add(U);Z.push({...Y,messageId:X})}return{messages:Z,processedIds:Q}}function FL5(J){let Z=new Set;for(let Q of J){let X=D80(Q);if(X)Z.add(X)}return Z}function Im(J,Z){let Q=[...J];for(let X of Z)if(X.type==="text"){let Y=Q[Q.length-1];if(Y?.type==="text")Q[Q.length-1]={...Y,text:Y.text+X.text};else Q.push(X)}else if(X.type==="tool_use"){let Y=Q.findIndex((U)=>U.type==="tool_use"&&U.id===X.id);if(Y>=0)Q[Y]=X;else Q.push(X)}else if(X.type==="thinking"){let Y=Q[Q.length-1];if(Y?.type==="thinking")Q[Q.length-1]={...Y,thinking:Y.thinking+X.thinking};else Q.push(X)}else Q.push(X);return Q}function WL5(J,Z,Q,X){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:X}}function HL5(J,Z){let Q=J.parentToolCallId,{completedMessages:X}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;let U=J.blocks??[];if(U.length>0)if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:U,parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:U,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){let U=J.blocks;if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:U,parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:U,parentToolCallId:Q});return}let Y=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")Y=Im(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&Y.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Y,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="tool_use"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=Im([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Im(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="start"||J.state==="generating"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=Im([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Im(Z.streamingBlocks,J.blocks)}}function BL5(J,Z,Q){if(Z.length===0)return J;let X=[],Y=J.length;for(let U of Z){if(Q.has(U.messageId))continue;Q.add(U.messageId);let V=Y++;if(U.role==="assistant")X.push({role:"assistant",content:U.blocks,state:{type:"complete",stopReason:"end_turn"},messageId:V,dtwMessageID:U.messageId,parentToolUseId:U.parentToolCallId});else X.push({role:"user",content:U.blocks,messageId:V,dtwMessageID:U.messageId,parentToolUseId:U.parentToolCallId})}if(X.length===0)return J;return[...J,...X]}function wL5(J,Z,Q){let X=J.message.messageId;if(Q.has(X))return Z;Q.add(X);let Y=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},messageId:Y,dtwMessageID:X,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,userState:J.message.userState,messageId:Y,dtwMessageID:X,parentToolUseId:J.parentToolUseId}]}function NL5(J,Z){let Q=Z.findIndex((K)=>D80(K)===J.messageId),X=Z.findIndex((K)=>D80(K)===J.truncateToMessageId);if(Q<0||X<0)throw Error("Unable to apply edit: message mapping not found");let Y=Z[Q];if(!Y||Y.role!=="user")throw Error("Unable to apply edit: target message is not editable");let U={role:"user",content:J.content,messageId:Y.messageId,dtwMessageID:J.messageId},V=Z.slice(0,X+1);return V[Q]=U,V}function Mm(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function sY4(J){let Z=J.queuedMessage,Q=Z.content.map((X)=>({...X}));return{id:J.id,queuedMessage:{role:"user",content:Q,userState:Z.userState,meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:J.id}}}function OL5(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>sY4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:sY4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function EL5(J,Z){let Q=OL5(Z);return Ly0(Mm(J)??[],Q,{dedupeAdded:!0})}function LL5(J){if(!J||J.length===0)return[];return J.map((Z)=>Z.id)}function IL5(J,Z){return{baseURL:J.workerUrl??Qq(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>z80(Z.threadId,J.configService,J.apiKey),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}class q80{threadSubject;editErrorSubject=new Y4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};subscriptions=[];threadVersion;messages;queuedMessages;threadTitle;processedIds;agentLoopState="idle";contextWindowRatio=null;lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,X){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Mm(J.queuedMessages)??[],this.processedIds=Q,this.transport=Z,this.threadVersion=X,this.threadSubject=new B4(J)}static async create(J){let Z=await z80(J.threadId,J.configService,J.apiKey),Q=await qL5(Z.threadId,J.configService,J.apiKey),{messages:X,processedIds:Y}=GL5(Q),U={...Q,id:Z.threadId,messages:X,queuedMessages:Mm(Q.queuedMessages)},V=new fW(IL5(J,Z)),K=new q80(U,V,Y,Q.v);return await K.connect(),K}threadChanges(){return this.threadSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getContextWindowRatio(){return this.contextWindowRatio}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;this.threadSubject.next({...Z,...{env:J}})}setAgentMode(J){if(!J)return;let Z=this.threadSubject.getValue();if(Z.agentMode)return;this.threadSubject.next({...Z,agentMode:J})}emitThread(){let J=this.threadSubject.getValue(),Z=WL5(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),Q=Z?[...this.messages,Z]:[...this.messages],X=Q.reduce((U,V)=>Math.max(U,V.messageId),-1)+1,Y={...J,id:this.threadId,v:this.threadVersion,title:this.threadTitle,messages:Q,queuedMessages:this.queuedMessages.length>0?Mm(this.queuedMessages):void 0,nextMessageId:Math.max(X,0)};this.threadSubject.next(Y)}runTransportHandler(J,Z){try{Z()}catch(Q){let X=Q instanceof Error?Q.message:String(Q);P.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${X}`)}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionInfo,Q=J.state!==this.lastConnectionState,X=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!X)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(X&&Z)this.logConnectionRoleTransition(Z,J);let Y=J.state;if(Y==="connected"&&this.lastConnectionState!=="connected")this.transport.resumeFromVersion(this.threadVersion);this.lastConnectionState=Y,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{if(P.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:J.message}),J.code==="PARSE_ERROR")this.editErrorSubject.next("Received an invalid DTW message. The connection will continue running.")})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state})}}),this.transport.deltas().subscribe({next:(J)=>{this.runTransportHandler("deltas",()=>{if(J.usage?.contextWindowRatio!==void 0){let Z=J.usage.contextWindowRatio;this.contextWindowRatio=Number.isFinite(Z)&&Z>=0&&Z<=1?Z:null}if(HL5(J,this.deltaState),this.deltaState.completedMessages.length>0)this.messages=BL5(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[];this.emitThread()})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{if(this.messages=wL5(J,this.messages,this.processedIds),this.deltaState.streamingMessageId===J.message.messageId)this.deltaState.streamingMessageId=null,this.deltaState.streamingBlocks=[],this.deltaState.streamingParentToolCallId=void 0;this.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{this.messages=NL5(J,this.messages),this.processedIds=FL5(this.messages),this.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.threadTitles().subscribe({next:(J)=>{this.runTransportHandler("threadTitles",()=>{this.threadTitle=J.title??void 0,this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=EL5(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,role:Z.role,clientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion};if(Z.state==="connected"){if(J==="reconnecting"){P.info("[dtw] Transport reconnected",Q);return}P.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){P.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){P.warn("[dtw] Transport disconnected",Q);return}P.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){P.info("[dtw] Transport role changed",{threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,fromClientId:J.clientId,toClientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion})}async connect(){this.subscribeToTransport(),await this.transport.connect(),this.emitThread()}sendUserMessage(J,Z,Q,X){this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q})}discardQueuedMessages(){let J=Mm(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=LL5(this.queuedMessages);this.queuedMessages=[],this.emitThread();try{for(let Q of Z)this.transport.removeQueuedMessage(Q)}catch(Q){throw this.queuedMessages=J??[],this.emitThread(),Q}}resumeFromVersion(J){this.transport.resumeFromVersion(J)}dispose(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.transport.dispose()}}h0();g5();u9();TJ();f4();Iz();KS0();W1();class hu0{threadWriter;deps;thread$;threadViewState$;pendingApprovals$;provider;threadSubject;threadViewStateSubject;providerSubscription=null;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;runnerClient;handshakeManager;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new B4([]);pendingSkillsSubject=new B4([]);pendingSkills$=this.pendingSkillsSubject;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let X=WW0("info"),Y=WW0("error");this.toolRunner=new th({executeBuiltinTool:()=>null,invokeTool:(U,V)=>this.invokeToolForLease(V),batchGuidanceFiles:T30,renderToolRunError:Mx,log:{info:(U,V)=>X(U,V),error:(U,V)=>Y(U,{error:V}),wsMessage:(U,V,K)=>{P.debug("DTW executor tool runner message",{direction:U,clientID:V,...typeof K==="object"&&K!==null?K:{message:K}})}}}),this.runnerClient=this.toolRunner.addClient(this.clientID,this.provider.transport),this.handshakeManager=this.createHandshakeManager(),this.threadSubject=new B4(this.threadWriter.read()),this.thread$=this.threadSubject,this.threadViewStateSubject=new B4(qK(this.threadWriter.read(),{state:"active",inferenceState:ML5(J)?"running":"idle",fileChanges:{files:[]}})),this.threadViewState$=this.threadViewStateSubject,this.pendingApprovals$=this.pendingApprovalsSubject,this.attachTransportHandlers(),this.handshakeManager.ensureHandshake("connect")}startProviderSubscription(J){this.providerSubscription?.unsubscribe(),this.providerSubscription=this.provider.threadChanges().subscribe({next:(Z)=>{J(Z)}})}readThread(){return this.threadWriter.read()}writeThread(J){this.threadWriter.write(J),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}setThreadViewState(J){this.threadViewStateSubject.next(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getResolvedTokenUsage(){let J=e7(this.threadWriter.read());if(J)return J;let Z=this.provider.getContextWindowRatio();if(Z===null)return;return{maxInputTokens:1,inputTokens:Z,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,totalInputTokens:Z}}async dispose(){this.providerSubscription?.unsubscribe(),this.providerSubscription=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.handshakeManager.dispose(),this.toolRunner.removeClient(this.clientID),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),this.threadSubject.complete(),this.threadViewStateSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){if(J.editIndex!==void 0){await this.handshakeManager.ensureReady();let U=this.threadWriter.read().messages[J.editIndex];if(!U||U.role!=="user"||!U.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let V=J.content.filter((K)=>K.type==="text"||K.type==="image");this.provider.transport.editUserMessage(U.dtwMessageID,V,Wy0(),J.agentMode);return}await this.handshakeManager.ensureReady();let Z=this.threadWriter.read();if(!Z.messages.some((Y)=>Y.role==="user")&&!Z.agentMode&&J.agentMode)this.updateThread((Y)=>{Y.agentMode=J.agentMode});let X=await this.collectUserState();this.provider.sendUserMessage(J.content,J.agentMode,X)}async editMessage(J){await this.handshakeManager.ensureReady();let X=[...this.threadWriter.read().messages.slice(0,J+1)].reverse().find((U)=>U.role==="user");if(!X?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let Y=X.content.filter((U)=>U.type==="text"||U.type==="image").map((U)=>{if(U.type==="image")return{...U,source:{...U.source}};return{...U}});if(Y.length===0)throw Error("Unable to edit message: no editable content found");this.provider.transport.editUserMessage(X.dtwMessageID,Y,Wy0())}async queueMessage(J){await this.handshakeManager.ensureReady();let Z=await this.collectUserState();this.provider.sendUserMessage(J,void 0,Z)}async discardQueuedMessages(){this.provider.discardQueuedMessages()}async setVisibility(J){let Z=await T6.setThreadMeta({thread:this.provider.threadId,meta:wU(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}updateThread(J){this.threadWriter.update(J),this.threadSubject.next(this.threadWriter.read())}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}dismissEphemeralError(){}async resolveApproval(J,Z,Q){let X=O9.safeParse(J);if(!X.success)return;this.provider.transport.resolveToolApproval(X.data,Z)}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.threadWriter.read();return(await pV({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((X)=>({uri:X.uri,type:X.type}))}async getFilesAffectedByTruncation(J){let Z=this.threadWriter.read(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((U)=>{if(U.role==="user"){for(let V of U.content)if(V.type==="tool_result")Q.add(V.toolUseID)}else for(let V of U.content)if(V.type==="tool_use")Q.add(V.id)});let X=new Set,Y=await this.deps.fs.tracker.getAllRecords();for(let[U]of Y.entries())if(!Q.has(U))X.add(U);return X}async collectUserState(){try{return await VS0()??Ix}catch(J){return P.warn("Failed to collect IDE user state for DTW message",{error:J}),Ix}}createHandshakeManager(){return new sh({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{P.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){P.error("DTW executor handshake exhausted",J)}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{this.handshakeManager.handleConnectionChange(J)}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(this.clientID,J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(this.clientID,J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}))}async sendExecutorHandshake(J){P.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,await _30({transport:this.provider.transport,executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,sendGitSnapshot:!1,executorType:"local-client"}),this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Z)=>{this.lastSentSettingsJSON=S30(this.provider.transport,Z,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await $Q();this.provider.setEnvironment({initial:J})}catch(J){P.debug("Failed to apply local environment",{error:J})}}async invokeToolForLease(J){let Z=await mW({toolName:J.toolName,threadID:this.provider.threadId,configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.runnerClient.discoveredGuidanceFileURIs}),Q=typeof J.args==="object"&&J.args!==null?J.args:{};return this.deps.toolService.invokeLeasedTool(J.toolName,{args:Q},Z)}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(this.clientID,J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z))}}function ML5(J){return J.willQueueNextUserMessage()}class Am{deps;recentThreadIDsSubject=new B4([]);threadTitlesSubject=new B4({});activeThreadHandleSubject=new B4(null);allConnectedThreadActivityStatusesSubject=new B4({});threadHandleMap=new Map;activeThreadContextID;constructor(J){this.deps=J}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get activeThreadHandle(){let J=this.threadHandleMap.get(this.activeThreadContextID);if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){return this.threadHandleMap.get(this.activeThreadContextID)?.provider}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}async createThread(J){await this.activateThread(J)}async switchThread(J){await this.activateThread(J)}async createHandoff(J,Z){let Q=await this.deps.threadService.get(J,Z.signal);if(!Q)throw Error("No thread available for handoff");if(!Q.env?.initial){let K=await this.deps.getThreadEnvironment();Q={...Q,env:{initial:K}}}let X=Z.signal??new AbortController().signal,Y=await cR(Q,Z.goal,Z.images,this.deps.configService,X,this.deps.osFileSystem),U=mu0(Z.queuedMessages??Q.queuedMessages),{threadID:V}=await this.createThreadWithDraft({parentThreadID:Q.id,agentMode:Z.agentMode??Q.agentMode,draft:Y,queuedMessages:U,comment:Z.goal,parentMessageIndex:Q.messages.length>0?Q.messages.length-1:void 0});return V}async createSystemPromptDeps(){return{toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService}}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();this.threadHandleMap.clear(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J){P.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Z=J?this.threadHandleMap.get(J):void 0;if(Z){let V=Z.readThread().id;this.activeThreadContextID=V,this.activeThreadHandleSubject.next(Z),this.addToRecentThreads(V),this.updateThreadViewState(V,Z.readThread()),P.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:V,handleCount:this.threadHandleMap.size});return}let Q=await this.createProvider(J),X=await this.deps.threadService.exclusiveSyncReadWriter(Q.threadId),Y=OP({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q.threadId),U=new hu0(Q,X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,fs:Y,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService});U.startProviderSubscription((V)=>{this.applyProviderState(Q.threadId,V)}),this.threadHandleMap.set(Q.threadId,U),await this.applyProviderState(Q.threadId,Q.getThread()),this.activeThreadContextID=Q.threadId,this.activeThreadHandleSubject.next(U),this.addToRecentThreads(Q.threadId),P.info("[dtw-thread-pool] activateThread:created",{activeThreadID:Q.threadId,handleCount:this.threadHandleMap.size})}async applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let X=AL5(Q.readThread(),Z);Q.writeThread(X),await this.deps.threadService.flushVersion(J,X.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J]:X.title}),this.updateThreadViewState(J,X)}updateThreadViewState(J,Z){let Q=this.threadHandleMap.get(J),X={state:"active",inferenceState:Q?.provider.willQueueNextUserMessage()?"running":"idle",fileChanges:{files:[]}},Y=qK(Z,X);Q?.setThreadViewState(Y),this.syncAllConnectedThreadActivityStatuses()}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}async createProvider(J){return q80.create({ampURL:this.deps.ampURL,configService:this.deps.configService,threadId:J,workerUrl:process.env.AMP_WORKER_URL})}async getApiKey(){let J=await this.deps.configService.getLatest();return J.secrets.getToken("apiKey",J.settings.url)}async createThreadWithDraft(J){let{threadId:Z}=await z80(void 0,this.deps.configService,await this.getApiKey()),Q=await this.deps.threadService.exclusiveSyncReadWriter(Z),X=Date.now(),Y=J.parentThreadID?[{threadID:J.parentThreadID,type:"handoff",role:"child",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X}]:void 0,U={id:Z,created:X,v:1,agentMode:J.agentMode,messages:[],draft:J.draft,autoSubmitDraft:!0,queuedMessages:mu0(J.queuedMessages),env:{initial:await this.deps.getThreadEnvironment()},relationships:Y};if(Q.write(U),await this.deps.threadService.flushVersion(Z,U.v).catch(()=>{return}),await Q.asyncDispose(),J.parentThreadID){let V=(D)=>{if(!D.relationships)D.relationships=[];if(!D.relationships.some((q)=>q.threadID===Z&&q.type==="handoff"&&q.role==="parent"))D.relationships.push({threadID:Z,type:"handoff",role:"parent",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X})},K=this.threadHandleMap.get(J.parentThreadID);if(K)K.updateThread((D)=>{V(D)});else{let D=await this.deps.threadService.exclusiveSyncReadWriter(J.parentThreadID);D.update((z)=>{V(z)}),await D.asyncDispose()}}return{threadID:Z}}}function mu0(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function AL5(J,Z){let Q=Z.messages.reduce((X,Y)=>Math.max(X,Y.messageId),-1)+1;return{...Z,draft:Z.draft??J.draft,autoSubmitDraft:Z.autoSubmitDraft??J.autoSubmitDraft,env:Z.env??J.env,queuedMessages:mu0(Z.queuedMessages),nextMessageId:Math.max(Q,0)}}vu0();import{readFile as QS5}from"node:fs/promises";import XS5 from"node:readline";import{setTimeout as YS5}from"node:timers/promises";O3();I$();Nj();f4();ez();W1();import{mkdir as jL5,writeFile as RL5}from"node:fs/promises";import PL5 from"node:path";function CL5(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function TL5(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function _L5(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${TL5(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function gu0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class pu0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=CL5(J.traceName),X=_L5(Z,Q);this.traceFilePath=PL5.join(J.traceDir,`${X}.json`),this.session={schemaVersion:1,sessionID:X,createdAt:Z,runtimeMode:J.runtimeMode,...Q?{traceName:Q}:{},threadId:J.threadId,scriptedCommands:[...J.scriptedCommands??[]],protocolEvents:[],providerStateEvents:[],adapterStateEvents:[],commandEvents:[],timeline:[]}}nextTimelineIndex(){return this.session.timeline.length}recordProtocolEvent(J,Z){let Q=this.nextTimelineIndex(),X=Date.now(),Y={timelineIndex:Q,timestamp:X,eventName:J,payload:gu0(Z)};this.session.protocolEvents.push(Y),this.session.timeline.push({timelineIndex:Q,timestamp:X,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),X=Date.now(),Y={timelineIndex:Q,timestamp:X,reason:J,state:gu0(Z)};this.session.providerStateEvents.push(Y),this.session.timeline.push({timelineIndex:Q,timestamp:X,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),X=Date.now(),Y={timelineIndex:Q,timestamp:X,reason:J,state:gu0(Z)};this.session.adapterStateEvents.push(Y),this.session.timeline.push({timelineIndex:Q,timestamp:X,kind:"adapter_state",adapterStateIndex:this.session.adapterStateEvents.length-1})}recordCommand(J){let Z=this.nextTimelineIndex(),Q=Date.now();this.session.commandEvents.push({timelineIndex:Z,timestamp:Q,command:J}),this.session.timeline.push({timelineIndex:Z,timestamp:Q,kind:"command",commandIndex:this.session.commandEvents.length-1})}async flush(){await jL5(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await RL5(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function eY4(J,Z){let Q=[J.connectionChanges().subscribe({next:(X)=>Z("connection_changes",X)}),J.errors().subscribe({next:(X)=>Z("errors",X)}),J.errorEvents().subscribe({next:(X)=>Z("error_events",X)}),J.agentStates().subscribe({next:(X)=>Z("agent_states",X)}),J.deltas().subscribe({next:(X)=>Z("deltas",X)}),J.messageEvents().subscribe({next:(X)=>Z("message_events",X)}),J.messageEdited().subscribe({next:(X)=>Z("message_edited",X)}),J.editRejected().subscribe({next:(X)=>Z("edit_rejected",X)}),J.threadTitles().subscribe({next:(X)=>Z("thread_titles",X)}),J.queuedMessages().subscribe({next:(X)=>Z("queued_messages",X)}),J.retryEvents().subscribe({next:(X)=>Z("retry_events",X)}),J.cancelledEvents().subscribe({next:(X)=>Z("cancelled_events",X)}),J.toolLeases().subscribe({next:(X)=>Z("tool_leases",X)}),J.toolLeaseRevoked().subscribe({next:(X)=>Z("tool_lease_revoked",X)}),J.toolApprovalQueue().subscribe({next:(X)=>Z("tool_approval_queue",X)}),J.executorToolApprovalResponses().subscribe({next:(X)=>Z("executor_tool_approval_responses",X)}),J.toolProgress().subscribe({next:(X)=>Z("tool_progress",X)}),J.executorErrors().subscribe({next:(X)=>Z("executor_errors",X)}),J.executorConnected().subscribe({next:(X)=>Z("executor_connected",X)}),J.executorRollbackRequests().subscribe({next:(X)=>Z("executor_rollback_requests",X)}),J.observers().subscribe({next:(X)=>Z("observers",X)}),J.executorStatuses().subscribe({next:(X)=>Z("executor_statuses",X)}),J.environmentUpdates().subscribe({next:(X)=>Z("environment_updates",X)}),J.gitStatuses().subscribe({next:(X)=>Z("git_statuses",X)}),J.compactionEvents().subscribe({next:(X)=>Z("compaction_events",X)}),J.compactionRecords().subscribe({next:(X)=>Z("compaction_records",X)})];return{unsubscribe:()=>{for(let X of Q)X.unsubscribe()}}}f4();N4();OJ();function UC(J,Z){let Q=(D)=>D===B7||D===c3||D===BZ||D===U9,X=new Map;for(let D of J)if(D.type==="toolResult"&&Q(D.toolUse.name))X.set(D.toolUse.id,{toolUseId:D.toolUse.id,toolName:D.toolUse.name,toolRun:D.toolResult.run});let Y=(D,z)=>{let q=X.get(D)?.toolRun;if(!q||q.status!=="cancelled"||m8(z))return z;return{status:"cancelled",reason:"Parent subagent was cancelled"}},U=Array.from(X.values()),V={},K={};for(let{toolUseId:D,toolRun:z}of U){let q=[],G;if(z.status==="in-progress"||z.status==="done"||z.status==="error"||z.status==="cancelled")G=z.progress;if(Array.isArray(G)){let F=0;for(let W of G)if(W.tool_uses)for(let H of W.tool_uses){let B=`${D}:progress:${F++}`,w=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},N=H.normalized_name??H.tool_name;q.push({toolUse:fM(N,H.input,B),toolRun:Y(D,w)})}}V[D]=q}if(Z){let D=new Map;for(let z of Z.messages){let q=z.parentToolUseId;if(!q)continue;let G=D.get(q)??[];G.push(z),D.set(q,G)}for(let[z,q]of D){let{items:G}=Dq({id:Z.id,messages:q},{includeSubagentMessages:!0});K[z]=G.filter((F)=>F.type==="toolResult").map((F)=>({toolUse:F.toolUse,toolRun:Y(z,F.toolResult.run)}))}}for(let[D,z]of Object.entries(K))if(z.length>0)V[D]=z;return V}function Dq(J,Z){let Q=[],X=new Set;if(Z?.includeSubagentMessages)for(let[V]of J.messages.entries())X.add(V);else for(let[V,K]of J.messages.entries())if(!K.parentToolUseId)X.add(V);let Y=new Map,U=new Set;for(let[V,K]of J.messages.entries()){if(!X.has(V))continue;let D=`${K.role}-${V}`;switch(K.role){case"assistant":{let z=K.state.type==="streaming";for(let G of K.content)if(G.type==="tool_use"){if(Y.set(G.id,G),z)U.add(G.id)}if(K.content.some((G)=>G.type==="text"&&G.text.trim()||G.type==="thinking"))Q.push({type:"message",id:D,message:K});for(let G of K.content)if(G.type==="tool_use"){let F=!1;for(let W=V+1;W<J.messages.length;W++){if(!X.has(W))continue;let H=J.messages[W];if(H){for(let B of H.content)if(B.type==="tool_result"&&B.toolUseID===G.id){F=!0;break}}if(F)break}if(!F)Q.push({type:"toolResult",id:G.id,toolUse:G,toolResult:{type:"tool_result",toolUseID:G.id,run:{status:"in-progress"}}})}break}case"info":{if(K.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:D,message:K});break}case"user":{let z=K.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of K.content)if(q.type==="tool_result"){let G=Y.get(q.toolUseID)??N$(J,q.toolUseID);if(!G)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:G,toolResult:q})}if(z)Q.push({type:"message",id:D,message:K});break}}}return{items:Q}}g5();f4();ez();W1();class L3{state=[!0,!1,!0,!1,!0,!1,!0,!1];previousState=[];generation=0;maxGenerations=15;neighborMap=[[1,3,4,5,7],[0,2,4,5,6],[1,3,5,6,7],[0,2,4,6,7],[0,1,3,5,7],[0,1,2,4,6],[1,2,3,5,7],[0,2,3,4,6]];step(){let J=this.state.map((U,V)=>{let K=this.neighborMap[V].filter((D)=>this.state[D]).length;if(U)return K===2||K===3;return K===3||K===6}),Z=J.every((U,V)=>U===this.state[V]),Q=this.previousState.length>0&&J.every((U,V)=>U===this.previousState[V]);this.previousState=[...this.state],this.state=J,this.generation++;let X=J.every((U)=>!U),Y=J.filter((U)=>U).length;if(Z||Q||this.generation>=this.maxGenerations||X||Y<2){let U;do U=Array.from({length:8},()=>Math.random()>0.6);while(U.filter((V)=>V).length<3);this.state=U,this.previousState=[],this.generation=0}}toBraille(){let J=[0,1,2,6,3,4,5,7],Z=10240;for(let Q=0;Q<8;Q++)if(this.state[Q])Z|=1<<J[Q];return String.fromCharCode(Z)}}class OU{element;widget;mediaQuery;parent;constructor(J,Z,Q=void 0,X=null){this.element=J;this.widget=Z;this.mediaQuery=Q;this.parent=X}findAncestorElementOfType(J){let Z=this.element.parent;while(Z){if(Z instanceof J)return Z;Z=Z.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Z=this.element.parent;while(Z){if("state"in Z&&Z.state instanceof J)return Z.state;Z=Z.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof OE?J:void 0}return}}class d1 extends a2{createElement(){return new du0(this)}}class du0 extends YQ{_child;_context;constructor(J){super(J)}get statelessWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new OU(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let J=this.statelessWidget.build(this._context);if(this._child){if(this._child.widget===J)return;if(this._child.widget.canUpdate(J))this._child.update(J);else this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}}class UQ extends f5{forceDim;constructor({key:J,forceDim:Z,child:Q}){super({key:J,child:Q});this.forceDim=Z}static maybeOf(J){let Z=J.dependOnInheritedWidgetOfExactType(UQ);if(Z)return Z.widget;return null}static shouldForceDim(J){return UQ.maybeOf(J)?.forceDim??!1}updateShouldNotify(J){return this.forceDim!==J.forceDim}}class T4{color;border;constructor(J,Z){this.color=J;this.border=Z}}class f1{top;right;bottom;left;constructor(J,Z,Q,X){this.top=J;this.right=Z;this.bottom=Q;this.left=X}static all(J){return new f1(J,J,J,J)}static symmetric(J,Z){return new f1(Z,J,Z,J)}}class y1{color;width;style;constructor(J=I0.black,Z=1,Q="rounded"){this.color=J;this.width=Z;this.style=Q}}class c0 extends D3{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Z,width:Q,height:X,padding:Y,margin:U,decoration:V,constraints:K}={}){super({...J?{key:J}:{},...Z?{child:Z}:{}});this.width=Q,this.height=X,this.padding=Y,this.margin=U,this.decoration=V,this.constraints=K}createElement(){return new $U4(this)}createRenderObject(){return new jm(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof jm))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}}class $U4 extends mK{constructor(J){super(J)}mount(){super.mount(),this._updateForceDim()}performRebuild(){super.performRebuild(),this._updateForceDim()}_updateForceDim(){if(!this.renderObject)return;let J=new OU(this,this.widget),Z=UQ.shouldForceDim(J);if(this.renderObject instanceof jm)this.renderObject.setForceDim(Z)}}class jm extends w4{_width;_height;_padding;_margin;_decoration;_constraints;_forceDim=!1;constructor(J,Z,Q,X,Y,U){super();this._width=J;this._height=Z;this._padding=Q;this._margin=X;this._decoration=Y;this._constraints=U}setForceDim(J){if(this._forceDim!==J)this._forceDim=J,this.markNeedsPaint()}updateProperties(J,Z,Q,X,Y,U){this._width=J,this._height=Z,this._padding=Q,this._margin=X,this._decoration=Y,this._constraints=U,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;u4(!!J,"performLayout called without constraints");let Z=this._margin?.horizontal??0,Q=this._margin?.vertical??0,X=this._padding?.horizontal??0,Y=this._padding?.vertical??0,U=this._decoration?.border,V=(U?.left?1:0)+(U?.right?1:0),K=(U?.top?1:0)+(U?.bottom?1:0);this.sendDebugData({margin:this._margin,padding:this._padding,decoration:this._decoration,width:this._width,height:this._height,constraints:this._constraints});let D=this._width!==void 0||this._height!==void 0?this._constraints?.tighten({width:this._width,height:this._height})??A1.tightFor({width:this._width,height:this._height}):this._constraints,z=D?J.enforce(D):J,q=z.maxWidth-Z-X-V,G=z.maxHeight-Q-Y-K,F=new A1(Math.max(0,z.minWidth-Z-X-V),Math.max(0,q),Math.max(0,z.minHeight-Q-Y-K),Math.max(0,G)),W,H;if(this.children.length>0){let N=this.children[0];if(!(N instanceof w4))throw Error("Child must be a RenderBox");N.layout(F),W=N.size.width,H=N.size.height;let O=U?.left?1:0,E=U?.top?1:0,L=(this._margin?.left??0)+O+(this._padding?.left??0),I=(this._margin?.top??0)+E+(this._padding?.top??0);N.setOffset(L,I)}else if(F.maxWidth!==1/0&&F.maxHeight!==1/0)W=F.maxWidth,H=F.maxHeight;else W=F.minWidth,H=F.minHeight;let B,w;if(z.minWidth===z.maxWidth&&isFinite(z.maxWidth))B=z.maxWidth;else B=W+X+V+Z;if(z.minHeight===z.maxHeight&&isFinite(z.maxHeight))w=z.maxHeight;else w=H+Y+K+Q;this.setSize(z.constrain(B,w).width,z.constrain(B,w).height)}getMinIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.minWidth!==0)return this._constraints.minWidth;let Z=this._margin?.horizontal??0,Q=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),U=0;if(this.children.length>0){let V=this.children[0],K=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));U=V.getMinIntrinsicWidth(K)}return U+Z+Q+Y}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.maxWidth!==1/0)return this._constraints.maxWidth;let Z=this._margin?.horizontal??0,Q=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),U=0;if(this.children.length>0){let V=this.children[0],K=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));U=V.getMaxIntrinsicWidth(K)}if(U===1/0)return 1/0;return U+Z+Q+Y}getMinIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.minHeight!==0)return this._constraints.minHeight;let Z=this._margin?.vertical??0,Q=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),U=0;if(this.children.length>0){let K=this.children[0],D=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));U=K.getMinIntrinsicHeight(D)}let V=U+Z+Q+Y;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(V,this._constraints.maxHeight);return V}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.maxHeight!==1/0)return this._constraints.maxHeight;let Z=this._margin?.vertical??0,Q=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),U=0;if(this.children.length>0){let V=this.children[0],K=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));U=V.getMaxIntrinsicHeight(K)}if(U===1/0)return 1/0;return U+Z+Q+Y}paint(J,Z=0,Q=0){let X=Math.floor(Z+this.offset.x),Y=Math.floor(Q+this.offset.y);if(this._decoration?.color){let U={bg:this._decoration.color};J.fill(X,Y,this.size.width,this.size.height," ",U)}if(this._decoration?.border)this._paintBorder(J,X,Y);super.paint(J,Z,Q)}_paintBorder(J,Z,Q){let X=this._decoration.border,Y=this.size.width,U=this.size.height,V=(W)=>{let H={fg:W};if(this._decoration?.color)H.bg=this._decoration.color;if(this._forceDim)H.dim=!0;return H},K=(W)=>{switch(W){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},D=(W)=>{switch(W){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},z=(W,H)=>{if(W===1)return H?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"};else return H?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┏",tr:"┓",bl:"┗",br:"┛"}};if(X.top){let W=V(X.top.color),H=K(X.top.width);for(let B=0;B<Y;B++)J.setChar(Z+B,Q,H,W,1)}if(X.bottom){let W=V(X.bottom.color),H=K(X.bottom.width);for(let B=0;B<Y;B++)J.setChar(Z+B,Q+U-1,H,W,1)}if(X.left){let W=V(X.left.color),H=D(X.left.width);for(let B=0;B<U;B++)J.setChar(Z,Q+B,H,W,1)}if(X.right){let W=V(X.right.color),H=D(X.right.width);for(let B=0;B<U;B++)J.setChar(Z+Y-1,Q+B,H,W,1)}let q=X.top?.style==="rounded",G=Math.max(X.top?.width??1,X.right?.width??1,X.bottom?.width??1,X.left?.width??1),F=z(G,q);if(X.top&&X.left){let W=V(X.top.color);J.setChar(Z,Q,F.tl,W,1)}if(X.top&&X.right){let W=V(X.top.color);J.setChar(Z+Y-1,Q,F.tr,W,1)}if(X.bottom&&X.left){let W=V(X.bottom.color);J.setChar(Z,Q+U-1,F.bl,W,1)}if(X.bottom&&X.right){let W=V(X.bottom.color);J.setChar(Z+Y-1,Q+U-1,F.br,W,1)}}hitTest(J,Z,Q=0,X=0){return super.hitTest(J,Z,Q,X)}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}function Rm(J,Z,Q){return Math.min(Math.max(J,Z),Q)}class Pm{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}class EE extends Pm{flex;fit;constructor(J=0,Z="tight"){super();this.flex=J,this.fit=Z}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}class Cm extends m${direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Z,children:Q=[],mainAxisAlignment:X="start",crossAxisAlignment:Y="center",mainAxisSize:U="min"}){super({...J?{key:J}:{},children:Q});this.direction=Z,this.mainAxisAlignment=X,this.crossAxisAlignment=Y,this.mainAxisSize=U}createRenderObject(){return new ZU4(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new JU4(this)}}class JU4 extends X80{constructor(J){super(J)}get flexWidget(){return this.widget}mount(){super.mount(),this._setupChildParentData()}update(J){super.update(J),this._setupChildParentData()}performRebuild(){super.performRebuild(),this._setupChildParentData()}_setupChildParentData(){for(let J of this.children){let Z=J.renderObject;if(Z&&!Z.parentData)Z.parentData=new EE(0,"tight")}}}class ZU4 extends w4{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Z,Q,X){super();this._direction=J;this._mainAxisAlignment=Z;this._crossAxisAlignment=Q;this._mainAxisSize=X}updateProperties(J,Z,Q,X){this._direction=J,this._mainAxisAlignment=Z,this._crossAxisAlignment=Q,this._mainAxisSize=X,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;u4(!!J,"performLayout called without constraints");let Z=this._direction==="horizontal",Q=[],X=[];for(let N of this.children){let O=N.parentData;if(O&&O.flex>0)Q.push({child:N,flex:O.flex,fit:O.fit});else X.push(N)}let Y=0,U=0,V,K=Z?J.maxHeight:J.maxWidth;if(isFinite(K))V=K;else{let N=0;for(let O of X){let E=Z?O.getMaxIntrinsicHeight(1/0):O.getMaxIntrinsicWidth(1/0);N=Math.max(N,E)}V=N}for(let N of X){let O=this._crossAxisAlignment==="stretch"?V:0,E=Z?new A1(0,1/0,O,V):new A1(O,V,0,1/0);if(N.layout(E),Z)Y+=N.size.width,U=Math.max(U,N.size.height);else Y+=N.size.height,U=Math.max(U,N.size.width)}let D=Z?J.maxWidth:J.maxHeight,z=Number.isFinite(D)?Math.max(0,D-Y):0,q=Q.reduce((N,O)=>N+O.flex,0),G=D<1/0;if(!G&&q>0){for(let{flex:N,fit:O}of Q)if(N>0&&(this._mainAxisSize==="max"||O==="tight")){let E=Z?"row":"column",L=Z?"horizontal":"vertical",I=Z?"width":"height";u4(!1,`RenderFlex children have non-zero flex but incoming ${I} constraints are unbounded.
6636
+ `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Q).option("--only <field>","Extract only the specified field from the result").option("--stream","Stream updates as they arrive instead of waiting for completion").allowUnknownOption(!0).allowExcessArguments(!0).action(async(X,Y,U)=>{let V=U.optsWithGlobals(),K=await Z(U,V),D=0,z=U.args.slice(1),q;if(aY4()){let G=[];for await(let F of process.stdin)G.push(F);q=Buffer.concat(G).toString("utf-8").trim()}await iY4({toolName:X,rawArgs:z,stdinInput:q,only:Y.only,stream:Y.stream,threadDeps:K,stdout:process.stdout,stderr:process.stderr,exit:(G)=>{D=G}}),await K.asyncDispose(),K.cleanupTerminal(),process.exit(D)})}f4();W1();function K80(J){return{get thread$(){return J.thread$},get threadViewState$(){return J.threadViewState$},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},sendMessage:J.sendMessage,editMessage:J.editMessage,restoreMessage:J.restoreMessage,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}function zL5(J){return{id:J,created:Date.now(),v:0,messages:[]}}class bu0{placeholderThreadID;recentThreadIDsSubject=new B4([]);threadTitlesSubject=new B4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new B4({});attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=J8()){this.placeholderThreadID=J;let Z=new B4(zL5(this.placeholderThreadID)),Q=new B4(qK(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new B4(K80({thread$:Z,threadViewState$:Q,pendingApprovals$:new B4([]),pendingSkills$:new B4([]),sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),editMessage:async(X)=>(await this.waitForActiveHandle()).editMessage(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},resolveApproval:async(X,Y,U)=>(await this.waitForActiveHandle()).resolveApproval(X,Y,U),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,Y)=>{this.readyResolve=X,this.readyReject=Y})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J,this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Z)=>this.recentThreadIDsSubject.next(Z)),J.threadTitles$.subscribe((Z)=>this.threadTitlesSubject.next(Z)),J.allConnectedThreadActivityStatuses$.subscribe((Z)=>this.allConnectedThreadActivityStatusesSubject.next(Z)),J.threadHandles$.subscribe((Z)=>{if(Z)this.threadHandlesSubject.next(Z)})],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async createSystemPromptDeps(){return(await this.waitForAttach()).createSystemPromptDeps()}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return L1(J.threadHandles$.pipe(k5((Z)=>Z!==null)))}}h0();s60();MC0();W1();h0();I$();W1();async function z80(J,Z,Q){let X=await F8("/api/durable-thread-workers",tY4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J?{threadId:J}:{})},Q),Z);if(!X.ok)throw Error(`Failed to create DTW thread: ${X.status} ${await X.text()}`);let Y=await X.json();if(!Y.threadId||!Y.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");return{threadId:Y.threadId,wsToken:Y.wsToken}}async function qL5(J,Z,Q){let X=await F8(`/api/threads/${J}`,tY4(void 0,Q),Z);if(!X.ok)throw Error(`Failed to fetch thread snapshot: ${X.status} ${await X.text()}`);return await X.json()}function tY4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function D80(J){let Z=l2.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=l2.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function GL5(J){let Z=[],Q=new Set;for(let[X,Y]of J.messages.entries()){let U=D80(Y);if(U)Q.add(U);Z.push({...Y,messageId:X})}return{messages:Z,processedIds:Q}}function FL5(J){let Z=new Set;for(let Q of J){let X=D80(Q);if(X)Z.add(X)}return Z}function Im(J,Z){let Q=[...J];for(let X of Z)if(X.type==="text"){let Y=Q[Q.length-1];if(Y?.type==="text")Q[Q.length-1]={...Y,text:Y.text+X.text};else Q.push(X)}else if(X.type==="tool_use"){let Y=Q.findIndex((U)=>U.type==="tool_use"&&U.id===X.id);if(Y>=0)Q[Y]=X;else Q.push(X)}else if(X.type==="thinking"){let Y=Q[Q.length-1];if(Y?.type==="thinking")Q[Q.length-1]={...Y,thinking:Y.thinking+X.thinking};else Q.push(X)}else Q.push(X);return Q}function WL5(J,Z,Q,X){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:X}}function HL5(J,Z){let Q=J.parentToolCallId,{completedMessages:X}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;let U=J.blocks??[];if(U.length>0)if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:U,parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:U,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){let U=J.blocks;if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:U,parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:U,parentToolCallId:Q});return}let Y=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")Y=Im(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&Y.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Y,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="tool_use"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=Im([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Im(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="start"||J.state==="generating"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=Im([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Im(Z.streamingBlocks,J.blocks)}}function BL5(J,Z,Q){if(Z.length===0)return J;let X=[],Y=J.length;for(let U of Z){if(Q.has(U.messageId))continue;Q.add(U.messageId);let V=Y++;if(U.role==="assistant")X.push({role:"assistant",content:U.blocks,state:{type:"complete",stopReason:"end_turn"},messageId:V,dtwMessageID:U.messageId,parentToolUseId:U.parentToolCallId});else X.push({role:"user",content:U.blocks,messageId:V,dtwMessageID:U.messageId,parentToolUseId:U.parentToolCallId})}if(X.length===0)return J;return[...J,...X]}function wL5(J,Z,Q){let X=J.message.messageId;if(Q.has(X))return Z;Q.add(X);let Y=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},messageId:Y,dtwMessageID:X,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,userState:J.message.userState,messageId:Y,dtwMessageID:X,parentToolUseId:J.parentToolUseId}]}function NL5(J,Z){let Q=Z.findIndex((K)=>D80(K)===J.messageId),X=Z.findIndex((K)=>D80(K)===J.truncateToMessageId);if(Q<0||X<0)throw Error("Unable to apply edit: message mapping not found");let Y=Z[Q];if(!Y||Y.role!=="user")throw Error("Unable to apply edit: target message is not editable");let U={role:"user",content:J.content,messageId:Y.messageId,dtwMessageID:J.messageId},V=Z.slice(0,X+1);return V[Q]=U,V}function Mm(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function sY4(J){let Z=J.queuedMessage,Q=Z.content.map((X)=>({...X}));return{id:J.id,queuedMessage:{role:"user",content:Q,userState:Z.userState,meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:J.id}}}function OL5(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>sY4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:sY4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function EL5(J,Z){let Q=OL5(Z);return Ly0(Mm(J)??[],Q,{dedupeAdded:!0})}function LL5(J){if(!J||J.length===0)return[];return J.map((Z)=>Z.id)}function IL5(J,Z){return{baseURL:J.workerUrl??Qq(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>z80(Z.threadId,J.configService,J.apiKey),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}class q80{threadSubject;editErrorSubject=new Y4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};subscriptions=[];threadVersion;messages;queuedMessages;threadTitle;processedIds;agentLoopState="idle";contextWindowRatio=null;lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,X){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Mm(J.queuedMessages)??[],this.processedIds=Q,this.transport=Z,this.threadVersion=X,this.threadSubject=new B4(J)}static async create(J){let Z=await z80(J.threadId,J.configService,J.apiKey),Q=await qL5(Z.threadId,J.configService,J.apiKey),{messages:X,processedIds:Y}=GL5(Q),U={...Q,id:Z.threadId,messages:X,queuedMessages:Mm(Q.queuedMessages)},V=new fW(IL5(J,Z)),K=new q80(U,V,Y,Q.v);return await K.connect(),K}threadChanges(){return this.threadSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getContextWindowRatio(){return this.contextWindowRatio}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;this.threadSubject.next({...Z,...{env:J}})}setAgentMode(J){if(!J)return;let Z=this.threadSubject.getValue();if(Z.agentMode)return;this.threadSubject.next({...Z,agentMode:J})}emitThread(){let J=this.threadSubject.getValue(),Z=WL5(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),Q=Z?[...this.messages,Z]:[...this.messages],X=Q.reduce((U,V)=>Math.max(U,V.messageId),-1)+1,Y={...J,id:this.threadId,v:this.threadVersion,title:this.threadTitle,messages:Q,queuedMessages:this.queuedMessages.length>0?Mm(this.queuedMessages):void 0,nextMessageId:Math.max(X,0)};this.threadSubject.next(Y)}runTransportHandler(J,Z){try{Z()}catch(Q){let X=Q instanceof Error?Q.message:String(Q);P.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${X}`)}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionInfo,Q=J.state!==this.lastConnectionState,X=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!X)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(X&&Z)this.logConnectionRoleTransition(Z,J);let Y=J.state;if(Y==="connected"&&this.lastConnectionState!=="connected")this.transport.resumeFromVersion(this.threadVersion);this.lastConnectionState=Y,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{if(P.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:J.message}),J.code==="PARSE_ERROR")this.editErrorSubject.next("Received an invalid DTW message. The connection will continue running.")})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state})}}),this.transport.deltas().subscribe({next:(J)=>{this.runTransportHandler("deltas",()=>{if(J.usage?.contextWindowRatio!==void 0){let Z=J.usage.contextWindowRatio;this.contextWindowRatio=Number.isFinite(Z)&&Z>=0&&Z<=1?Z:null}if(HL5(J,this.deltaState),this.deltaState.completedMessages.length>0)this.messages=BL5(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[];this.emitThread()})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{if(this.messages=wL5(J,this.messages,this.processedIds),this.deltaState.streamingMessageId===J.message.messageId)this.deltaState.streamingMessageId=null,this.deltaState.streamingBlocks=[],this.deltaState.streamingParentToolCallId=void 0;this.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{this.messages=NL5(J,this.messages),this.processedIds=FL5(this.messages),this.threadVersion=Math.max(this.threadVersion,J.seq),this.emitThread()})}}),this.transport.threadTitles().subscribe({next:(J)=>{this.runTransportHandler("threadTitles",()=>{this.threadTitle=J.title??void 0,this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=EL5(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,role:Z.role,clientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion};if(Z.state==="connected"){if(J==="reconnecting"){P.info("[dtw] Transport reconnected",Q);return}P.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){P.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){P.warn("[dtw] Transport disconnected",Q);return}P.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){P.info("[dtw] Transport role changed",{threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,fromClientId:J.clientId,toClientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadVersion})}async connect(){this.subscribeToTransport(),await this.transport.connect(),this.emitThread()}sendUserMessage(J,Z,Q,X){this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q})}discardQueuedMessages(){let J=Mm(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=LL5(this.queuedMessages);this.queuedMessages=[],this.emitThread();try{for(let Q of Z)this.transport.removeQueuedMessage(Q)}catch(Q){throw this.queuedMessages=J??[],this.emitThread(),Q}}resumeFromVersion(J){this.transport.resumeFromVersion(J)}dispose(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.transport.dispose()}}h0();g5();u9();TJ();f4();Iz();KS0();W1();class hu0{threadWriter;deps;thread$;threadViewState$;pendingApprovals$;provider;threadSubject;threadViewStateSubject;providerSubscription=null;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;runnerClient;handshakeManager;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new B4([]);pendingSkillsSubject=new B4([]);pendingSkills$=this.pendingSkillsSubject;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let X=WW0("info"),Y=WW0("error");this.toolRunner=new th({executeBuiltinTool:()=>null,invokeTool:(U,V)=>this.invokeToolForLease(V),batchGuidanceFiles:T30,renderToolRunError:Mx,log:{info:(U,V)=>X(U,V),error:(U,V)=>Y(U,{error:V}),wsMessage:(U,V,K)=>{P.debug("DTW executor tool runner message",{direction:U,clientID:V,...typeof K==="object"&&K!==null?K:{message:K}})}}}),this.runnerClient=this.toolRunner.addClient(this.clientID,this.provider.transport),this.handshakeManager=this.createHandshakeManager(),this.threadSubject=new B4(this.threadWriter.read()),this.thread$=this.threadSubject,this.threadViewStateSubject=new B4(qK(this.threadWriter.read(),{state:"active",inferenceState:ML5(J)?"running":"idle",fileChanges:{files:[]}})),this.threadViewState$=this.threadViewStateSubject,this.pendingApprovals$=this.pendingApprovalsSubject,this.attachTransportHandlers(),this.handshakeManager.ensureHandshake("connect")}startProviderSubscription(J){this.providerSubscription?.unsubscribe(),this.providerSubscription=this.provider.threadChanges().subscribe({next:(Z)=>{J(Z)}})}readThread(){return this.threadWriter.read()}writeThread(J){this.threadWriter.write(J),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}setThreadViewState(J){this.threadViewStateSubject.next(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getResolvedTokenUsage(){let J=e7(this.threadWriter.read());if(J)return J;let Z=this.provider.getContextWindowRatio();if(Z===null)return;return{maxInputTokens:1,inputTokens:Z,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,totalInputTokens:Z}}async dispose(){this.providerSubscription?.unsubscribe(),this.providerSubscription=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.handshakeManager.dispose(),this.toolRunner.removeClient(this.clientID),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),this.threadSubject.complete(),this.threadViewStateSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){if(J.editIndex!==void 0){await this.handshakeManager.ensureReady();let U=this.threadWriter.read().messages[J.editIndex];if(!U||U.role!=="user"||!U.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let V=J.content.filter((K)=>K.type==="text"||K.type==="image");this.provider.transport.editUserMessage(U.dtwMessageID,V,Wy0(),J.agentMode);return}await this.handshakeManager.ensureReady();let Z=this.threadWriter.read();if(!Z.messages.some((Y)=>Y.role==="user")&&!Z.agentMode&&J.agentMode)this.updateThread((Y)=>{Y.agentMode=J.agentMode});let X=await this.collectUserState();this.provider.sendUserMessage(J.content,J.agentMode,X)}async editMessage(J){await this.handshakeManager.ensureReady();let X=[...this.threadWriter.read().messages.slice(0,J+1)].reverse().find((U)=>U.role==="user");if(!X?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let Y=X.content.filter((U)=>U.type==="text"||U.type==="image").map((U)=>{if(U.type==="image")return{...U,source:{...U.source}};return{...U}});if(Y.length===0)throw Error("Unable to edit message: no editable content found");this.provider.transport.editUserMessage(X.dtwMessageID,Y,Wy0())}async queueMessage(J){await this.handshakeManager.ensureReady();let Z=await this.collectUserState();this.provider.sendUserMessage(J,void 0,Z)}async discardQueuedMessages(){this.provider.discardQueuedMessages()}async setVisibility(J){let Z=await T6.setThreadMeta({thread:this.provider.threadId,meta:wU(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}updateThread(J){this.threadWriter.update(J),this.threadSubject.next(this.threadWriter.read())}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}dismissEphemeralError(){}async resolveApproval(J,Z,Q){let X=O9.safeParse(J);if(!X.success)return;this.provider.transport.resolveToolApproval(X.data,Z)}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.threadWriter.read();return(await pV({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((X)=>({uri:X.uri,type:X.type}))}async getFilesAffectedByTruncation(J){let Z=this.threadWriter.read(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((U)=>{if(U.role==="user"){for(let V of U.content)if(V.type==="tool_result")Q.add(V.toolUseID)}else for(let V of U.content)if(V.type==="tool_use")Q.add(V.id)});let X=new Set,Y=await this.deps.fs.tracker.getAllRecords();for(let[U]of Y.entries())if(!Q.has(U))X.add(U);return X}async collectUserState(){try{return await VS0()??Ix}catch(J){return P.warn("Failed to collect IDE user state for DTW message",{error:J}),Ix}}createHandshakeManager(){return new sh({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{P.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){P.error("DTW executor handshake exhausted",J)}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{this.handshakeManager.handleConnectionChange(J)}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(this.clientID,J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(this.clientID,J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}))}async sendExecutorHandshake(J){P.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,await _30({transport:this.provider.transport,executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,sendGitSnapshot:!1,executorType:"local-client"}),this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Z)=>{this.lastSentSettingsJSON=S30(this.provider.transport,Z,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await $Q();this.provider.setEnvironment({initial:J})}catch(J){P.debug("Failed to apply local environment",{error:J})}}async invokeToolForLease(J){let Z=await mW({toolName:J.toolName,threadID:this.provider.threadId,configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.runnerClient.discoveredGuidanceFileURIs}),Q=typeof J.args==="object"&&J.args!==null?J.args:{};return this.deps.toolService.invokeLeasedTool(J.toolName,{args:Q},Z)}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(this.clientID,J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z))}}function ML5(J){return J.willQueueNextUserMessage()}class Am{deps;recentThreadIDsSubject=new B4([]);threadTitlesSubject=new B4({});activeThreadHandleSubject=new B4(null);allConnectedThreadActivityStatusesSubject=new B4({});threadHandleMap=new Map;activeThreadContextID;constructor(J){this.deps=J}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get activeThreadHandle(){let J=this.threadHandleMap.get(this.activeThreadContextID);if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){return this.threadHandleMap.get(this.activeThreadContextID)?.provider}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}async createThread(J){await this.activateThread(J)}async switchThread(J){await this.activateThread(J)}async createHandoff(J,Z){let Q=await this.deps.threadService.get(J,Z.signal);if(!Q)throw Error("No thread available for handoff");if(!Q.env?.initial){let K=await this.deps.getThreadEnvironment();Q={...Q,env:{initial:K}}}let X=Z.signal??new AbortController().signal,Y=await cR(Q,Z.goal,Z.images,this.deps.configService,X,this.deps.osFileSystem),U=mu0(Z.queuedMessages??Q.queuedMessages),{threadID:V}=await this.createThreadWithDraft({parentThreadID:Q.id,agentMode:Z.agentMode??Q.agentMode,draft:Y,queuedMessages:U,comment:Z.goal,parentMessageIndex:Q.messages.length>0?Q.messages.length-1:void 0});return V}async createSystemPromptDeps(){return{toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService}}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();this.threadHandleMap.clear(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J){P.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Z=J?this.threadHandleMap.get(J):void 0;if(Z){let V=Z.readThread().id;this.activeThreadContextID=V,this.activeThreadHandleSubject.next(Z),this.addToRecentThreads(V),this.updateThreadViewState(V,Z.readThread()),P.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:V,handleCount:this.threadHandleMap.size});return}let Q=await this.createProvider(J),X=await this.deps.threadService.exclusiveSyncReadWriter(Q.threadId),Y=OP({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q.threadId),U=new hu0(Q,X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,fs:Y,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService});U.startProviderSubscription((V)=>{this.applyProviderState(Q.threadId,V)}),this.threadHandleMap.set(Q.threadId,U),await this.applyProviderState(Q.threadId,Q.getThread()),this.activeThreadContextID=Q.threadId,this.activeThreadHandleSubject.next(U),this.addToRecentThreads(Q.threadId),P.info("[dtw-thread-pool] activateThread:created",{activeThreadID:Q.threadId,handleCount:this.threadHandleMap.size})}async applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let X=AL5(Q.readThread(),Z);Q.writeThread(X),await this.deps.threadService.flushVersion(J,X.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J]:X.title}),this.updateThreadViewState(J,X)}updateThreadViewState(J,Z){let Q=this.threadHandleMap.get(J),X={state:"active",inferenceState:Q?.provider.willQueueNextUserMessage()?"running":"idle",fileChanges:{files:[]}},Y=qK(Z,X);Q?.setThreadViewState(Y),this.syncAllConnectedThreadActivityStatuses()}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}async createProvider(J){return q80.create({ampURL:this.deps.ampURL,configService:this.deps.configService,threadId:J,workerUrl:process.env.AMP_WORKER_URL})}async getApiKey(){let J=await this.deps.configService.getLatest();return J.secrets.getToken("apiKey",J.settings.url)}async createThreadWithDraft(J){let{threadId:Z}=await z80(void 0,this.deps.configService,await this.getApiKey()),Q=await this.deps.threadService.exclusiveSyncReadWriter(Z),X=Date.now(),Y=J.parentThreadID?[{threadID:J.parentThreadID,type:"handoff",role:"child",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X}]:void 0,U={id:Z,created:X,v:1,agentMode:J.agentMode,messages:[],draft:J.draft,autoSubmitDraft:!0,queuedMessages:mu0(J.queuedMessages),env:{initial:await this.deps.getThreadEnvironment()},relationships:Y};if(Q.write(U),await this.deps.threadService.flushVersion(Z,U.v).catch(()=>{return}),await Q.asyncDispose(),J.parentThreadID){let V=(D)=>{if(!D.relationships)D.relationships=[];if(!D.relationships.some((q)=>q.threadID===Z&&q.type==="handoff"&&q.role==="parent"))D.relationships.push({threadID:Z,type:"handoff",role:"parent",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X})},K=this.threadHandleMap.get(J.parentThreadID);if(K)K.updateThread((D)=>{V(D)});else{let D=await this.deps.threadService.exclusiveSyncReadWriter(J.parentThreadID);D.update((z)=>{V(z)}),await D.asyncDispose()}}return{threadID:Z}}}function mu0(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function AL5(J,Z){let Q=Z.messages.reduce((X,Y)=>Math.max(X,Y.messageId),-1)+1;return{...Z,draft:Z.draft??J.draft,autoSubmitDraft:Z.autoSubmitDraft??J.autoSubmitDraft,env:Z.env??J.env,queuedMessages:mu0(Z.queuedMessages),nextMessageId:Math.max(Q,0)}}vu0();import{readFile as QS5}from"node:fs/promises";import XS5 from"node:readline";import{setTimeout as YS5}from"node:timers/promises";O3();I$();Nj();f4();ez();W1();import{mkdir as jL5,writeFile as RL5}from"node:fs/promises";import PL5 from"node:path";function CL5(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function TL5(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function _L5(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${TL5(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function gu0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class pu0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=CL5(J.traceName),X=_L5(Z,Q);this.traceFilePath=PL5.join(J.traceDir,`${X}.json`),this.session={schemaVersion:1,sessionID:X,createdAt:Z,runtimeMode:J.runtimeMode,...Q?{traceName:Q}:{},threadId:J.threadId,scriptedCommands:[...J.scriptedCommands??[]],protocolEvents:[],providerStateEvents:[],adapterStateEvents:[],commandEvents:[],timeline:[]}}nextTimelineIndex(){return this.session.timeline.length}recordProtocolEvent(J,Z){let Q=this.nextTimelineIndex(),X=Date.now(),Y={timelineIndex:Q,timestamp:X,eventName:J,payload:gu0(Z)};this.session.protocolEvents.push(Y),this.session.timeline.push({timelineIndex:Q,timestamp:X,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),X=Date.now(),Y={timelineIndex:Q,timestamp:X,reason:J,state:gu0(Z)};this.session.providerStateEvents.push(Y),this.session.timeline.push({timelineIndex:Q,timestamp:X,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),X=Date.now(),Y={timelineIndex:Q,timestamp:X,reason:J,state:gu0(Z)};this.session.adapterStateEvents.push(Y),this.session.timeline.push({timelineIndex:Q,timestamp:X,kind:"adapter_state",adapterStateIndex:this.session.adapterStateEvents.length-1})}recordCommand(J){let Z=this.nextTimelineIndex(),Q=Date.now();this.session.commandEvents.push({timelineIndex:Z,timestamp:Q,command:J}),this.session.timeline.push({timelineIndex:Z,timestamp:Q,kind:"command",commandIndex:this.session.commandEvents.length-1})}async flush(){await jL5(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await RL5(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function eY4(J,Z){let Q=[J.connectionChanges().subscribe({next:(X)=>Z("connection_changes",X)}),J.errors().subscribe({next:(X)=>Z("errors",X)}),J.errorEvents().subscribe({next:(X)=>Z("error_events",X)}),J.agentStates().subscribe({next:(X)=>Z("agent_states",X)}),J.deltas().subscribe({next:(X)=>Z("deltas",X)}),J.messageEvents().subscribe({next:(X)=>Z("message_events",X)}),J.messageEdited().subscribe({next:(X)=>Z("message_edited",X)}),J.editRejected().subscribe({next:(X)=>Z("edit_rejected",X)}),J.threadTitles().subscribe({next:(X)=>Z("thread_titles",X)}),J.queuedMessages().subscribe({next:(X)=>Z("queued_messages",X)}),J.retryEvents().subscribe({next:(X)=>Z("retry_events",X)}),J.cancelledEvents().subscribe({next:(X)=>Z("cancelled_events",X)}),J.toolLeases().subscribe({next:(X)=>Z("tool_leases",X)}),J.toolLeaseRevoked().subscribe({next:(X)=>Z("tool_lease_revoked",X)}),J.toolApprovalQueue().subscribe({next:(X)=>Z("tool_approval_queue",X)}),J.executorToolApprovalResponses().subscribe({next:(X)=>Z("executor_tool_approval_responses",X)}),J.toolProgress().subscribe({next:(X)=>Z("tool_progress",X)}),J.executorErrors().subscribe({next:(X)=>Z("executor_errors",X)}),J.executorConnected().subscribe({next:(X)=>Z("executor_connected",X)}),J.executorRollbackRequests().subscribe({next:(X)=>Z("executor_rollback_requests",X)}),J.observers().subscribe({next:(X)=>Z("observers",X)}),J.executorStatuses().subscribe({next:(X)=>Z("executor_statuses",X)}),J.environmentUpdates().subscribe({next:(X)=>Z("environment_updates",X)}),J.gitStatuses().subscribe({next:(X)=>Z("git_statuses",X)}),J.compactionEvents().subscribe({next:(X)=>Z("compaction_events",X)}),J.compactionRecords().subscribe({next:(X)=>Z("compaction_records",X)})];return{unsubscribe:()=>{for(let X of Q)X.unsubscribe()}}}f4();N4();OJ();function UC(J,Z){let Q=(D)=>D===B7||D===c3||D===BZ||D===U9,X=new Map;for(let D of J)if(D.type==="toolResult"&&Q(D.toolUse.name))X.set(D.toolUse.id,{toolUseId:D.toolUse.id,toolName:D.toolUse.name,toolRun:D.toolResult.run});let Y=(D,z)=>{let q=X.get(D)?.toolRun;if(!q||q.status!=="cancelled"||m8(z))return z;return{status:"cancelled",reason:"Parent subagent was cancelled"}},U=Array.from(X.values()),V={},K={};for(let{toolUseId:D,toolRun:z}of U){let q=[],G;if(z.status==="in-progress"||z.status==="done"||z.status==="error"||z.status==="cancelled")G=z.progress;if(Array.isArray(G)){let F=0;for(let W of G)if(W.tool_uses)for(let H of W.tool_uses){let B=`${D}:progress:${F++}`,w=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},N=H.normalized_name??H.tool_name;q.push({toolUse:fM(N,H.input,B),toolRun:Y(D,w)})}}V[D]=q}if(Z){let D=new Map;for(let z of Z.messages){let q=z.parentToolUseId;if(!q)continue;let G=D.get(q)??[];G.push(z),D.set(q,G)}for(let[z,q]of D){let{items:G}=Dq({id:Z.id,messages:q},{includeSubagentMessages:!0});K[z]=G.filter((F)=>F.type==="toolResult").map((F)=>({toolUse:F.toolUse,toolRun:Y(z,F.toolResult.run)}))}}for(let[D,z]of Object.entries(K))if(z.length>0)V[D]=z;return V}function Dq(J,Z){let Q=[],X=new Set;if(Z?.includeSubagentMessages)for(let[V]of J.messages.entries())X.add(V);else for(let[V,K]of J.messages.entries())if(!K.parentToolUseId)X.add(V);let Y=new Map,U=new Set;for(let[V,K]of J.messages.entries()){if(!X.has(V))continue;let D=`${K.role}-${V}`;switch(K.role){case"assistant":{let z=K.state.type==="streaming";for(let G of K.content)if(G.type==="tool_use"){if(Y.set(G.id,G),z)U.add(G.id)}if(K.content.some((G)=>G.type==="text"&&G.text.trim()||G.type==="thinking"))Q.push({type:"message",id:D,message:K});for(let G of K.content)if(G.type==="tool_use"){let F=!1;for(let W=V+1;W<J.messages.length;W++){if(!X.has(W))continue;let H=J.messages[W];if(H){for(let B of H.content)if(B.type==="tool_result"&&B.toolUseID===G.id){F=!0;break}}if(F)break}if(!F)Q.push({type:"toolResult",id:G.id,toolUse:G,toolResult:{type:"tool_result",toolUseID:G.id,run:{status:"in-progress"}}})}break}case"info":{if(K.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:D,message:K});break}case"user":{let z=K.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of K.content)if(q.type==="tool_result"){let G=Y.get(q.toolUseID)??N$(J,q.toolUseID);if(!G)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:G,toolResult:q})}if(z)Q.push({type:"message",id:D,message:K});break}}}return{items:Q}}g5();f4();ez();W1();class L3{state=[!0,!1,!0,!1,!0,!1,!0,!1];previousState=[];generation=0;maxGenerations=15;neighborMap=[[1,3,4,5,7],[0,2,4,5,6],[1,3,5,6,7],[0,2,4,6,7],[0,1,3,5,7],[0,1,2,4,6],[1,2,3,5,7],[0,2,3,4,6]];step(){let J=this.state.map((U,V)=>{let K=this.neighborMap[V].filter((D)=>this.state[D]).length;if(U)return K===2||K===3;return K===3||K===6}),Z=J.every((U,V)=>U===this.state[V]),Q=this.previousState.length>0&&J.every((U,V)=>U===this.previousState[V]);this.previousState=[...this.state],this.state=J,this.generation++;let X=J.every((U)=>!U),Y=J.filter((U)=>U).length;if(Z||Q||this.generation>=this.maxGenerations||X||Y<2){let U;do U=Array.from({length:8},()=>Math.random()>0.6);while(U.filter((V)=>V).length<3);this.state=U,this.previousState=[],this.generation=0}}toBraille(){let J=[0,1,2,6,3,4,5,7],Z=10240;for(let Q=0;Q<8;Q++)if(this.state[Q])Z|=1<<J[Q];return String.fromCharCode(Z)}}class OU{element;widget;mediaQuery;parent;constructor(J,Z,Q=void 0,X=null){this.element=J;this.widget=Z;this.mediaQuery=Q;this.parent=X}findAncestorElementOfType(J){let Z=this.element.parent;while(Z){if(Z instanceof J)return Z;Z=Z.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Z=this.element.parent;while(Z){if("state"in Z&&Z.state instanceof J)return Z.state;Z=Z.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof OE?J:void 0}return}}class d1 extends a2{createElement(){return new du0(this)}}class du0 extends YQ{_child;_context;constructor(J){super(J)}get statelessWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new OU(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let J=this.statelessWidget.build(this._context);if(this._child){if(this._child.widget===J)return;if(this._child.widget.canUpdate(J))this._child.update(J);else this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}}class UQ extends f5{forceDim;constructor({key:J,forceDim:Z,child:Q}){super({key:J,child:Q});this.forceDim=Z}static maybeOf(J){let Z=J.dependOnInheritedWidgetOfExactType(UQ);if(Z)return Z.widget;return null}static shouldForceDim(J){return UQ.maybeOf(J)?.forceDim??!1}updateShouldNotify(J){return this.forceDim!==J.forceDim}}class T4{color;border;constructor(J,Z){this.color=J;this.border=Z}}class f1{top;right;bottom;left;constructor(J,Z,Q,X){this.top=J;this.right=Z;this.bottom=Q;this.left=X}static all(J){return new f1(J,J,J,J)}static symmetric(J,Z){return new f1(Z,J,Z,J)}}class y1{color;width;style;constructor(J=I0.black,Z=1,Q="rounded"){this.color=J;this.width=Z;this.style=Q}}class c0 extends D3{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Z,width:Q,height:X,padding:Y,margin:U,decoration:V,constraints:K}={}){super({...J?{key:J}:{},...Z?{child:Z}:{}});this.width=Q,this.height=X,this.padding=Y,this.margin=U,this.decoration=V,this.constraints=K}createElement(){return new $U4(this)}createRenderObject(){return new jm(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof jm))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}}class $U4 extends mK{constructor(J){super(J)}mount(){super.mount(),this._updateForceDim()}performRebuild(){super.performRebuild(),this._updateForceDim()}_updateForceDim(){if(!this.renderObject)return;let J=new OU(this,this.widget),Z=UQ.shouldForceDim(J);if(this.renderObject instanceof jm)this.renderObject.setForceDim(Z)}}class jm extends w4{_width;_height;_padding;_margin;_decoration;_constraints;_forceDim=!1;constructor(J,Z,Q,X,Y,U){super();this._width=J;this._height=Z;this._padding=Q;this._margin=X;this._decoration=Y;this._constraints=U}setForceDim(J){if(this._forceDim!==J)this._forceDim=J,this.markNeedsPaint()}updateProperties(J,Z,Q,X,Y,U){this._width=J,this._height=Z,this._padding=Q,this._margin=X,this._decoration=Y,this._constraints=U,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;u4(!!J,"performLayout called without constraints");let Z=this._margin?.horizontal??0,Q=this._margin?.vertical??0,X=this._padding?.horizontal??0,Y=this._padding?.vertical??0,U=this._decoration?.border,V=(U?.left?1:0)+(U?.right?1:0),K=(U?.top?1:0)+(U?.bottom?1:0);this.sendDebugData({margin:this._margin,padding:this._padding,decoration:this._decoration,width:this._width,height:this._height,constraints:this._constraints});let D=this._width!==void 0||this._height!==void 0?this._constraints?.tighten({width:this._width,height:this._height})??A1.tightFor({width:this._width,height:this._height}):this._constraints,z=D?J.enforce(D):J,q=z.maxWidth-Z-X-V,G=z.maxHeight-Q-Y-K,F=new A1(Math.max(0,z.minWidth-Z-X-V),Math.max(0,q),Math.max(0,z.minHeight-Q-Y-K),Math.max(0,G)),W,H;if(this.children.length>0){let N=this.children[0];if(!(N instanceof w4))throw Error("Child must be a RenderBox");N.layout(F),W=N.size.width,H=N.size.height;let O=U?.left?1:0,E=U?.top?1:0,L=(this._margin?.left??0)+O+(this._padding?.left??0),I=(this._margin?.top??0)+E+(this._padding?.top??0);N.setOffset(L,I)}else if(F.maxWidth!==1/0&&F.maxHeight!==1/0)W=F.maxWidth,H=F.maxHeight;else W=F.minWidth,H=F.minHeight;let B,w;if(z.minWidth===z.maxWidth&&isFinite(z.maxWidth))B=z.maxWidth;else B=W+X+V+Z;if(z.minHeight===z.maxHeight&&isFinite(z.maxHeight))w=z.maxHeight;else w=H+Y+K+Q;this.setSize(z.constrain(B,w).width,z.constrain(B,w).height)}getMinIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.minWidth!==0)return this._constraints.minWidth;let Z=this._margin?.horizontal??0,Q=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),U=0;if(this.children.length>0){let V=this.children[0],K=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));U=V.getMinIntrinsicWidth(K)}return U+Z+Q+Y}getMaxIntrinsicWidth(J){if(this._width!==void 0)return this._width;if(this._constraints&&this._constraints.maxWidth!==1/0)return this._constraints.maxWidth;let Z=this._margin?.horizontal??0,Q=this._padding?.horizontal??0,X=this._decoration?.border,Y=(X?.left?1:0)+(X?.right?1:0),U=0;if(this.children.length>0){let V=this.children[0],K=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((X?.top?1:0)+(X?.bottom?1:0)));U=V.getMaxIntrinsicWidth(K)}if(U===1/0)return 1/0;return U+Z+Q+Y}getMinIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.minHeight!==0)return this._constraints.minHeight;let Z=this._margin?.vertical??0,Q=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),U=0;if(this.children.length>0){let K=this.children[0],D=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));U=K.getMinIntrinsicHeight(D)}let V=U+Z+Q+Y;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(V,this._constraints.maxHeight);return V}getMaxIntrinsicHeight(J){if(this._height!==void 0)return this._height;if(this._constraints&&this._constraints.maxHeight!==1/0)return this._constraints.maxHeight;let Z=this._margin?.vertical??0,Q=this._padding?.vertical??0,X=this._decoration?.border,Y=(X?.top?1:0)+(X?.bottom?1:0),U=0;if(this.children.length>0){let V=this.children[0],K=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((X?.left?1:0)+(X?.right?1:0)));U=V.getMaxIntrinsicHeight(K)}if(U===1/0)return 1/0;return U+Z+Q+Y}paint(J,Z=0,Q=0){let X=Math.floor(Z+this.offset.x),Y=Math.floor(Q+this.offset.y);if(this._decoration?.color){let U={bg:this._decoration.color};J.fill(X,Y,this.size.width,this.size.height," ",U)}if(this._decoration?.border)this._paintBorder(J,X,Y);super.paint(J,Z,Q)}_paintBorder(J,Z,Q){let X=this._decoration.border,Y=this.size.width,U=this.size.height,V=(W)=>{let H={fg:W};if(this._decoration?.color)H.bg=this._decoration.color;if(this._forceDim)H.dim=!0;return H},K=(W)=>{switch(W){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},D=(W)=>{switch(W){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},z=(W,H)=>{if(W===1)return H?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┌",tr:"┐",bl:"└",br:"┘"};else return H?{tl:"╭",tr:"╮",bl:"╰",br:"╯"}:{tl:"┏",tr:"┓",bl:"┗",br:"┛"}};if(X.top){let W=V(X.top.color),H=K(X.top.width);for(let B=0;B<Y;B++)J.setChar(Z+B,Q,H,W,1)}if(X.bottom){let W=V(X.bottom.color),H=K(X.bottom.width);for(let B=0;B<Y;B++)J.setChar(Z+B,Q+U-1,H,W,1)}if(X.left){let W=V(X.left.color),H=D(X.left.width);for(let B=0;B<U;B++)J.setChar(Z,Q+B,H,W,1)}if(X.right){let W=V(X.right.color),H=D(X.right.width);for(let B=0;B<U;B++)J.setChar(Z+Y-1,Q+B,H,W,1)}let q=X.top?.style==="rounded",G=Math.max(X.top?.width??1,X.right?.width??1,X.bottom?.width??1,X.left?.width??1),F=z(G,q);if(X.top&&X.left){let W=V(X.top.color);J.setChar(Z,Q,F.tl,W,1)}if(X.top&&X.right){let W=V(X.top.color);J.setChar(Z+Y-1,Q,F.tr,W,1)}if(X.bottom&&X.left){let W=V(X.bottom.color);J.setChar(Z,Q+U-1,F.bl,W,1)}if(X.bottom&&X.right){let W=V(X.bottom.color);J.setChar(Z+Y-1,Q+U-1,F.br,W,1)}}hitTest(J,Z,Q=0,X=0){return super.hitTest(J,Z,Q,X)}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}function Rm(J,Z,Q){return Math.min(Math.max(J,Z),Q)}class Pm{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}class EE extends Pm{flex;fit;constructor(J=0,Z="tight"){super();this.flex=J,this.fit=Z}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}class Cm extends m${direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Z,children:Q=[],mainAxisAlignment:X="start",crossAxisAlignment:Y="center",mainAxisSize:U="min"}){super({...J?{key:J}:{},children:Q});this.direction=Z,this.mainAxisAlignment=X,this.crossAxisAlignment=Y,this.mainAxisSize=U}createRenderObject(){return new ZU4(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new JU4(this)}}class JU4 extends X80{constructor(J){super(J)}get flexWidget(){return this.widget}mount(){super.mount(),this._setupChildParentData()}update(J){super.update(J),this._setupChildParentData()}performRebuild(){super.performRebuild(),this._setupChildParentData()}_setupChildParentData(){for(let J of this.children){let Z=J.renderObject;if(Z&&!Z.parentData)Z.parentData=new EE(0,"tight")}}}class ZU4 extends w4{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Z,Q,X){super();this._direction=J;this._mainAxisAlignment=Z;this._crossAxisAlignment=Q;this._mainAxisSize=X}updateProperties(J,Z,Q,X){this._direction=J,this._mainAxisAlignment=Z,this._crossAxisAlignment=Q,this._mainAxisSize=X,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;u4(!!J,"performLayout called without constraints");let Z=this._direction==="horizontal",Q=[],X=[];for(let N of this.children){let O=N.parentData;if(O&&O.flex>0)Q.push({child:N,flex:O.flex,fit:O.fit});else X.push(N)}let Y=0,U=0,V,K=Z?J.maxHeight:J.maxWidth;if(isFinite(K))V=K;else{let N=0;for(let O of X){let E=Z?O.getMaxIntrinsicHeight(1/0):O.getMaxIntrinsicWidth(1/0);N=Math.max(N,E)}V=N}for(let N of X){let O=this._crossAxisAlignment==="stretch"?V:0,E=Z?new A1(0,1/0,O,V):new A1(O,V,0,1/0);if(N.layout(E),Z)Y+=N.size.width,U=Math.max(U,N.size.height);else Y+=N.size.height,U=Math.max(U,N.size.width)}let D=Z?J.maxWidth:J.maxHeight,z=Number.isFinite(D)?Math.max(0,D-Y):0,q=Q.reduce((N,O)=>N+O.flex,0),G=D<1/0;if(!G&&q>0){for(let{flex:N,fit:O}of Q)if(N>0&&(this._mainAxisSize==="max"||O==="tight")){let E=Z?"row":"column",L=Z?"horizontal":"vertical",I=Z?"width":"height";u4(!1,`RenderFlex children have non-zero flex but incoming ${I} constraints are unbounded.
6637
6637
 
6638
6638
  When a ${E} is in a parent that does not provide a finite ${I} constraint, for example if it is in a ${L} scrollable, it will try to shrink-wrap its children along the ${L} axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining space in the ${L} direction.
6639
6639
 
@@ -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 T4(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 A1(U,U,0,V),decoration:new T4(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 _4({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 A1(Y,Y,0,U),decoration:new T4(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 _4({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 A1(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.1772502119-g224ee4"},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 $4("ArrowDown"),new zT],[new $4("ArrowUp"),new qT],[new $4("Tab"),new zT],[new $4("Tab",{shift:!0}),new qT],[new $4("n",{ctrl:!0}),new zT],[new $4("p",{ctrl:!0}),new qT],[new $4("Enter"),new T20],[new $4("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 N6({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=(e,B0)=>new j0({width:B0,child:D1.end([new Q0({text:new C(e,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 e=[],B0=O.ancestorsAreLast.slice(1);for(let U0 of B0)e.push(new C(g.getAncestorPrefix(U0),new b({color:g.connectorColor,dim:g.connectorDim})));let n=O.isLast?g.elbow:g.tee,V0=g.getConnectorText(n);e.push(new C(V0,new b({color:g.connectorColor,dim:g.connectorDim}))),k.push(new Q0({text:new C("",void 0,e)}))}let a=[],m=D===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 i=O.title;if(O.relationshipType==="fork"){let e=i.match(/^Forked\((\d+)\): /);if(e)i=i.slice(e[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);a.push(new Q0({text:new C("[fork] ",new b({color: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(i,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 e=E?{success:y,warning:y,destructive:y}:j;a.push(...zm5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,e)),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 $4("ArrowDown"),new GT],[new $4("ArrowUp"),new FT],[new $4("Tab"),new GT],[new $4("Tab",{shift:!0}),new FT],[new $4("n",{ctrl:!0}),new GT],[new $4("p",{ctrl:!0}),new FT],[new $4("Enter"),new v20],[new $4("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 N6({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 N6({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 T4(Q.background,Y),child:new j0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new _4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class 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 N6({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 _4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new 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 T4(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 A1(U,U,0,V),decoration:new T4(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 _4({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 A1(Y,Y,0,U),decoration:new T4(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 _4({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 A1(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.1772503238-g61db4a"},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 $4("ArrowDown"),new zT],[new $4("ArrowUp"),new qT],[new $4("Tab"),new zT],[new $4("Tab",{shift:!0}),new qT],[new $4("n",{ctrl:!0}),new zT],[new $4("p",{ctrl:!0}),new qT],[new $4("Enter"),new T20],[new $4("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 N6({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=(e,B0)=>new j0({width:B0,child:D1.end([new Q0({text:new C(e,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 e=[],B0=O.ancestorsAreLast.slice(1);for(let U0 of B0)e.push(new C(g.getAncestorPrefix(U0),new b({color:g.connectorColor,dim:g.connectorDim})));let n=O.isLast?g.elbow:g.tee,V0=g.getConnectorText(n);e.push(new C(V0,new b({color:g.connectorColor,dim:g.connectorDim}))),k.push(new Q0({text:new C("",void 0,e)}))}let a=[],m=D===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 i=O.title;if(O.relationshipType==="fork"){let e=i.match(/^Forked\((\d+)\): /);if(e)i=i.slice(e[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);a.push(new Q0({text:new C("[fork] ",new b({color: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(i,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 e=E?{success:y,warning:y,destructive:y}:j;a.push(...zm5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,e)),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 $4("ArrowDown"),new GT],[new $4("ArrowUp"),new FT],[new $4("Tab"),new GT],[new $4("Tab",{shift:!0}),new FT],[new $4("n",{ctrl:!0}),new GT],[new $4("p",{ctrl:!0}),new FT],[new $4("Enter"),new v20],[new $4("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 N6({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 N6({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 T4(Q.background,Y),child:new j0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new _4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class 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 N6({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 _4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new 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=[],I1=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 $p5(D.result.displayText)+`
7284
7284
  `),process.exit(0)})}var Ei5=gp.join(NZ,"logs","headless.log"),pd0=gp.join(oP,"device-id.json");function Li5(){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 Ii5(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 Mi5(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 G4("You are not allowed to do this.",1);N7("systemPrompt",await Mi5(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 Ai5(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=Ai5(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 G4(`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,ji5=(J)=>("hidden"in J)&&J.hidden===!0,Ri5=(J)=>("default"in J),Pi5=(J)=>("default"in J)?J.default:void 0,kI4=[{name:"toggle-skills-count",entryPoint:Ku0}];function Ci5(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 G4(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(Oi5.homedir()),id0=process.env.XDG_CONFIG_HOME?q1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(n$0,".config");function Ti5(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 _i5(){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.1772502119-g224ee4");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(i,d,e)=>{let B0=`${i}:${d}`,n=D.get(B0);if(n)return P.debug("Reusing existing OAuth provider for server",{serverName:i,serverUrl:d}),n;P.debug("Creating OAuth provider for server",{serverName:i,serverUrl:d});let V0=(async()=>{let U0=new UN(J.secrets),N0=await U0.getClientInfo(i,d),Y0=e?.scopes??N0?.scopes,W0=zQ4();P.info("OAuth headless mode check",{useHeadless:W0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let l;if(W0)l=J.executeMode?DQ4():KQ4(i);let s=new dO0({storage:U0,serverName:i,serverUrl:d,clientId:e?.clientId??N0?.clientId,clientSecret:e?.clientSecret??N0?.clientSecret,authUrl:e?.authUrl??N0?.authUrl,tokenUrl:e?.tokenUrl??N0?.tokenUrl,scopes:Y0,headlessAuthHandler:l});return P.debug("OAuth provider created",{serverName:i,serverUrl:d,hasManualClientId:!!(e?.clientId??N0?.clientId),willUseDCR:!(e?.clientId??N0?.clientId),scopes:Y0,headlessMode:W0,executeMode:J.executeMode}),s})();return D.set(B0,V0),V0}}),W=LS0({configService:Y,filesystem:a6,spawn:$50}),H;if(J.executeMode){let i=await X54({toolService:V,providers:[F,W],initialTimeout:15000});H=i.registrations;for(let[d,e]of i.initErrors)P.warn(`${d} provider initialization slow or failed:`,e)}else H=MS0({toolService:V,providers:[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&&Li5()){let i=lD.find((d)=>d.listConfigs().length>0);if(i){let d=jo(i.ideName);if(d)fw(d)}}if(J.executeMode)HM1(!0);let B,w=_8.status.pipe(B1((i)=>Boolean(i.connected&&i.authenticated&&i.ideName&&SM1(i.ideName))),I4()).subscribe((i)=>{if(i){if(!B)B=V.registerTool(Q54)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let i=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new j30(process.cwd(),{alwaysIncludePaths:i},!0)}else N=new class extends j30{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let i=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(i),P.info("API key lookup before login",{found:Boolean(i),ampURL:J.ampURL,deferAuth:X}),!i)if(X)P.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
7285
+ `)}function Ii5(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 Mi5(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 G4("You are not allowed to do this.",1);N7("systemPrompt",await Mi5(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 Ai5(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=Ai5(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 G4(`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,ji5=(J)=>("hidden"in J)&&J.hidden===!0,Ri5=(J)=>("default"in J),Pi5=(J)=>("default"in J)?J.default:void 0,kI4=[{name:"toggle-skills-count",entryPoint:Ku0}];function Ci5(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 G4(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(Oi5.homedir()),id0=process.env.XDG_CONFIG_HOME?q1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(n$0,".config");function Ti5(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 _i5(){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.1772503238-g61db4a");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(i,d,e)=>{let B0=`${i}:${d}`,n=D.get(B0);if(n)return P.debug("Reusing existing OAuth provider for server",{serverName:i,serverUrl:d}),n;P.debug("Creating OAuth provider for server",{serverName:i,serverUrl:d});let V0=(async()=>{let U0=new UN(J.secrets),N0=await U0.getClientInfo(i,d),Y0=e?.scopes??N0?.scopes,W0=zQ4();P.info("OAuth headless mode check",{useHeadless:W0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let l;if(W0)l=J.executeMode?DQ4():KQ4(i);let s=new dO0({storage:U0,serverName:i,serverUrl:d,clientId:e?.clientId??N0?.clientId,clientSecret:e?.clientSecret??N0?.clientSecret,authUrl:e?.authUrl??N0?.authUrl,tokenUrl:e?.tokenUrl??N0?.tokenUrl,scopes:Y0,headlessAuthHandler:l});return P.debug("OAuth provider created",{serverName:i,serverUrl:d,hasManualClientId:!!(e?.clientId??N0?.clientId),willUseDCR:!(e?.clientId??N0?.clientId),scopes:Y0,headlessMode:W0,executeMode:J.executeMode}),s})();return D.set(B0,V0),V0}}),W=LS0({configService:Y,filesystem:a6,spawn:$50}),H;if(J.executeMode){let i=await X54({toolService:V,providers:[F,W],initialTimeout:15000});H=i.registrations;for(let[d,e]of i.initErrors)P.warn(`${d} provider initialization slow or failed:`,e)}else H=MS0({toolService:V,providers:[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&&Li5()){let i=lD.find((d)=>d.listConfigs().length>0);if(i){let d=jo(i.ideName);if(d)fw(d)}}if(J.executeMode)HM1(!0);let B,w=_8.status.pipe(B1((i)=>Boolean(i.connected&&i.authenticated&&i.ideName&&SM1(i.ideName))),I4()).subscribe((i)=>{if(i){if(!B)B=V.registerTool(Q54)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let i=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new j30(process.cwd(),{alwaysIncludePaths:i},!0)}else N=new class extends j30{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let i=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(i),P.info("API key lookup before login",{found:Boolean(i),ampURL:J.ampURL,deferAuth:X}),!i)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 Si5(J),e=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:d,storedKeyPresent:Boolean(e),ampURL:J.ampURL}),!d)await Zq(),process.exit(1);O=!0}}{let i=await Y.getLatest(),d=i.settings.url,e=i.secrets.isSet?.[d];P.info("Config secrets state after login",{configURL:d,apiKeySet:e?.apiKey??!1})}let E=L1(_J(Y).pipe(k5((i)=>i!=="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=_?_i5():sh1({threadService:M,threadHistoryService:A,configService:Y,isExtensionDevelopment:!1}),y;_8.status.subscribe((i)=>{y=i});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(i){P.warn("Failed to parse current file URI",{uri:y.openFile,error:i});return}},getOpenFiles:()=>{if(!y?.visibleFiles?.length)return[];let i=y.openFile;return y.visibleFiles.filter((d)=>d!==i).map((d)=>{try{return q1.parse(d)}catch(e){return P.warn("Failed to parse visible file URI",{uri:d,error:e}),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 i of H.values())i.dispose();await m.mcpService.dispose(),z(),await m.threadService.asyncDispose(),m.configService.unsubscribe(),K(),m.fuzzyServer.dispose(),m.threadSyncService.dispose(),m.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),a.dispose(),m.pluginService.dispose()}}}async function Si5(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=Bi5(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 vi5(){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-03T01:47:49.598Z"))} ago`}catch{}s6.write(`0.0.1772502119-g224ee4 (released 2026-03-03T01:47:49.598Z${B??""})
7293
+ `),!1}}function vi5(){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-03T02:06:20.819Z"))} ago`}catch{}s6.write(`0.0.1772503238-g61db4a (released 2026-03-03T02:06:20.819Z${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 hi5(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 bi5(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 ii5(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 di5(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 ci5(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.1772502119-g224ee4",async notify(L){P.debug("plugin notification (TUI not loaded): %s",L)},async open(L){q7.write(`
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 ii5(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 di5(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 ci5(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.1772503238-g61db4a",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=Pi5(H);if(L)E.default(L);if(E.hidden=ji5(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)&&!Ri5(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 ki5(J){if(!J.userEmail||!pQ(J.userEmail))throw new G4("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 yi5(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 ui5(J,Z,Q){if(J.remote&&!Z)throw new G4("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new G4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new G4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new G4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new G4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new G4("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 G4("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 G4("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=(n,V0)=>{let U0=Number(process.hrtime.bigint()-V0)/1e6,N0=x94();P.info("Startup phase",{phase:n,phaseMs:Math.round(U0),sinceMainMs:N0===null?void 0:Math.round(N0)})},{userInput:U,stdinInput:V}=await yi5(Z),K=!!Z.streamJson||!!Z.streamJsonThinking;ui5({...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 n=gh(Error(W.error.message));if(n.message===Y8.networkOffline||n.message===Y8.networkTimeout)throw ld0(J.ampURL);throw new G4(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 G4(`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 G4("Headless DTW mode is only available for Amp employees",1);let n=await G.secretStorage.get("apiKey",J.ampURL);if(!n)throw new G4("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 G4(`Invalid thread ID: ${V0}`,1);let U0=V0??await ni5({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:n,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 n=await F30(J.settings,process.cwd(),L,I);if(n instanceof Error)q3(n.message);return cb0(F,{threadMeta:n?wU(n):void 0,agentMode:Z.mode,onFirstAssistantMessage:PI4})},validateThreadOwnership:async(n,V0)=>{if(V0?.nonBlockingOwnershipCheck){CI4(n,G.configService).catch((U0)=>{if(U0 instanceof G4){if(V0.onOwnershipError){V0.onOwnershipError(U0,n);return}iP(U0,n);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})});return}try{await CI4(n,G.configService)}catch(U0){if(U0 instanceof G4)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(n,V0)=>{try{if(n==="dtw")return ki5({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 G4)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 n=await G.configService.getLatest(),V0=lv(n),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(n){P.error("Failed to fetch free tier status:",n);return}})(),S=!J.executeMode?new bu0:null,y,h=null;if(S)y=S,h=(async()=>{let n=q?await G.serverStatusPromise:G.serverStatus;await dd0(Q,Z,n);let V0=process.hrtime.bigint(),U0=cd0(Z.dtw,n),N0=L5(n)?n.user.email:void 0,Y0=await A(U0?"dtw":"worker",{dtwUserEmail:N0});if(Y("runMainThread:createThreadPool",V0),S.attach(Y0),U){let W0=await L1(Y0.threadHandles$);if(!W0)throw new G4("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(n)=>{let V0=n instanceof Error?n:Error(String(n));S.setInitError(V0),await iP(n,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(),Ti5({configService:G.configService,threadService:G.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(e1((n)=>{if(!n)return v0.of({});return t6(n.thread$,n.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 G4("Execute mode is not supported with the DTW thread pool",1);let n=y.getWorkerForExecuteMode();if(await kZ4({worker:n,threadID:n.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:n.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 n=pw({jetbrainsOnly:Z.jetbrains});if(n.length===0){if(Z.jetbrains)g=!await G.configService.get("jetbrains.skipInstall")}else if(n.length===1){let V0=n[0];if(V0)_8.selectConfig(V0)}else a=!0}D=process.hrtime.bigint();let m=Qu0("0.0.1772502119-g224ee4",G.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let i=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 n=await L1(y.threadHandles$);if(!n)throw new G4("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:U}]})}D=process.hrtime.bigint();let e=await fK();Y("runMainThread:loadSessionState",D),P.info("Loaded session state:",e);let B0={...e,launchCount:e.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:i,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-03T01:47:49.598Z",pluginPlatform:G.pluginPlatform,pluginService:G.pluginService},(n)=>new Bh0({...n,threadPool:n.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 wi5(gp.dirname(pd0),{recursive:!0}),await Ni5(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 xi5(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 fi5(){u94();let J=xi5(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?Ei5: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(Ii5(P),P.info("Starting Amp CLI.",{version:"0.0.1772502119-g224ee4",buildTimestamp:"2026-03-03T01:47:49.598Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new G4(Y8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await vi5().parseAsync(process.argv)}d84().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await fi5().catch(iP)});async function bi5(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}
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 n=await G.configService.getLatest(),V0=lv(n),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(n){P.error("Failed to fetch free tier status:",n);return}})(),S=!J.executeMode?new bu0:null,y,h=null;if(S)y=S,h=(async()=>{let n=q?await G.serverStatusPromise:G.serverStatus;await dd0(Q,Z,n);let V0=process.hrtime.bigint(),U0=cd0(Z.dtw,n),N0=L5(n)?n.user.email:void 0,Y0=await A(U0?"dtw":"worker",{dtwUserEmail:N0});if(Y("runMainThread:createThreadPool",V0),S.attach(Y0),U){let W0=await L1(Y0.threadHandles$);if(!W0)throw new G4("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(n)=>{let V0=n instanceof Error?n:Error(String(n));S.setInitError(V0),await iP(n,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(),Ti5({configService:G.configService,threadService:G.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(e1((n)=>{if(!n)return v0.of({});return t6(n.thread$,n.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 G4("Execute mode is not supported with the DTW thread pool",1);let n=y.getWorkerForExecuteMode();if(await kZ4({worker:n,threadID:n.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:n.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 n=pw({jetbrainsOnly:Z.jetbrains});if(n.length===0){if(Z.jetbrains)g=!await G.configService.get("jetbrains.skipInstall")}else if(n.length===1){let V0=n[0];if(V0)_8.selectConfig(V0)}else a=!0}D=process.hrtime.bigint();let m=Qu0("0.0.1772503238-g61db4a",G.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let i=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 n=await L1(y.threadHandles$);if(!n)throw new G4("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:U}]})}D=process.hrtime.bigint();let e=await fK();Y("runMainThread:loadSessionState",D),P.info("Loaded session state:",e);let B0={...e,launchCount:e.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:i,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-03T02:06:20.819Z",pluginPlatform:G.pluginPlatform,pluginService:G.pluginService},(n)=>new Bh0({...n,threadPool:n.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 wi5(gp.dirname(pd0),{recursive:!0}),await Ni5(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 xi5(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 fi5(){u94();let J=xi5(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?Ei5: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(Ii5(P),P.info("Starting Amp CLI.",{version:"0.0.1772503238-g61db4a",buildTimestamp:"2026-03-03T02:06:20.819Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new G4(Y8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await vi5().parseAsync(process.argv)}d84().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await fi5().catch(iP)});async function bi5(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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1772502119-g224ee4",
3
+ "version": "0.0.1772503238-g61db4a",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {