@sourcegraph/amp 0.0.1773302873-g092245 → 0.0.1773304029-gee323e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6116,11 +6116,11 @@ ${W}`))}},error:(q)=>{if(!D)D=!0,z(Error(`Failed to spawn brew: ${q.message}`))}
|
|
|
6116
6116
|
${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
|
|
6117
6117
|
|
|
6118
6118
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6119
|
-
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(q)=>{if(!F)F=!0,z(Error(`Failed to spawn ${X}: ${q.message}`))},complete:()=>{if(!F)F=!0,K()}})})}h0();h0();Ij();async function s80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),U=G.version??G["dist-tags"]?.latest;if(!U)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=DK4(J,U),D=F<0,q,W;if(G.time){let H=G.time[J],B=G.time[U],w=Date.now();if(H)q=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:U,compareResult:F,hasUpdate:D,currentVersionAge:q,latestVersionAge:W}),{hasUpdate:D,latestVersion:U,currentVersion:J,currentVersionAge:q,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var zj5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function t80(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${zj5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=DK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var Gj5=604800000;function FK4(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>Gj5)return{ageMs:Q};return null}function DK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function fx0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?jq(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function bx0(J,Z,Q={}){let Y=new e1,X=Y.pipe(j6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Qz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let U=await Z.get("updates.mode");if(U==="disabled"){V.debug("checking disabled");return}let F=await r80(),D=F==="binary"||F==="brew";V.debug("checking",{currentVersion:J,mode:U,packageManager:F,isBinaryDistribution:D});let q=D?await t80(J):await s80(J,lE());if(!(q.latestVersion&&q.hasUpdate)){V.debug("no update available");return}let W=()=>{if(q.currentVersionAge!==void 0&&q.latestVersionAge!==void 0){let H=q.currentVersionAge-q.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:q.currentVersionAge,latestVersionAge:q.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!U)U=F==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:U});if(F==="brew"){if(!W())Y.next("update-available-brew");return}if(F==="binary"&&process.execPath!==Sx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(U==="warn"){if(!W())Y.next("update-available");return}if(!F){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(F==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await em(q.latestVersion,F);let H=await zH(q.latestVersion),B={from:q.currentVersion,to:q.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Ij();import{stderr as nz}from"node:process";function qK4(J){let Z=new oW().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Px0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6119
|
+
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(q)=>{if(!F)F=!0,z(Error(`Failed to spawn ${X}: ${q.message}`))},complete:()=>{if(!F)F=!0,K()}})})}h0();h0();Ij();async function s80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),U=G.version??G["dist-tags"]?.latest;if(!U)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=DK4(J,U),D=F<0,q,W;if(G.time){let H=G.time[J],B=G.time[U],w=Date.now();if(H)q=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:U,compareResult:F,hasUpdate:D,currentVersionAge:q,latestVersionAge:W}),{hasUpdate:D,latestVersion:U,currentVersion:J,currentVersionAge:q,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var zj5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function t80(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${zj5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=DK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var Gj5=604800000;function FK4(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>Gj5)return{ageMs:Q};return null}function DK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function fx0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?jq(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function bx0(J,Z,Q={}){let Y=new e1,X=Y.pipe(j6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Qz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let U=await Z.get("updates.mode");if(U==="disabled"){V.debug("checking disabled");return}let F=await r80(),D=F==="binary"||F==="brew";V.debug("checking",{currentVersion:J,mode:U,packageManager:F,isBinaryDistribution:D});let q=D?await t80(J):await s80(J,lE());if(!(q.latestVersion&&q.hasUpdate)){V.debug("no update available");return}let W=()=>{if(q.currentVersionAge!==void 0&&q.latestVersionAge!==void 0){let H=q.currentVersionAge-q.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:q.currentVersionAge,latestVersionAge:q.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!U)U=F==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:U});if(F==="brew"){if(!W())Y.next("update-available-brew");return}if(F==="binary"&&process.execPath!==Sx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(U==="warn"){if(!W())Y.next("update-available");return}if(!F){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(F==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await em(q.latestVersion,F);let H=await zH(q.latestVersion),B={from:q.currentVersion,to:q.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Ij();import{stderr as nz}from"node:process";function qK4(J){let Z=new oW().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await Px0(Y.force||!1,Y.verbose||!1,"0.0.1773304029-gee323e"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new oW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await Uj5(Y.targetVersion)});J.addCommand(Q)}async function Uj5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")nz.write(Q1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6120
6120
|
|
|
6121
6121
|
`));try{if(!J){nz.write(Q1.blue(`Checking for updates...
|
|
6122
|
-
`));let{hasUpdate:Y,latestVersion:X}=Cx0()?await t80("0.0.
|
|
6123
|
-
`));let z=await zH("0.0.
|
|
6122
|
+
`));let{hasUpdate:Y,latestVersion:X}=Cx0()?await t80("0.0.1773304029-gee323e"):await s80("0.0.1773304029-gee323e",lE());if(!Y){let V=fx0("0.0.1773304029-gee323e"),K=V?.age?`released ${V.age} ago`:`built ${jq(new Date("2026-03-12T08:33:00.594Z"))} ago`;nz.write(Q1.green(`✓ Amp is already up to date on version ${"0.0.1773304029-gee323e"} (${K})
|
|
6123
|
+
`));let z=await zH("0.0.1773304029-gee323e");if(z.warning)nz.write(`
|
|
6124
6124
|
`+Q1.yellow(z.warning)+`
|
|
6125
6125
|
`);process.exit(0)}if(!X)nz.write(Q1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}nz.write(Q1.blue(`Updating to version ${J}...
|
|
6126
6126
|
`)),await em(J,void 0,(Y)=>{nz.write(Q1.dim(`Running: ${Y}
|
|
@@ -6881,7 +6881,7 @@ Available parameters:`),F.push(LT5(Z));return F.join(`
|
|
|
6881
6881
|
See https://ampcode.com/manual#toolboxes`);return Z[0]||EI}function OG4(J,Z){let Q=J.command("tools").alias("tool").description("Tool management commands");return RT5(Q,Z),PT5(Q,Z),CT5(Q,Z),TT5(Q,Z),Q}function RT5(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,Y)=>{let X=Y.optsWithGlobals(),V=await Z(Y,X),K=X.sp||X.systemPrompt;if(X.inspect&&K){let G=k6(V.serverStatus)?V.serverStatus.features.some((D)=>D.name===v$.HARNESS_SYSTEM_PROMPT&&D.enabled):!1,U=k6(V.serverStatus)?V.serverStatus.user.email:void 0;if(!G&&!(U&&TJ(U)))process.stderr.write(`You are not allowed to do this.
|
|
6882
6882
|
`),await V.asyncDispose(),V.cleanupTerminal(),process.exit(1);let F=await IT5(K,"utf-8").catch(()=>K);S$("systemPrompt",F)}let z=0;await GG4({json:X.json,inspect:X.inspect,isTTY:V.context.isTTY,mode:X.mode,toolService:V.toolService,configService:V.configService,mcpService:V.mcpService,skillService:V.skillService,threadService:V.threadService,fileSystem:V.fileSystem,getThreadEnvironment:V.getThreadEnvironment,serverStatus:V.serverStatus,toolboxService:V.toolboxService,stderr:process.stderr,stdout:process.stdout,exit:(G)=>{z=G}}),await V.asyncDispose(),V.cleanupTerminal(),process.exit(z)})}function PT5(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,Y,X)=>{let V=X.optsWithGlobals(),K=await Z(X,V),z=0,G=K.toolService;await qG4({toolName:Q,json:V.json,isTTY:K.context.isTTY,mode:V.mode,toolService:G,mcpService:K.mcpService,stdout:process.stdout,exit:(U)=>{z=U}}),await K.asyncDispose(),K.cleanupTerminal(),process.exit(z)})}function CT5(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,Y,X)=>{let V="bun";if(Y.zsh)V="zsh";else if(Y.bash)V="bash";else if(Y.bun)V="bun";try{let K=jT5();await DG4({fs:FG4,toolName:Q,toolboxDir:K,force:Y.force,language:V,stdout:process.stdout,exit:process.exit})}catch(K){process.stdout.write(`${K instanceof Error?K.message:String(K)}
|
|
6883
6883
|
`),process.exit(1)}})}function TT5(J,Z){let Q=[Q1.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 ${Q1.green("amp tools list")} to get a list of all tools available in this environment.`,"",`Use ${Q1.green("amp tools show <tool-name>")} to see the schema of a tool.`].join(`
|
|
6884
|
-
`);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(Y,X,V)=>{let K=V.optsWithGlobals(),z=await Z(V,K),G=0,U=V.args.slice(1),F;if(wG4()){let D=[];for await(let q of process.stdin)D.push(q);F=Buffer.concat(D).toString("utf-8").trim()}await HG4({toolName:Y,rawArgs:U,stdinInput:F,only:X.only,stream:X.stream,threadDeps:z,stdout:process.stdout,stderr:process.stderr,exit:(D)=>{G=D}}),await z.asyncDispose(),z.cleanupTerminal(),process.exit(G)})}h4();H1();function _90(J){return{get thread$(){return J.thread$},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return J.toolProgressByToolUseID$},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,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 _T5(J){return{id:J,created:Date.now(),v:0,messages:[]}}class Af0{placeholderThreadID;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new F4({});pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=z8()){this.placeholderThreadID=J;let Z=new F4(_T5(this.placeholderThreadID)),Q=new F4(new Map),Y=new F4(IP(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new F4(_90({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(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:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,V,K)=>(await this.waitForActiveHandle()).resolveApproval(X,V,K),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,V)=>{this.readyResolve=X,this.readyReject=V}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],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 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(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return E1(J.threadHandles$.pipe(G5((Z)=>Z!==null)))}}h0();n50();Z_0();H1();h0();x$();H1();async function v90(J,Z,Q,Y={}){let X={...J?{threadId:J}:{},...Y.repositoryURL?{repositoryURL:Y.repositoryURL}:{},...!J&&Y.executorType?{executorType:Y.executorType}:{}},V=await L8("/api/durable-thread-workers",LG4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)},Q),Z);if(!V.ok)throw Error(`Failed to create DTW thread: ${V.status} ${await V.text()}`);let K=await V.json();if(!K.threadId||!K.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");return{threadId:K.threadId,wsToken:K.wsToken}}async function ST5(J,Z,Q){let Y=await L8(`/api/threads/${J}`,LG4(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function LG4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function S90(J){let Z=N2.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=N2.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function vT5(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let V=S90(X);if(V)Q.add(V);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function kT5(J){let Z=new Set;for(let Q of J){let Y=S90(Q);if(Y)Z.add(Y)}return Z}function Hg(J,Z){let Q=[...J];for(let Y of Z)if(Y.type==="text"){let X=Q[Q.length-1];if(X?.type==="text")Q[Q.length-1]={...X,text:X.text+Y.text};else Q.push(Y)}else if(Y.type==="tool_use"){let X=Q.findIndex((V)=>V.type==="tool_use"&&V.id===Y.id);if(X>=0)Q[X]=Y;else Q.push(Y)}else if(Y.type==="thinking"){let X=Q[Q.length-1];if(X?.type==="thinking")Q[Q.length-1]={...X,thinking:X.thinking+Y.thinking};else Q.push(Y)}else Q.push(Y);return Q}function yT5(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function MG4(J){if(typeof J==="string")return J;if(!J||typeof J!=="object")return;if("output"in J&&typeof J.output==="string")return J.output;if("value"in J)return MG4(J.value);return}function uT5(J){return J.type==="text"}function xT5(J){if(J===void 0)return;let Z;try{Z=M80(J,"snapshot")}catch{return}if(Z.type==="snapshot")return MG4(Z.value);let Q=(Z.blocks??[]).filter(uT5).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}function fT5(J,Z){let Q=J.parentToolCallId,{completedMessages:Y}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;let V=J.blocks??[];if(V.length>0)if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){let V=J.blocks;if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}let X=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")X=Hg(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&X.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:X,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=Hg([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Hg(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)Y.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=Hg([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Hg(Z.streamingBlocks,J.blocks)}}function bT5(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let V of Z){if(Q.has(V.messageId))continue;Q.add(V.messageId);let K=X++;if(V.role==="assistant")Y.push({role:"assistant",content:V.blocks,state:{type:"complete",stopReason:"end_turn"},messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId});else Y.push({role:"user",content:V.blocks,messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function hT5(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y))return Z;Q.add(Y);let X=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];if(J.message.role==="info")return[...Z,{role:"info",content:J.message.content,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,userState:J.message.userState,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function mT5(J,Z){let Q=Z.findIndex((z)=>S90(z)===J.messageId),Y=Z.findIndex((z)=>S90(z)===J.truncateToMessageId);if(Q<0||Y<0)throw Error("Unable to apply edit: message mapping not found");let X=Z[Q];if(!X||X.role!=="user")throw Error("Unable to apply edit: target message is not editable");let V={role:"user",content:J.content,messageId:X.messageId,dtwMessageID:J.messageId},K=Z.slice(0,Y+1);return K[Q]=V,K}function Bg(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function EG4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:J.id,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:J.id}}}function gT5(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>EG4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:EG4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function pT5(J,Z){let Q=gT5(Z);return $x0(Bg(J)??[],Q,{dedupeAdded:!0})}function dT5(J,Z){return{baseURL:J.workerUrl??mY(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>v90(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}class k90{threadSubject;agentLoopStateSubject=new F4("idle");editErrorSubject=new e1;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new F4(new Map);toolProgressSubject=new e1;subscriptions=[];threadVersion;messages;queuedMessages;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;contextWindowRatio=null;compactionStateSubject=new F4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Bg(J.queuedMessages)??[],this.processedIds=Q,this.transport=Z,this.threadVersion=Y,this.threadSubject=new F4(J)}static async create(J){let Z=await v90(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType}),Q=await ST5(Z.threadId,J.configService,J.apiKey),{messages:Y,processedIds:X}=vT5(Q),V={...Q,id:Z.threadId,messages:Y,queuedMessages:Bg(Q.queuedMessages)},K=new QH(dT5(J,Z)),z=new k90(V,K,X,Q.v);try{return await z.connect(),z}catch(G){throw z.dispose(),G}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getContextWindowRatio(){return this.contextWindowRatio}getCompactionState(){return this.compactionState}compactionStateChanges(){return this.compactionStateSubject}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;let Q={...Z,...{env:J}};this.threadSubject.next(Q)}setAgentMode(J){if(!J)return;let Z=this.threadSubject.getValue();if(Z.agentMode)return;let Q={...Z,agentMode:J};this.threadSubject.next(Q)}emitThread(){let J=this.threadSubject.getValue(),Z=yT5(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),Y=Z?[...this.messages,Z]:[...this.messages],X=Y.reduce((K,z)=>Math.max(K,z.messageId),-1)+1,V={...J,id:this.threadId,v:this.threadVersion,title:this.threadTitle,messages:Y,queuedMessages:this.queuedMessages.length>0?Bg(this.queuedMessages):void 0,nextMessageId:Math.max(X,0)};this.threadSubject.next(V)}emitToolProgress(){this.toolProgressByToolUseIDSubject.next(new Map(this.toolProgressByToolUseID))}clearToolProgress(J){if(this.toolProgressByToolUseID.delete(J))this.emitToolProgress()}clearToolProgressFromBlocks(J){for(let Z of J)if(Z.type==="tool_result")this.clearToolProgress(Z.toolUseID)}setCompactionState(J){if(this.compactionState===J)return;this.compactionState=J,this.compactionStateSubject.next(J)}runTransportHandler(J,Z){try{Z()}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);j.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${Y}`)}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionInfo,Q=J.state!==this.lastConnectionState,Y=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!Y)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(Y&&Z)this.logConnectionRoleTransition(Z,J);let X=J.state;if(X==="connected"&&this.lastConnectionState!=="connected")this.transport.resumeFromVersion(this.threadVersion);this.lastConnectionState=X,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?au0(J.message):null;if(j.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:Z!==null?"Received invalid DTW payload (see parse details)":J.message,parseErrorSource:Z?.source,parseErrorDirection:Z?.direction,parseErrorStage:Z?.stage,parseErrorSummary:Z?.summary,parseErrorMessageType:Z?.messageType,parseErrorIssues:Z?.issues,parseErrorPayloadPreview:Z?.payloadPreview}),J.code==="PARSE_ERROR"){let Q=Z?.messageType?` (type="${Z.messageType}")`:"";this.editErrorSubject.next(`Received an invalid DTW message${Q}. The connection will continue running. Check logs for details.`)}})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state,this.agentLoopStateSubject.next(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(fT5(J,this.deltaState),J.role==="user"&&(J.state==="complete"||J.state==="error")&&J.blocks)this.clearToolProgressFromBlocks(J.blocks);if(this.deltaState.completedMessages.length>0){for(let Z of this.deltaState.completedMessages)if(Z.role==="user")this.clearToolProgressFromBlocks(Z.blocks);this.messages=bT5(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{this.toolProgressSubject.next(J);let Z=J.toolCallId,Q=xT5(J.progress);if(Q===void 0){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}if(this.toolProgressByToolUseID.get(Z)===Q)return;this.toolProgressByToolUseID.set(Z,Q),this.emitToolProgress()})}}),this.transport.compactionEvents().subscribe({next:(J)=>{this.runTransportHandler("compactionEvents",()=>{if(J.type==="compaction_started"){this.setCompactionState("compacting");return}this.setCompactionState("idle")})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{if(this.messages=hT5(J,this.messages,this.processedIds),J.message.role==="user")this.clearToolProgressFromBlocks(J.message.content);if(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=mT5(J,this.messages),this.processedIds=kT5(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=pT5(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"){j.info("[dtw] Transport reconnected",Q);return}j.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){j.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){j.warn("[dtw] Transport disconnected",Q);return}j.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){j.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){return this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q})}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Bg(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>Q.id);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.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}h0();l5();d9();f$();Y00();h4();xU();fv0();O4();H1();C$();function cT5(J){let Z=-1;for(let V=J.messages.length-1;V>=0;V--)if(J.messages[V]?.role==="assistant"){Z=V;break}if(Z<0)return{running:0,blocked:0};let Q=J.messages[Z];if(!Q)return{running:0,blocked:0};let Y=new Map;for(let V of J.messages.slice(Z+1)){if(V.role!=="user")continue;for(let K of V.content)if(K.type==="tool_result")Y.set(K.toolUseID,K.run)}let X=0;for(let V of Q.content){if(V.type!=="tool_use")continue;let K=Y.get(V.id);if(!K||!w8(K))X++}return{running:X,blocked:0}}function lT5(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function iT5(J){let Z=lT5(J);if(Z)return Z;return!1}function If0(J,Z,Q={files:[]},Y=void 0){let X=cT5(J),V=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let K=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:K>0?"tool-running":!1,toolState:{running:K,blocked:V}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:V}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:iT5(J),toolState:{running:X.running,blocked:V}}}h4();class jf0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.buildProjection();case"edit":return this.optimisticEdit(J)}}optimisticSubmit(J){if(Q_5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(F_5(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=zw0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:$_5(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return aT5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingEdit)}reconcilePending(J){let Z=eT5(this.authoritativeThread);this.pendingMessageSubmits=Y_5(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=z_5(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingEdit=G_5(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return nT5(this.authoritativeThread,(Z)=>oT5(Z,J),(Z)=>rT5(Z,this.pendingMessageSubmits),(Z)=>sT5(Z,this.pendingQueuedSubmits))}}function nT5(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function aT5(J,Z,Q){return J.length>0||Z.length>0||Q!==void 0}function oT5(J,Z){if(!Z)return J;let Q=TI1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,V=J.messages.slice(0,Y+1);return V[Y]={...X,content:Z.content},{...J,messages:V,nextMessageId:Kw0({messages:V,nextMessageId:J.nextMessageId})}}function rT5(J,Z){if(Z.length===0)return J;let Q=Kw0(J),Y=Z.map((X,V)=>IG4(X,Q+V));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function sT5(J,Z){if(Z.length===0)return J;let Q=Z.map(tT5);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function IG4(J,Z){return{role:"user",content:J.content,userState:J.userState,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function tT5(J){return{id:J.clientMessageID,queuedMessage:IG4(J,-1)}}function eT5(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let V of J.messages)if(typeof V.dtwMessageID==="string"){if(X.add(V.dtwMessageID),V.role==="user")Z.add(V.dtwMessageID),Y.set(V.dtwMessageID,V)}for(let V of J.queuedMessages??[])Q.add(V.id);return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function $_5(J,Z){return J.messages.slice(Z+1).map((Q)=>Q.dtwMessageID).filter((Q)=>typeof Q==="string")}function J_5(J,Z){return J.messages.some((Q)=>Q.role==="user"&&Q.dtwMessageID===Z)}function Z_5(J,Z){return(J.queuedMessages??[]).some((Q)=>Q.id===Z)}function Q_5(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||J_5(Q,Y)||Z_5(Q,Y)}function Y_5(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:V}=X_5(Y,Q.userMessageIDs);if(X.length===0)return[];let K=V_5(J,Z);if(!K)return X;let z=K_5(K,V,X.length);return X.slice(z)}function X_5(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function V_5(J,Z){let Q=AG4(J),Y=AG4(Z);if(!(Q.length<=Y.length&&Q.every((V,K)=>V.dtwMessageID===Y[K]?.dtwMessageID)))return;return Y.slice(Q.length)}function K_5(J,Z,Q){let Y=0;for(let X of J){if(typeof X.dtwMessageID==="string"&&Z.has(X.dtwMessageID))continue;if(Y++,Y===Q)return Y}return Y}function AG4(J){return J.messages.filter((Z)=>Z.role==="user")}function z_5(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let V=Y.findIndex((K)=>Gw0(X.content,K.queuedMessage.content));if(V>=0)return Y.splice(V,1),!1;return!0})}function G_5(J,Z){if(!Z)return;return U_5(J,Z)?void 0:Z}function U_5(J,Z){let Q=J.userMessagesByID.get(Z.targetMessageID);if(!Q)return!1;if(!Gw0(Q.content,Z.content))return!1;return Z.truncatedMessageIDs.every((X)=>!J.messageIDsInTimeline.has(X))}function F_5(J){return D_5.has(J)}var D_5=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);class Rf0{threadWriter;deps;thread$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadViewStateSubject;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;handshakeManager;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);inferenceErrorsSubject=new e1;pendingSkills$=this.pendingSkillsSubject;fileChanges={files:[]};activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];providerSubscriptions=null;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let Y=SH0("info"),X=SH0("error");this.toolRunner=new dm({clientID:this.clientID,transport:this.provider.transport,executeBuiltinTool:()=>null,invokeTool:(G)=>this.invokeToolForLease(G),batchGuidanceFiles:u80,renderToolRunError:ex,log:{info:(G,U)=>Y(G,U),error:(G,U)=>X(G,{error:U}),wsMessage:(G,U,F)=>{j.debug("DTW executor tool runner message",{direction:G,clientID:U,...typeof F==="object"&&F!==null?F:{message:F}})}}}),this.handshakeManager=this.createHandshakeManager();let V=J.getThread();this.optimisticThreadProjection=new jf0(V,J.getAgentLoopState());let K=this.optimisticThreadProjection.resolve(V),z=If0(K,J.getAgentLoopState(),this.fileChanges,this.currentEphemeralError());this.threadSubject=new F4(K),this.thread$=this.threadSubject,this.threadViewStateSubject=new F4(z),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges(),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handshakeManager.ensureHandshake("connect")}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.threadWriter.write(J),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getResolvedTokenUsage(){let J=Y2(this.thread$.getValue());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.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.handshakeManager.dispose(),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),this.threadSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){await this.handshakeManager.ensureReady();let Z=this.thread$.getValue();if(J.editIndex!==void 0){let K=Z.messages[J.editIndex];if(!K||K.role!=="user"||!K.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");this.provider.transport.editUserMessage(K.dtwMessageID,J.content,mu0(),J.agentMode);let z=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:K.dtwMessageID,content:J.content});this.writeThread(z);return}if(!Z.messages.some((K)=>K.role==="user")&&!Z.agentMode&&J.agentMode)this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=await this.collectUserState(),X=this.provider.sendUserMessage(J.content,J.agentMode,Y),V=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:X,content:J.content,userState:Y});this.writeThread(V)}async restoreTo(J){await this.handshakeManager.ensureReady();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((K)=>K.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((K)=>K.type==="text"||K.type==="image").map((K)=>{if(K.type==="image")return{...K,source:{...K.source}};return{...K}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.transport.editUserMessage(Y.dtwMessageID,X,mu0());let V=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(V)}async queueMessage(J){await this.handshakeManager.ensureReady();let Z=await this.collectUserState(),Q=this.provider.sendUserMessage(J,void 0,Z),Y=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Q,content:J,userState:Z});this.writeThread(Y)}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.handshakeManager.ensureReady(),this.provider.interruptQueuedMessage(J)}async setVisibility(J){let Z=await M6.setThreadMeta({thread:this.provider.threadId,meta:yV(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}updateThread(J){let Z=this.threadWriter.update(J),Q=this.optimisticThreadProjection.resolve(Z);if(Q!==Z)this.threadWriter.write(Q);this.threadSubject.next(Q)}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}invokeBashTool(J,Z){let Q=PY4();return new v0((Y)=>{let X=!1,V=null,K=(F)=>{this.provider.transport.appendManualBashInvocation({args:J,run:F,hidden:Z.hidden})},z=(F,D={emitRun:!0})=>{if(X)return;if(X=!0,K(F),D.emitRun)Y.next(F);Y.complete()},G=(F)=>F instanceof Error?F.message:String(F),U=()=>{V?.unsubscribe(),z({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",U),(async()=>{try{let F=await OF({toolName:P6,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:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});if(X)return;Y.next({status:"in-progress"}),V=this.deps.toolService.invokeTool(P6,{args:J},F).subscribe({next:(D)=>{if(X)return;if(Y.next(D),D.status!=="in-progress")z(D,{emitRun:!1})},error:(D)=>{z({status:"error",error:{message:G(D)}})}})}catch(F){z({status:"error",error:{message:G(F)}})}})(),()=>{V?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",U)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=R9.safeParse(J);if(!Y.success)return;this.provider.transport.resolveToolApproval(Y.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.thread$.getValue();return(await Jz({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),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((V)=>{if(V.role==="user"){for(let K of V.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of V.content)if(K.type==="tool_use")Q.add(K.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[V]of X.entries())if(!Q.has(V))Y.add(V);return Y}async collectUserState(){try{return await o50()??sx}catch(J){return j.warn("Failed to collect IDE user state for DTW message",{error:J}),sx}}createHandshakeManager(){return new pm({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{j.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){j.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(mE));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let V=mE(X);if(this.toolRunner.sentApprovalRequests.has(V))continue;let K=v80(X);this.provider.transport.sendExecutorToolApprovalRequest(K),this.toolRunner.sentApprovalRequests.add(V)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted)}syncExecutorTools(J){let Z=this.provider.transport.getConnectionInfo();if(Z.state!=="connected"||Z.role!=="executor")return;this.advertisedExecutorTools=mm({transport:this.provider.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{this.handshakeManager.handleConnectionChange(J)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.transport.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.transport.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(CC(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){j.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await x80({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",previouslyAdvertisedTools:this.advertisedExecutorTools,initialToolDiscovery:this.deps.initialToolDiscovery});this.advertisedExecutorTools=Z,this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=f80(this.provider.transport,Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await t$();this.provider.setEnvironment({initial:J})}catch(J){j.debug("Failed to apply local environment",{error:J})}}async invokeToolForLease(J){let Z=await OF({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.toolRunner.discoveredGuidanceFileURIs}),Q=typeof J.args==="object"&&J.args!==null?J.args:{};return this.deps.toolService.invokeTool(J.toolName,{args:Q},Z)}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await h80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await m80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await Q00(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(If0(this.threadSubject.getValue(),this.provider.getAgentLoopState(),this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}class Ng{deps;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});activeThreadHandleSubject=new F4(null);allConnectedThreadActivityStatusesSubject=new F4({});threadHandleMap=new Map;pendingHandoffSeeds=new Map;activeThreadContextID;queueOnSubmitByDefault=!0;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}isDTWMode(){return!0}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThread(J)}async switchThread(J){await this.activateThread(J)}async createHandoff(J,Z){let Q=this.activeProvider?.getThread();if(!Q)throw Error("No thread available for handoff");if(!Q.env?.initial){let z=await this.deps.getThreadEnvironment();Q={...Q,env:{initial:z}}}let Y=Z.signal??new AbortController().signal,X=await AP(Q,Z.goal,Z.images,this.deps.configService,Y,this.deps.osFileSystem),V=wg(Z.queuedMessages??Q.queuedMessages),{threadID:K}=await this.createThreadWithDraft({parentThreadID:Q.id,agentMode:Z.agentMode??Q.agentMode,draft:X,queuedMessages:V,comment:Z.goal,parentMessageIndex:Q.messages.length>0?Q.messages.length-1:void 0});return K}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){j.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 z=Z.thread$.getValue().id;this.activeThreadContextID=z,this.activeThreadHandleSubject.next(Z),this.addToRecentThreads(z),this.syncAllConnectedThreadActivityStatuses(),j.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:z,handleCount:this.threadHandleMap.size});return}let Q=await this.createProvider(J),Y=await this.deps.threadService.exclusiveSyncReadWriter(Q.threadId),X=rP({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q.threadId),V=new Rf0(Q,Y,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,initialToolDiscovery:this.deps.initialToolDiscovery,fs:X,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()}}),K=this.pendingHandoffSeeds.get(Q.threadId);if(K){this.pendingHandoffSeeds.delete(Q.threadId);let z={...V.thread$.getValue(),draft:K.draft,autoSubmitDraft:K.autoSubmitDraft,relationships:K.relationships,queuedMessages:wg(K.queuedMessages)};V.writeThread(z)}this.threadHandleMap.set(Q.threadId,V),V.startProviderSubscription((z)=>{this.applyProviderState(Q.threadId,z)}),await this.applyProviderState(Q.threadId,Q.getThread()),this.activeThreadContextID=Q.threadId,this.activeThreadHandleSubject.next(V),this.addToRecentThreads(Q.threadId),j.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 Y=q_5(Q.thread$.getValue(),Z),X=Q.resolveAuthoritativeThread(Y);Q.writeThread(X),await this.deps.threadService.flushVersion(J,X.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J]:X.title}),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){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return k90.create({ampURL:this.deps.ampURL,configService:this.deps.configService,executorType:Q,repositoryURL:Z,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 Z=await this.deps.getThreadEnvironment(),{threadId:Q}=await v90(void 0,this.deps.configService,await this.getApiKey(),{executorType:"local-client",repositoryURL:Z.trees?.[0]?.repository?.url}),Y=await this.deps.threadService.exclusiveSyncReadWriter(Q),X=Date.now(),V=J.parentThreadID?[{threadID:J.parentThreadID,type:"handoff",role:"child",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X}]:void 0,K={id:Q,created:X,v:1,agentMode:J.agentMode,messages:[],draft:J.draft,autoSubmitDraft:!0,queuedMessages:wg(J.queuedMessages),env:{initial:Z},relationships:V};if(Y.write(K),await this.deps.threadService.flushVersion(Q,K.v).catch(()=>{return}),await Y.asyncDispose(),this.pendingHandoffSeeds.set(Q,{draft:K.draft,autoSubmitDraft:K.autoSubmitDraft,relationships:K.relationships,queuedMessages:wg(K.queuedMessages)}),J.parentThreadID){let z=(U)=>{if(!U.relationships)U.relationships=[];if(!U.relationships.some((D)=>D.threadID===Q&&D.type==="handoff"&&D.role==="parent"))U.relationships.push({threadID:Q,type:"handoff",role:"parent",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X})},G=this.threadHandleMap.get(J.parentThreadID);if(G)G.updateThread((U)=>{z(U)});else{let U=await this.deps.threadService.exclusiveSyncReadWriter(J.parentThreadID);U.update((F)=>{z(F)}),await U.asyncDispose()}}return{threadID:Q}}}function wg(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function q_5(J,Z){let Q=Z.messages.reduce((Y,X)=>Math.max(Y,X.messageId),-1)+1;return{...Z,draft:Z.draft??J.draft,autoSubmitDraft:Z.autoSubmitDraft??J.autoSubmitDraft,env:Z.env??J.env,relationships:Z.relationships??J.relationships,queuedMessages:wg(Z.queuedMessages),nextMessageId:Math.max(Q,0)}}Ff0();import{readFile as sh5}from"node:fs/promises";import th5 from"node:readline";import{setTimeout as eh5}from"node:timers/promises";D3();x$();ij();h4();HF();H1();import{mkdir as W_5,writeFile as H_5}from"node:fs/promises";import B_5 from"node:path";function w_5(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function N_5(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function O_5(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${N_5(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function Pf0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class Cf0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=w_5(J.traceName),Y=O_5(Z,Q);this.traceFilePath=B_5.join(J.traceDir,`${Y}.json`),this.session={schemaVersion:1,sessionID:Y,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(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,eventName:J,payload:Pf0(Z)};this.session.protocolEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Pf0(Z)};this.session.providerStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Pf0(Z)};this.session.adapterStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,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 W_5(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await H_5(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function jG4(J,Z){let Q=[J.connectionChanges().subscribe({next:(Y)=>Z("connection_changes",Y)}),J.errors().subscribe({next:(Y)=>Z("errors",Y)}),J.errorEvents().subscribe({next:(Y)=>Z("error_events",Y)}),J.agentStates().subscribe({next:(Y)=>Z("agent_states",Y)}),J.deltas().subscribe({next:(Y)=>Z("deltas",Y)}),J.messageEvents().subscribe({next:(Y)=>Z("message_events",Y)}),J.messageEdited().subscribe({next:(Y)=>Z("message_edited",Y)}),J.editRejected().subscribe({next:(Y)=>Z("edit_rejected",Y)}),J.threadTitles().subscribe({next:(Y)=>Z("thread_titles",Y)}),J.queuedMessages().subscribe({next:(Y)=>Z("queued_messages",Y)}),J.retryEvents().subscribe({next:(Y)=>Z("retry_events",Y)}),J.cancelledEvents().subscribe({next:(Y)=>Z("cancelled_events",Y)}),J.toolLeases().subscribe({next:(Y)=>Z("tool_leases",Y)}),J.toolLeaseRevoked().subscribe({next:(Y)=>Z("tool_lease_revoked",Y)}),J.toolApprovalQueue().subscribe({next:(Y)=>Z("tool_approval_queue",Y)}),J.executorToolApprovalResponses().subscribe({next:(Y)=>Z("executor_tool_approval_responses",Y)}),J.toolProgress().subscribe({next:(Y)=>Z("tool_progress",Y)}),J.executorErrors().subscribe({next:(Y)=>Z("executor_errors",Y)}),J.executorConnected().subscribe({next:(Y)=>Z("executor_connected",Y)}),J.executorRollbackRequests().subscribe({next:(Y)=>Z("executor_rollback_requests",Y)}),J.observers().subscribe({next:(Y)=>Z("observers",Y)}),J.executorStatuses().subscribe({next:(Y)=>Z("executor_statuses",Y)}),J.environmentUpdates().subscribe({next:(Y)=>Z("environment_updates",Y)}),J.gitStatuses().subscribe({next:(Y)=>Z("git_statuses",Y)}),J.compactionEvents().subscribe({next:(Y)=>Z("compaction_events",Y)}),J.compactionRecords().subscribe({next:(Y)=>Z("compaction_records",Y)})];return{unsubscribe:()=>{for(let Y of Q)Y.unsubscribe()}}}h4();O4();C$();function lC(J,Z){let Q=(G)=>G===I7||G===I3||G===I$||G===q9,Y=new Map;for(let G of J)if(G.type==="toolResult"&&Q(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=(G,U)=>{let F=Y.get(G)?.toolRun;if(!F||F.status!=="cancelled"||w8(U))return U;return{status:"cancelled",reason:"Parent subagent was cancelled"}},V=Array.from(Y.values()),K={},z={};for(let{toolUseId:G,toolRun:U}of V){let F=[],D;if(U.status==="in-progress"||U.status==="done"||U.status==="error"||U.status==="cancelled")D=U.progress;if(Array.isArray(D)){let q=0;for(let W of D)if(W.tool_uses)for(let H of W.tool_uses){let B=`${G}:progress:${q++}`,w=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},N=H.normalized_name??H.tool_name;F.push({toolUse:HI(N,H.input,B),toolRun:X(G,w)})}}K[G]=F}if(Z){let G=new Map;for(let U of Z.messages){let F=U.parentToolUseId;if(!F)continue;let D=G.get(F)??[];D.push(U),G.set(F,D)}for(let[U,F]of G){let{items:D}=PF({id:Z.id,messages:F},{includeSubagentMessages:!0});z[U]=D.filter((q)=>q.type==="toolResult").map((q)=>({toolUse:q.toolUse,toolRun:X(U,q.toolResult.run)}))}}for(let[G,U]of Object.entries(z))if(U.length>0)K[G]=U;return K}function PF(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[K]of J.messages.entries())Y.add(K);else for(let[K,z]of J.messages.entries())if(!z.parentToolUseId)Y.add(K);let X=new Map,V=new Set;for(let[K,z]of J.messages.entries()){if(!Y.has(K))continue;let G=`${z.role}-${K}`;switch(z.role){case"assistant":{let U=z.state.type==="streaming";for(let D of z.content)if(D.type==="tool_use"){if(X.set(D.id,D),U)V.add(D.id)}if(z.content.some((D)=>D.type==="text"&&D.text.trim()||D.type==="thinking"))Q.push({type:"message",id:G,message:z});for(let D of z.content)if(D.type==="tool_use"){let q=!1;for(let W=K+1;W<J.messages.length;W++){if(!Y.has(W))continue;let H=J.messages[W];if(H){for(let B of H.content)if(B.type==="tool_result"&&B.toolUseID===D.id){q=!0;break}}if(q)break}if(!q)Q.push({type:"toolResult",id:D.id,toolUse:D,toolResult:{type:"tool_result",toolUseID:D.id,run:{status:"in-progress"}}})}break}case"info":{if(z.content.some((F)=>F.type==="manual_bash_invocation"||F.type==="summary"&&F.summary.type==="message"))Q.push({type:"message",id:G,message:z});break}case"user":{let U=z.content.some((F)=>F.type==="text"&&F.text.trim()||F.type==="image");for(let F of z.content)if(F.type==="tool_result"){let D=X.get(F.toolUseID)??T$(J,F.toolUseID);if(!D)throw Error(`(bug) tool use ${F.toolUseID} not found`);Q.push({type:"toolResult",id:F.toolUseID,toolUse:D,toolResult:F})}if(U)Q.push({type:"message",id:G,message:z});break}}}return{items:Q}}l5();h4();HF();H1();class C3{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((V,K)=>{let z=this.neighborMap[K].filter((G)=>this.state[G]).length;if(V)return z===2||z===3;return z===3||z===6}),Z=J.every((V,K)=>V===this.state[K]),Q=this.previousState.length>0&&J.every((V,K)=>V===this.previousState[K]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((V)=>!V),X=J.filter((V)=>V).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let V;do V=Array.from({length:8},()=>Math.random()>0.6);while(V.filter((K)=>K).length<3);this.state=V,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 p1 extends $${createElement(){return new Tf0(this)}}class Tf0 extends NQ{_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 fV(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{let Z=this._child,Q=this.findNearestRenderObjectAncestor();if(Q&&Z.renderObject)Q.dropChild(Z.renderObject);else if(!Q&&Z.renderObject)Z.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Q&&this._child.renderObject)Q.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Q&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}}class v4{color;border;constructor(J,Z){this.color=J;this.border=Z}}class u1{top;right;bottom;left;constructor(J,Z,Q,Y){this.top=J;this.right=Z;this.bottom=Q;this.left=Y}static all(J){return new u1(J,J,J,J)}static symmetric(J,Z){return new u1(Z,J,Z,J)}}class v1{color;width;style;constructor(J=I0.black,Z=1,Q="rounded"){this.color=J;this.width=Z;this.style=Q}}class c0 extends H3{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Z,width:Q,height:Y,padding:X,margin:V,decoration:K,constraints:z}={}){super({...J?{key:J}:{},...Z?{child:Z}:{}});this.width=Q,this.height=Y,this.padding=X,this.margin=V,this.decoration=K,this.constraints=z}createElement(){return new RG4(this)}createRenderObject(){return new y90(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof y90))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}}class RG4 extends tz{constructor(J){super(J)}mount(){super.mount(),this._updateForceDim()}performRebuild(){super.performRebuild(),this._updateForceDim()}_updateForceDim(){if(!this.renderObject)return;let J=new fV(this,this.widget),Z=OQ.shouldForceDim(J);if(this.renderObject instanceof y90)this.renderObject.setForceDim(Z)}}class y90 extends M4{_width;_height;_padding;_margin;_decoration;_constraints;_forceDim=!1;constructor(J,Z,Q,Y,X,V){super();this._width=J;this._height=Z;this._padding=Q;this._margin=Y;this._decoration=X;this._constraints=V}setForceDim(J){if(this._forceDim!==J)this._forceDim=J,this.markNeedsPaint()}updateProperties(J,Z,Q,Y,X,V){this._width=J,this._height=Z,this._padding=Q,this._margin=Y,this._decoration=X,this._constraints=V,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=this._margin?.horizontal??0,Q=this._margin?.vertical??0,Y=this._padding?.horizontal??0,X=this._padding?.vertical??0,V=this._decoration?.border,K=(V?.left?1:0)+(V?.right?1:0),z=(V?.top?1:0)+(V?.bottom?1:0);this.sendDebugData({margin:this._margin,padding:this._padding,decoration:this._decoration,width:this._width,height:this._height,constraints:this._constraints});let G=this._width!==void 0||this._height!==void 0?this._constraints?.tighten({width:this._width,height:this._height})??M1.tightFor({width:this._width,height:this._height}):this._constraints,U=G?J.enforce(G):J,F=U.maxWidth-Z-Y-K,D=U.maxHeight-Q-X-z,q=new M1(Math.max(0,U.minWidth-Z-Y-K),Math.max(0,F),Math.max(0,U.minHeight-Q-X-z),Math.max(0,D)),W,H;if(this.children.length>0){let N=this.children[0];if(!(N instanceof M4))throw Error("Child must be a RenderBox");N.layout(q),W=N.size.width,H=N.size.height;let O=V?.left?1:0,E=V?.top?1:0,L=(this._margin?.left??0)+O+(this._padding?.left??0),M=(this._margin?.top??0)+E+(this._padding?.top??0);N.setOffset(L,M)}else if(q.maxWidth!==1/0&&q.maxHeight!==1/0)W=q.maxWidth,H=q.maxHeight;else W=q.minWidth,H=q.minHeight;let B,w;if(U.minWidth===U.maxWidth&&isFinite(U.maxWidth))B=U.maxWidth;else B=W+Y+K+Z;if(U.minHeight===U.maxHeight&&isFinite(U.maxHeight))w=U.maxHeight;else w=H+X+z+Q;this.setSize(U.constrain(B,w).width,U.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,Y=this._decoration?.border,X=(Y?.left?1:0)+(Y?.right?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((Y?.top?1:0)+(Y?.bottom?1:0)));V=K.getMinIntrinsicWidth(z)}return V+Z+Q+X}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,Y=this._decoration?.border,X=(Y?.left?1:0)+(Y?.right?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((Y?.top?1:0)+(Y?.bottom?1:0)));V=K.getMaxIntrinsicWidth(z)}if(V===1/0)return 1/0;return V+Z+Q+X}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,Y=this._decoration?.border,X=(Y?.top?1:0)+(Y?.bottom?1:0),V=0;if(this.children.length>0){let z=this.children[0],G=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((Y?.left?1:0)+(Y?.right?1:0)));V=z.getMinIntrinsicHeight(G)}let K=V+Z+Q+X;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(K,this._constraints.maxHeight);return K}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,Y=this._decoration?.border,X=(Y?.top?1:0)+(Y?.bottom?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((Y?.left?1:0)+(Y?.right?1:0)));V=K.getMaxIntrinsicHeight(z)}if(V===1/0)return 1/0;return V+Z+Q+X}paint(J,Z=0,Q=0){let Y=Math.floor(Z+this.offset.x),X=Math.floor(Q+this.offset.y);if(this._decoration?.color){let V={bg:this._decoration.color};J.fill(Y,X,this.size.width,this.size.height," ",V)}if(this._decoration?.border)this._paintBorder(J,Y,X);super.paint(J,Z,Q)}_paintBorder(J,Z,Q){let Y=this._decoration.border,X=this.size.width,V=this.size.height,K=(W)=>{let H={fg:W};if(this._decoration?.color)H.bg=this._decoration.color;if(this._forceDim)H.dim=!0;return H},z=(W)=>{switch(W){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},G=(W)=>{switch(W){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},U=(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(Y.top){let W=K(Y.top.color),H=z(Y.top.width);for(let B=0;B<X;B++)J.setChar(Z+B,Q,H,W,1)}if(Y.bottom){let W=K(Y.bottom.color),H=z(Y.bottom.width);for(let B=0;B<X;B++)J.setChar(Z+B,Q+V-1,H,W,1)}if(Y.left){let W=K(Y.left.color),H=G(Y.left.width);for(let B=0;B<V;B++)J.setChar(Z,Q+B,H,W,1)}if(Y.right){let W=K(Y.right.color),H=G(Y.right.width);for(let B=0;B<V;B++)J.setChar(Z+X-1,Q+B,H,W,1)}let F=Y.top?.style==="rounded",D=Math.max(Y.top?.width??1,Y.right?.width??1,Y.bottom?.width??1,Y.left?.width??1),q=U(D,F);if(Y.top&&Y.left){let W=K(Y.top.color);J.setChar(Z,Q,q.tl,W,1)}if(Y.top&&Y.right){let W=K(Y.top.color);J.setChar(Z+X-1,Q,q.tr,W,1)}if(Y.bottom&&Y.left){let W=K(Y.bottom.color);J.setChar(Z,Q+V-1,q.bl,W,1)}if(Y.bottom&&Y.right){let W=K(Y.bottom.color);J.setChar(Z+X-1,Q+V-1,q.br,W,1)}}hitTest(J,Z,Q=0,Y=0){return super.hitTest(J,Z,Q,Y)}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}function Og(J,Z,Q){return Math.min(Math.max(J,Z),Q)}class Eg{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}class eE extends Eg{flex;fit;constructor(J=0,Z="tight"){super();this.flex=J,this.fit=Z}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}class Lg extends ZJ{direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Z,children:Q=[],mainAxisAlignment:Y="start",crossAxisAlignment:X="center",mainAxisSize:V="min"}){super({...J?{key:J}:{},children:Q});this.direction=Z,this.mainAxisAlignment=Y,this.crossAxisAlignment=X,this.mainAxisSize=V}createRenderObject(){return new CG4(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new PG4(this)}}class PG4 extends w90{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 CG4 extends M4{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Z,Q,Y){super();this._direction=J;this._mainAxisAlignment=Z;this._crossAxisAlignment=Q;this._mainAxisSize=Y}updateProperties(J,Z,Q,Y){this._direction=J,this._mainAxisAlignment=Z,this._crossAxisAlignment=Q,this._mainAxisSize=Y,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=this._direction==="horizontal",Q=[],Y=[];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 Y.push(N)}let X=0,V=0,K,z=Z?J.maxHeight:J.maxWidth;if(isFinite(z))K=z;else{let N=0;for(let O of Y){let E=Z?O.getMaxIntrinsicHeight(1/0):O.getMaxIntrinsicWidth(1/0);N=Math.max(N,E)}K=N}for(let N of Y){let O=this._crossAxisAlignment==="stretch"?K:0,E=Z?new M1(0,1/0,O,K):new M1(O,K,0,1/0);if(N.layout(E),Z)X+=N.size.width,V=Math.max(V,N.size.height);else X+=N.size.height,V=Math.max(V,N.size.width)}let G=Z?J.maxWidth:J.maxHeight,U=Number.isFinite(G)?Math.max(0,G-X):0,F=Q.reduce((N,O)=>N+O.flex,0),D=G<1/0;if(!D&&F>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",M=Z?"width":"height";b4(!1,`RenderFlex children have non-zero flex but incoming ${M} constraints are unbounded.
|
|
6884
|
+
`);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(Y,X,V)=>{let K=V.optsWithGlobals(),z=await Z(V,K),G=0,U=V.args.slice(1),F;if(wG4()){let D=[];for await(let q of process.stdin)D.push(q);F=Buffer.concat(D).toString("utf-8").trim()}await HG4({toolName:Y,rawArgs:U,stdinInput:F,only:X.only,stream:X.stream,threadDeps:z,stdout:process.stdout,stderr:process.stderr,exit:(D)=>{G=D}}),await z.asyncDispose(),z.cleanupTerminal(),process.exit(G)})}h4();H1();function _90(J){return{get thread$(){return J.thread$},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return J.toolProgressByToolUseID$},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,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 _T5(J){return{id:J,created:Date.now(),v:0,messages:[]}}class Af0{placeholderThreadID;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new F4({});pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=z8()){this.placeholderThreadID=J;let Z=new F4(_T5(this.placeholderThreadID)),Q=new F4(new Map),Y=new F4(IP(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new F4(_90({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(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:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,V,K)=>(await this.waitForActiveHandle()).resolveApproval(X,V,K),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,V)=>{this.readyResolve=X,this.readyReject=V}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],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 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(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return E1(J.threadHandles$.pipe(G5((Z)=>Z!==null)))}}h0();n50();Z_0();H1();h0();x$();H1();async function v90(J,Z,Q,Y={}){let X={...J?{threadId:J}:{},...Y.repositoryURL?{repositoryURL:Y.repositoryURL}:{},...!J&&Y.executorType?{executorType:Y.executorType}:{}},V=await L8("/api/durable-thread-workers",LG4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)},Q),Z);if(!V.ok)throw Error(`Failed to create DTW thread: ${V.status} ${await V.text()}`);let K=await V.json();if(!K.threadId||!K.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");return{threadId:K.threadId,wsToken:K.wsToken}}async function ST5(J,Z,Q){let Y=await L8(`/api/threads/${J}`,LG4(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function LG4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function S90(J){let Z=N2.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=N2.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function vT5(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let V=S90(X);if(V)Q.add(V);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function kT5(J){let Z=new Set;for(let Q of J){let Y=S90(Q);if(Y)Z.add(Y)}return Z}function Hg(J,Z){let Q=[...J];for(let Y of Z)if(Y.type==="text"){let X=Q[Q.length-1];if(X?.type==="text")Q[Q.length-1]={...X,text:X.text+Y.text};else Q.push(Y)}else if(Y.type==="tool_use"){let X=Q.findIndex((V)=>V.type==="tool_use"&&V.id===Y.id);if(X>=0)Q[X]=Y;else Q.push(Y)}else if(Y.type==="thinking"){let X=Q[Q.length-1];if(X?.type==="thinking")Q[Q.length-1]={...X,thinking:X.thinking+Y.thinking};else Q.push(Y)}else Q.push(Y);return Q}function yT5(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function MG4(J){if(typeof J==="string")return J;if(!J||typeof J!=="object")return;if("output"in J&&typeof J.output==="string")return J.output;if("value"in J)return MG4(J.value);return}function uT5(J){return J.type==="text"}function xT5(J){if(J===void 0)return;let Z;try{Z=M80(J,"snapshot")}catch{return}if(Z.type==="snapshot")return MG4(Z.value);let Q=(Z.blocks??[]).filter(uT5).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}function fT5(J,Z){let Q=J.parentToolCallId,{completedMessages:Y}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;let V=J.blocks??[];if(V.length>0)if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){let V=J.blocks;if(J.role==="user")Y.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q});else Y.push({messageId:J.messageId,role:"assistant",blocks:V,parentToolCallId:Q});return}let X=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")X=Hg(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&X.length>0)Y.push({messageId:Z.streamingMessageId,role:"assistant",blocks:X,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=Hg([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Hg(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)Y.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=Hg([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Hg(Z.streamingBlocks,J.blocks)}}function bT5(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let V of Z){if(Q.has(V.messageId))continue;Q.add(V.messageId);let K=X++;if(V.role==="assistant")Y.push({role:"assistant",content:V.blocks,state:{type:"complete",stopReason:"end_turn"},messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId});else Y.push({role:"user",content:V.blocks,messageId:K,dtwMessageID:V.messageId,parentToolUseId:V.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function hT5(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y))return Z;Q.add(Y);let X=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];if(J.message.role==="info")return[...Z,{role:"info",content:J.message.content,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,userState:J.message.userState,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function mT5(J,Z){let Q=Z.findIndex((z)=>S90(z)===J.messageId),Y=Z.findIndex((z)=>S90(z)===J.truncateToMessageId);if(Q<0||Y<0)throw Error("Unable to apply edit: message mapping not found");let X=Z[Q];if(!X||X.role!=="user")throw Error("Unable to apply edit: target message is not editable");let V={role:"user",content:J.content,messageId:X.messageId,dtwMessageID:J.messageId},K=Z.slice(0,Y+1);return K[Q]=V,K}function Bg(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function EG4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:J.id,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:J.id}}}function gT5(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>EG4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:EG4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function pT5(J,Z){let Q=gT5(Z);return $x0(Bg(J)??[],Q,{dedupeAdded:!0})}function dT5(J,Z){return{baseURL:J.workerUrl??mY(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>v90(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}class k90{threadSubject;agentLoopStateSubject=new F4("idle");editErrorSubject=new e1;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new F4(new Map);toolProgressSubject=new e1;subscriptions=[];threadVersion;messages;queuedMessages;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;contextWindowRatio=null;compactionStateSubject=new F4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Bg(J.queuedMessages)??[],this.processedIds=Q,this.transport=Z,this.threadVersion=Y,this.threadSubject=new F4(J)}static async create(J){let Z=await v90(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType}),Q=await ST5(Z.threadId,J.configService,J.apiKey),{messages:Y,processedIds:X}=vT5(Q),V={...Q,id:Z.threadId,messages:Y,queuedMessages:Bg(Q.queuedMessages)},K=new QH(dT5(J,Z)),z=new k90(V,K,X,Q.v);try{return await z.connect(),z}catch(G){throw z.dispose(),G}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getContextWindowRatio(){return this.contextWindowRatio}getCompactionState(){return this.compactionState}compactionStateChanges(){return this.compactionStateSubject}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;let Q={...Z,...{env:J}};this.threadSubject.next(Q)}setAgentMode(J,Z){if(!J)return;let Q=this.threadSubject.getValue();if(!Z?.overwrite&&Q.agentMode)return;if(Q.agentMode===J)return;let Y={...Q,agentMode:J};this.threadSubject.next(Y)}emitThread(){let J=this.threadSubject.getValue(),Z=yT5(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),Y=Z?[...this.messages,Z]:[...this.messages],X=Y.reduce((K,z)=>Math.max(K,z.messageId),-1)+1,V={...J,id:this.threadId,v:this.threadVersion,title:this.threadTitle,messages:Y,queuedMessages:this.queuedMessages.length>0?Bg(this.queuedMessages):void 0,nextMessageId:Math.max(X,0)};this.threadSubject.next(V)}emitToolProgress(){this.toolProgressByToolUseIDSubject.next(new Map(this.toolProgressByToolUseID))}clearToolProgress(J){if(this.toolProgressByToolUseID.delete(J))this.emitToolProgress()}clearToolProgressFromBlocks(J){for(let Z of J)if(Z.type==="tool_result")this.clearToolProgress(Z.toolUseID)}setCompactionState(J){if(this.compactionState===J)return;this.compactionState=J,this.compactionStateSubject.next(J)}runTransportHandler(J,Z){try{Z()}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);j.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${Y}`)}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionInfo,Q=J.state!==this.lastConnectionState,Y=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!Y)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(Y&&Z)this.logConnectionRoleTransition(Z,J);let X=J.state;if(X==="connected"&&this.lastConnectionState!=="connected")this.transport.resumeFromVersion(this.threadVersion);this.lastConnectionState=X,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?au0(J.message):null;if(j.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:Z!==null?"Received invalid DTW payload (see parse details)":J.message,parseErrorSource:Z?.source,parseErrorDirection:Z?.direction,parseErrorStage:Z?.stage,parseErrorSummary:Z?.summary,parseErrorMessageType:Z?.messageType,parseErrorIssues:Z?.issues,parseErrorPayloadPreview:Z?.payloadPreview}),J.code==="PARSE_ERROR"){let Q=Z?.messageType?` (type="${Z.messageType}")`:"";this.editErrorSubject.next(`Received an invalid DTW message${Q}. The connection will continue running. Check logs for details.`)}})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state,this.agentLoopStateSubject.next(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(fT5(J,this.deltaState),J.role==="user"&&(J.state==="complete"||J.state==="error")&&J.blocks)this.clearToolProgressFromBlocks(J.blocks);if(this.deltaState.completedMessages.length>0){for(let Z of this.deltaState.completedMessages)if(Z.role==="user")this.clearToolProgressFromBlocks(Z.blocks);this.messages=bT5(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{this.toolProgressSubject.next(J);let Z=J.toolCallId,Q=xT5(J.progress);if(Q===void 0){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}if(this.toolProgressByToolUseID.get(Z)===Q)return;this.toolProgressByToolUseID.set(Z,Q),this.emitToolProgress()})}}),this.transport.compactionEvents().subscribe({next:(J)=>{this.runTransportHandler("compactionEvents",()=>{if(J.type==="compaction_started"){this.setCompactionState("compacting");return}this.setCompactionState("idle")})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{if(this.messages=hT5(J,this.messages,this.processedIds),J.message.role==="user")this.clearToolProgressFromBlocks(J.message.content);if(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=mT5(J,this.messages),this.processedIds=kT5(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=pT5(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"){j.info("[dtw] Transport reconnected",Q);return}j.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){j.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){j.warn("[dtw] Transport disconnected",Q);return}j.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){j.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){return this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q})}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Bg(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>Q.id);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.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}h0();l5();d9();f$();Y00();h4();xU();fv0();O4();H1();C$();function cT5(J){let Z=-1;for(let V=J.messages.length-1;V>=0;V--)if(J.messages[V]?.role==="assistant"){Z=V;break}if(Z<0)return{running:0,blocked:0};let Q=J.messages[Z];if(!Q)return{running:0,blocked:0};let Y=new Map;for(let V of J.messages.slice(Z+1)){if(V.role!=="user")continue;for(let K of V.content)if(K.type==="tool_result")Y.set(K.toolUseID,K.run)}let X=0;for(let V of Q.content){if(V.type!=="tool_use")continue;let K=Y.get(V.id);if(!K||!w8(K))X++}return{running:X,blocked:0}}function lT5(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function iT5(J){let Z=lT5(J);if(Z)return Z;return!1}function If0(J,Z,Q={files:[]},Y=void 0){let X=cT5(J),V=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let K=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:K>0?"tool-running":!1,toolState:{running:K,blocked:V}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:V}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:iT5(J),toolState:{running:X.running,blocked:V}}}h4();class jf0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.buildProjection();case"edit":return this.optimisticEdit(J)}}optimisticSubmit(J){if(Q_5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(F_5(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=zw0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:$_5(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return aT5(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingEdit)}reconcilePending(J){let Z=eT5(this.authoritativeThread);this.pendingMessageSubmits=Y_5(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=z_5(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingEdit=G_5(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return nT5(this.authoritativeThread,(Z)=>oT5(Z,J),(Z)=>rT5(Z,this.pendingMessageSubmits),(Z)=>sT5(Z,this.pendingQueuedSubmits))}}function nT5(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function aT5(J,Z,Q){return J.length>0||Z.length>0||Q!==void 0}function oT5(J,Z){if(!Z)return J;let Q=TI1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,V=J.messages.slice(0,Y+1);return V[Y]={...X,content:Z.content},{...J,messages:V,nextMessageId:Kw0({messages:V,nextMessageId:J.nextMessageId})}}function rT5(J,Z){if(Z.length===0)return J;let Q=Kw0(J),Y=Z.map((X,V)=>IG4(X,Q+V));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function sT5(J,Z){if(Z.length===0)return J;let Q=Z.map(tT5);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function IG4(J,Z){return{role:"user",content:J.content,userState:J.userState,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function tT5(J){return{id:J.clientMessageID,queuedMessage:IG4(J,-1)}}function eT5(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let V of J.messages)if(typeof V.dtwMessageID==="string"){if(X.add(V.dtwMessageID),V.role==="user")Z.add(V.dtwMessageID),Y.set(V.dtwMessageID,V)}for(let V of J.queuedMessages??[])Q.add(V.id);return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function $_5(J,Z){return J.messages.slice(Z+1).map((Q)=>Q.dtwMessageID).filter((Q)=>typeof Q==="string")}function J_5(J,Z){return J.messages.some((Q)=>Q.role==="user"&&Q.dtwMessageID===Z)}function Z_5(J,Z){return(J.queuedMessages??[]).some((Q)=>Q.id===Z)}function Q_5(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||J_5(Q,Y)||Z_5(Q,Y)}function Y_5(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:V}=X_5(Y,Q.userMessageIDs);if(X.length===0)return[];let K=V_5(J,Z);if(!K)return X;let z=K_5(K,V,X.length);return X.slice(z)}function X_5(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function V_5(J,Z){let Q=AG4(J),Y=AG4(Z);if(!(Q.length<=Y.length&&Q.every((V,K)=>V.dtwMessageID===Y[K]?.dtwMessageID)))return;return Y.slice(Q.length)}function K_5(J,Z,Q){let Y=0;for(let X of J){if(typeof X.dtwMessageID==="string"&&Z.has(X.dtwMessageID))continue;if(Y++,Y===Q)return Y}return Y}function AG4(J){return J.messages.filter((Z)=>Z.role==="user")}function z_5(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let V=Y.findIndex((K)=>Gw0(X.content,K.queuedMessage.content));if(V>=0)return Y.splice(V,1),!1;return!0})}function G_5(J,Z){if(!Z)return;return U_5(J,Z)?void 0:Z}function U_5(J,Z){let Q=J.userMessagesByID.get(Z.targetMessageID);if(!Q)return!1;if(!Gw0(Q.content,Z.content))return!1;return Z.truncatedMessageIDs.every((X)=>!J.messageIDsInTimeline.has(X))}function F_5(J){return D_5.has(J)}var D_5=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);class Rf0{threadWriter;deps;thread$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadViewStateSubject;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;handshakeManager;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);inferenceErrorsSubject=new e1;pendingSkills$=this.pendingSkillsSubject;fileChanges={files:[]};activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];providerSubscriptions=null;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let Y=SH0("info"),X=SH0("error");this.toolRunner=new dm({clientID:this.clientID,transport:this.provider.transport,executeBuiltinTool:()=>null,invokeTool:(G)=>this.invokeToolForLease(G),batchGuidanceFiles:u80,renderToolRunError:ex,log:{info:(G,U)=>Y(G,U),error:(G,U)=>X(G,{error:U}),wsMessage:(G,U,F)=>{j.debug("DTW executor tool runner message",{direction:G,clientID:U,...typeof F==="object"&&F!==null?F:{message:F}})}}}),this.handshakeManager=this.createHandshakeManager();let V=J.getThread();this.optimisticThreadProjection=new jf0(V,J.getAgentLoopState());let K=this.optimisticThreadProjection.resolve(V),z=If0(K,J.getAgentLoopState(),this.fileChanges,this.currentEphemeralError());this.threadSubject=new F4(K),this.thread$=this.threadSubject,this.threadViewStateSubject=new F4(z),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges(),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handshakeManager.ensureHandshake("connect")}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.threadWriter.write(J),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getResolvedTokenUsage(){let J=Y2(this.thread$.getValue());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.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.handshakeManager.dispose(),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),this.threadSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){await this.handshakeManager.ensureReady();let Z=this.thread$.getValue();if(J.editIndex!==void 0){let K=Z.messages[J.editIndex];if(!K||K.role!=="user"||!K.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let z=Z.messages.findIndex((F)=>F.role==="user");if(J.editIndex===z&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((F)=>{F.agentMode=J.agentMode});this.provider.transport.editUserMessage(K.dtwMessageID,J.content,mu0(),J.agentMode);let U=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:K.dtwMessageID,content:J.content});this.writeThread(U);return}if(!Z.messages.some((K)=>K.role==="user")&&!Z.agentMode&&J.agentMode)this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=await this.collectUserState(),X=this.provider.sendUserMessage(J.content,J.agentMode,Y),V=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:X,content:J.content,userState:Y});this.writeThread(V)}async restoreTo(J){await this.handshakeManager.ensureReady();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((K)=>K.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((K)=>K.type==="text"||K.type==="image").map((K)=>{if(K.type==="image")return{...K,source:{...K.source}};return{...K}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.transport.editUserMessage(Y.dtwMessageID,X,mu0());let V=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(V)}async queueMessage(J){await this.handshakeManager.ensureReady();let Z=await this.collectUserState(),Q=this.provider.sendUserMessage(J,void 0,Z),Y=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Q,content:J,userState:Z});this.writeThread(Y)}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.handshakeManager.ensureReady(),this.provider.interruptQueuedMessage(J)}async setVisibility(J){let Z=await M6.setThreadMeta({thread:this.provider.threadId,meta:yV(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}updateThread(J){let Z=this.threadWriter.update(J),Q=this.optimisticThreadProjection.resolve(Z);if(Q!==Z)this.threadWriter.write(Q);this.threadSubject.next(Q)}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}invokeBashTool(J,Z){let Q=PY4();return new v0((Y)=>{let X=!1,V=null,K=(F)=>{this.provider.transport.appendManualBashInvocation({args:J,run:F,hidden:Z.hidden})},z=(F,D={emitRun:!0})=>{if(X)return;if(X=!0,K(F),D.emitRun)Y.next(F);Y.complete()},G=(F)=>F instanceof Error?F.message:String(F),U=()=>{V?.unsubscribe(),z({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",U),(async()=>{try{let F=await OF({toolName:P6,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:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});if(X)return;Y.next({status:"in-progress"}),V=this.deps.toolService.invokeTool(P6,{args:J},F).subscribe({next:(D)=>{if(X)return;if(Y.next(D),D.status!=="in-progress")z(D,{emitRun:!1})},error:(D)=>{z({status:"error",error:{message:G(D)}})}})}catch(F){z({status:"error",error:{message:G(F)}})}})(),()=>{V?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",U)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=R9.safeParse(J);if(!Y.success)return;this.provider.transport.resolveToolApproval(Y.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.thread$.getValue();return(await Jz({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),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((V)=>{if(V.role==="user"){for(let K of V.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of V.content)if(K.type==="tool_use")Q.add(K.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[V]of X.entries())if(!Q.has(V))Y.add(V);return Y}async collectUserState(){try{return await o50()??sx}catch(J){return j.warn("Failed to collect IDE user state for DTW message",{error:J}),sx}}createHandshakeManager(){return new pm({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{j.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){j.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(mE));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let V=mE(X);if(this.toolRunner.sentApprovalRequests.has(V))continue;let K=v80(X);this.provider.transport.sendExecutorToolApprovalRequest(K),this.toolRunner.sentApprovalRequests.add(V)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted)}syncExecutorTools(J){let Z=this.provider.transport.getConnectionInfo();if(Z.state!=="connected"||Z.role!=="executor")return;this.advertisedExecutorTools=mm({transport:this.provider.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{this.handshakeManager.handleConnectionChange(J)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.transport.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.transport.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(CC(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){j.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await x80({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",previouslyAdvertisedTools:this.advertisedExecutorTools,initialToolDiscovery:this.deps.initialToolDiscovery});this.advertisedExecutorTools=Z,this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=f80(this.provider.transport,Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await t$();this.provider.setEnvironment({initial:J})}catch(J){j.debug("Failed to apply local environment",{error:J})}}async invokeToolForLease(J){let Z=await OF({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.toolRunner.discoveredGuidanceFileURIs}),Q=typeof J.args==="object"&&J.args!==null?J.args:{};return this.deps.toolService.invokeTool(J.toolName,{args:Q},Z)}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await h80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await m80({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await Q00(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(If0(this.threadSubject.getValue(),this.provider.getAgentLoopState(),this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}class Ng{deps;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});activeThreadHandleSubject=new F4(null);allConnectedThreadActivityStatusesSubject=new F4({});threadHandleMap=new Map;pendingHandoffSeeds=new Map;activeThreadContextID;queueOnSubmitByDefault=!0;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}isDTWMode(){return!0}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThread(J)}async switchThread(J){await this.activateThread(J)}async createHandoff(J,Z){let Q=this.activeProvider?.getThread();if(!Q)throw Error("No thread available for handoff");if(!Q.env?.initial){let z=await this.deps.getThreadEnvironment();Q={...Q,env:{initial:z}}}let Y=Z.signal??new AbortController().signal,X=await AP(Q,Z.goal,Z.images,this.deps.configService,Y,this.deps.osFileSystem),V=wg(Z.queuedMessages??Q.queuedMessages),{threadID:K}=await this.createThreadWithDraft({parentThreadID:Q.id,agentMode:Z.agentMode??Q.agentMode,draft:X,queuedMessages:V,comment:Z.goal,parentMessageIndex:Q.messages.length>0?Q.messages.length-1:void 0});return K}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){j.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 z=Z.thread$.getValue().id;this.activeThreadContextID=z,this.activeThreadHandleSubject.next(Z),this.addToRecentThreads(z),this.syncAllConnectedThreadActivityStatuses(),j.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:z,handleCount:this.threadHandleMap.size});return}let Q=await this.createProvider(J),Y=await this.deps.threadService.exclusiveSyncReadWriter(Q.threadId),X=rP({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q.threadId),V=new Rf0(Q,Y,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,initialToolDiscovery:this.deps.initialToolDiscovery,fs:X,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()}}),K=this.pendingHandoffSeeds.get(Q.threadId);if(K){this.pendingHandoffSeeds.delete(Q.threadId);let z={...V.thread$.getValue(),draft:K.draft,autoSubmitDraft:K.autoSubmitDraft,relationships:K.relationships,queuedMessages:wg(K.queuedMessages)};V.writeThread(z)}this.threadHandleMap.set(Q.threadId,V),V.startProviderSubscription((z)=>{this.applyProviderState(Q.threadId,z)}),await this.applyProviderState(Q.threadId,Q.getThread()),this.activeThreadContextID=Q.threadId,this.activeThreadHandleSubject.next(V),this.addToRecentThreads(Q.threadId),j.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 Y=q_5(Q.thread$.getValue(),Z),X=Q.resolveAuthoritativeThread(Y);Q.writeThread(X),await this.deps.threadService.flushVersion(J,X.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J]:X.title}),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){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return k90.create({ampURL:this.deps.ampURL,configService:this.deps.configService,executorType:Q,repositoryURL:Z,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 Z=await this.deps.getThreadEnvironment(),{threadId:Q}=await v90(void 0,this.deps.configService,await this.getApiKey(),{executorType:"local-client",repositoryURL:Z.trees?.[0]?.repository?.url}),Y=await this.deps.threadService.exclusiveSyncReadWriter(Q),X=Date.now(),V=J.parentThreadID?[{threadID:J.parentThreadID,type:"handoff",role:"child",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X}]:void 0,K={id:Q,created:X,v:1,agentMode:J.agentMode,messages:[],draft:J.draft,autoSubmitDraft:!0,queuedMessages:wg(J.queuedMessages),env:{initial:Z},relationships:V};if(Y.write(K),await this.deps.threadService.flushVersion(Q,K.v).catch(()=>{return}),await Y.asyncDispose(),this.pendingHandoffSeeds.set(Q,{draft:K.draft,autoSubmitDraft:K.autoSubmitDraft,relationships:K.relationships,queuedMessages:wg(K.queuedMessages)}),J.parentThreadID){let z=(U)=>{if(!U.relationships)U.relationships=[];if(!U.relationships.some((D)=>D.threadID===Q&&D.type==="handoff"&&D.role==="parent"))U.relationships.push({threadID:Q,type:"handoff",role:"parent",messageIndex:J.parentMessageIndex,comment:J.comment,createdAt:X})},G=this.threadHandleMap.get(J.parentThreadID);if(G)G.updateThread((U)=>{z(U)});else{let U=await this.deps.threadService.exclusiveSyncReadWriter(J.parentThreadID);U.update((F)=>{z(F)}),await U.asyncDispose()}}return{threadID:Q}}}function wg(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q}))}}))}function q_5(J,Z){let Q=Z.messages.reduce((Y,X)=>Math.max(Y,X.messageId),-1)+1;return{...Z,draft:Z.draft??J.draft,autoSubmitDraft:Z.autoSubmitDraft??J.autoSubmitDraft,env:Z.env??J.env,relationships:Z.relationships??J.relationships,queuedMessages:wg(Z.queuedMessages),nextMessageId:Math.max(Q,0)}}Ff0();import{readFile as sh5}from"node:fs/promises";import th5 from"node:readline";import{setTimeout as eh5}from"node:timers/promises";D3();x$();ij();h4();HF();H1();import{mkdir as W_5,writeFile as H_5}from"node:fs/promises";import B_5 from"node:path";function w_5(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function N_5(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function O_5(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${N_5(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function Pf0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class Cf0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=w_5(J.traceName),Y=O_5(Z,Q);this.traceFilePath=B_5.join(J.traceDir,`${Y}.json`),this.session={schemaVersion:1,sessionID:Y,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(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,eventName:J,payload:Pf0(Z)};this.session.protocolEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Pf0(Z)};this.session.providerStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Pf0(Z)};this.session.adapterStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,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 W_5(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await H_5(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function jG4(J,Z){let Q=[J.connectionChanges().subscribe({next:(Y)=>Z("connection_changes",Y)}),J.errors().subscribe({next:(Y)=>Z("errors",Y)}),J.errorEvents().subscribe({next:(Y)=>Z("error_events",Y)}),J.agentStates().subscribe({next:(Y)=>Z("agent_states",Y)}),J.deltas().subscribe({next:(Y)=>Z("deltas",Y)}),J.messageEvents().subscribe({next:(Y)=>Z("message_events",Y)}),J.messageEdited().subscribe({next:(Y)=>Z("message_edited",Y)}),J.editRejected().subscribe({next:(Y)=>Z("edit_rejected",Y)}),J.threadTitles().subscribe({next:(Y)=>Z("thread_titles",Y)}),J.queuedMessages().subscribe({next:(Y)=>Z("queued_messages",Y)}),J.retryEvents().subscribe({next:(Y)=>Z("retry_events",Y)}),J.cancelledEvents().subscribe({next:(Y)=>Z("cancelled_events",Y)}),J.toolLeases().subscribe({next:(Y)=>Z("tool_leases",Y)}),J.toolLeaseRevoked().subscribe({next:(Y)=>Z("tool_lease_revoked",Y)}),J.toolApprovalQueue().subscribe({next:(Y)=>Z("tool_approval_queue",Y)}),J.executorToolApprovalResponses().subscribe({next:(Y)=>Z("executor_tool_approval_responses",Y)}),J.toolProgress().subscribe({next:(Y)=>Z("tool_progress",Y)}),J.executorErrors().subscribe({next:(Y)=>Z("executor_errors",Y)}),J.executorConnected().subscribe({next:(Y)=>Z("executor_connected",Y)}),J.executorRollbackRequests().subscribe({next:(Y)=>Z("executor_rollback_requests",Y)}),J.observers().subscribe({next:(Y)=>Z("observers",Y)}),J.executorStatuses().subscribe({next:(Y)=>Z("executor_statuses",Y)}),J.environmentUpdates().subscribe({next:(Y)=>Z("environment_updates",Y)}),J.gitStatuses().subscribe({next:(Y)=>Z("git_statuses",Y)}),J.compactionEvents().subscribe({next:(Y)=>Z("compaction_events",Y)}),J.compactionRecords().subscribe({next:(Y)=>Z("compaction_records",Y)})];return{unsubscribe:()=>{for(let Y of Q)Y.unsubscribe()}}}h4();O4();C$();function lC(J,Z){let Q=(G)=>G===I7||G===I3||G===I$||G===q9,Y=new Map;for(let G of J)if(G.type==="toolResult"&&Q(G.toolUse.name))Y.set(G.toolUse.id,{toolUseId:G.toolUse.id,toolName:G.toolUse.name,toolRun:G.toolResult.run});let X=(G,U)=>{let F=Y.get(G)?.toolRun;if(!F||F.status!=="cancelled"||w8(U))return U;return{status:"cancelled",reason:"Parent subagent was cancelled"}},V=Array.from(Y.values()),K={},z={};for(let{toolUseId:G,toolRun:U}of V){let F=[],D;if(U.status==="in-progress"||U.status==="done"||U.status==="error"||U.status==="cancelled")D=U.progress;if(Array.isArray(D)){let q=0;for(let W of D)if(W.tool_uses)for(let H of W.tool_uses){let B=`${G}:progress:${q++}`,w=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},N=H.normalized_name??H.tool_name;F.push({toolUse:HI(N,H.input,B),toolRun:X(G,w)})}}K[G]=F}if(Z){let G=new Map;for(let U of Z.messages){let F=U.parentToolUseId;if(!F)continue;let D=G.get(F)??[];D.push(U),G.set(F,D)}for(let[U,F]of G){let{items:D}=PF({id:Z.id,messages:F},{includeSubagentMessages:!0});z[U]=D.filter((q)=>q.type==="toolResult").map((q)=>({toolUse:q.toolUse,toolRun:X(U,q.toolResult.run)}))}}for(let[G,U]of Object.entries(z))if(U.length>0)K[G]=U;return K}function PF(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[K]of J.messages.entries())Y.add(K);else for(let[K,z]of J.messages.entries())if(!z.parentToolUseId)Y.add(K);let X=new Map,V=new Set;for(let[K,z]of J.messages.entries()){if(!Y.has(K))continue;let G=`${z.role}-${K}`;switch(z.role){case"assistant":{let U=z.state.type==="streaming";for(let D of z.content)if(D.type==="tool_use"){if(X.set(D.id,D),U)V.add(D.id)}if(z.content.some((D)=>D.type==="text"&&D.text.trim()||D.type==="thinking"))Q.push({type:"message",id:G,message:z});for(let D of z.content)if(D.type==="tool_use"){let q=!1;for(let W=K+1;W<J.messages.length;W++){if(!Y.has(W))continue;let H=J.messages[W];if(H){for(let B of H.content)if(B.type==="tool_result"&&B.toolUseID===D.id){q=!0;break}}if(q)break}if(!q)Q.push({type:"toolResult",id:D.id,toolUse:D,toolResult:{type:"tool_result",toolUseID:D.id,run:{status:"in-progress"}}})}break}case"info":{if(z.content.some((F)=>F.type==="manual_bash_invocation"||F.type==="summary"&&F.summary.type==="message"))Q.push({type:"message",id:G,message:z});break}case"user":{let U=z.content.some((F)=>F.type==="text"&&F.text.trim()||F.type==="image");for(let F of z.content)if(F.type==="tool_result"){let D=X.get(F.toolUseID)??T$(J,F.toolUseID);if(!D)throw Error(`(bug) tool use ${F.toolUseID} not found`);Q.push({type:"toolResult",id:F.toolUseID,toolUse:D,toolResult:F})}if(U)Q.push({type:"message",id:G,message:z});break}}}return{items:Q}}l5();h4();HF();H1();class C3{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((V,K)=>{let z=this.neighborMap[K].filter((G)=>this.state[G]).length;if(V)return z===2||z===3;return z===3||z===6}),Z=J.every((V,K)=>V===this.state[K]),Q=this.previousState.length>0&&J.every((V,K)=>V===this.previousState[K]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((V)=>!V),X=J.filter((V)=>V).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let V;do V=Array.from({length:8},()=>Math.random()>0.6);while(V.filter((K)=>K).length<3);this.state=V,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 p1 extends $${createElement(){return new Tf0(this)}}class Tf0 extends NQ{_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 fV(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{let Z=this._child,Q=this.findNearestRenderObjectAncestor();if(Q&&Z.renderObject)Q.dropChild(Z.renderObject);else if(!Q&&Z.renderObject)Z.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Q&&this._child.renderObject)Q.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Q&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}}class v4{color;border;constructor(J,Z){this.color=J;this.border=Z}}class u1{top;right;bottom;left;constructor(J,Z,Q,Y){this.top=J;this.right=Z;this.bottom=Q;this.left=Y}static all(J){return new u1(J,J,J,J)}static symmetric(J,Z){return new u1(Z,J,Z,J)}}class v1{color;width;style;constructor(J=I0.black,Z=1,Q="rounded"){this.color=J;this.width=Z;this.style=Q}}class c0 extends H3{width;height;padding;margin;decoration;constraints;constructor({key:J,child:Z,width:Q,height:Y,padding:X,margin:V,decoration:K,constraints:z}={}){super({...J?{key:J}:{},...Z?{child:Z}:{}});this.width=Q,this.height=Y,this.padding=X,this.margin=V,this.decoration=K,this.constraints=z}createElement(){return new RG4(this)}createRenderObject(){return new y90(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}updateRenderObject(J){if(!(J instanceof y90))throw Error("renderObject must be an instance of ContainerRenderObject");J.updateProperties(this.width,this.height,this.padding,this.margin,this.decoration,this.constraints)}}class RG4 extends tz{constructor(J){super(J)}mount(){super.mount(),this._updateForceDim()}performRebuild(){super.performRebuild(),this._updateForceDim()}_updateForceDim(){if(!this.renderObject)return;let J=new fV(this,this.widget),Z=OQ.shouldForceDim(J);if(this.renderObject instanceof y90)this.renderObject.setForceDim(Z)}}class y90 extends M4{_width;_height;_padding;_margin;_decoration;_constraints;_forceDim=!1;constructor(J,Z,Q,Y,X,V){super();this._width=J;this._height=Z;this._padding=Q;this._margin=Y;this._decoration=X;this._constraints=V}setForceDim(J){if(this._forceDim!==J)this._forceDim=J,this.markNeedsPaint()}updateProperties(J,Z,Q,Y,X,V){this._width=J,this._height=Z,this._padding=Q,this._margin=Y,this._decoration=X,this._constraints=V,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=this._margin?.horizontal??0,Q=this._margin?.vertical??0,Y=this._padding?.horizontal??0,X=this._padding?.vertical??0,V=this._decoration?.border,K=(V?.left?1:0)+(V?.right?1:0),z=(V?.top?1:0)+(V?.bottom?1:0);this.sendDebugData({margin:this._margin,padding:this._padding,decoration:this._decoration,width:this._width,height:this._height,constraints:this._constraints});let G=this._width!==void 0||this._height!==void 0?this._constraints?.tighten({width:this._width,height:this._height})??M1.tightFor({width:this._width,height:this._height}):this._constraints,U=G?J.enforce(G):J,F=U.maxWidth-Z-Y-K,D=U.maxHeight-Q-X-z,q=new M1(Math.max(0,U.minWidth-Z-Y-K),Math.max(0,F),Math.max(0,U.minHeight-Q-X-z),Math.max(0,D)),W,H;if(this.children.length>0){let N=this.children[0];if(!(N instanceof M4))throw Error("Child must be a RenderBox");N.layout(q),W=N.size.width,H=N.size.height;let O=V?.left?1:0,E=V?.top?1:0,L=(this._margin?.left??0)+O+(this._padding?.left??0),M=(this._margin?.top??0)+E+(this._padding?.top??0);N.setOffset(L,M)}else if(q.maxWidth!==1/0&&q.maxHeight!==1/0)W=q.maxWidth,H=q.maxHeight;else W=q.minWidth,H=q.minHeight;let B,w;if(U.minWidth===U.maxWidth&&isFinite(U.maxWidth))B=U.maxWidth;else B=W+Y+K+Z;if(U.minHeight===U.maxHeight&&isFinite(U.maxHeight))w=U.maxHeight;else w=H+X+z+Q;this.setSize(U.constrain(B,w).width,U.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,Y=this._decoration?.border,X=(Y?.left?1:0)+(Y?.right?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((Y?.top?1:0)+(Y?.bottom?1:0)));V=K.getMinIntrinsicWidth(z)}return V+Z+Q+X}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,Y=this._decoration?.border,X=(Y?.left?1:0)+(Y?.right?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.vertical??0)-(this._padding?.vertical??0)-((Y?.top?1:0)+(Y?.bottom?1:0)));V=K.getMaxIntrinsicWidth(z)}if(V===1/0)return 1/0;return V+Z+Q+X}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,Y=this._decoration?.border,X=(Y?.top?1:0)+(Y?.bottom?1:0),V=0;if(this.children.length>0){let z=this.children[0],G=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((Y?.left?1:0)+(Y?.right?1:0)));V=z.getMinIntrinsicHeight(G)}let K=V+Z+Q+X;if(this._constraints&&this._constraints.maxHeight!==1/0)return Math.min(K,this._constraints.maxHeight);return K}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,Y=this._decoration?.border,X=(Y?.top?1:0)+(Y?.bottom?1:0),V=0;if(this.children.length>0){let K=this.children[0],z=Math.max(0,J-(this._margin?.horizontal??0)-(this._padding?.horizontal??0)-((Y?.left?1:0)+(Y?.right?1:0)));V=K.getMaxIntrinsicHeight(z)}if(V===1/0)return 1/0;return V+Z+Q+X}paint(J,Z=0,Q=0){let Y=Math.floor(Z+this.offset.x),X=Math.floor(Q+this.offset.y);if(this._decoration?.color){let V={bg:this._decoration.color};J.fill(Y,X,this.size.width,this.size.height," ",V)}if(this._decoration?.border)this._paintBorder(J,Y,X);super.paint(J,Z,Q)}_paintBorder(J,Z,Q){let Y=this._decoration.border,X=this.size.width,V=this.size.height,K=(W)=>{let H={fg:W};if(this._decoration?.color)H.bg=this._decoration.color;if(this._forceDim)H.dim=!0;return H},z=(W)=>{switch(W){case 1:return"─";case 2:return"━";case 3:return"━";default:return"━"}},G=(W)=>{switch(W){case 1:return"│";case 2:return"┃";case 3:return"┃";default:return"┃"}},U=(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(Y.top){let W=K(Y.top.color),H=z(Y.top.width);for(let B=0;B<X;B++)J.setChar(Z+B,Q,H,W,1)}if(Y.bottom){let W=K(Y.bottom.color),H=z(Y.bottom.width);for(let B=0;B<X;B++)J.setChar(Z+B,Q+V-1,H,W,1)}if(Y.left){let W=K(Y.left.color),H=G(Y.left.width);for(let B=0;B<V;B++)J.setChar(Z,Q+B,H,W,1)}if(Y.right){let W=K(Y.right.color),H=G(Y.right.width);for(let B=0;B<V;B++)J.setChar(Z+X-1,Q+B,H,W,1)}let F=Y.top?.style==="rounded",D=Math.max(Y.top?.width??1,Y.right?.width??1,Y.bottom?.width??1,Y.left?.width??1),q=U(D,F);if(Y.top&&Y.left){let W=K(Y.top.color);J.setChar(Z,Q,q.tl,W,1)}if(Y.top&&Y.right){let W=K(Y.top.color);J.setChar(Z+X-1,Q,q.tr,W,1)}if(Y.bottom&&Y.left){let W=K(Y.bottom.color);J.setChar(Z,Q+V-1,q.bl,W,1)}if(Y.bottom&&Y.right){let W=K(Y.bottom.color);J.setChar(Z+X-1,Q+V-1,q.br,W,1)}}hitTest(J,Z,Q=0,Y=0){return super.hitTest(J,Z,Q,Y)}dispose(){this._decoration=void 0,this._constraints=void 0,this._padding=void 0,this._margin=void 0,super.dispose()}}function Og(J,Z,Q){return Math.min(Math.max(J,Z),Q)}class Eg{detach(){}toString(){return`${this.constructor.name}#${this.hashCode()}`}hashCode(){return Math.random().toString(36).substr(2,9)}}class eE extends Eg{flex;fit;constructor(J=0,Z="tight"){super();this.flex=J,this.fit=Z}toString(){return`FlexParentData(flex: ${this.flex}, fit: ${this.fit})`}}class Lg extends ZJ{direction;mainAxisAlignment;crossAxisAlignment;mainAxisSize;constructor({key:J,direction:Z,children:Q=[],mainAxisAlignment:Y="start",crossAxisAlignment:X="center",mainAxisSize:V="min"}){super({...J?{key:J}:{},children:Q});this.direction=Z,this.mainAxisAlignment=Y,this.crossAxisAlignment=X,this.mainAxisSize=V}createRenderObject(){return new CG4(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}updateRenderObject(J){J.updateProperties(this.direction,this.mainAxisAlignment,this.crossAxisAlignment,this.mainAxisSize)}createElement(){return new PG4(this)}}class PG4 extends w90{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 CG4 extends M4{_direction;_mainAxisAlignment;_crossAxisAlignment;_mainAxisSize;constructor(J,Z,Q,Y){super();this._direction=J;this._mainAxisAlignment=Z;this._crossAxisAlignment=Q;this._mainAxisSize=Y}updateProperties(J,Z,Q,Y){this._direction=J,this._mainAxisAlignment=Z,this._crossAxisAlignment=Q,this._mainAxisSize=Y,this.markNeedsLayout()}performLayout(){super.performLayout();let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=this._direction==="horizontal",Q=[],Y=[];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 Y.push(N)}let X=0,V=0,K,z=Z?J.maxHeight:J.maxWidth;if(isFinite(z))K=z;else{let N=0;for(let O of Y){let E=Z?O.getMaxIntrinsicHeight(1/0):O.getMaxIntrinsicWidth(1/0);N=Math.max(N,E)}K=N}for(let N of Y){let O=this._crossAxisAlignment==="stretch"?K:0,E=Z?new M1(0,1/0,O,K):new M1(O,K,0,1/0);if(N.layout(E),Z)X+=N.size.width,V=Math.max(V,N.size.height);else X+=N.size.height,V=Math.max(V,N.size.width)}let G=Z?J.maxWidth:J.maxHeight,U=Number.isFinite(G)?Math.max(0,G-X):0,F=Q.reduce((N,O)=>N+O.flex,0),D=G<1/0;if(!D&&F>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",M=Z?"width":"height";b4(!1,`RenderFlex children have non-zero flex but incoming ${M} constraints are unbounded.
|
|
6885
6885
|
|
|
6886
6886
|
When a ${E} is in a parent that does not provide a finite ${M} 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.
|
|
6887
6887
|
|
|
@@ -7281,7 +7281,7 @@ Ctrl-X, Y, Z to unlock`;if(q){let f=U.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7281
7281
|
`),V=[];for(let K=0;K<X.length;K++){let U=X[K].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let F of U)if(F.startsWith("\x00")&&F.endsWith("\x01"))V.push(new C(F.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else V.push(new C(F,new h({color:Q.colorScheme.foreground})));if(K<X.length-1)V.push(new C(`
|
|
7282
7282
|
`))}return new c0({decoration:{color:Q.colorScheme.background,border:u1.all(new v1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,V)})})})}}class cg0 extends O2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=R$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new pg0({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function BN4(J,Z,Q,Y,X,V,K){if(V<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<V?z:null}case"bar":case"stacked-bar":{let z=K?d8:0,G=Y-z;if(G<=0)return null;let U=Z-z;if(U<0||U>=G)return null;let F=Math.max(1,Math.floor(G/V)),D=Math.floor(U/F);return D>=0&&D<V?D:null}case"line":case"sparkline":case"stacked-area":{let z=K?d8:0,G=Y-z;if(G<=0)return null;let U=Math.max(0,Math.min(G-1,Z-z));if(V===1)return 0;let F=G/(V-1),D=Math.round(U/F);return Math.max(0,Math.min(V-1,D))}default:return null}}function Il5(J,Z,Q,Y,X,V,K,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let U=V?d8:0,F=Q-U,D=Y-(V?G:0);if(F<=0||D<=0)return null;let q=Math.max(1,Math.floor(F/X)),W=U+Z*q+Math.floor(q/2),H=z>0?K/z:0,B=Math.round((1-H)*(D-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let U=V?d8:0,F=Q-U,D=Y-(V?G:0);if(F<=0||D<=0)return null;let q=X>1?U+Math.round(Z/(X-1)*(F-1)):U+Math.floor(F/2),W=z>0?K/z:0,H=Math.round((1-W)*(D-1));return{x:q,y:H}}default:return null}}function jl5(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function Rl5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let V=J.label.length,K=0;for(let z of Q){let G=z.points[Z];if(!G)continue;K+=G.value;let U=2+z.name.length+2+Y(G.value).length;V=Math.max(V,U)}if(X){let z=9+Y(K).length;V=Math.max(V,z)}return V}function Pl5(J,Z,Q,Y,X,V,K){let z;try{let H=I1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new h({color:z.foreground,bold:!0}),U=new h({color:z.foreground}),F=new h({color:z.foreground,dim:!0}),D=[],q=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,q,void 0,F90(H),()=>{D8(J,H)});if(Y.length<=1){if(D.push(new C(`${Z.label}: `,G)),Z.link)D.push(W(Z.link,V(Z.value)));else D.push(new C(V(Z.value),U));if(Z.meta)D.push(new C(` (${Z.meta})`,F))}else{let H=K==="stacked-bar"||K==="stacked-area";D.push(new C(`${Z.label}
|
|
7283
7283
|
`,G));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??X[w%X.length]??z.foreground;if(D.push(new C("● ",new h({color:E}))),D.push(new C(`${N.name}: `,F)),O.link)D.push(W(O.link,V(O.value)));else D.push(new C(V(O.value),U));if(w<Y.length-1||H)D.push(new C(`
|
|
7284
|
-
`))}if(H)D.push(new C(" ",F)),D.push(new C("Total: ",F)),D.push(new C(V(B),U))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,D)})})}aw();h0();e9();import{execSync as Zi5}from"node:child_process";XN();R$();D3();j7();ab();bX();x$();f$();uX();BE();h4();Vx();Gk();H1();var WO4=W4(RU(),1);import{writeFile as GO4}from"fs/promises";import UO4 from"path";h0();x$();class lg0{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.1773302873-g092245"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await jt(Z,this.configService)}catch(Z){j.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 oH extends d0{props;constructor(J){super();this.props=J}createState(){return new wN4}}class wN4 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 NN4 extends g0{controller=new d7;focusNode=new s4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new zJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),U=new F1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(K)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let q=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,D)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[F,new R0({height:1}),U,new X3,q]})})}}class mp extends d0{props;constructor(J){super();this.props=J}createState(){return new NN4}}import{isDeepStrictEqual as ig0}from"node:util";var Cl5=/[\\/_ +.#"@[({&]/,Tl5=/[\\/_ +.#"@[({&]/g,_l5=/[\s-]/,ON4=/[\s-]/g;function T$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),U=Q.indexOf(G,X),F=0,D,q,W,H;while(U>=0){if(D=T$0(J,Z,Q,Y,U+1,V+1,K),D>F){if(U===X)D*=1;else if(_l5.test(J.charAt(U-1))){if(D*=0.9,H=J.slice(X,U-1).match(ON4),H&&X>0)D*=0.999**H.length}else if(Cl5.test(J.charAt(U-1))){if(D*=0.8,W=J.slice(X,U-1).match(Tl5),W&&X>0)D*=0.999**W.length}else if(D*=0.3,X>0)D*=0.999**(U-X);if(J.charAt(U)!==Z.charAt(V))D*=0.9999}if(D<0.1&&(Q.charAt(U-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(U-1)!==Y.charAt(V))){if(q=T$0(J,Z,Q,Y,U+1,V+2,K),q*0.1>D)D=q*0.1}if(D>F)F=D;U=Q.indexOf(G,U+1)}return K[z]=F,F}function C$0(J){return J.toLowerCase().replace(ON4," ")}function EN4(J,Z){let Q=T$0(J,Z,C$0(J),C$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=T$0(J,z,C$0(J),C$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class xT{}class fT{}class _$0{}class S$0{}class LN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new MN4}}class MN4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}function Sl5(J,Z){if(J==="")return{matches:!0,score:1};let Q=EN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new AN4}}class AN4 extends g0{textController;focusNode;scrollController=new Q5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new d7(this.widget.props.controller?.query??""),this.focusNode=new s4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),W6.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)=>ig0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!ig0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>ig0(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 xT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof fT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof _$0){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 S$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...Sl5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;_T(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new zJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new I2({shortcuts:new Map([[new Q4("ArrowDown"),new xT],[new Q4("ArrowUp"),new fT],[new Q4("Tab"),new xT],[new Q4("Tab",{shift:!0}),new fT],[new Q4("n",{ctrl:!0}),new xT],[new Q4("p",{ctrl:!0}),new fT],[new Q4("Enter"),new _$0],[new Q4("Escape"),new S$0]]),focusNode:this.focusNode,child:z}),U=new _9({actions:new Map([[xT,new t4(this.invoke)],[fT,new t4(this.invoke)],[_$0,new t4(this.invoke)],[S$0,new t4(this.invoke)]]),child:G}),F=new F1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:U})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";D=new R0({height:10,child:new c1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new T1({child:new c1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new LN4(new i1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});D=new u0({children:w,crossAxisAlignment:"start"})}let q=new i1({onScroll:this.handleScroll,opaque:!1,child:new I6({controller:this.scrollController,autofocus:!1,child:D})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(F,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:q}),new c0({padding:C0.only({top:1}),child:new c1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:q}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function IN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class ng0 extends p1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>IN4(X.pubDate).length));return new o9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,V,K,z)=>{let G=f0.of(z),{colors:U}=G,F=G.app,D=V?F.selectionBackground:void 0,q=V?F.selectionForeground:U.foreground,W=U.mutedForeground,H=(B,w)=>new R0({width:w,child:F1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new F1({children:[new T1({child:new $0({text:new C(X.title,new h({color:q})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(IN4(X.pubDate),Q)]})})}})}}h4();class ag0 extends d0{createState(){return new jN4}}class jN4 extends g0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var vl5=/\/threads\/(T-[^/?#\s<>]+)/i;function kl5(J){let Z=J.trim(),Y=Z.match(vl5)?.[1];if(Y&&N8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(N8(X))return X;return null}function yl5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,U=Q.get(G)||[];U.push(K),Q.set(G,U)}else X.push(K)}return J20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function og0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function ul5(J,Z,Q,Y){return[og0("+",J,Y.success),X3.horizontal(1),og0("~",Z,Y.warning),X3.horizontal(1),og0("-",Q,Y.destructive)]}function xl5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class v$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new RN4}}class RN4 extends g0{spinner=new C3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,U=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),F=yl5(U),D=Math.max(0,...F.map((O)=>O.description.timeAgo.length)),q=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new c1({child:new $0({text:new C("",new h({color:q.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:q.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:q.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=kl5(O);return B};return new o9({items:F,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(!xl5(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:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:R}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:R.foreground,y=R.mutedForeground,m=(s,O0)=>new R0({width:O0,child:F1.end([new $0({text:new C(s,new h({color:y}))})])}),f=Z.threadViewStates[O.id],k=[],x=O.relationshipType==="handoff",c=new Gp({connectorColor:R.mutedForeground});if(O.depth>0){let s=[],O0=O.ancestorsAreLast.slice(1);for(let G0 of O0)s.push(new C(c.getAncestorPrefix(G0),new h({color:c.connectorColor,dim:c.connectorDim})));let n=O.isLast?c.elbow:c.tee,z0=c.getConnectorText(n);s.push(new C(z0,new h({color:c.connectorColor,dim:c.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],b=G===O.id?new C("(current) ",new h({color:R.success})):z.has(O.id)?new C("(visited) ",new h({color:R.foreground,dim:!0})):null;if(b)l.push(new $0({text:b}));if(hO(f))l.push(new ag0),l.push(new R0({width:1}));let o=O.title;if(O.relationshipType==="fork"){let s=o.match(/^Forked\((\d+)\): /);if(s)o=o.slice(s[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:R.primary}))}))}else if(x)l.push(new $0({text:new C("[handoff] ",new h({color:R.accent}))}));if(l.push(new T1({child:new $0({text:new C(o,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:R;l.push(...ul5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,D)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new F1({children:[...k,...l]})})}})}}function PN4(J){return 1-(1-J)**3}function CN4(J,Z,Q){return J+(Z-J)*Q}function gp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),V=PN4(Y),K=PN4(X);return{x:CN4(J.startOffset.x,J.targetOffset.x,V),y:CN4(J.startOffset.y,J.targetOffset.y,K)}}var fl5={nodeWidth:3,horizontalSpacing:3};class bT{options;constructor(J={}){this.options={...fl5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let V=0,K=(z,G)=>{let U=Z.get(z.id)??[];if(this.options.comparator)U.sort(this.options.comparator);let F={...z,parentID:Q.get(z.id)};if(U.length===0){Y.push({node:F,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of U)D.push(K(B,G+1));let q=Math.min(...D),W=Math.max(...D),H=Math.floor((q+W)/2);return Y.push({node:F,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var bl5={nodeWidth:3,nodeHeight:2};class hT{options;constructor(J={}){this.options={...bl5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var hl5={nodeWidth:3,nodeHeight:2},ml5={x:0,y:0};class y$0{options;constructor(J={}){this.options={...hl5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ml5,X,V,K,z){let G=z?f0.of(z):null,U=G?.colors,F=G?.app,D=U?.mutedForeground??U?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:D}))});let q=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=q;I>=0;I--){let R=J.filter((y)=>y.position.y===I);R.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,f=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,x=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,f,k,x,F,U)),S=y.position.x+this.options.nodeWidth}if(w.push(new F1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=R,f=this.renderConnectors(y,m,Z,H,U,F);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(q+1)*B,M=[new R0({width:H,height:L}),new u6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),R=q-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+R*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(I,y,U,F)}))}return new c0({padding:C0.horizontal(2),child:new OH(new c6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,U=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",U=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:U}))}),new $0({text:new C(z,new h({color:G,bold:U}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((q)=>q.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",U=Q?.border??Y?.threadGraphConnector??Q?.foreground,F=Q?.foreground,D=[new $0({text:new C(z,new h({color:U}))})];for(let q of X){let W=" ".repeat(V-q.length);D.push(new $0({text:new C("│ ",new h({color:U}),[new C(q+W,new h({color:F??U})),new C(" │",new h({color:U}))])}))}return D.push(new $0({text:new C(G,new h({color:U}))})),new u0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,U=Array(Y).fill(" ");for(let q of Z){let W=q.position.x+z;if(W>=0&&W<Y)U[W]="▲"}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((O)=>O.node.parentID===q.node.id);if(W.length===0)continue;let H=q.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)F[O]="│";else if(O===w)F[O]="└";else if(O===N)F[O]="┘";else F[O]="┬";else if(B.includes(O))if(O===w)F[O]="└";else if(O===N)F[O]="┘";else F[O]="┴";else if(F[O]===" ")F[O]="─"}}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let D=Array(Y).fill(" ");for(let q of J){if(Z.filter((B)=>B.node.parentID===q.node.id).length===0)continue;let H=q.position.x+z;if(H>=0&&H<Y)D[H]="│"}return K.push(new $0({text:new C(D.join(""),new h({color:G}))})),K}}var gl5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},pl5={x:0,y:0};class rg0{options;constructor(J={}){this.options={...gl5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=pl5,X,V,K,z){let G=z?f0.of(z):null,U=G?.colors,F=G?.app,D=U?.mutedForeground??U?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:D}))});let q=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=q;I>=0;I--){let R=J.filter((y)=>y.position.y===I);R.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,f=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,f,k,F,U)),S=y.position.x+this.options.nodeWidth}if(w.push(new F1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=R,f=this.renderConnectors(y,m,Z,H,U,F);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(q+1)*B,M=[new R0({width:H,height:L}),new u6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),R=q-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+R*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(I,y,U)}))}return new c0({padding:C0.horizontal(2),child:new OH(new c6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,U=Array(Y).fill(" ");for(let F of J){let D=Z.filter((w)=>w.node.parentID===F.node.id);if(D.length===0)continue;let q=F.position.x+z,W=D.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===q,O=W.includes(w);if(N&&O)if(D.length===1)U[w]="│";else if(w===H)U[w]="└";else if(w===B)U[w]="┘";else U[w]="┼";else if(N)if(w===H)U[w]="└";else if(w===B)U[w]="┘";else U[w]="┬";else if(O)if(w===H)U[w]="└";else if(w===B)U[w]="┘";else U[w]="┴";else if(U[w]===" ")U[w]="─"}}return K.push(new $0({text:new C(U.join(""),new h({color:G}))})),K}}class pp extends H3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new TN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class TN4 extends M4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class uL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new vN4}}var _N4=400,SN4=300,dl5=16;class vN4 extends g0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new bT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new hT;renderer=new rg0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let U=this.widget.props.threads.find((F)=>F.id===V);if(U)this.selectedNodeId=U.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:_N4,durationY:SN4};let Z=Math.max(_N4,SN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=gp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},dl5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),F=Math.floor(G/2)-K;return{x:V,y:F}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let F=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(F){let D=Math.max(...this.positionedNodes.map((q)=>q.position.y));this.currentOffset=this.calculateCenterOffset(F.position.x,F.position.y,D)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(U)=>U.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(U)=>U.isActive??!1,J),G=new pp({onWidth:(U)=>{if(this.viewportWidth!==U)this.viewportWidth=U,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(U)=>{if(this.viewportHeight!==U)this.viewportHeight=U,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class yN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new uN4}}class uN4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}var kN4=30,cl5=30;class mT{}class gT{}class u$0{}class x$0{}class sg0 extends d0{props;constructor(J){super();this.props=J}createState(){return new xN4}}class xN4 extends g0{highlightedIndex=0;controller=new d7;focusNode;scrollController=new Q5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;_T(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof mT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof gT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof u$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof x$0)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(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=o1.of(J).size.width>=cl5+kN4,G=u1.all(new v1(Y.foreground,1,"solid")),U=this.filteredClusters[this.highlightedIndex]??null,F=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new zJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),q=new I2({shortcuts:new Map([[new Q4("ArrowDown"),new mT],[new Q4("ArrowUp"),new gT],[new Q4("Tab"),new mT],[new Q4("Tab",{shift:!0}),new gT],[new Q4("n",{ctrl:!0}),new mT],[new Q4("p",{ctrl:!0}),new gT],[new Q4("Enter"),new u$0],[new Q4("Escape"),new x$0]]),focusNode:this.focusNode,child:D}),W=new _9({actions:new Map([[mT,new t4(this.invoke)],[gT,new t4(this.invoke)],[u$0,new t4(this.invoke)],[x$0,new t4(this.invoke)]]),child:q}),H=new F1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(R)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new yN4(new i1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new i1({onScroll:this.handleScroll,child:new I6({controller:this.scrollController,autofocus:!1,child:w})})}),O=U?U.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=U?new c0({padding:C0.all(1),child:new uL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:kN4});L=new F1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new i1({onScroll:this.handleScroll,child:new I6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[F,H,new R0({height:1}),new T1({child:L})]})})}}class GJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!GJ._instance)GJ._instance=new GJ;return GJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class fN4 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){j.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){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(U)=>{if("__isCreateMarker"in U)return this.currentQuery.trim().toLowerCase();return U.name},onAccept:(U)=>{if("__isCreateMarker"in U)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(U.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(U,F,D,q)=>{let W=F?Q.selectionBackground:void 0,H=F?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in U&&U.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(U.name,new h({color:H}))})})},filterItem:(U,F)=>{if(this.currentQuery!==F)this.currentQuery=F,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in U&&U.__isCreateMarker)return this.shouldShowCreateMarker(F);let q=F.trim().toLowerCase();return q.length===0||U.name.includes(q)},sortItems:(U,F,D)=>{let q="__isCreateMarker"in U.item&&U.item.__isCreateMarker,W="__isCreateMarker"in F.item&&F.item.__isCreateMarker;if(q&&!W)return-1;if(!q&&W)return 1;return F.score-U.score}})}}class tg0 extends d0{props;constructor(J){super();this.props=J}createState(){return new fN4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new bN4}}class bN4 extends g0{_spinner=new C3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let U=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(F)=>{if(F.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:U});return U}}var dp={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},f$0=["workspace","global","flag","default","external","skill","other"];function ll5(J){return Array.from(new Set(J))}function hN4(J){return ll5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function pT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return hN4(J).length>0?"skill":"other"}function eg0(J){return pT(J)==="skill"}function mN4(J){let Z=hN4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=pT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${dp[Y].description}: ${Q}`}function gN4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class v8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new pN4}}class pN4 extends g0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),U=X-z,F=Math.max(0,U*G),D=F+z;return J>=F&&J<=D}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),U=V-G;if(U<=0)return;let F=Z-Q,D=U/F,q=K/D,W=Math.max(0,Math.min(F,this._dragStartOffset+q));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),U=Q-Y,F=K-G,D=Math.max(0,Math.min(1,X/(Q-Y))),q=Math.max(0,F*D),W=q+G;if(Z>=q&&Z<=W)return;if(Z<q)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(U,X+Y))};build(J){return new i1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new dN4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class dN4 extends mC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new cN4(this)}updateRenderObject(J){J.updateWidget(this)}}class cN4 extends M4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],U=Y,F=Y+X;for(let D=0;D<this.size.height;D++){let q="█",W=!0;if(D===Math.floor(U)){let H=1-(U-D),B=Math.floor(H*8);q=G[B]||"█",W=!1}else if(D===Math.floor(F)){let H=1-(F-D),B=Math.floor(H*8);q=G[B]||"█"}else if(D>U&&D<F)W=!1;J.setChar(Z,Q+D,q,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class xL extends d0{props;constructor(J){super();this.props=J}createState(){return new lN4}}class lN4 extends g0{scrollController=new Q5;scrollAreaKey=new b7("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 P2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let F=D$0(Q);return{title:F.title,type:F.type,description:F.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new j2({child:new c0({padding:C0.symmetric(1,0),child:new F1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new I6({controller:this.scrollController,autofocus:!0,child:z})}),new v8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let F=this.scrollController.maxScrollExtent,D=this.scrollController.offset,q=this.getViewportHeight(),W=F+q;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(D,0)}}})]})})})}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let F=this.resolveFooterStyle(this.widget.props.message);if(F==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(F==="help"){let D=new h({color:Z.app.keybind}),q=new h({color:Z.colors.foreground,dim:!0});return new C("",q,[new C("Press ",q),new C("Escape",D),new C(" to close • Use ",q),new C("↑↓",D),new C(" or ",q),new C("j/k",D),new C(" to scroll",q)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(F)=>{if(this.widget.props.onRetry&&F.key==="r")return this.widget.props.onRetry(),"handled";if(F.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:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,U]})})})}}e9();class iN4 extends d0{props;constructor(J){super();this.props=J}createState(){return new nN4}}class nN4 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=g8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,U)=>G+U.registeredCommands.length,0),z=this.plugins.reduce((G,U)=>G+U.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${p4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${p4(K,"command")}, ${z} ${p4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
|
|
7284
|
+
`))}if(H)D.push(new C(" ",F)),D.push(new C("Total: ",F)),D.push(new C(V(B),U))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,D)})})}aw();h0();e9();import{execSync as Zi5}from"node:child_process";XN();R$();D3();j7();ab();bX();x$();f$();uX();BE();h4();Vx();Gk();H1();var WO4=W4(RU(),1);import{writeFile as GO4}from"fs/promises";import UO4 from"path";h0();x$();class lg0{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.1773304029-gee323e"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await jt(Z,this.configService)}catch(Z){j.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 oH extends d0{props;constructor(J){super();this.props=J}createState(){return new wN4}}class wN4 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 NN4 extends g0{controller=new d7;focusNode=new s4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new zJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),U=new F1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(K)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let q=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,D)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[F,new R0({height:1}),U,new X3,q]})})}}class mp extends d0{props;constructor(J){super();this.props=J}createState(){return new NN4}}import{isDeepStrictEqual as ig0}from"node:util";var Cl5=/[\\/_ +.#"@[({&]/,Tl5=/[\\/_ +.#"@[({&]/g,_l5=/[\s-]/,ON4=/[\s-]/g;function T$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),U=Q.indexOf(G,X),F=0,D,q,W,H;while(U>=0){if(D=T$0(J,Z,Q,Y,U+1,V+1,K),D>F){if(U===X)D*=1;else if(_l5.test(J.charAt(U-1))){if(D*=0.9,H=J.slice(X,U-1).match(ON4),H&&X>0)D*=0.999**H.length}else if(Cl5.test(J.charAt(U-1))){if(D*=0.8,W=J.slice(X,U-1).match(Tl5),W&&X>0)D*=0.999**W.length}else if(D*=0.3,X>0)D*=0.999**(U-X);if(J.charAt(U)!==Z.charAt(V))D*=0.9999}if(D<0.1&&(Q.charAt(U-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(U-1)!==Y.charAt(V))){if(q=T$0(J,Z,Q,Y,U+1,V+2,K),q*0.1>D)D=q*0.1}if(D>F)F=D;U=Q.indexOf(G,U+1)}return K[z]=F,F}function C$0(J){return J.toLowerCase().replace(ON4," ")}function EN4(J,Z){let Q=T$0(J,Z,C$0(J),C$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=T$0(J,z,C$0(J),C$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class xT{}class fT{}class _$0{}class S$0{}class LN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new MN4}}class MN4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}function Sl5(J,Z){if(J==="")return{matches:!0,score:1};let Q=EN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new AN4}}class AN4 extends g0{textController;focusNode;scrollController=new Q5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new d7(this.widget.props.controller?.query??""),this.focusNode=new s4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),W6.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)=>ig0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!ig0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>ig0(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 xT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof fT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof _$0){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 S$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...Sl5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;_T(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new zJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new I2({shortcuts:new Map([[new Q4("ArrowDown"),new xT],[new Q4("ArrowUp"),new fT],[new Q4("Tab"),new xT],[new Q4("Tab",{shift:!0}),new fT],[new Q4("n",{ctrl:!0}),new xT],[new Q4("p",{ctrl:!0}),new fT],[new Q4("Enter"),new _$0],[new Q4("Escape"),new S$0]]),focusNode:this.focusNode,child:z}),U=new _9({actions:new Map([[xT,new t4(this.invoke)],[fT,new t4(this.invoke)],[_$0,new t4(this.invoke)],[S$0,new t4(this.invoke)]]),child:G}),F=new F1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:U})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";D=new R0({height:10,child:new c1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new T1({child:new c1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new LN4(new i1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});D=new u0({children:w,crossAxisAlignment:"start"})}let q=new i1({onScroll:this.handleScroll,opaque:!1,child:new I6({controller:this.scrollController,autofocus:!1,child:D})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(F,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:q}),new c0({padding:C0.only({top:1}),child:new c1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:q}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function IN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class ng0 extends p1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>IN4(X.pubDate).length));return new o9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,V,K,z)=>{let G=f0.of(z),{colors:U}=G,F=G.app,D=V?F.selectionBackground:void 0,q=V?F.selectionForeground:U.foreground,W=U.mutedForeground,H=(B,w)=>new R0({width:w,child:F1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new F1({children:[new T1({child:new $0({text:new C(X.title,new h({color:q})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(IN4(X.pubDate),Q)]})})}})}}h4();class ag0 extends d0{createState(){return new jN4}}class jN4 extends g0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var vl5=/\/threads\/(T-[^/?#\s<>]+)/i;function kl5(J){let Z=J.trim(),Y=Z.match(vl5)?.[1];if(Y&&N8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(N8(X))return X;return null}function yl5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,U=Q.get(G)||[];U.push(K),Q.set(G,U)}else X.push(K)}return J20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function og0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function ul5(J,Z,Q,Y){return[og0("+",J,Y.success),X3.horizontal(1),og0("~",Z,Y.warning),X3.horizontal(1),og0("-",Q,Y.destructive)]}function xl5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class v$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new RN4}}class RN4 extends g0{spinner=new C3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,U=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),F=yl5(U),D=Math.max(0,...F.map((O)=>O.description.timeAgo.length)),q=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new c1({child:new $0({text:new C("",new h({color:q.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:q.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:q.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=kl5(O);return B};return new o9({items:F,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(!xl5(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:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:R}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:R.foreground,y=R.mutedForeground,m=(s,O0)=>new R0({width:O0,child:F1.end([new $0({text:new C(s,new h({color:y}))})])}),f=Z.threadViewStates[O.id],k=[],x=O.relationshipType==="handoff",c=new Gp({connectorColor:R.mutedForeground});if(O.depth>0){let s=[],O0=O.ancestorsAreLast.slice(1);for(let G0 of O0)s.push(new C(c.getAncestorPrefix(G0),new h({color:c.connectorColor,dim:c.connectorDim})));let n=O.isLast?c.elbow:c.tee,z0=c.getConnectorText(n);s.push(new C(z0,new h({color:c.connectorColor,dim:c.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],b=G===O.id?new C("(current) ",new h({color:R.success})):z.has(O.id)?new C("(visited) ",new h({color:R.foreground,dim:!0})):null;if(b)l.push(new $0({text:b}));if(hO(f))l.push(new ag0),l.push(new R0({width:1}));let o=O.title;if(O.relationshipType==="fork"){let s=o.match(/^Forked\((\d+)\): /);if(s)o=o.slice(s[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:R.primary}))}))}else if(x)l.push(new $0({text:new C("[handoff] ",new h({color:R.accent}))}));if(l.push(new T1({child:new $0({text:new C(o,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:R;l.push(...ul5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,D)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new F1({children:[...k,...l]})})}})}}function PN4(J){return 1-(1-J)**3}function CN4(J,Z,Q){return J+(Z-J)*Q}function gp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),V=PN4(Y),K=PN4(X);return{x:CN4(J.startOffset.x,J.targetOffset.x,V),y:CN4(J.startOffset.y,J.targetOffset.y,K)}}var fl5={nodeWidth:3,horizontalSpacing:3};class bT{options;constructor(J={}){this.options={...fl5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let V=0,K=(z,G)=>{let U=Z.get(z.id)??[];if(this.options.comparator)U.sort(this.options.comparator);let F={...z,parentID:Q.get(z.id)};if(U.length===0){Y.push({node:F,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of U)D.push(K(B,G+1));let q=Math.min(...D),W=Math.max(...D),H=Math.floor((q+W)/2);return Y.push({node:F,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var bl5={nodeWidth:3,nodeHeight:2};class hT{options;constructor(J={}){this.options={...bl5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var hl5={nodeWidth:3,nodeHeight:2},ml5={x:0,y:0};class y$0{options;constructor(J={}){this.options={...hl5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ml5,X,V,K,z){let G=z?f0.of(z):null,U=G?.colors,F=G?.app,D=U?.mutedForeground??U?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:D}))});let q=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=q;I>=0;I--){let R=J.filter((y)=>y.position.y===I);R.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,f=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,x=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,f,k,x,F,U)),S=y.position.x+this.options.nodeWidth}if(w.push(new F1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=R,f=this.renderConnectors(y,m,Z,H,U,F);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(q+1)*B,M=[new R0({width:H,height:L}),new u6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),R=q-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+R*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(I,y,U,F)}))}return new c0({padding:C0.horizontal(2),child:new OH(new c6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,U=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",U=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:U}))}),new $0({text:new C(z,new h({color:G,bold:U}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((q)=>q.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",U=Q?.border??Y?.threadGraphConnector??Q?.foreground,F=Q?.foreground,D=[new $0({text:new C(z,new h({color:U}))})];for(let q of X){let W=" ".repeat(V-q.length);D.push(new $0({text:new C("│ ",new h({color:U}),[new C(q+W,new h({color:F??U})),new C(" │",new h({color:U}))])}))}return D.push(new $0({text:new C(G,new h({color:U}))})),new u0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,U=Array(Y).fill(" ");for(let q of Z){let W=q.position.x+z;if(W>=0&&W<Y)U[W]="▲"}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((O)=>O.node.parentID===q.node.id);if(W.length===0)continue;let H=q.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)F[O]="│";else if(O===w)F[O]="└";else if(O===N)F[O]="┘";else F[O]="┬";else if(B.includes(O))if(O===w)F[O]="└";else if(O===N)F[O]="┘";else F[O]="┴";else if(F[O]===" ")F[O]="─"}}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let D=Array(Y).fill(" ");for(let q of J){if(Z.filter((B)=>B.node.parentID===q.node.id).length===0)continue;let H=q.position.x+z;if(H>=0&&H<Y)D[H]="│"}return K.push(new $0({text:new C(D.join(""),new h({color:G}))})),K}}var gl5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},pl5={x:0,y:0};class rg0{options;constructor(J={}){this.options={...gl5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=pl5,X,V,K,z){let G=z?f0.of(z):null,U=G?.colors,F=G?.app,D=U?.mutedForeground??U?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:D}))});let q=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=q;I>=0;I--){let R=J.filter((y)=>y.position.y===I);R.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,f=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,f,k,F,U)),S=y.position.x+this.options.nodeWidth}if(w.push(new F1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=R,f=this.renderConnectors(y,m,Z,H,U,F);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(q+1)*B,M=[new R0({width:H,height:L}),new u6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),R=q-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+R*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(I,y,U)}))}return new c0({padding:C0.horizontal(2),child:new OH(new c6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,U=Array(Y).fill(" ");for(let F of J){let D=Z.filter((w)=>w.node.parentID===F.node.id);if(D.length===0)continue;let q=F.position.x+z,W=D.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===q,O=W.includes(w);if(N&&O)if(D.length===1)U[w]="│";else if(w===H)U[w]="└";else if(w===B)U[w]="┘";else U[w]="┼";else if(N)if(w===H)U[w]="└";else if(w===B)U[w]="┘";else U[w]="┬";else if(O)if(w===H)U[w]="└";else if(w===B)U[w]="┘";else U[w]="┴";else if(U[w]===" ")U[w]="─"}}return K.push(new $0({text:new C(U.join(""),new h({color:G}))})),K}}class pp extends H3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new TN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class TN4 extends M4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class uL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new vN4}}var _N4=400,SN4=300,dl5=16;class vN4 extends g0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new bT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new hT;renderer=new rg0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let U=this.widget.props.threads.find((F)=>F.id===V);if(U)this.selectedNodeId=U.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:_N4,durationY:SN4};let Z=Math.max(_N4,SN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=gp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},dl5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),F=Math.floor(G/2)-K;return{x:V,y:F}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let F=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(F){let D=Math.max(...this.positionedNodes.map((q)=>q.position.y));this.currentOffset=this.calculateCenterOffset(F.position.x,F.position.y,D)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(U)=>U.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(U)=>U.isActive??!1,J),G=new pp({onWidth:(U)=>{if(this.viewportWidth!==U)this.viewportWidth=U,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(U)=>{if(this.viewportHeight!==U)this.viewportHeight=U,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class yN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new uN4}}class uN4 extends g0{build(J){return this.widget.onContext(J),this.widget.child}}var kN4=30,cl5=30;class mT{}class gT{}class u$0{}class x$0{}class sg0 extends d0{props;constructor(J){super();this.props=J}createState(){return new xN4}}class xN4 extends g0{highlightedIndex=0;controller=new d7;focusNode;scrollController=new Q5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;_T(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof mT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof gT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof u$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof x$0)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(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=o1.of(J).size.width>=cl5+kN4,G=u1.all(new v1(Y.foreground,1,"solid")),U=this.filteredClusters[this.highlightedIndex]??null,F=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new zJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),q=new I2({shortcuts:new Map([[new Q4("ArrowDown"),new mT],[new Q4("ArrowUp"),new gT],[new Q4("Tab"),new mT],[new Q4("Tab",{shift:!0}),new gT],[new Q4("n",{ctrl:!0}),new mT],[new Q4("p",{ctrl:!0}),new gT],[new Q4("Enter"),new u$0],[new Q4("Escape"),new x$0]]),focusNode:this.focusNode,child:D}),W=new _9({actions:new Map([[mT,new t4(this.invoke)],[gT,new t4(this.invoke)],[u$0,new t4(this.invoke)],[x$0,new t4(this.invoke)]]),child:q}),H=new F1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(R)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new yN4(new i1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new i1({onScroll:this.handleScroll,child:new I6({controller:this.scrollController,autofocus:!1,child:w})})}),O=U?U.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=U?new c0({padding:C0.all(1),child:new uL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:kN4});L=new F1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new i1({onScroll:this.handleScroll,child:new I6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[F,H,new R0({height:1}),new T1({child:L})]})})}}class GJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!GJ._instance)GJ._instance=new GJ;return GJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class fN4 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){j.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){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(U)=>{if("__isCreateMarker"in U)return this.currentQuery.trim().toLowerCase();return U.name},onAccept:(U)=>{if("__isCreateMarker"in U)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(U.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(U,F,D,q)=>{let W=F?Q.selectionBackground:void 0,H=F?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in U&&U.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(U.name,new h({color:H}))})})},filterItem:(U,F)=>{if(this.currentQuery!==F)this.currentQuery=F,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in U&&U.__isCreateMarker)return this.shouldShowCreateMarker(F);let q=F.trim().toLowerCase();return q.length===0||U.name.includes(q)},sortItems:(U,F,D)=>{let q="__isCreateMarker"in U.item&&U.item.__isCreateMarker,W="__isCreateMarker"in F.item&&F.item.__isCreateMarker;if(q&&!W)return-1;if(!q&&W)return 1;return F.score-U.score}})}}class tg0 extends d0{props;constructor(J){super();this.props=J}createState(){return new fN4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new bN4}}class bN4 extends g0{_spinner=new C3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let U=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(F)=>{if(F.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:U});return U}}var dp={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},f$0=["workspace","global","flag","default","external","skill","other"];function ll5(J){return Array.from(new Set(J))}function hN4(J){return ll5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function pT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return hN4(J).length>0?"skill":"other"}function eg0(J){return pT(J)==="skill"}function mN4(J){let Z=hN4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=pT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${dp[Y].description}: ${Q}`}function gN4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class v8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new pN4}}class pN4 extends g0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),U=X-z,F=Math.max(0,U*G),D=F+z;return J>=F&&J<=D}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),U=V-G;if(U<=0)return;let F=Z-Q,D=U/F,q=K/D,W=Math.max(0,Math.min(F,this._dragStartOffset+q));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),U=Q-Y,F=K-G,D=Math.max(0,Math.min(1,X/(Q-Y))),q=Math.max(0,F*D),W=q+G;if(Z>=q&&Z<=W)return;if(Z<q)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(U,X+Y))};build(J){return new i1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new dN4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class dN4 extends mC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new cN4(this)}updateRenderObject(J){J.updateWidget(this)}}class cN4 extends M4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],U=Y,F=Y+X;for(let D=0;D<this.size.height;D++){let q="█",W=!0;if(D===Math.floor(U)){let H=1-(U-D),B=Math.floor(H*8);q=G[B]||"█",W=!1}else if(D===Math.floor(F)){let H=1-(F-D),B=Math.floor(H*8);q=G[B]||"█"}else if(D>U&&D<F)W=!1;J.setChar(Z,Q+D,q,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class xL extends d0{props;constructor(J){super();this.props=J}createState(){return new lN4}}class lN4 extends g0{scrollController=new Q5;scrollAreaKey=new b7("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 P2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let F=D$0(Q);return{title:F.title,type:F.type,description:F.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new j2({child:new c0({padding:C0.symmetric(1,0),child:new F1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new I6({controller:this.scrollController,autofocus:!0,child:z})}),new v8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let F=this.scrollController.maxScrollExtent,D=this.scrollController.offset,q=this.getViewportHeight(),W=F+q;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(D,0)}}})]})})})}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let F=this.resolveFooterStyle(this.widget.props.message);if(F==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(F==="help"){let D=new h({color:Z.app.keybind}),q=new h({color:Z.colors.foreground,dim:!0});return new C("",q,[new C("Press ",q),new C("Escape",D),new C(" to close • Use ",q),new C("↑↓",D),new C(" or ",q),new C("j/k",D),new C(" to scroll",q)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(F)=>{if(this.widget.props.onRetry&&F.key==="r")return this.widget.props.onRetry(),"handled";if(F.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:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,U]})})})}}e9();class iN4 extends d0{props;constructor(J){super();this.props=J}createState(){return new nN4}}class nN4 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=g8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,U)=>G+U.registeredCommands.length,0),z=this.plugins.reduce((G,U)=>G+U.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${p4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${p4(K,"command")}, ${z} ${p4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
|
|
7285
7285
|
|
|
7286
7286
|
`));for(let G of this.plugins){let{icon:U,color:F}=this.statusIcon(G.status),D=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${U} `,new h({color:F}))),Y.push(new C(D,new h({bold:!0}))),Y.push(new C(` ${G.status}`,new h({dim:!0}))),Y.push(new C(`
|
|
7287
7287
|
`)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
|
|
@@ -7499,7 +7499,7 @@ ${Z0.content||""}`:Z0.content||"",a0=[],U1=Z0.baseDir.startsWith("file://")?EJ0(
|
|
|
7499
7499
|
`)}function PM4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),V=await Z(X),K=await V.settings.get("proxy"),z=Fj1({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(U,F)=>V.secrets.get(U,F)}}),G=await M6.userDisplayBalanceInfo({},{config:z});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(Q1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Q1.red("Error: ")+G.error.message+`
|
|
7500
7500
|
`),process.exit(1)}process.stdout.write(await Er5(G.result.displayText)+`
|
|
7501
7501
|
`),process.exit(0)})}var m03=HB.join(_$,"logs","headless.log"),Ml0=HB.join(_C,"device-id.json");async function g03(){for(let J of KN)try{if((await J.listConfigs()).length>0)return J}catch(Z){j.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => W4(H_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){O7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7502
|
-
`)}function p03(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function N7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")S$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")S$("experimental.agentMode",Z.mode)}function QR4(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 d03(J){try{return await JR4(J,"utf-8")}catch{return J}}async function Al0(J,Z,Q){let Y=QR4(J,Z);if(!Y)return;let X=k6(Q)?Q.features:[],V=k6(Q)?Q.user.email:void 0;if(!X.some((z)=>z.name===v$.HARNESS_SYSTEM_PROMPT&&z.enabled)&&!YR4(V))throw new z4("You are not allowed to do this.",1);S$("systemPrompt",await d03(Y))}function YR4(J){return!!(J&&Eo(J))}function Il0(J,Z){if(typeof J==="boolean")return J;if(!k6(Z))return!1;return TJ(Z.user.email)}function jl0(J){if(!k6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function c03(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 Rl0(J){let Y=c03(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new z4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var oj4=[{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??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${xE})`},{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:a9(),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:uK.SMART.key,description:`Set the agent mode (${SX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SX().map((J)=>J.mode).concat("large","deep","internal")},{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}],rj4=(J)=>("deprecated"in J)&&J.deprecated===!0,l03=(J)=>("hidden"in J)&&J.hidden===!0,i03=(J)=>("default"in J),n03=(J)=>("default"in J)?J.default:void 0,XR4=[{name:"toggle-skills-count",entryPoint:px0}];function a03(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new z4(F8.unknownCommand(Q),1,K)}}async function Cl0(J){return{...J,getThreadEnvironment:t$,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:a00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iJ(J.configService),pluginService:J.pluginService}}function VR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:t$,filesystem:J.fileSystem,threadService:J.threadService}}var UZ0=z1.file(ZR4.homedir()),Pl0=process.env.XDG_CONFIG_HOME?z1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(UZ0,".config");function o03(J){return w24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){B24(Z);let Q=O90(),Y=Uf0();if((!Q||Y||Jz4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(AF("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(AF("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(O90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function r03(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function v9(J,Z,Q){let Y=Q?.deferAuth??!1;Yj1("0.0.
|
|
7502
|
+
`)}function p03(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function N7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")S$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")S$("experimental.agentMode",Z.mode)}function QR4(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 d03(J){try{return await JR4(J,"utf-8")}catch{return J}}async function Al0(J,Z,Q){let Y=QR4(J,Z);if(!Y)return;let X=k6(Q)?Q.features:[],V=k6(Q)?Q.user.email:void 0;if(!X.some((z)=>z.name===v$.HARNESS_SYSTEM_PROMPT&&z.enabled)&&!YR4(V))throw new z4("You are not allowed to do this.",1);S$("systemPrompt",await d03(Y))}function YR4(J){return!!(J&&Eo(J))}function Il0(J,Z){if(typeof J==="boolean")return J;if(!k6(Z))return!1;return TJ(Z.user.email)}function jl0(J){if(!k6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function c03(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 Rl0(J){let Y=c03(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new z4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var oj4=[{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??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${xE})`},{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:a9(),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:uK.SMART.key,description:`Set the agent mode (${SX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SX().map((J)=>J.mode).concat("large","deep","internal")},{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}],rj4=(J)=>("deprecated"in J)&&J.deprecated===!0,l03=(J)=>("hidden"in J)&&J.hidden===!0,i03=(J)=>("default"in J),n03=(J)=>("default"in J)?J.default:void 0,XR4=[{name:"toggle-skills-count",entryPoint:px0}];function a03(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new z4(F8.unknownCommand(Q),1,K)}}async function Cl0(J){return{...J,getThreadEnvironment:t$,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:a00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iJ(J.configService),pluginService:J.pluginService}}function VR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:t$,filesystem:J.fileSystem,threadService:J.threadService}}var UZ0=z1.file(ZR4.homedir()),Pl0=process.env.XDG_CONFIG_HOME?z1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(UZ0,".config");function o03(J){return w24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){B24(Z);let Q=O90(),Y=Uf0();if((!Q||Y||Jz4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(AF("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(AF("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(O90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function r03(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function v9(J,Z,Q){let Y=Q?.deferAuth??!1;Yj1("0.0.1773304029-gee323e");let X=Ur({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([z1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:UZ0,userConfigDir:Pl0});rK4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=F24({configService:X}),G=new Map,U=()=>G.clear(),F=new oL0(X,J.settings.getWorkspaceRootPath()),D=ih1({configService:X,filesystem:a6}),q=lu1({configService:X,trustStore:F,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(s,O0,n)=>{let z0=`${s}:${O0}`,G0=G.get(z0);if(G0)return j.debug("Reusing existing OAuth provider for server",{serverName:s,serverUrl:O0}),G0;j.debug("Creating OAuth provider for server",{serverName:s,serverUrl:O0});let H0=(async()=>{let Y0=new CN(J.secrets),W0=await Y0.getClientInfo(s,O0),i=n?.scopes??W0?.scopes,a=tX4();j.info("OAuth headless mode check",{useHeadless:a,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:$5.isTTY});let e;if(a)e=J.executeMode?sX4():rX4(s);let J0=new qL0({storage:Y0,serverName:s,serverUrl:O0,clientId:n?.clientId??W0?.clientId,clientSecret:n?.clientSecret??W0?.clientSecret,authUrl:n?.authUrl??W0?.authUrl,tokenUrl:n?.tokenUrl??W0?.tokenUrl,scopes:i,headlessAuthHandler:e});return j.debug("OAuth provider created",{serverName:s,serverUrl:O0,hasManualClientId:!!(n?.clientId??W0?.clientId),willUseDCR:!(n?.clientId??W0?.clientId),scopes:i,headlessMode:a,executeMode:J.executeMode}),J0})();return G.set(z0,H0),H0}}),W=sv0({configService:X,filesystem:a6,spawn:t50}),H;if(J.executeMode){let s=await M84({toolService:K,providers:[q,W],initialTimeout:15000});H=s.registrations;for(let[O0,n]of s.initErrors)j.warn(`${O0} provider initialization slow or failed:`,n)}else H=tv0({toolService:K,providers:[q,W]});if(Z.jetbrains)QN("JetBrains");else if(Z.ide&&yV4())QN("VS Code");else if(Z.ide&&uV4())QN("Neovim");else if(Z.ide){let s=await g03();if(s){let O0=Or(s.ideName);if(O0)QN(O0)}}if(J.executeMode)Xj1(!0);let B,w=f8.status.pipe(W1((s)=>Boolean(s.connected&&s.authenticated&&s.ideName&&fj1(s.ideName))),A4()).subscribe((s)=>{if(s){if(!B)B=K.registerTool(L84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let s=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new S80(process.cwd(),{alwaysIncludePaths:s},!0)}else N=new class extends S80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let s=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(s),j.info("API key lookup before login",{found:Boolean(s),ampURL:J.ampURL,deferAuth:Y}),!s)if(Y)j.info("No API key found, continuing startup with deferred auth");else{$5.write(`No API key found. Starting login flow...
|
|
7503
7503
|
`);let O0=await s03(J),n=await J.secrets.get("apiKey",J.ampURL);if(j.info("Login flow completed",{success:O0,storedKeyPresent:Boolean(n),ampURL:J.ampURL}),!O0)await NF(),process.exit(1);O=!0}}{let s=await X.getLatest(),O0=s.settings.url,n=s.secrets.isSet?.[O0];j.info("Config secrets state after login",{configURL:O0,apiKeySet:n?.apiKey??!1})}let E=E1(iJ(X).pipe(G5((s)=>s!=="pending"))),L=await th1({isDevelopment:!1}),M=Y?"pending":await E;if(!Y)j.info("Server status resolved",{status:"ready",isAuthenticated:k6(M),isError:Iq(M),errorMessage:Iq(M)?M.error.message:void 0});let A=new oI0(L,X),I=new pA0(L,{lazy:!0,maxThreads:200});j.info("Starting Amp background services");let R=Il0(Z.dtw,M),_=Boolean(R||Z.headless);if(_)j.info("DTW mode enabled: thread sync service disabled");let S=_?r03():Mg1({threadService:A,threadHistoryService:I,configService:X,isExtensionDevelopment:!1}),y;f8.status.subscribe((s)=>{y=s});let m=new Uw0({workspaceRoots:[z1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?kt:a6,getCurrentFile:()=>{if(!y?.openFile)return;try{return z1.parse(y.openFile)}catch(s){j.warn("Failed to parse current file URI",{uri:y.openFile,error:s});return}},getOpenFiles:()=>{if(!y?.visibleFiles?.length)return[];let s=y.openFile;return y.visibleFiles.filter((O0)=>O0!==s).map((O0)=>{try{return z1.parse(O0)}catch(n){return j.warn("Failed to parse visible file URI",{uri:O0,error:n}),null}}).filter((O0)=>O0!==null)}}),f=new qf0,k=process.env.PLUGINS??"off",x=Z.headless?xK4():void 0,c=x??new J90({configService:X}),l=c instanceof J90?c:void 0;if(l)l.pluginExecutorKind=R?"local":"unknown";let b=WM0({configService:X,fileSystem:Z.jetbrains||Z.ide?kt:a6,platform:c,internalPlugins:XR4,pluginFilter:k}),o=nx1({pluginService:b,toolService:K}),d={codebaseContextService:m,configService:X,toolService:K,mcpService:q,skillService:D,toolboxService:W,trustStore:F,threadService:A,threadHistoryService:I,threadSyncService:S,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?kt:a6,terminal:f,pluginService:b,pluginPlatform:l,headlessPluginPlatform:x,serverStatus:M,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...d,async asyncDispose(){if(d.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await d.mcpService.waitForAuthentication();for(let s of H.values())s.dispose();await d.mcpService.dispose(),U(),await d.threadService.asyncDispose(),d.configService.unsubscribe(),z(),d.fuzzyServer.dispose(),d.threadSyncService.dispose(),d.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),o.dispose(),await d.pluginService.dispose()}}}async function s03(J){if(!J.executeMode){if(!await mx0("Would you like to log in to Amp? [(y)es, (n)o]: "))return $5.write(`Login cancelled. Run the command again to retry.
|
|
7504
7504
|
`),!1}return await KR4(J)}async function KR4(J){let Z=x03(32).toString("hex"),Q=await vC(J.ampURL,Z),Y=new AbortController;try{await fX(Q,Y.signal)}catch(V){j.error("Error opening browser",{error:V})}let X=await vC(J.ampURL,Z,!1);$5.write(`If your browser does not open automatically, visit:
|
|
7505
7505
|
|
|
@@ -7507,7 +7507,7 @@ ${Q1.blue.bold(X)}
|
|
|
7507
7507
|
|
|
7508
7508
|
`);try{return await HK4(J.ampURL,Z,J.secrets,Y),$5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return j.error("Login failed",{error:V}),O7.write(`
|
|
7509
7509
|
Login failed: ${V instanceof Error?V.message:String(V)}
|
|
7510
|
-
`),!1}}function t03(){let J=new oW().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)bE(),process.exit(0);let B=H.originalError??H;XX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${jq(new Date("2026-03-12T08:
|
|
7510
|
+
`),!1}}function t03(){let J=new oW().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)bE(),process.exit(0);let B=H.originalError??H;XX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${jq(new Date("2026-03-12T08:33:00.594Z"))} ago`}catch{}$5.write(`0.0.1773304029-gee323e (released 2026-03-12T08:33:00.594Z${B??""})
|
|
7511
7511
|
`),process.exit(0)}),J.addHelpText("after",SV4()),J.configureHelp({formatHelp:vV4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await w3(w);await X13(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 w3(w);await Y13(N,await Ox0(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 w3(N);await SX4(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 w3(w);await vX4(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",`
|
|
7512
7512
|
Actions:
|
|
7513
7513
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7563,8 +7563,8 @@ ${L}
|
|
|
7563
7563
|
|
|
7564
7564
|
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 e03(J){if(!J.userEmail||!TJ(J.userEmail))throw new z4("DTW TUI mode is only available for Amp employees",1);j.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Ng({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:t$,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new JV(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw j.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function $13(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Zg()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Zg()).trimEnd(),stdinInput:null}}function J13(J,Z,Q){if(J.remote&&!Z)throw new z4("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new z4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new z4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new z4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new z4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new z4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new z4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new z4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7565
7565
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function FZ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(n,z0)=>{let G0=Number(process.hrtime.bigint()-z0)/1e6,H0=V$4();j.info("Startup phase",{phase:n,phaseMs:Math.round(G0),sinceMainMs:H0===null?void 0:Math.round(H0)})},{userInput:V,stdinInput:K}=await $13(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;J13({...Z,streamJson:z},J.executeMode,V),N7(Q,Z);let G=process.hrtime.bigint(),U=Boolean(await J.secrets.get("apiKey",J.ampURL)),F=!J.executeMode&&!Z.headless&&U;j.info("Interactive auth startup mode",{deferInteractiveAuth:F,hasAPIKeyAtStartup:U,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await v9(J,Z,{deferAuth:F});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let q=await Cl0(D);X("runMainThread:createWorkerDeps",G);let{serverStatus:W}=D;if(!F&&Iq(W)){let n=Sm(Error(W.error.message));if(n.message===F8.networkOffline||n.message===F8.networkTimeout)throw Rl0(J.ampURL);throw new z4(F8.invalidAPIKey,1)}let H=k6(W)?W:null,B=H?.user.email,w=YR4(B),N=H!==null&&Il0(Z.dtw,H);if(!F)await Al0(Q,Z,W);let O=jl0(W),E=O?.features??[],L=O?.team??null,M=e80(Z,O);if(M instanceof Error)z3(M.message);if((J.executeMode||z)&&K8(Z.mode)&&!w)throw new z4(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!cD(Z.mode,B))throw new z4(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await hK4(V,K,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!TJ(B))throw new z4("Headless DTW mode is only available for Amp employees",1);let n=await D.secretStorage.get("apiKey",J.ampURL);if(!n)throw new z4("API key required for headless mode. Please run `amp login` first.",1);let z0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(z0&&!N8(z0))throw new z4(`Invalid thread ID: ${z0}`,1);let G0=z0??await q13({dependencies:D,visibility:M??void 0}),H0=await ZV4(G0);if(H0.status==="already-running")await D.asyncDispose(),await NF(),process.exit(0);try{await oX4({ampURL:J.ampURL,apiKey:n,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:G0,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform})}finally{await H0.release(),await D.asyncDispose()}await NF(),process.exit(0)}let A={threadService:D.threadService,workerDeps:q,createThread:async()=>{let n=F?await D.serverStatusPromise:W,z0=await w80(J.settings,process.cwd(),jl0(n),M);if(z0 instanceof Error)z3(z0.message);return Rm0(q,{threadMeta:z0?yV(z0):void 0,agentMode:Z.mode,onFirstAssistantMessage:sj4})},validateThreadOwnership:async(n,z0)=>{if(z0?.nonBlockingOwnershipCheck){tj4(n,D.configService).catch((G0)=>{if(G0 instanceof z4){if(z0.onOwnershipError){z0.onOwnershipError(G0,n);return}IC(G0,n);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})});return}try{await tj4(n,D.configService)}catch(G0){if(G0 instanceof z4)throw G0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:G0})}},switchThreadVisibility:M,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:sj4},I=async(n,z0)=>{try{if(n==="dtw")return e03({userEmail:z0?.dtwUserEmail??B,ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId});return ZH4(A,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(G0){if(G0 instanceof z4)throw G0;throw await IC(G0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")O7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7566
|
-
`),await NF(),process.exit(1);let R=(async()=>{if(F){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let n=await D.configService.getLatest(),z0=Pk(n),G0=await M6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout(z0)});if(G0.ok)return j.info("User free tier status:",G0),G0.result;return}catch(n){j.error("Failed to fetch free tier status:",n);return}})(),S=!J.executeMode?new Af0:null,y,m=null;if(S)y=S,m=(async()=>{let n=F?await D.serverStatusPromise:D.serverStatus;await Al0(Q,Z,n);let z0=process.hrtime.bigint(),G0=Il0(Z.dtw,n),H0=k6(n)?n.user.email:void 0,Y0=await I(G0?"dtw":"worker",{dtwUserEmail:H0});if(X("runMainThread:createThreadPool",z0),S.attach(Y0),V){let W0=await E1(Y0.threadHandles$);if(!W0)throw new z4("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:V}]})}})(),m.catch(async(n)=>{let z0=n instanceof Error?n:Error(String(n));S.setInitError(z0),await IC(n,Z.threadId)});else G=process.hrtime.bigint(),y=await I(N?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let k=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),o03({configService:D.configService,threadService:D.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(Z4((n)=>{if(!n)return v0.of({});return Y5(n.thread$,n.threadViewState$).pipe(W1(([z0,G0])=>({[z0.id]:G0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){PK4(D.mcpService,J.settings);let n={userInput:V,stdinInput:K,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},z0=await BX4({threadPool:y,...n});if(Z.archive)await M6.archiveThread({thread:z0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let x=!1,c=!1;if(Z.jetbrains||Z.ide){await dj1();let n=await GN({jetbrainsOnly:Z.jetbrains});if(n.length===0){if(Z.jetbrains)x=!await D.configService.get("jetbrains.skipInstall")}else if(n.length===1){let z0=n[0];if(z0)f8.selectConfig(z0)}else c=!0}G=process.hrtime.bigint();let l=bx0("0.0.
|
|
7567
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await su1({get:async(z)=>{if(z!==Eu)return;try{let G=await JR4(Ml0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Eu)return;await $R4(HB.dirname(Ml0),{recursive:!0}),await f03(Ml0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:mK()});Vj1(Y);let X=await HV4({...J,workspaceTrust:{current:!0,changes:Fk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await jK4(J.mcpConfig);X=RK4(X,z)}let V=HB.dirname(X.getSettingsFilePath());H24(_C,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!Jq(K))j.info("Targeting custom Amp server",{ampURL:K});return X=rI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:cK4(await Ox0(J,X))}}function Z13(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function Q13(){X$4();let J=Z13(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));NY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?m03:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Q1.level=0;if(p03(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
7566
|
+
`),await NF(),process.exit(1);let R=(async()=>{if(F){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let n=await D.configService.getLatest(),z0=Pk(n),G0=await M6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout(z0)});if(G0.ok)return j.info("User free tier status:",G0),G0.result;return}catch(n){j.error("Failed to fetch free tier status:",n);return}})(),S=!J.executeMode?new Af0:null,y,m=null;if(S)y=S,m=(async()=>{let n=F?await D.serverStatusPromise:D.serverStatus;await Al0(Q,Z,n);let z0=process.hrtime.bigint(),G0=Il0(Z.dtw,n),H0=k6(n)?n.user.email:void 0,Y0=await I(G0?"dtw":"worker",{dtwUserEmail:H0});if(X("runMainThread:createThreadPool",z0),S.attach(Y0),V){let W0=await E1(Y0.threadHandles$);if(!W0)throw new z4("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:V}]})}})(),m.catch(async(n)=>{let z0=n instanceof Error?n:Error(String(n));S.setInitError(z0),await IC(n,Z.threadId)});else G=process.hrtime.bigint(),y=await I(N?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let k=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),o03({configService:D.configService,threadService:D.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(Z4((n)=>{if(!n)return v0.of({});return Y5(n.thread$,n.threadViewState$).pipe(W1(([z0,G0])=>({[z0.id]:G0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){PK4(D.mcpService,J.settings);let n={userInput:V,stdinInput:K,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},z0=await BX4({threadPool:y,...n});if(Z.archive)await M6.archiveThread({thread:z0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let x=!1,c=!1;if(Z.jetbrains||Z.ide){await dj1();let n=await GN({jetbrainsOnly:Z.jetbrains});if(n.length===0){if(Z.jetbrains)x=!await D.configService.get("jetbrains.skipInstall")}else if(n.length===1){let z0=n[0];if(z0)f8.selectConfig(z0)}else c=!0}G=process.hrtime.bigint();let l=bx0("0.0.1773304029-gee323e",D.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let b=new gA0(D.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let o=new gx0(D.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let n=await E1(y.threadHandles$);if(!n)throw new z4("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let d=await az();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",d);let s={...d,launchCount:d.launchCount+1};oz(s);let O0=Z.threadId&&N8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await UB4({codebaseContextService:D.codebaseContextService,history:new Qx0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,threadHistoryService:D.threadHistoryService,threadFuzzyIndexer:b,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:M6,threadPool:y,createSystemPromptDeps:async()=>VR4(D),ideClient:f8,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:o,updateService:l,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:O0,showJetBrainsInstaller:x,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:s,freeTierStatusPromise:R,workspace:L??null,features:E,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-12T08:33:00.594Z"},(n)=>new tm0({...n,threadPool:n.threadPool},(z0)=>new ad0({...z0,threadState:z0.threadState}))),X("runMainThread:mountApp-returned",G),m)await m}finally{}await D.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function w3(J){if(j.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)O7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7567
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await su1({get:async(z)=>{if(z!==Eu)return;try{let G=await JR4(Ml0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Eu)return;await $R4(HB.dirname(Ml0),{recursive:!0}),await f03(Ml0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:mK()});Vj1(Y);let X=await HV4({...J,workspaceTrust:{current:!0,changes:Fk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await jK4(J.mcpConfig);X=RK4(X,z)}let V=HB.dirname(X.getSettingsFilePath());H24(_C,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!Jq(K))j.info("Targeting custom Amp server",{ampURL:K});return X=rI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:cK4(await Ox0(J,X))}}function Z13(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function Q13(){X$4();let J=Z13(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));NY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?m03:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Q1.level=0;if(p03(j),j.info("Starting Amp CLI.",{version:"0.0.1773304029-gee323e",buildTimestamp:"2026-03-12T08:33:00.594Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new z4(F8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await t03().parseAsync(process.argv)}q24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Q13().catch(IC)});async function Y13(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"),$5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7568
7568
|
`);else if(!Jq(J.ampURL))$5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7569
7569
|
`);let Y=process.env.AMP_API_KEY;if(Y)$5.write(`API key found in environment variable, storing...
|
|
7570
7570
|
`),await Z.set("apiKey",Y,J.ampURL),$5.write(`API key successfully stored.
|