@sourcegraph/amp 0.0.1774195348-g48946d → 0.0.1774240952-g432b79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -101,7 +101,7 @@ Expected format:
101
101
  `),K.newLines.join(`
102
102
  `))));Q.push({path:Y.movePath??Y.path,diffStat:X})}return Q}function _10(J){let Z=0,Q=0,Y=0;return J.messages.forEach((X)=>{if(X.role!=="assistant")return;X.content.forEach((K)=>{let V=Zf1(K);if(!V)return;let{name:z,input:G}=V,F=null;if(z==="edit_file"){if("old_str"in G&&"new_str"in G){let{old_str:q,new_str:W}=G;F=gH(q,W)}}else if(z==="apply_patch"){let q=Qf1(G);F=pj0(q.map((W)=>W.diffStat))}else if((z==="write_file"||z==="create_file")&&"content"in G&&typeof G.content==="string")F=mH(G.content);if(F)Z+=F.added,Y+=F.deleted,Q+=F.changed})}),{added:Z,changed:Q,deleted:Y}}function Yf1(J){let Z=new Map;return J.messages.forEach((Q)=>{if(Q.role!=="assistant")return;Q.content.forEach((Y)=>{let X=Zf1(Y);if(!X)return;let{name:K,input:V}=X,z,G=null;if(K==="edit_file"){if("path"in V&&typeof V.path==="string"&&"old_str"in V&&"new_str"in V){z=V.path;let{old_str:F,new_str:q}=V;G=gH(F,q)}}else if(K==="apply_patch"){for(let F of Qf1(V)){let q=sx1(F.path,J.env?.initial?.trees);if(q){let W=Z.get(q)??{added:0,changed:0,deleted:0};W.added+=F.diffStat.added,W.changed+=F.diffStat.changed,W.deleted+=F.diffStat.deleted,Z.set(q,W)}}return}else if((K==="write_file"||K==="create_file")&&"path"in V&&typeof V.path==="string"&&"content"in V&&typeof V.content==="string")z=V.path,G=mH(V.content);if(z&&G){let F=sx1(z,J.env?.initial?.trees);if(F){let q=Z.get(F)??{added:0,changed:0,deleted:0};q.added+=G.added,q.changed+=G.changed,q.deleted+=G.deleted,Z.set(F,q)}}})}),Z}function sx1(J,Z){let Q=J.startsWith("/"),Y=/^[a-zA-Z]:[\\/]/.test(J);if(!Q&&!Y)return J;let X=J.replace(/\\/g,"/");if(Z&&Z.length>0)for(let z of Z){if(!z.uri)continue;let G=z.uri.match(/^file:\/\/(.+)$/);if(!G?.[1])continue;let F=decodeURIComponent(G[1]).replace(/\\/g,"/"),q=F.startsWith("/")&&/^\/[a-zA-Z]:/.test(F)?F.slice(1):F;if(X.startsWith(q)){let W=X.slice(q.length);return W.startsWith("/")?W.slice(1):W}}let K=X.match(/\/(?:Users|home)\/[^/]+\/[^/]+\/(.+)/);if(K?.[1])return K[1];let V=X.match(/^[a-zA-Z]:\/Users\/[^/]+\/[^/]+\/(.+)/);if(V?.[1])return V[1];return null}function S10(){return Z10((J,Z,Q)=>{if(Q===0){if(Z instanceof Array)throw Error("expected first event to be a full thread");return Z}if(!(Z instanceof Array))throw Error("expected all but first event to be a patch");return Wx1(J,Z)})}function JC(J,Z){let Q=J.relationships?.filter((K)=>K.role==="child")??[],Y=Nb(J),X=[...Q,...Y];return Z?X.filter((K)=>K.type===Z):X}function k10(J,Z){return JC(J,Z)[0]}function oZ(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user")return Q}return}function Bb(J){for(let Z=J.messages.length-1;Z>=0;Z--){let Q=J.messages[Z];if(Q?.role==="user"&&Q.agentMode)return Q.agentMode}return}function Nb(J){let Z=[],Q=new Set;if(!J.messages)return Z;return J.messages.forEach((Y,X)=>{if(Y.role!=="assistant")return;Y.content.forEach((K)=>{if(K.type!=="tool_use")return;if(K.name!==IW)return;if(!v8(K))return;let V=K.input;if(V.threadID&&f9(V.threadID)&&!Q.has(V.threadID))Q.add(V.threadID),Z.push({threadID:V.threadID,type:"mention",role:"parent",messageIndex:X,createdAt:Date.now()})})}),Z}var f4=Y0(()=>{N1();$J();uj0();g0();P4();YE();K10()});var U4=Y0(()=>{eu();r00();oL()});import Mk6 from"os";import y10 from"path";var dH,KE,cH,ZC,Vf1,A08,j08,Ak6,jk6;var wb=Y0(()=>{dH=Mk6.homedir(),{env:KE}=process,cH=KE.XDG_DATA_HOME||(dH?y10.join(dH,".local","share"):void 0),ZC=KE.XDG_CONFIG_HOME||(dH?y10.join(dH,".config"):void 0),Vf1=KE.XDG_STATE_HOME||(dH?y10.join(dH,".local","state"):void 0),A08=KE.XDG_CACHE_HOME||(dH?y10.join(dH,".cache"):void 0),j08=KE.XDG_RUNTIME_DIR||void 0,Ak6=(KE.XDG_DATA_DIRS||"/usr/local/share/:/usr/share/").split(":");if(cH)Ak6.unshift(cH);jk6=(KE.XDG_CONFIG_DIRS||"/etc/xdg").split(":");if(ZC)jk6.unshift(ZC)});import{homedir as v10}from"node:os";import CW from"node:path";var zf1,Rk6,Gf1,Ik6,QC,Pk6,YC,Ck6,rZ;var _X=Y0(()=>{wb();zf1=CW.join(v10(),".local/share"),Rk6=process.platform==="win32"||process.platform==="darwin"?zf1:cH??zf1,Gf1=CW.join(v10(),".config"),Ik6=process.platform==="win32"||process.platform==="darwin"?Gf1:ZC??Gf1,QC=CW.join(Rk6,"amp"),Pk6=CW.join(Ik6,"amp"),YC=CW.join(Pk6,"tools"),Ck6=process.platform==="win32"?CW.join(process.env.LOCALAPPDATA??CW.join(v10(),"AppData","Local"),"amp"):CW.join(process.env.XDG_CACHE_HOME??CW.join(v10(),".cache"),"amp"),rZ=Ck6});function _k6(){return!1}function Ff1(J){return J.trim().toLowerCase()}function Sk6(J){if(!J.endsWith("@sourcegraph.com"))return!1;if(_k6())return!0;return Tk6.has(J)}function x10(J){let Z=Ff1(J);if(Z.length===0)return!1;return Z.endsWith("@sourcegraph.com")||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}function JJ(J){let Z=Ff1(J);if(Z.length===0)return!1;return Sk6(Z)||Z.endsWith("@ampcode.com")||Z==="auth-bypass-user@example.com"}var Tk6;var VE=Y0(()=>{Tk6=new Set(["alex.kemper@sourcegraph.com","beyang@sourcegraph.com","brady.jeong@sourcegraph.com","brett.jones@sourcegraph.com","camden@sourcegraph.com","connor.obrien@sourcegraph.com","dario.hamidi@sourcegraph.com","hamish.bultitude@sourcegraph.com","harry.charlesworth@sourcegraph.com","hitesh.sagtani@sourcegraph.com","isuru.fonseka@sourcegraph.com","jesse.edelstein@sourcegraph.com","jim.espelico@sourcegraph.com","karl.clement@sourcegraph.com","lewis.metcalf@sourcegraph.com","nicolay.gerold@sourcegraph.com","sqs@sourcegraph.com","thorsten@sourcegraph.com","tim.culverhouse@sourcegraph.com","tim.lucas@sourcegraph.com","will.dollman@sourcegraph.com","devsqs@sourcegraph.com"])});function d4(J,Z,Q=Z+"s"){return J===1?Z:Q}var P2=()=>{};function rj0(J){return f10[J]??0}function kk6(J){return typeof J==="number"&&Number.isInteger(J)&&J>=1&&J<=3600}function Wf1(J){let Z=J.settings["tools.inactivityTimeout"],Q=J.settings["tools.stopTimeout"],Y=Z;if(Y===void 0&&Q!==void 0)Y=Q;if(Y===void 0)Y=rj0("amp.tools.inactivityTimeout");if(!kk6(Y))return null;return Y*1000}function Uf1(J){let Z=J.settings["tools.stopTimeout"],Q=rj0("amp.tools.stopTimeout");return(Z??Q)*1000}function Ob(J){let Z=J.settings["network.timeout"],Q=rj0("amp.network.timeout");return(Z??Q)*1000}var f10,qf1;var XC=Y0(()=>{f10={"amp.tools.inactivityTimeout":300,"amp.tools.stopTimeout":300,"amp.network.timeout":30},qf1={"amp.tools.inactivityTimeout":{default:f10["amp.tools.inactivityTimeout"]},"amp.tools.stopTimeout":{default:f10["amp.tools.stopTimeout"]},"amp.network.timeout":{default:f10["amp.network.timeout"]}}});function ok6(J){return Af1.safeParse(J)}function lH(J){return ak6.safeParse(J)}function GC(J){if(!J||!Array.isArray(J))return[];let Z=[];for(let[Q,Y]of J.entries()){let X=ok6(Y);if(X.success)Z.push(X.data);else{let K=typeof Y==="object"&&Y!==null&&"tool"in Y?String(Y.tool):`entry at index ${Q}`;P.warn(`Permission entry for tool "${K}" is invalid: ${X.error.issues.map((V)=>`${V.path.join(".")}: ${V.message}`).join(", ")}`)}}return Z}var XR0,Af1,ak6;var GE=Y0(()=>{t$();g0();XR0=y.lazy(()=>y.union([y.string().describe('Pattern match where "*" matches any number of any characters'),y.array(XR0).min(1).describe("OR match of each entry"),y.boolean().describe("A literal boolean match"),y.number().describe("A literal number match"),y.null().describe("A literal null match"),y.undefined().describe("A literal undefined match"),y.record(y.string(),XR0).describe("Matching individual keys of an object")])),Af1=y.object({tool:y.string().min(1).describe("The name of the tool to which this entry applies"),matches:y.record(y.string(),XR0).optional().describe("Maps tool inputs to conditions"),action:y.enum(["allow","reject","ask","delegate"]).describe("How Amp should proceed in case of a match"),context:y.enum(["thread","subagent"]).optional().describe("Only apply this entry in this context"),to:y.string().min(1).optional().describe('Command to delegate to when action is "delegate"'),message:y.string().optional().describe('Message to return to the model when action is "reject". If set, the rejection is returned as an error so the model can continue.')}).superRefine((J,Z)=>{if(J.action==="delegate"&&!J.to)Z.addIssue({code:"custom",message:'delegate action requires "to" field',path:["to"]});if(J.action!=="delegate"&&J.to)Z.addIssue({code:"custom",message:'"to" field only allowed with delegate action',path:["to"]});if(J.message&&J.action!=="reject")Z.addIssue({code:"custom",message:'"message" field only allowed with reject action',path:["message"]})}),ak6=y.array(Af1).describe("Entries checked in sequence to configure tool permissions")});function n8(J,Z){let Q=rk6(J,Z);return typeof Q==="string"?Q:Q.toString()}function rk6(J,Z,Q=!0){if(!Z)Z=sk6();let{workspaceFolders:Y,isWindows:X,homeDir:K}=Z,V=typeof J==="string"?X1.parse(J):X1.from(J);if(Y)for(let z of Y){let G=S6(z);if(K1.hasPrefix(V,G)){let F=G.path.endsWith("/")?G.path.slice(0,-1):G.path,W=Q&&Y&&Y.length>=2?jW(G.path)+(X?"\\":"/"):"";return KR0(W+V.path.slice(F.length+1),X,V.scheme)}}if(V?.scheme==="file"){if(K){let z=S6(K);if(K1.hasPrefix(V,z)){let G=z.path.endsWith("/")?z.path.slice(0,-1):z.path,F=V.path.slice(G.length+1);return KR0("~"+(X?"\\":"/")+F,X,V.scheme)}}return KR0(V.fsPath,X,V.scheme)}return V}function KR0(J,Z,Q){return Z&&Q==="file"?J.replaceAll("/","\\"):J}function p10(J){let Z=m10;return m10=J,Z}function sk6(){if(m10)return m10;throw Error("must call setDisplayPathEnvInfo before calling displayPath() and related functions")}var m10=null;var MV=Y0(()=>{U4();oL();r00()});function C2(J){if(!J)return{};return{[VR0]:J.id,[tk6]:J.agentMode??""}}var z2="x-amp-feature",VR0="x-amp-thread-id",ZJ="x-amp-message-id",tk6="x-amp-mode",jf1="X-Amp-Client-Application",jb="X-Amp-Client-Type",Rf1="X-Amp-Client-Version",If1="X-Amp-Installation-ID",Pf1="X-Amp-Device-Fingerprint";var sZ=()=>{};function _f1(J){Cf1=J}function FE(J){Rb=J}function Sf1(J){Tf1=J}function kf1(J){Ib=J.installationID,Pb=J.deviceFingerprint}function yf1(){if(!Ib||!Pb)return;return{installationID:Ib,deviceFingerprint:Pb}}function qE(){let J=typeof process<"u"?process.env.AMP_SDK_VERSION:void 0;if(J)return{type:"cli",name:"AmpSDK",version:J};let Z;if(!Rb)Z="CLI";else if(["Neovim","JetBrains","Zed"].includes(Rb))Z=Rb;else Z=`${Rb} CLI`;return{type:"cli",name:Tf1?`${Z} Execute Mode`:Z,version:Cf1}}function T2(){let J=qE(),Z={};if(Z[jf1]=J.name,Z[jb]=J.type,Ib)Z[If1]=Ib;if(Pb)Z[Pf1]=Pb;if(J.version)Z[Rf1]=J.version;return Z}var Cf1=null,Rb=null,Tf1=!1,Ib=null,Pb=null;var QJ=Y0(()=>{sZ()});function ek6(J){if(typeof process>"u"||!process.versions?.node)return"unknown";try{switch(J){case"darwin":{try{let{execSync:Q}=R0("node:child_process"),X=Q("/usr/bin/sw_vers -productVersion",{encoding:"utf8",timeout:3000,stdio:["ignore","pipe","ignore"]}).trim();if(X&&/^\d+\.\d+/.test(X))return X}catch{}return R0("node:os").release()}case"linux":try{let Y=R0("node:fs").readFileSync("/etc/os-release","utf8").split(`
103
103
  `);for(let K of Y)if(K.startsWith("PRETTY_NAME=")){let V=K.match(/PRETTY_NAME="?([^"]*)"?/);if(V?.[1])return V[1]}return R0("node:os").release()}catch{return R0("node:os").release()}case"windows":try{let{execSync:Z}=R0("node:child_process"),Y=Z('systeminfo | findstr /B /C:"OS Name" /C:"OS Version"',{encoding:"utf8",timeout:5000}).split(`
104
- `),X=Y.find((z)=>z.includes("OS Name")),K=Y.find((z)=>z.includes("OS Version"));if(X&&K){let z=X.split(":")[1]?.trim(),G=K.split(":")[1]?.trim();return`${z} ${G}`}return R0("node:os").release()}catch{return R0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function vG(){if(!zR0){let J=typeof process<"u"&&process.versions?.node,Z=!J,Q="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Q="darwin";else if(process.platform==="win32")Q="windows";Y=ek6(Q),X=process.arch}else if(typeof navigator<"u"){let K=navigator.platform.toLowerCase();if(K.includes("mac")||K.includes("ios"))Q="darwin";else if(K.includes("win"))Q="windows";let V=navigator.userAgent;if(Q==="darwin"){let z=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(z?.[1])Y=z[1].replace(/_/g,".")}else if(Q==="windows"){let z=V.match(/Windows NT (\d+\.\d+)/);if(z?.[1])Y=z[1]}else{let z=V.match(/Linux.*?(\d+\.\d+)/);if(z?.[1])Y=z[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}zR0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:qE().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return zR0}var zR0;var FC=Y0(()=>{QJ()});function i3(J){let Z=J5[J];return`${Z.provider}/${Z.name}`}function xG(J){let Z=J.indexOf("/");if(Z===-1)throw Error(`Invalid provider/model format: ${J}`);return{provider:J.slice(0,Z),model:J.slice(Z+1)}}function B$(J){let{provider:Z,model:Q}=xG(J);for(let Y of Object.values(J5))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return J5.CLAUDE_SONNET_4_5;case"openai":return J5.GPT_5;case"xai":return J5.GROK_CODE_FAST_1;case"cerebras":return J5.Z_AI_GLM_4_7;case"fireworks":return J5.FIREWORKS_GLM_4P6;case"baseten":return J5.BASETEN_KIMI_K2P5;case"moonshotai":return J5.KIMI_K2_INSTRUCT;case"openrouter":return J5.SONOMA_SKY_ALPHA;case"groq":return J5.GPT_OSS_120B;case"vertexai":return J5.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function Cb(J){for(let Q of Object.values(J5))if(Q.name===J)return Q;let Z=J.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Z){let Q=Z[1];for(let Y of Object.values(J5))if(Y.name===Q)return Y}return}function x8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function YJ(J){let Z=B$(J);return Z.contextWindow-Z.maxOutputTokens}function d10(J){return B$(J).maxOutputTokens}var h6,J5,GR0;var P7=Y0(()=>{h6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},J5={CLAUDE_SONNET_4:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:h6.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:h6.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:h6.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:h6.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:h6.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:h6.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:h6.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:h6.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:h6.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:h6.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:h6.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:h6.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:h6.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:h6.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:h6.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:h6.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:h6.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:h6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:h6.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:h6.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:h6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:h6.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:h6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:h6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:h6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:h6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:h6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:h6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};GR0={FINDER:"finder"}});function l10(J){return J===c10}function VY(J){return J==="deep"||J===c10}function iH(J,Z){if(!l10(J))return!0;return Boolean(Z&&JJ(Z))}function qR0(J,Z){let Q=XJ(Z);if(!Q)return!1;if($y6.has(J)){let Y=Q.finder??GR0.FINDER,X=Jy6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function hf1(J,Z){let Q=XJ(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function AV(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(fG).filter((z)=>{if(!iH(z.key,Q?.userEmail))return!1;if(z.key===i10)return!1;if(K.includes(`!${z.key}`))return!1;if(Z===!1&&w8(z.key))return!1;if(V.has(z.key))return!1;if(Q?.v2&&!(("visibleInV2"in z)&&z.visibleInV2))return!1;let F="visible"in z?z.visible:!1,q=K.includes(z.key);return F||q}).map((z)=>({mode:z.key,description:"description"in z?z.description:void 0})).sort((z,G)=>z.mode.localeCompare(G.mode))}function XJ(J){return Object.values(fG).find((Z)=>Z.key===J)}function SX(J){return XJ(J)?.primaryModel??i3("CLAUDE_SONNET_4_5")}function Tb(J){let Z=XJ(J);if(!Z)return!1;return B$(Z.primaryModel).capabilities?.vision??!1}function w8(J){return J==="free"||J.startsWith("free-")}function WR0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function UR0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var $y6,Jy6,uf1,bf1,c10="internal",Zy6,Qy6,vf1,xf1,ff1,Yy6,Xy6,Ky6,fG,i10,FR0;var N$=Y0(()=>{VE();P7();$y6=new Set(["finder"]),Jy6={finder:"finder"},uf1={r:0,g:55,b:0},bf1={r:0,g:255,b:136};Zy6=["Read","Grep","glob","finder","Bash","create_file","edit_file","get_diagnostics","web_search","read_web_page","task_list","read_thread","find_thread","mermaid","chart","skill"],Qy6=["Read","Grep","glob","finder","Bash","create_file","edit_file","undo_edit","get_diagnostics","web_search","read_web_page","read_mcp_resource","mermaid","chart","read_thread","find_thread","skill","oracle","handoff","librarian","Task","task_list","look_at","painter"],vf1=["Read","finder","Bash","repl","create_file","edit_file","undo_edit","web_search","read_web_page","task_list","read_thread","find_thread","skill","oracle","code_tour","librarian","Task","Grep","glob","read_mcp_resource","mermaid","chart","look_at","get_diagnostics","handoff","painter","restore_snapshot","slack_write","slack_read"],xf1=["code_tour","code_review","walkthrough","walkthrough_diagram"],ff1=["code_tour","code_review"],Yy6=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],Xy6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],Ky6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],fG={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:i3("CLAUDE_OPUS_4_6"),includeTools:vf1,deferredTools:xf1,visible:!0,visibleInV2:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},FREE:{key:"free",displayName:"Free",description:"Amp Free",primaryModel:i3("CLAUDE_HAIKU_4_5"),includeTools:Zy6,visible:!0,uiHints:{primaryColor:{r:0,g:26,b:51},secondaryColor:{r:0,g:184,b:255}}},RUSH:{key:"rush",displayName:"Rush",description:"Faster and cheaper for small, well-defined tasks",primaryModel:i3("CLAUDE_HAIKU_4_5"),includeTools:Qy6,visible:!0,uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:i3("CLAUDE_OPUS_4_6"),includeTools:Yy6,visible:!1,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:i3("CLAUDE_OPUS_4_6"),includeTools:vf1,deferredTools:xf1,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.3 Codex",primaryModel:i3("GPT_5_3_CODEX"),includeTools:Xy6,deferredTools:ff1,visible:!0,visibleInV2:!0,reasoningEffort:"high",uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},INTERNAL:{key:c10,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:i3("GPT_5_4"),includeTools:Ky6,deferredTools:ff1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},i10=fG.AGG.key,FR0=Object.values(fG).map((J)=>J.key)});var n3=Y0(()=>{N$();P7()});function _b(J){return J["agent.deepReasoningEffort"]??"high"}function DR0(J){let Z=Vy6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function HR0(J){return zy6.includes(J)}function mf1(J){let Z=J["internal.model"];if(Z&&typeof Z==="object"){let Q=Z.oracle?.trim();if(Q&&Q.length>0){let Y=Q.indexOf(":");return Y===-1?Q:Q.slice(Y+1).trim()}}return J5.GPT_5_4.name}function pf1(J,Z){let Q=J["internal.model"];if(!Q)return null;let Y;if(typeof Q==="string")Y=Q.trim();else Y=Q[Z]?.trim();if(!Y||Y.length===0)return null;let X=Y.indexOf(":");if(X===-1)return null;let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K||!V)return null;return`${K}/${V}`}var Vy6,zy6,n10,gf1;var TW=Y0(()=>{n3();Vy6=["agent.deepReasoningEffort","agent.skipTitleGenerationIfMessageContains","anthropic.effort","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.speed","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];zy6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];n10=["mcpServers","mcpPermissions","url"],gf1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var C7;var WE=Y0(()=>{C7={AD_IMPRESSION_ESTIMATES:"ad-impression-estimates",AD_LOADING_ANIMATION:"ad-loading-animation",ANTHROPIC_FAST:"anthropic-fast",AGENTS_VIEW:"agents-view",BITBUCKET_ENTERPRISE:"bitbucket-enterprise",FILE_CHANGE_SYNC:"file-change-sync",HARNESS_SYSTEM_PROMPT:"harness-system-prompt",OPENAI_FAST:"openai-fast",PAYMENT_METHOD_EXEMPT:"payment-method-exempt",V2:"v2",V2_CHANGES_ARTIFACT_PANEL:"v2-changes-artifact-panel",DTW_TUI:"dtw-tui",GRAVITY:"gravity",REPOS_PLUGINS_OVERVIEW:"repos-plugins-overview",PLUGIN_API:"plugin-api",TASK_LIST:"task-list",THREAD_TIMING:"thread-timing",THREAD_TRACE_VIEWER:"thread-trace-viewer",TEAM_LABELS_FILTER:"team-labels-filter",UNIFIED_AD_RANKING:"unified-ad-ranking",USE_GENERATED_AD_CONTEXT:"use-generated-ad-context",PLUGINS:"plugins"}});var cf1;var BR0=Y0(()=>{tu();tu();cf1=y});var kX;var j9=Y0(()=>{BR0();BR0();kX=cf1});function o10(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function _W(J){if(J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){let Q=Z?.code;if(Q==="ESRCH")return!1;if(Q==="EPERM"||Q==="EACCES")return!0;return P.debug("PID check error",{pid:J,code:Q}),!1}}var UE=Y0(()=>{g0()});import{execFile as Gy6,spawnSync as kb}from"node:child_process";import qC from"node:fs";import NR0 from"node:os";import tZ from"node:path";import{promisify as Fy6}from"node:util";async function wy6(J){try{if(!await hy6())return[];let Z=await fy6(J);if(!Z)return[];let Q=await ef1(J);return(await tf1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return P.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function Oy6(J,Z){if(!Z.pid||!_W(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await ef1(J),K=(await tf1(J,Y)).find((z)=>s10(z.workspaceFolder)===s10(Q));if(!K)return null;let V=await Ay6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function Ly6(J,Z){let{filePath:Q,line:Y,column:X}=My6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=gy6(J);if(!V)return if1(J,Q,Y,X);if(kb(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return if1(J,Q,Y,X)}function if1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((q)=>encodeURIComponent(q)).join("/"),z=Q?`:${Q}${Y?`:${Y}`:""}`:"",G=`${J.urlScheme}://file${V}${z}`,F=Ey6(G);if(F.status===0)return!0;return P.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:G,status:F.status,stderr:F.stderr?.toString().trim()}),!1}function Ey6(J){if(process.platform==="darwin")return kb("open",[J],{stdio:"ignore"});if(process.platform==="win32")return kb("cmd.exe",["/c","start","",J],{stdio:"ignore"});return kb("xdg-open",[J],{stdio:"ignore"})}function My6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return{};let Q=Z.fragment?.match(/^L(\d+)(?::(\d+))?(?:-L(\d+)(?::(\d+))?)?$/),Y=Q?.[1]?Number.parseInt(Q[1],10):void 0,X=Q?.[2]?Number.parseInt(Q[2],10):void 0;return{filePath:Z.fsPath,line:Y,column:X}}catch{return{}}}async function Ay6(J){let Z=await vy6(J,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Z.length===0)return null;let Q=jy6(Z.find((G)=>G.key==="memento/workbench.parts.editor")?.value);if(!Q)return null;let Y=Q.leaves.flatMap((G)=>G.editors),X=Q.leaves.find((G)=>G.id===Q.activeGroup)??Q.leaves[0],K=X?Iy6(X):void 0,V=Py6(Z.find((G)=>G.key==="memento/workbench.editors.files.textFileEditor")?.value),z=K?await Cy6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:z}}function jy6(J){if(!J)return null;try{let Z=JSON.parse(J),Q=Z["editorpart.state"]??Z.editorpart?.state,Y=Q?.activeGroup;if(typeof Y!=="number")return null;let X=Q?.serializedGrid,K=sf1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return P.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function sf1(J){if(!J||typeof J!=="object")return[];let Z=J;if(Z.type==="leaf"){let Q=Z.data;if(typeof Q?.id!=="number")return[];let Y=Q.editors?.map((X)=>Ry6(X.value)).filter((X)=>Boolean(X))??[];return[{id:Q.id,editors:Y,preview:typeof Q.preview==="number"?Q.preview:void 0,mru:Array.isArray(Q.mru)?Q.mru.filter((X)=>Number.isInteger(X)):[]}]}if(Z.type==="branch")return(Array.isArray(Z.data??[])?Z.data??[]:[]).flatMap((Y)=>sf1(Y));return[]}function Ry6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return o1(X1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return o1(X1.file(Z.resourceJSON.path))}catch(Z){P.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function Iy6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function Py6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return P.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function Cy6(J,Z,Q){let Y=Q.get(J)??Q.get(decodeURIComponent(J))??Q.get(encodeURI(J));if(!Y)return;let K=(Y[String(Z)]??Object.values(Y)[0])?.cursorState?.[0];if(!K)return;let V=await Ty6(J);if(V===void 0)return;let z=nf1(K.selectionStart.lineNumber,K.selectionStart.column),G=nf1(K.position.lineNumber,K.position.column),F=af1(z,G)<=0?z:G,q=af1(z,G)<=0?G:z,U=F.line===q.line&&F.character===q.character?_y6(V,F.line):Sy6(V,F.line,F.character,q.line,q.character);return{range:{startLine:F.line,startCharacter:F.character,endLine:q.line,endCharacter:q.character},content:U}}async function Ty6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return;return await qC.promises.readFile(Z.fsPath,"utf-8")}catch(Z){P.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function nf1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function af1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function _y6(J,Z){return J.split(`
104
+ `),X=Y.find((z)=>z.includes("OS Name")),K=Y.find((z)=>z.includes("OS Version"));if(X&&K){let z=X.split(":")[1]?.trim(),G=K.split(":")[1]?.trim();return`${z} ${G}`}return R0("node:os").release()}catch{return R0("node:os").release()}default:return"unknown"}}catch{return"unknown"}}function vG(){if(!zR0){let J=typeof process<"u"&&process.versions?.node,Z=!J,Q="linux",Y="unknown",X="unknown";if(J){if(process.platform==="darwin")Q="darwin";else if(process.platform==="win32")Q="windows";Y=ek6(Q),X=process.arch}else if(typeof navigator<"u"){let K=navigator.platform.toLowerCase();if(K.includes("mac")||K.includes("ios"))Q="darwin";else if(K.includes("win"))Q="windows";let V=navigator.userAgent;if(Q==="darwin"){let z=V.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);if(z?.[1])Y=z[1].replace(/_/g,".")}else if(Q==="windows"){let z=V.match(/Windows NT (\d+\.\d+)/);if(z?.[1])Y=z[1]}else{let z=V.match(/Linux.*?(\d+\.\d+)/);if(z?.[1])Y=z[1]}if(V.includes("x86_64")||V.includes("WOW64"))X="x64";else if(V.includes("i686"))X="x86";else if(V.includes("ARM64")||V.includes("arm64"))X="arm64";else if(V.includes("ARM"))X="arm"}zR0={webBrowser:Z,os:Q,osVersion:Y,cpuArchitecture:X,client:qE().name,optionAltKeyShort:Q==="darwin"?"⌥":"Alt",ctrlCmdKeyShort:Q==="darwin"?"⌘":"⌃",ctrlCmdKey:Q==="darwin"?"⌘":"Ctrl"}}return zR0}var zR0;var FC=Y0(()=>{QJ()});function i3(J){let Z=J5[J];return`${Z.provider}/${Z.name}`}function xG(J){let Z=J.indexOf("/");if(Z===-1)throw Error(`Invalid provider/model format: ${J}`);return{provider:J.slice(0,Z),model:J.slice(Z+1)}}function B$(J){let{provider:Z,model:Q}=xG(J);for(let Y of Object.values(J5))if(Y.provider===Z&&Y.name===Q)return Y;switch(Z){case"anthropic":return J5.CLAUDE_SONNET_4_5;case"openai":return J5.GPT_5;case"xai":return J5.GROK_CODE_FAST_1;case"cerebras":return J5.Z_AI_GLM_4_7;case"fireworks":return J5.FIREWORKS_GLM_4P6;case"baseten":return J5.BASETEN_KIMI_K2P5;case"moonshotai":return J5.KIMI_K2_INSTRUCT;case"openrouter":return J5.SONOMA_SKY_ALPHA;case"groq":return J5.GPT_OSS_120B;case"vertexai":return J5.GEMINI_3_1_PRO_PREVIEW;default:throw Error(`Unknown provider: ${Z}`)}}function Cb(J){for(let Q of Object.values(J5))if(Q.name===J)return Q;let Z=J.match(/^(.*)-\d{4}-\d{2}-\d{2}$/);if(Z){let Q=Z[1];for(let Y of Object.values(J5))if(Y.name===Q)return Y}return}function x8(J){let Z=J.indexOf("/");if(Z===-1)return J;return J.slice(Z+1)}function YJ(J){let Z=B$(J);return Z.contextWindow-Z.maxOutputTokens}function d10(J){return B$(J).maxOutputTokens}var h6,J5,GR0;var P7=Y0(()=>{h6={ANTHROPIC:"anthropic",BASENTEN:"baseten",OPENAI:"openai",XAI:"xai",CEREBRAS:"cerebras",FIREWORKS:"fireworks",GROQ:"groq",MOONSHOT:"moonshotai",OPENROUTER:"openrouter",VERTEXAI:"vertexai"},J5={CLAUDE_SONNET_4:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_5:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",contextWindow:1e6,maxOutputTokens:32000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_SONNET_4_6:{provider:h6.ANTHROPIC,name:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64000,pricing:{input:3,output:15,cached:0.3,cacheWrite:3.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4:{provider:h6.ANTHROPIC,name:"claude-opus-4-20250514",displayName:"Claude Opus 4",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_1:{provider:h6.ANTHROPIC,name:"claude-opus-4-1-20250805",displayName:"Claude Opus 4.1",contextWindow:200000,maxOutputTokens:32000,pricing:{input:15,output:75,cached:1.5,cacheWrite:18.75,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_5:{provider:h6.ANTHROPIC,name:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_OPUS_4_6:{provider:h6.ANTHROPIC,name:"claude-opus-4-6",displayName:"Claude Opus 4.6",contextWindow:332000,maxOutputTokens:32000,pricing:{input:5,output:25,cached:0.5,cacheWrite:6.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},CLAUDE_HAIKU_4_5:{provider:h6.ANTHROPIC,name:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",contextWindow:200000,maxOutputTokens:64000,pricing:{input:1,output:5,cached:0.1,cacheWrite:1.25,cacheTTL:300},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5:{provider:h6.OPENAI,name:"gpt-5",displayName:"GPT-5",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_1:{provider:h6.OPENAI,name:"gpt-5.1",displayName:"GPT-5.1",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_2:{provider:h6.OPENAI,name:"gpt-5.2",displayName:"GPT-5.2",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_4:{provider:h6.OPENAI,name:"gpt-5.4",displayName:"GPT-5.4",contextWindow:400000,maxOutputTokens:128000,pricing:{input:2.5,output:15,cached:0.25},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_CODEX:{provider:h6.OPENAI,name:"gpt-5-codex",displayName:"GPT-5 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_1_CODEX:{provider:h6.OPENAI,name:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.25,output:10,cached:0.125},capabilities:{reasoning:!0,tools:!0}},GPT_5_2_CODEX:{provider:h6.OPENAI,name:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_3_CODEX:{provider:h6.OPENAI,name:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",contextWindow:400000,maxOutputTokens:128000,pricing:{input:1.75,output:14,cached:0.175},capabilities:{reasoning:!0,tools:!0,vision:!0}},GPT_5_MINI:{provider:h6.OPENAI,name:"gpt-5-mini",displayName:"GPT-5 Mini",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.25,output:2,cached:0.025},capabilities:{reasoning:!0,vision:!0,tools:!0}},GPT_5_NANO:{provider:h6.OPENAI,name:"gpt-5-nano",displayName:"GPT-5 Nano",contextWindow:400000,maxOutputTokens:128000,pricing:{input:0.05,output:0.4,cached:0.005},capabilities:{reasoning:!0,vision:!0,tools:!0}},O3:{provider:h6.OPENAI,name:"o3",displayName:"o3",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:2,output:8,cached:0.5},capabilities:{reasoning:!0,tools:!0}},O3_MINI:{provider:h6.OPENAI,name:"o3-mini",displayName:"o3-mini",contextWindow:200000,maxOutputTokens:1e5,pricing:{input:1.1,output:4.4,cached:0.55},capabilities:{reasoning:!0,tools:!0}},GPT_OSS_120B:{provider:h6.OPENAI,name:"openai/gpt-oss-120b",displayName:"GPT OSS 120B",contextWindow:128000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GROK_CODE_FAST_1:{provider:h6.XAI,name:"grok-code-fast-1",displayName:"Grok Code Fast 1",contextWindow:256000,maxOutputTokens:32000,capabilities:{reasoning:!0,tools:!0}},GEMINI_3_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_1_PRO_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI3_FLASH_PREVIEW:{provider:h6.VERTEXAI,name:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",contextWindow:1048576,maxOutputTokens:65535,capabilities:{tools:!0,reasoning:!0,vision:!0}},GEMINI_3_PRO_IMAGE:{provider:h6.VERTEXAI,name:"gemini-3-pro-image-preview",displayName:"Gemini 3 Pro Image",contextWindow:1048576,maxOutputTokens:65535,capabilities:{vision:!0,imageGeneration:!0}},Z_AI_GLM_4_7:{provider:h6.CEREBRAS,name:"zai-glm-4.7",displayName:"Z.ai GLM 4.7",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},FIREWORKS_QWEN3_CODER_480B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",displayName:"Qwen3 Coder 480B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_KIMI_K2_INSTRUCT:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_QWEN3_235B:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/qwen3-235b-a22b-instruct-2507",displayName:"Qwen3 235B",contextWindow:230144,maxOutputTokens:32000,capabilities:{tools:!0}},FIREWORKS_GLM_4P6:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-4p6",displayName:"GLM 4P6",contextWindow:162752,maxOutputTokens:40000,capabilities:{tools:!0,reasoning:!0}},FIREWORKS_GLM_5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/glm-5",displayName:"GLM 5",contextWindow:202800,maxOutputTokens:40000,pricing:{input:1,output:3.2},capabilities:{tools:!0}},FIREWORKS_MINIMAX_M2P5:{provider:h6.FIREWORKS,name:"accounts/fireworks/models/minimax-m2p5",displayName:"MiniMax M2.5",contextWindow:200000,maxOutputTokens:32000,pricing:{input:0.3,output:1.2,cached:0.03},capabilities:{tools:!0}},BASETEN_KIMI_K2P5:{provider:h6.BASENTEN,name:"moonshotai/Kimi-K2.5",displayName:"Kimi K2.5",contextWindow:262144,maxOutputTokens:32000,pricing:{input:0.6,output:3,cached:0.1},capabilities:{tools:!0,vision:!0}},KIMI_K2_INSTRUCT:{provider:h6.MOONSHOT,name:"kimi-k2-instruct-0905",displayName:"Kimi K2 Instruct",contextWindow:1e6,maxOutputTokens:32000,capabilities:{tools:!0}},SONOMA_SKY_ALPHA:{provider:h6.OPENROUTER,name:"sonoma-sky-alpha",displayName:"Sonoma Sky Alpha",contextWindow:256000,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_GLM_4_6:{provider:h6.OPENROUTER,name:"z-ai/glm-4.6",displayName:"OpenRouter GLM 4.6",contextWindow:131000,maxOutputTokens:40000,capabilities:{tools:!0}},OPENROUTER_KIMI_K2_0905:{provider:h6.OPENROUTER,name:"moonshotai/kimi-k2-0905",displayName:"Kimi K2 0905 (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_CODER_480B:{provider:h6.OPENROUTER,name:"qwen/qwen3-coder",displayName:"Qwen3 Coder 480B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}},OPENROUTER_QWEN3_235B:{provider:h6.OPENROUTER,name:"qwen/qwen3-235b-a22b-2507",displayName:"Qwen3 235B A22B (OpenRouter)",contextWindow:262144,maxOutputTokens:32000,capabilities:{tools:!0}}};GR0={FINDER:"finder"}});function l10(J){return J===c10}function VY(J){return J==="deep"||J===c10}function iH(J,Z){if(!l10(J))return!0;return Boolean(Z&&JJ(Z))}function qR0(J,Z){let Q=XJ(Z);if(!Q)return!1;if($y6.has(J)){let Y=Q.finder??GR0.FINDER,X=Jy6[Y];if(J!==X)return!1}if(Q.includeTools){if(Q.deferredTools?.includes(J))return!0;return Q.includeTools.includes(J)}return!0}function hf1(J,Z){let Q=XJ(Z);if(!Q)return!1;return Q.deferredTools?.includes(J)??!1}function AV(J,Z,Q){let Y=J?.["internal.visibleModes"]??[],X=J?.["experimental.modes"]??[],K=[...Y,...X],V=new Set(J?.disabledAgentModes??[]);return Object.values(fG).filter((z)=>{if(!iH(z.key,Q?.userEmail))return!1;if(z.key===i10)return!1;if(K.includes(`!${z.key}`))return!1;if(Z===!1&&w8(z.key))return!1;if(V.has(z.key))return!1;if(Q?.v2&&!(("visibleInV2"in z)&&z.visibleInV2))return!1;let F="visible"in z?z.visible:!1,q=K.includes(z.key);return F||q}).map((z)=>({mode:z.key,description:"description"in z?z.description:void 0})).sort((z,G)=>z.mode.localeCompare(G.mode))}function XJ(J){return Object.values(fG).find((Z)=>Z.key===J)}function SX(J){return XJ(J)?.primaryModel??i3("CLAUDE_SONNET_4_5")}function Tb(J){let Z=XJ(J);if(!Z)return!1;return B$(Z.primaryModel).capabilities?.vision??!1}function w8(J){return J==="free"||J.startsWith("free-")}function WR0(J,Z){return Z.find((Q)=>Q.mode===J)?.description}function UR0(J,Z){let Y=(Z.findIndex((K)=>K.mode===J)+1)%Z.length;return Z[Y]?.mode??"smart"}var $y6,Jy6,uf1,bf1,c10="internal",Zy6,Qy6,vf1,xf1,ff1,Yy6,Xy6,Ky6,fG,i10,FR0;var N$=Y0(()=>{VE();P7();$y6=new Set(["finder"]),Jy6={finder:"finder"},uf1={r:0,g:55,b:0},bf1={r:0,g:255,b:136};Zy6=["Read","Grep","glob","finder","Bash","create_file","edit_file","get_diagnostics","web_search","read_web_page","task_list","read_thread","find_thread","mermaid","chart","skill"],Qy6=["Read","Grep","glob","finder","Bash","create_file","edit_file","undo_edit","get_diagnostics","web_search","read_web_page","read_mcp_resource","mermaid","chart","read_thread","find_thread","skill","oracle","handoff","librarian","Task","task_list","look_at","painter"],vf1=["Read","finder","Bash","repl","create_file","edit_file","undo_edit","web_search","read_web_page","task_list","read_thread","find_thread","skill","oracle","code_tour","librarian","Task","Grep","glob","read_mcp_resource","mermaid","chart","look_at","get_diagnostics","handoff","painter","restore_snapshot","slack_write","slack_read"],xf1=["code_tour","code_review","walkthrough","walkthrough_diagram"],ff1=["code_tour","code_review"],Yy6=["find_thread","read_thread","web_search","read_web_page","docs_list","docs_read","docs_write","render_agg_man","create_project","create_thread","archive_thread","unarchive_thread","send_message_to_thread","slack_write","slack_read","github_repo_ci_status","read_github","search_github","commit_search","list_directory_github","list_repositories","glob_github","diff"],Xy6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],Ky6=["shell_command","apply_patch","web_search","read_web_page","chart","skill","read_thread","find_thread","librarian","oracle","code_tour","finder","painter","handoff","thread_status","send_message_to_aggman"],fG={SMART:{key:"smart",displayName:"Smart",description:"The most capable model and set of tools",primaryModel:i3("CLAUDE_OPUS_4_6"),includeTools:vf1,deferredTools:xf1,visible:!0,visibleInV2:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:55,b:20},secondaryColor:{r:0,g:255,b:136}}},FREE:{key:"free",displayName:"Free",description:"Amp Free",primaryModel:i3("CLAUDE_HAIKU_4_5"),includeTools:Zy6,visible:!0,uiHints:{primaryColor:{r:0,g:26,b:51},secondaryColor:{r:0,g:184,b:255}}},RUSH:{key:"rush",displayName:"Rush",description:"Faster and cheaper for small, well-defined tasks",primaryModel:i3("CLAUDE_HAIKU_4_5"),includeTools:Qy6,visible:!0,uiHints:{fasterAnimation:!0,labelAnimation:"jitter",primaryColor:{r:128,g:51,b:0},secondaryColor:{r:255,g:215,b:0}}},AGG:{key:"agg-man",displayName:"Agg",description:"Navigate work across Amp projects, threads, and context",primaryModel:i3("CLAUDE_OPUS_4_6"),includeTools:Yy6,visible:!1,uiHints:{primaryColor:{r:26,g:0,b:77},secondaryColor:{r:102,g:153,b:255}}},LARGE:{key:"large",displayName:"Large",description:"The biggest context window possible (Opus 4.6 1M tokens), for large tasks",primaryModel:i3("CLAUDE_OPUS_4_6"),includeTools:vf1,deferredTools:xf1,visible:!0,uiHints:{labelAnimation:"glow",primaryColor:{r:42,g:26,b:77},secondaryColor:{r:153,g:102,b:255}}},DEEP:{key:"deep",displayName:"Deep",description:"Deep reasoning with GPT-5.3 Codex",primaryModel:i3("GPT_5_3_CODEX"),includeTools:Xy6,deferredTools:ff1,visible:!0,visibleInV2:!0,reasoningEffort:"high",uiHints:{labelAnimation:"glow",primaryColor:{r:0,g:77,b:64},secondaryColor:{r:29,g:233,b:182}}},INTERNAL:{key:c10,displayName:"Internal",description:"Internal-only mode for Amp development and debugging",primaryModel:i3("GPT_5_4"),includeTools:Ky6,deferredTools:ff1,visible:!0,visibleInV2:!0,reasoningEffort:"xhigh",uiHints:{labelAnimation:"glow",primaryColor:{r:77,g:18,b:0},secondaryColor:{r:255,g:119,b:42}}}},i10=fG.AGG.key,FR0=Object.values(fG).map((J)=>J.key)});var n3=Y0(()=>{N$();P7()});function _b(J){return J["agent.deepReasoningEffort"]??"high"}function DR0(J){let Z=Vy6.flatMap((Q)=>{let Y=J[Q];return Y===void 0?[]:[[Q,Y]]});return Object.fromEntries(Z)}function HR0(J){return zy6.includes(J)}function mf1(J){let Z=J["internal.model"];if(Z&&typeof Z==="object"){let Q=Z.oracle?.trim();if(Q&&Q.length>0){let Y=Q.indexOf(":");return Y===-1?Q:Q.slice(Y+1).trim()}}return J5.GPT_5_4.name}function pf1(J,Z){let Q=J["internal.model"];if(!Q)return null;let Y;if(typeof Q==="string")Y=Q.trim();else Y=Q[Z]?.trim();if(!Y||Y.length===0)return null;let X=Y.indexOf(":");if(X===-1)return null;let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K||!V)return null;return`${K}/${V}`}var Vy6,zy6,n10,gf1;var TW=Y0(()=>{n3();Vy6=["agent.deepReasoningEffort","agent.skipTitleGenerationIfMessageContains","anthropic.effort","anthropic.interleavedThinking.enabled","anthropic.provider","anthropic.speed","anthropic.temperature","anthropic.thinking.enabled","gemini.thinkingLevel","internal.compactionThresholdPercent","internal.model","internal.openai.websocket.enabled","internal.oracleReasoningEffort","openai.speed","tools.disable","tools.enable"];zy6=["guardedFiles.allowlist","mcpPermissions","tools.disable","tools.enable","permissions"];n10=["mcpServers","mcpPermissions","url"],gf1=["apiKey","buildkite-access-token","github-access-token","gitlab-access-token","gitlab-instance-url","mcp-oauth-client-secret","mcp-oauth-token"]});var C7;var WE=Y0(()=>{C7={AD_IMPRESSION_ESTIMATES:"ad-impression-estimates",AD_LOADING_ANIMATION:"ad-loading-animation",ANTHROPIC_FAST:"anthropic-fast",AGENTS_VIEW:"agents-view",BITBUCKET_ENTERPRISE:"bitbucket-enterprise",FILE_CHANGE_SYNC:"file-change-sync",HARNESS_SYSTEM_PROMPT:"harness-system-prompt",OPENAI_FAST:"openai-fast",PAYMENT_METHOD_EXEMPT:"payment-method-exempt",V2:"v2",V2_CHANGES_ARTIFACT_PANEL:"v2-changes-artifact-panel",DTW_TUI:"dtw-tui",GRAVITY:"gravity",REPOS_PLUGINS_OVERVIEW:"repos-plugins-overview",PLUGIN_API:"plugin-api",TASK_LIST:"task-list",THREAD_TIMING:"thread-timing",THREAD_TRACE_VIEWER:"thread-trace-viewer",TEAM_LABELS_FILTER:"team-labels-filter",UNIFIED_AD_RANKING:"unified-ad-ranking",USE_GENERATED_AD_CONTEXT:"use-generated-ad-context",PLUGINS:"plugins"}});var cf1;var BR0=Y0(()=>{tu();tu();cf1=y});var kX;var j9=Y0(()=>{BR0();BR0();kX=cf1});function o10(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}function _W(J){if(J<=0)return!1;try{return process.kill(J,0),!0}catch(Z){let Q=Z?.code;if(Q==="ESRCH")return!1;if(Q==="EPERM"||Q==="EACCES")return!0;return P.debug("PID check error",{pid:J,code:Q}),!1}}var UE=Y0(()=>{g0()});import{execFile as Gy6,spawnSync as kb}from"node:child_process";import qC from"node:fs";import NR0 from"node:os";import tZ from"node:path";import{promisify as Fy6}from"node:util";async function wy6(J){try{if(!await hy6())return[];let Z=await fy6(J);if(!Z)return[];let Q=await ef1(J);return(await tf1(J,Q)).map((X)=>({workspaceFolders:[X.workspaceFolder],port:0,ideName:J.ideName,authToken:"",pid:Z,connection:"query"}))}catch(Z){return P.debug(`Failed to list ${J.ideName} configs`,{error:Z instanceof Error?Z.message:String(Z)}),[]}}async function Oy6(J,Z){if(!Z.pid||!_W(Z.pid))return null;let Q=Z.workspaceFolders[0];if(!Q)return null;let Y=await ef1(J),K=(await tf1(J,Y)).find((z)=>s10(z.workspaceFolder)===s10(Q));if(!K)return null;let V=await Ay6(K.stateDBPath);if(!V)return{openFiles:[]};return V}function Ly6(J,Z){let{filePath:Q,line:Y,column:X}=My6(Z);if(!Q)return!1;let K=Y?`${Q}:${Y}${X?`:${X}`:""}`:Q,V=gy6(J);if(!V)return if1(J,Q,Y,X);if(kb(V,["--goto",K],{stdio:"ignore"}).status===0)return!0;return if1(J,Q,Y,X)}function if1(J,Z,Q,Y){let X=Z.replaceAll("\\","/"),V=(X.startsWith("/")?X:`/${X}`).split("/").map((q)=>encodeURIComponent(q)).join("/"),z=Q?`:${Q}${Y?`:${Y}`:""}`:"",G=`${J.urlScheme}://file${V}${z}`,F=Ey6(G);if(F.status===0)return!0;return P.debug(`Failed to open URI with ${J.ideName} URL scheme`,{schemeURI:G,status:F.status,stderr:F.stderr?.toString().trim()}),!1}function Ey6(J){if(process.platform==="darwin")return kb("open",[J],{stdio:"ignore"});if(process.platform==="win32")return kb("cmd.exe",["/c","start","",J],{stdio:"ignore"});return kb("xdg-open",[J],{stdio:"ignore"})}function My6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return{};let Q=Z.fragment?.match(/^L(\d+)(?::(\d+))?(?:-L(\d+)(?::(\d+))?)?$/),Y=Q?.[1]?Number.parseInt(Q[1],10):void 0,X=Q?.[2]?Number.parseInt(Q[2],10):void 0;return{filePath:Z.fsPath,line:Y,column:X}}catch{return{}}}async function Ay6(J){let Z=await vy6(J,"select key, value from ItemTable where key in ('memento/workbench.parts.editor', 'memento/workbench.editors.files.textFileEditor')");if(Z.length===0)return null;let Q=jy6(Z.find((G)=>G.key==="memento/workbench.parts.editor")?.value);if(!Q)return null;let Y=Q.leaves.flatMap((G)=>G.editors),X=Q.leaves.find((G)=>G.id===Q.activeGroup)??Q.leaves[0],K=X?Iy6(X):void 0,V=Py6(Z.find((G)=>G.key==="memento/workbench.editors.files.textFileEditor")?.value),z=K?await Cy6(K,Q.activeGroup,V):void 0;return{openFile:K,openFiles:Y,selection:z}}function jy6(J){if(!J)return null;try{let Z=JSON.parse(J),Q=Z["editorpart.state"]??Z.editorpart?.state,Y=Q?.activeGroup;if(typeof Y!=="number")return null;let X=Q?.serializedGrid,K=sf1(X?.root??X);return{activeGroup:Y,leaves:K}}catch(Z){return P.debug("Failed to parse VS Code editor state",{error:Z instanceof Error?Z.message:String(Z)}),null}}function sf1(J){if(!J||typeof J!=="object")return[];let Z=J;if(Z.type==="leaf"){let Q=Z.data;if(typeof Q?.id!=="number")return[];let Y=Q.editors?.map((X)=>Ry6(X.value)).filter((X)=>Boolean(X))??[];return[{id:Q.id,editors:Y,preview:typeof Q.preview==="number"?Q.preview:void 0,mru:Array.isArray(Q.mru)?Q.mru.filter((X)=>Number.isInteger(X)):[]}]}if(Z.type==="branch")return(Array.isArray(Z.data??[])?Z.data??[]:[]).flatMap((Y)=>sf1(Y));return[]}function Ry6(J){if(!J)return;try{let Z=JSON.parse(J),Q=Z.resourceJSON?.external;if(Q)return o1(X1.parse(Q));if(Z.resourceJSON?.scheme==="file"&&Z.resourceJSON.path)return o1(X1.file(Z.resourceJSON.path))}catch(Z){P.debug("Failed to parse VS Code editor URI",{error:Z instanceof Error?Z.message:String(Z)})}return}function Iy6(J){let Z=J.mru[0]??J.preview??0;return J.editors[Z]??J.editors[0]}function Py6(J){if(!J)return new Map;try{let Q=JSON.parse(J).textEditorViewState??[];return new Map(Q)}catch(Z){return P.debug("Failed to parse VS Code text editor state",{error:Z instanceof Error?Z.message:String(Z)}),new Map}}async function Cy6(J,Z,Q){let Y=Q.get(J)??Q.get(decodeURIComponent(J))??Q.get(encodeURI(J));if(!Y)return;let K=(Y[String(Z)]??Object.values(Y)[0])?.cursorState?.[0];if(!K)return;let V=await Ty6(J);if(V===void 0)return;let z=nf1(K.selectionStart.lineNumber,K.selectionStart.column),G=nf1(K.position.lineNumber,K.position.column),F=af1(z,G)<=0?z:G,q=af1(z,G)<=0?G:z,U=F.line===q.line&&F.character===q.character?_y6(V,F.line):Sy6(V,F.line,F.character,q.line,q.character);return{range:{startLine:F.line,startCharacter:F.character,endLine:q.line,endCharacter:q.character},content:U}}async function Ty6(J){try{let Z=X1.parse(J);if(Z.scheme!=="file")return;return await qC.promises.readFile(Z.fsPath,"utf-8")}catch(Z){P.debug("Failed to read VS Code active file content",{fileURI:J,error:Z instanceof Error?Z.message:String(Z)});return}}function nf1(J,Z){return{line:Math.max(0,J-1),character:Math.max(0,Z-1)}}function af1(J,Z){if(J.line===Z.line)return J.character-Z.character;return J.line-Z.line}function _y6(J,Z){return J.split(`
105
105
  `)[Z]??""}function Sy6(J,Z,Q,Y,X){let K=of1(J,Z,Q),V=of1(J,Y,X);if(V<=K)return"";return J.slice(K,V)}function of1(J,Z,Q){let Y=0,X=0;for(let K=0;K<J.length;K+=1){if(Y===Z&&X===Q)return K;if(J[K]===`
106
106
  `)Y+=1,X=0;else X+=1}return J.length}async function tf1(J,Z){if(Z?.size===0)return[];let Q=tZ.join($u1(J),"workspaceStorage");if(!await Sb(Q))return[];let Y=await qC.promises.readdir(Q,{withFileTypes:!0});return(await Promise.all(Y.filter((V)=>V.isDirectory()).map(async(V)=>{let z=V.name,G=tZ.join(Q,z),F=tZ.join(G,"state.vscdb"),q=tZ.join(G,"workspace.json");if(!await Sb(F)||!await Sb(q))return null;let W=await yy6(q);if(!W||!await Sb(W))return null;if(Z&&!Z.has(s10(W)))return null;let U=await qC.promises.stat(F);return{storageID:z,workspaceFolder:W,stateDBPath:F,mtime:U.mtimeMs}}))).filter((V)=>V!==null).sort((V,z)=>z.mtime-V.mtime).slice(0,qy6)}async function ef1(J){let Z=tZ.join($u1(J),"globalStorage","storage.json");if(!await Sb(Z))return null;try{let Q=await qC.promises.readFile(Z,"utf-8"),X=JSON.parse(Q).windowsState,K=Array.isArray(X?.openedWindows)?X.openedWindows:[],V=K.length>0?K:[X?.lastActiveWindow],z=new Set;for(let G of V){if(!G)continue;let F=ky6(G);if(!F)continue;z.add(s10(F))}return z}catch(Q){return P.debug(`Failed to parse ${J.ideName} windowsState`,{storageFilePath:Z,error:Q instanceof Error?Q.message:String(Q)}),null}}function ky6(J){if(J.folder)return rf1(J.folder);let Z=J.workspaceIdentifier?.configURIPath;if(!Z)return null;let Q=rf1(Z);return Q?tZ.dirname(Q):null}function rf1(J){try{return X1.parse(J).fsPath}catch{if(tZ.isAbsolute(J))return J;return null}}async function yy6(J){try{let Z=await qC.promises.readFile(J,"utf-8"),Q=JSON.parse(Z);if(Q.folder)return X1.parse(Q.folder).fsPath;if(Q.configuration)return tZ.dirname(X1.parse(Q.configuration).fsPath)}catch(Z){P.debug("Failed to parse VS Code workspace metadata",{workspaceMetadataPath:J,error:Z instanceof Error?Z.message:String(Z)})}return null}async function Sb(J){try{return await qC.promises.access(J),!0}catch{return!1}}async function vy6(J,Z){let Q=await r10("sqlite3",["-readonly","-json",xy6(J),Z],{timeout:By6});if(Q.status!==0)return P.debug("sqlite3 query failed for VS Code database",{status:Q.status,stderr:Q.stderr?.trim()}),[];let Y=Q.stdout?.trim();if(!Y)return[];try{return JSON.parse(Y).filter((K)=>typeof K.key==="string"&&typeof K.value==="string")}catch(X){return P.debug("Failed to parse sqlite3 JSON output for VS Code database",{error:X instanceof Error?X.message:String(X)}),[]}}function xy6(J){let Q=J.replaceAll("\\","/").split("/").map((X)=>encodeURIComponent(X)).join("/");return`file:${Q.startsWith("/")?Q:`/${Q}`}?immutable=1`}async function fy6(J){return(await uy6()).find((Y)=>by6(J,Y.command))?.pid??null}async function uy6(){if(process.platform==="win32"){let Z=await r10("tasklist",["/FO","CSV"]);if(Z.status!==0)return[];return Z.stdout.split(`
107
107
  `).slice(1).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{let[Y,X]=Q.replaceAll('"',"").split(",");return{pid:Number.parseInt(X??"",10),command:Y??""}}).filter((Q)=>Number.isFinite(Q.pid)&&Q.command)}let J=await r10("ps",["-ax","-o","pid=","-o","command="]);if(J.status!==0)return[];return J.stdout.split(`
@@ -4630,7 +4630,7 @@ ${G9(zy5)}
4630
4630
  `))}await q.asyncDispose(),process.exit(0)}catch(W){await q.asyncDispose();let U=`Failed to analyze thread context: ${W instanceof Error?W.message:String(W)}`;F(U)}}var UU4=process.hrtime.bigint(),yp0=null;function DU4(){yp0=process.hrtime.bigint()}function HU4(){if(yp0===null)return null;return Number(process.hrtime.bigint()-yp0)/1e6}_X();g0();var RN4=z4(L4(),1),dY=z4(AN4(),1),IN4=z4(dA(),1);import RZ0 from"node:fs";import IZ0 from"node:path";var jN4=Object.keys(P),hm5=IZ0.join(rZ,"logs"),nA=IZ0.join(hm5,"cli.log"),gm5=10485760;function mm5(J){try{if(RZ0.statSync(J).size>gm5)RZ0.truncateSync(J,0)}catch{}}var wl,Oc0=!1,Nl=null;function pm5(J){return J instanceof Error&&J.message.includes("write after end")}function Bl(J,Z,Q,Y){if(Oc0)return;try{J[Z](Q,...Y)}catch(X){if(!pm5(X))throw X}}function PN4(J){Oc0=!1,Nl=null;let Z=IZ0.resolve(J?.logFile||nA),Q=J?.logLevel||"info";if(!jN4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{RZ0.mkdirSync(IZ0.dirname(Z),{recursive:!0})}catch(z){console.error(`Failed to create log directory: ${z}`)}mm5(Z);let Y=dY.default.format((z)=>{for(let G of Object.keys(z)){let F=z[G];if(F instanceof Error)z[G]={name:F.name,message:F.message,stack:F.stack}}return z}),X=dY.default.format((z)=>{return z.pid=process.pid,z}),K=[new dY.default.transports.File({filename:Z}),new CN4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new dY.default.transports.Console({level:"debug",format:dY.default.format.combine(dY.default.format.colorize(),dY.default.format.simple())}));wl=dY.default.createLogger({level:jN4.includes(Q)?Q:"info",format:dY.default.format.combine(dY.default.format.timestamp(),X(),Y(),dY.default.format.json(),dY.default.format.errors({stack:!0})),transports:K});let V=wl;cv1({error:(z,...G)=>{Bl(V,"error",z,G)},warn:(z,...G)=>{Bl(V,"warn",z,G)},info:(z,...G)=>{Bl(V,"info",z,G)},debug:(z,...G)=>{Bl(V,"debug",z,G)},audit:(z,...G)=>{let F=typeof G[0]==="object"&&G[0]!==null?{audit:!0,...G[0]}:{audit:!0};Bl(V,"info",z,[F])}})}class CN4 extends IN4.default{log({message:J,...Z},Q){RN4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function lF(){if(Nl)return Nl;let J=wl;if(!J)return Promise.resolve();return Oc0=!0,Nl=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,wl===J)wl=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),Nl}g0();import{execFile as dm5}from"node:child_process";import{promisify as cm5}from"node:util";var lm5=cm5(dm5),im5=["private","public","workspace"];function Lc0(J){return J.endsWith("/")?J.slice(0,-1):J}function nm5(J){let Z=oJ0(J);try{let X=new URL(Z);return Lc0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return Lc0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return Lc0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function SN4(J){try{let{stdout:Z}=await lm5("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return nm5(Q)}catch{return null}}function am5(J){let Z=[...im5];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function TN4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function om5(J){if(J?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
4631
4631
  `].join(""));return Error(`Group visibility is not available.
4632
4632
  `)}function _N4(J,Z){let Y=[`Invalid ${J?`visibility for amp.defaultVisibility.${J}`:"visibility"}. `,`Must be one of: ${Z.join(", ")}.
4633
- `].join("");return Error(Y)}function rm5(J,Z){return Z.includes(J)}function sm5(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function kN4(J,Z,Q){if(J===void 0||J===null)return;let Y=am5(Z);if(typeof J!=="string")return _N4(Q,Y);if(J==="group"&&!Y.includes("group"))return om5(Z);if(rm5(J,Y))return J;return _N4(Q,Y)}async function tm5(J,Z,Q){let Y=await SN4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return kN4(K,Q,Y)}async function PZ0(J,Z,Q,Y){if(Y)return Y;if(!sm5(Q))return TN4(Q);let X=await tm5(J,Z,Q);if(X instanceof Error)return X;return X??TN4(Q)}function yN4(J,Z){return kN4(J,Z)}async function vN4(J,Z,Q){let Y=await SN4(Z);if(!Y)return Error("No git origin remote found for this repository.");let K={...await J.get("defaultVisibility","global")??{},[Y]:Q};return await J.set("defaultVisibility",K,"global"),{repoKey:Y}}t$();function CZ0(J){let Z=J.replace(/-/g,"");if(Z.length!==32)throw Error(`Invalid UUID hex length: ${Z.length}`);let Q=BigInt("0x"+Z),Y="";while(Q>0n)Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(Q%62n)]+Y,Q=Q/62n;return Y.padStart(22,"0")}U4();uj0();t$();var G8=y.string().min(1),Mc0=y.string().regex(/^[0-9A-Za-z]{22}$/),em5=y.templateLiteral([y.string().regex(/^[0-9a-f]{8}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{12}$/)]),Ol=y.templateLiteral(["T-",em5]),$p5=y.enum(["fork","handoff","mention"]),Jp5=y.enum(["parent","child"]),xN4=y.object({threadID:Ol,type:$p5,role:Jp5,messageIndex:y.number().int().nonnegative().optional(),blockIndex:y.number().int().nonnegative().optional(),createdAt:y.number().int().nonnegative(),comment:y.string().optional()}),q5=y.templateLiteral(["M-",Mc0]);function iF(){return`M-${CZ0(ZE())}`}var j8=y.templateLiteral(["TU-",Mc0]);function fN4(){return`TU-${CZ0(ZE())}`}var Ll=y.templateLiteral(["E-",Mc0]);function Ac0(){return`E-${CZ0(ZE())}`}var Zp5=y.looseObject({type:y.literal("object"),properties:y.record(y.string(),y.unknown()),required:y.array(y.string()).optional(),additionalProperties:y.boolean().optional()}),Qp5=y.union([y.literal("builtin"),y.object({toolbox:G8}).strict(),y.object({mcp:G8,target:y.enum(["global","workspace","flag","default"]).optional()}).strict(),y.object({plugin:G8}).strict(),y.object({remote:G8}).strict()]),Yp5=y.object({serial:y.boolean().optional(),deferred:y.boolean().optional(),skillNames:y.array(G8).optional()}),uN4=y.looseObject({name:G8,description:y.string(),inputSchema:Zp5,source:Qp5,meta:Yp5.optional()}),ut8=y.object({id:G8,category:G8,title:G8,description:y.string().optional(),pluginName:G8}),jc0=y.strictObject({"agent.deepReasoningEffort":y.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":y.array(y.string()).optional(),"anthropic.thinking.enabled":y.boolean().optional(),"anthropic.interleavedThinking.enabled":y.boolean().optional(),"anthropic.temperature":y.number().optional(),"anthropic.effort":y.enum(["low","medium","high","max"]).optional(),"anthropic.speed":y.enum(["standard","fast"]).optional(),"anthropic.provider":y.enum(["anthropic","vertex"]).optional(),"openai.speed":y.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":y.number().min(0).max(100).optional(),"internal.model":y.union([y.string(),y.record(y.string(),y.string())]).optional(),"internal.oracleReasoningEffort":y.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":y.enum(["minimal","low","medium","high"]).optional(),"tools.disable":y.array(y.string()).optional(),"tools.enable":y.array(y.string()).optional()}),bN4=y.object({settings:jc0,workspaceId:y.string(),workingDirectory:y.string(),environment:y.object({os:y.enum(["darwin","linux","windows"]),hasDocker:y.boolean().optional(),hasBrowser:y.boolean().optional()}).strict(),tags:y.array(y.string())}).strict(),hN4=y.enum(["sandbox","local-client"]),El=y.any().and(y.object({status:y.string()})),gN4=y.discriminatedUnion("type",[y.object({type:y.literal("delta"),blocks:y.array(y.unknown()).optional(),state:y.enum(["start","generating","tool_use","complete","error"])}),y.object({type:y.literal("snapshot"),value:y.unknown()})]),nF=G8,mN4=30000,Bk=CG,Xp5=y.enum(["file","directory"]),Kp5=y.object({mtimeMs:y.number().nonnegative().optional()}),Ml=y.tuple([y.string(),Xp5,Kp5.optional()]),Vp5=y.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),sN=y.object({code:Vp5,message:y.string()}),zp5=y.object({ok:y.literal(!0),entries:y.array(Ml)}),Gp5=y.object({ok:y.literal(!1),error:sN}),bt8=y.discriminatedUnion("ok",[zp5,Gp5]),Fp5=y.object({ok:y.literal(!0),contentBase64:y.string()}),qp5=y.object({ok:y.literal(!1),error:sN}),ht8=y.discriminatedUnion("ok",[Fp5,qp5]),Wp5=G8,Rc0=y.object({key:G8,dataType:Wp5,contentBase64:y.string()}),Ic0=Rc0.extend({toolCallId:j8.optional(),updatedAt:y.string()}),Nk=y.looseObject({uri:CG,content:y.string().optional(),lineCount:y.int().optional(),hash:y.string().optional()}),pN4=y.object({name:G8,description:y.string(),baseDir:CG,frontmatter:y.object({name:G8,description:y.string()}).catchall(y.unknown()),files:y.array(y.string()).optional()}),Pc0=y.object({type:y.literal("text"),text:y.string(),hidden:y.boolean().optional()}),dN4=y.looseObject({type:y.literal("image"),source:y.discriminatedUnion("type",[y.object({type:y.literal("base64"),mediaType:y.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()}),y.object({type:y.literal("url"),url:y.string()})]),sourcePath:y.string()}),wk=y.array(y.discriminatedUnion("type",[Pc0,dN4])),Hk=y.record(y.string(),y.unknown()),cN4=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),normalizedName:y.string().optional(),metadata:y.record(y.string(),y.unknown()).optional()}),Up5=cN4.extend({complete:y.literal(!0),input:Hk,normalizedInput:Hk.optional()}),Dp5=cN4.extend({complete:y.literal(!1),input:Hk,inputIncomplete:Hk,inputPartialJSON:y.object({json:y.string()}),normalizedInput:Hk.optional()}),Hp5=y.object({accepted:y.boolean(),askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}),Bp5=y.object({type:y.literal("tool_result"),toolUseID:y.string().min(1),run:El,userInput:Hp5.optional()}),Np5=y.object({type:y.literal("thinking"),thinking:y.string(),signature:y.string()}),wp5=y.object({type:y.literal("redacted_thinking"),data:y.string()}),Op5=y.object({type:y.literal("server_tool_use"),id:y.string().min(1),name:y.string().min(1),input:Hk}),Lp5=y.object({type:y.literal("manual_bash_invocation"),args:y.object({cmd:y.string(),args:y.array(y.string()).readonly().optional(),cwd:y.string().optional()}),toolRun:El,hidden:y.boolean().optional()}),Ep5=y.object({sentAt:y.number().int().nonnegative().optional(),fromAggman:y.boolean().optional(),fromExecutorThreadID:Ol.optional()}),Mp5=y.object({uri:CG,lineCount:y.number().int().nonnegative(),content:y.string().optional()}),Ap5=y.union([Pc0,dN4,Bp5]),jp5=y.union([Pc0,Np5,wp5,Up5,Dp5,Op5]),Cc0=y.array(Ap5),Tc0=y.array(jp5),Rp5=y.array(Lp5),Ec0=y.looseObject({line:y.number().int(),column:y.number().int()}),Ip5=y.looseObject({start:Ec0,end:Ec0}),Pp5=y.looseObject({name:y.string(),repositoryURL:y.string()}),Cp5=y.looseObject({currentURL:y.string(),availableProjects:y.array(Pp5).optional()}),Tp5=y.object({treeOID:y.string(),repoRoot:y.string()}),_c0=y.looseObject({currentlyVisibleFiles:y.array(CG),runningTerminalCommands:y.array(y.string()).optional(),activeEditor:y.any().optional(),cursorLocation:Ec0.optional(),cursorLocationLine:y.string().optional(),selectionRange:Ip5.optional(),snapshotOIDs:y.array(Tp5).optional(),aggmanContext:Cp5.optional()}),_p5=y.object({threadId:Ol,role:y.literal("user"),content:Cc0,discoveredGuidanceFiles:y.array(Mp5).optional(),meta:Ep5.optional(),userState:_c0.optional(),readAt:y.string().nullable().optional(),messageId:q5,createdAt:y.string().optional()}),Sc0=y.object({model:y.string().optional(),maxInputTokens:y.number(),inputTokens:y.number(),outputTokens:y.number(),cacheCreationInputTokens:y.number().nullable(),cacheReadInputTokens:y.number().nullable(),totalInputTokens:y.number(),thinkingBudget:y.number().optional(),timestamp:y.string().optional()}),Sp5=y.union([y.object({type:y.literal("complete")}),y.object({type:y.literal("cancelled")})]),kp5=y.object({threadId:Ol,role:y.literal("assistant"),content:Tc0,state:Sp5.optional(),usage:Sc0.optional(),readAt:y.string().nullable().optional(),messageId:q5,createdAt:y.string().optional()}),yp5=y.object({threadId:Ol,role:y.literal("info"),content:Rp5,messageId:q5,createdAt:y.string().optional()}),lN4=y.discriminatedUnion("role",[_p5,kp5,yp5]),Al=y.object({workspaceRoot:CG.optional(),workingDirectory:CG.optional(),rootDirectoryListing:y.string().nullable().optional(),trees:y.array(y.any()).optional(),platform:y.any().optional(),tags:y.array(y.string()).optional(),updatedAt:y.string().optional()}),vp5=y.object({added:y.number().int().nonnegative(),deleted:y.number().int().nonnegative(),changed:y.number().int().nonnegative()}),xp5=y.object({path:y.string(),previousPath:y.string().optional(),changeType:y.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:y.boolean(),diff:y.string(),fullFileDiff:y.string().optional(),diffStat:vp5}),fp5=y.object({hash:y.string(),shortHash:y.string(),subject:y.string()}),TZ0=y.object({provider:y.literal("git"),capturedAt:y.number(),available:y.boolean(),repositoryRoot:y.string().nullable(),repositoryName:y.string().nullable(),branch:y.string().nullable(),head:y.string().nullable(),baseRef:y.string().nullable().optional(),baseRefHead:y.string().nullable().optional(),aheadCount:y.number().int().nonnegative().optional(),behindCount:y.number().int().nonnegative().optional(),aheadCommits:y.array(fp5).optional(),files:y.array(xp5),unavailableReason:y.string().optional(),unchanged:y.boolean().optional()}),_Z0=y.object({id:y.string(),toolCallId:j8,toolName:y.string(),args:y.record(y.string(),y.unknown()),reason:y.string().optional(),toAllow:y.array(y.string()).optional(),context:y.enum(["thread","subagent"]),subagentToolName:y.string().optional(),parentToolCallId:j8.optional(),timestamp:y.number(),matchedRule:y.object({tool:y.string(),action:y.string(),matches:y.record(y.string(),y.unknown()).optional()}).optional(),ruleSource:y.enum(["user","built-in"]).optional()}),up5=y.object({type:y.literal("request"),id:G8,method:G8,params:y.unknown()}),bp5=y.object({type:y.literal("response"),id:G8,result:y.unknown().optional(),error:y.string().optional()}),hp5=y.object({type:y.literal("event"),event:G8,data:y.unknown(),span:y.string().optional()}),SZ0=y.discriminatedUnion("type",[up5,bp5,hp5]);var gp5=y.object({type:y.literal("executor_connect"),clientId:G8,capabilities:bN4,executorType:hN4.optional()}),mp5=y.object({type:y.literal("executor_settings_update"),settings:jc0}),pp5=y.object({type:y.literal("executor_tools_register"),tools:y.array(uN4)}),dp5=y.object({type:y.literal("executor_tools_unregister"),toolNames:y.array(G8)}),cp5=y.object({type:y.literal("executor_tools_bootstrap_complete"),ok:y.boolean(),error:y.string().optional()}),lp5=y.object({type:y.literal("executor_tool_lease_ack"),toolCallId:j8}),kc0=y.object({type:y.literal("tool_progress"),toolCallId:j8,progress:y.union([gN4,y.unknown()]).optional(),parentToolCallId:j8.optional()}),ip5=y.object({type:y.literal("executor_tool_result"),toolCallId:j8,run:El}),np5=y.object({type:y.literal("executor_guidance_snapshot"),snapshotId:G8,files:y.array(Nk),isLast:y.boolean(),userConfigDir:y.any().optional()}),ap5=y.object({type:y.literal("executor_guidance_discovery"),toolCallId:j8,files:y.array(Nk),isLast:y.boolean()}),op5=y.object({type:y.literal("executor_skill_snapshot"),snapshotId:G8,skills:y.array(pN4),isLast:y.boolean()}),rp5=y.object({type:y.literal("executor_rollback_ack"),editId:Ll,ok:y.boolean(),error:y.string().optional()}),sp5=y.object({type:y.literal("executor_revocation_ack"),toolCallId:j8}),tp5=y.object({type:y.literal("executor_environment_snapshot"),environment:Al}),ep5=y.object({type:y.literal("executor_environment_update"),environment:Al}),$d5=y.object({type:y.literal("executor_artifact_upsert"),artifact:Rc0,toolCallId:j8.optional()}),Jd5=y.object({type:y.literal("executor_artifact_delete"),key:G8}),Zd5=y.object({type:y.literal("executor_git_status"),status:TZ0,toolCallId:j8.optional()}),Qd5=y.object({type:y.literal("executor_tool_approval_request"),approval:_Z0}),Yd5=y.object({type:y.literal("executor_plugin_message"),message:SZ0}),Xd5=y.object({type:y.literal("client_append_user_msg"),content:wk,userState:_c0.optional(),discoveredGuidanceFiles:y.array(Nk).optional(),agentMode:y.string().optional(),messageId:q5}),Kd5=y.object({type:y.literal("client_remove_queued_msg"),queuedMessageId:q5}),Vd5=y.object({type:y.literal("client_interrupt_queued_msg"),queuedMessageId:q5}),zd5=y.object({type:y.literal("client_edit_message"),messageId:q5,editId:Ll,content:wk,agentMode:y.string().optional()}),Gd5=y.object({type:y.literal("client_mark_message_read"),messageId:q5}),Fd5=y.object({type:y.literal("client_mark_message_unread"),messageId:q5}),qd5=y.object({type:y.literal("client_set_thread_title"),title:y.string().trim().min(1).max(256)}),Wd5=y.object({auth:y.string().min(1),p256dh:y.string().min(1)}),Ud5=y.object({endpoint:y.string().url(),keys:Wd5}),Dd5=y.object({type:y.literal("client_upsert_notification_subscription"),subscription:Ud5,threadURL:y.string().min(1)}),Hd5=y.object({type:y.literal("client_filesystem_read_directory"),requestId:nF,uri:Bk}),Bd5=y.object({type:y.literal("client_filesystem_read_file"),requestId:nF,uri:Bk}),Nd5=y.object({type:y.literal("executor_filesystem_read_directory_result"),requestId:nF,ok:y.boolean(),entries:y.array(Ml).optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),wd5=y.object({type:y.literal("executor_filesystem_read_file_result"),requestId:nF,ok:y.boolean(),contentBase64:y.string().optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),Od5=y.object({type:y.literal("client_resume"),version:y.number()}),Ld5=y.object({type:y.literal("client_retry")}),Ed5=y.object({type:y.literal("client_cancel")}),Md5=y.object({type:y.literal("client_append_manual_bash_invocation"),args:y.object({cmd:y.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:y.array(y.string()).optional(),cwd:y.string().optional()}),run:El,hidden:y.boolean().optional()}),Ad5=y.object({type:y.literal("client_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional()}).optional()}),jd5=y.object({type:y.literal("client_spawn_executor"),requestId:y.string().optional(),repositoryURL:y.string().optional(),projectID:y.uuid().optional(),additionalRepositories:y.array(y.object({name:y.string(),url:y.string()})).optional()}),dt8=y.enum(["agg-man"]),iN4=y.discriminatedUnion("type",[gp5,mp5,pp5,dp5,cp5,lp5,kc0,ip5,np5,ap5,op5,rp5,sp5,tp5,ep5,$d5,Jd5,Zd5,Qd5,Yd5,Xd5,Kd5,Vd5,zd5,Gd5,Fd5,qd5,Dd5,Hd5,Bd5,Nd5,wd5,Od5,Ld5,Ed5,Md5,Ad5,jd5]);t$();t$();var Rd5=y.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),Id5=y.enum(["start","generating","tool_use","complete","error"]),Pd5=y.object({message:y.string(),code:y.string().optional(),stack:y.string().optional(),retryAt:y.number().optional(),attempt:y.number().optional()}),Cd5=y.object({userId:y.string(),name:y.string(),avatarURL:y.string().optional()}),Td5=y.enum(["starting","running","failed"]),_d5=y.object({cutMessageId:q5,createdAt:y.string()}),nN4=y.object({interrupt:y.boolean(),queuedMessage:y.object({role:y.literal("user"),messageId:q5,content:wk,userState:y.any().optional(),discoveredGuidanceFiles:y.array(Nk).optional(),createdAt:y.string().optional()})}),Sd5=y.object({type:y.literal("agent_state"),state:Rd5,messageId:q5.optional()}),kd5=y.object({type:y.literal("error"),message:y.string(),code:y.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),yd5=y.object({type:y.literal("error_set"),seq:y.number(),error:Pd5}),vd5=y.object({type:y.literal("error_cleared"),seq:y.number()}),xd5=y.object({type:y.literal("cancelled"),seq:y.number(),messageId:q5.optional()}),fd5=y.object({type:y.literal("retry_scheduled"),retryAt:y.number(),attempt:y.number(),maxAttempts:y.number(),reason:y.string()}),ud5=y.object({type:y.literal("retry_started")}),bd5=y.object({type:y.literal("retry_cancelled")}),hd5=y.object({type:y.literal("executor_connected"),executorId:y.string(),registeredToolCount:y.number(),rejectedTools:y.array(y.object({name:y.string(),reason:y.string()})).optional()}),gd5=y.object({type:y.literal("tool_lease"),toolCallId:j8,toolName:y.string(),args:y.unknown(),messageId:q5,parentToolCallId:j8.optional()}),md5=y.object({type:y.literal("executor_filesystem_read_directory"),requestId:nF,uri:Bk}),pd5=y.object({type:y.literal("executor_filesystem_read_file"),requestId:nF,uri:Bk}),dd5=y.object({type:y.literal("client_filesystem_read_directory_result"),requestId:nF,ok:y.boolean(),entries:y.array(Ml).optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),cd5=y.object({type:y.literal("client_filesystem_read_file_result"),requestId:nF,ok:y.boolean(),contentBase64:y.string().optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),ld5=y.object({type:y.literal("tool_approval_queue"),approvals:y.array(_Z0)}),id5=y.object({type:y.literal("executor_rollback_request"),editId:Ll,messageId:q5,reason:y.literal("message_edit"),toolUseIdsToRevert:y.array(j8)}),nd5=y.object({type:y.literal("executor_tool_lease_revoked"),toolCallId:j8,reason:y.enum(["executor_disconnected","reassigned","user_canceled"])}),ad5=y.object({type:y.literal("plugin_message"),message:SZ0}),od5=y.object({type:y.literal("executor_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional()}).optional()}),rd5=y.object({type:y.literal("executor_error"),message:y.string(),code:y.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),sd5=y.object({type:y.literal("delta"),messageId:q5,role:y.literal("assistant"),blocks:Tc0.optional(),state:Id5,usage:Sc0.optional(),parentToolCallId:j8.optional()}),td5=y.object({type:y.literal("delta"),messageId:q5,role:y.literal("user"),blocks:Cc0.optional(),state:y.literal("complete"),parentToolCallId:j8.optional()}),ed5=y.discriminatedUnion("role",[sd5,td5]),$c5=y.object({type:y.literal("queued_messages"),messages:y.array(nN4)}),Jc5=y.object({type:y.literal("queued_message_added"),message:nN4,seq:y.number()}),Zc5=y.object({type:y.literal("queued_message_removed"),queuedMessageId:q5,seq:y.number()}),Qc5=y.object({type:y.literal("message_added"),message:lN4,seq:y.number(),parentToolUseId:G8.optional()}),Yc5=y.object({type:y.literal("edit_rejected"),editId:y.string(),message:y.string()}),Xc5=y.object({type:y.literal("message_edited"),seq:y.number(),editId:y.string(),messageId:q5,content:wk,truncateToMessageId:q5,reason:y.literal("message_edit")}),Kc5=y.looseObject({type:y.literal("cf_agent_state")}),Vc5=y.looseObject({type:y.literal("cf_agent_mcp_servers")}),zc5=y.looseObject({type:y.literal("cf_agent_identity")}),Gc5=y.object({type:y.literal("observers"),count:y.number(),observers:y.array(Cd5),hasExecutor:y.boolean().optional()}),Fc5=y.object({type:y.literal("executor_status"),spawnId:y.string(),status:Td5,message:y.string().optional(),executorId:y.string().optional()}),qc5=y.object({type:y.literal("environment_update"),environment:Al}),Wc5=y.object({type:y.literal("artifacts_snapshot"),artifacts:y.array(Ic0)}),Uc5=y.object({type:y.literal("artifact_upserted"),artifact:Ic0}),Dc5=y.object({type:y.literal("artifact_deleted"),key:G8}),Hc5=y.object({type:y.literal("git_status"),status:TZ0,toolCallId:j8.optional()}),Bc5=y.object({type:y.literal("thread_title"),title:y.string().nullable()}),Nc5=y.object({type:y.literal("thread_status"),status:y.union([y.literal("merging"),y.literal("merged"),y.null()])}),wc5=y.object({type:y.literal("thread_relationships"),seq:y.number(),relationships:y.array(xN4)}),Oc5=y.object({type:y.literal("compaction_started")}),Lc5=y.object({type:y.literal("compaction_complete"),cutMessageId:q5}),Ec5=y.object({type:y.literal("compaction_records"),records:y.array(_d5)}),kZ0=y.discriminatedUnion("type",[Sd5,kd5,yd5,vd5,xd5,fd5,ud5,bd5,hd5,gd5,md5,pd5,dd5,cd5,ld5,id5,nd5,ad5,od5,kc0,rd5,ed5,$c5,Jc5,Zc5,Qc5,Yc5,Xc5,Kc5,Vc5,zc5,Gc5,Fc5,qc5,Wc5,Uc5,Dc5,Hc5,Bc5,Nc5,wc5,Oc5,Lc5,Ec5]);var yc0=(J)=>y.codec(y.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),y.NEVER}},encode:(Z)=>JSON.stringify(Z)}),aN4=yc0(iN4),Mc5=y.union([kZ0,y.array(kZ0)]),oN4=yc0(kZ0),rN4=yc0(Mc5);U4();function sN4(J,Z={}){let Y=(Z.mode??"lenient")==="strict";if(!Array.isArray(J))return Y?null:[];let X=[];for(let K of J){if(typeof K!=="object"||K===null){if(Y)return null;continue}let V=K;if(typeof V.uri!=="string"||V.uri.length===0){if(Y)return null;continue}let z;try{z=o1(X1.parse(V.uri))}catch{if(Y)return null;continue}let G={uri:z};if(typeof V.content==="string")G.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))G.lineCount=V.lineCount;if(typeof V.hash==="string")G.hash=V.hash;X.push(G)}return X}var tN4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function vc0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function Ac5(J){return J.replace(/\s+/g," ").trim()}function jc5(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function Rc5(J){if(J===void 0)return null;if(typeof J==="string")return JSON.stringify(J);if(typeof J==="number"||typeof J==="boolean"||J===null)return JSON.stringify(J);try{return vc0(JSON.stringify(J),120)}catch{return vc0(String(J),120)}}function eN4(J){if(!Array.isArray(J)||J.length===0)return null;let Z=J.map((Q)=>typeof Q==="number"?`[${Q}]`:String(Q)).join(".").replace(/\.\[/g,"[");return Z.length>0?Z:null}function Ic5(J){if(!J||typeof J!=="object")return null;let Z=J,Q=typeof Z.message==="string"?Z.message:null,Y=typeof Z.note==="string"?Z.note:null,X=eN4(Z.path);if(X&&Q&&Q!=="Invalid input")return`${X}: ${Q}`;if(X&&Y)return`${X}: ${Y}`;if(X&&Q)return`invalid value at ${X}`;return Y??Q}function $w4(J){for(let Z of J){let Q=Ic5(Z);if(Q)return Q}return null}function Pc5(J){return J.some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;return Q.code==="invalid_union"&&(Q.note==="No matching discriminator"||Q.discriminator==="type"||eN4(Q.path)==="type")})}function Cc5(J,Z){let Q=$w4(Z);if(J&&Q)return`type ${JSON.stringify(J)} failed validation: ${Q}`;if(J)return`type ${JSON.stringify(J)} failed validation`;if(Q)return`message payload failed validation: ${Q}`;return"message payload failed validation"}function Jw4(J,Z,Q){let Y=jc5(Z),X=(()=>{let F=Ac5(J);if(F.length===0)return null;return vc0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=$w4(Y);return{failureType:"invalid_json",summary:F?`malformed JSON: ${F}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let z=V.type,G=Rc5(z);if(typeof z!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${G??"unknown value"}`,messageType:null,typePreview:G,payloadPreview:X,issues:Y};if(Pc5(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(z)} (likely protocol version mismatch)`,messageType:z,typePreview:G,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:Cc5(z,Y),messageType:z,typePreview:G,payloadPreview:X,issues:Y}}function jl(J,Z){if(J&&typeof J==="object"&&"type"in J){let Y=J;if(Y.type==="delta"||Y.type==="snapshot")return Y}if(Z==="snapshot")return{type:"snapshot",value:J};let Q=typeof J==="string"?J:J!==void 0?JSON.stringify(J):"";return{type:"delta",blocks:Q?[{type:"text",text:Q}]:void 0,state:"generating"}}function Zw4(J){let Z=Number.isFinite(J)?J:0,Q=0,Y=Z;function X(V=Z){if(Number.isFinite(V))Z=V;return Q=0,Y=Z,Z}function K(V){if(!Number.isFinite(V)||V<1)return Z;if(V<=Q)return Z;if(Q===0)Y=Z-(V-1);return Z=Math.max(Z,Y+V),Q=V,Z}return{getVersion:()=>Z,reset:X,advanceFromSeq:K}}t$();var Qw4="[dtw-parse-error]",fc0="dtw-parse-error",Tc5=y.object({kind:y.literal(fc0),failureType:y.enum(tN4).nullable().optional(),source:y.string().nullable().optional(),direction:y.string().nullable().optional(),stage:y.string().nullable().optional(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),typePreview:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough(),_c5=y.object({source:y.string(),direction:y.string(),stage:y.string(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough();function xc0(J){return{kind:fc0,failureType:J.failureType??null,source:J.source??null,direction:J.direction??null,stage:J.stage??null,summary:J.summary??null,messageType:J.messageType??null,typePreview:J.typePreview??null,payloadPreview:J.payloadPreview??null,issues:J.issues??[]}}function Yw4(J){let Z=xc0(J);return JSON.stringify(Z)}function Xw4(J,Z){let Q=Jw4(J,Z);return Yw4({failureType:Q.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:Q.summary,messageType:Q.messageType,typePreview:Q.typePreview,payloadPreview:Q.payloadPreview,issues:Q.issues})}function uc0(J){let Z=J.startsWith(Qw4)?J.slice(Qw4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=Tc5.safeParse(Q);if(Y.success)return xc0(Y.data);let X=_c5.safeParse(Q);if(X.success)return xc0(X.data);return null}N1();class bc0 extends Error{constructor(J){super(J);this.name="DTWError"}}class T9 extends bc0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}N1();var Sc5=1000,kc5=30000,yc5=5,vc5=30000,xc5=200,fc5=30000,Kw4=["online","focus","pageshow","keydown","pointerdown"],Vw4=["visibilitychange"];function gc0(){return globalThis}function Gw4(J){if(!J||typeof J!=="object")return null;let Z=J;if(typeof Z.addEventListener!=="function"||typeof Z.removeEventListener!=="function")return null;return Z}function zw4(){return Gw4(gc0().window)}function hc0(){let J=gc0().document;if(!Gw4(J))return null;return J}function uc5(){let J=gc0().navigator;if(!J||typeof J!=="object")return null;return J}function bc5(J){if(!J)return"none";let Z=[J.type];if(J.code!==void 0)Z.push(`code=${J.code}`);if(J.reason!==void 0)Z.push(`reason=${J.reason}`);if(J.error!==void 0)Z.push(`error=${J.error}`);return Z.join(" ")}function yZ0(J){return!!(J.apiKey&&J.WebSocketClass)}function mc0(J){if(yZ0(J))return"one-step";return"two-step"}class pc0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null,threadId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;disposed=!1;lastPongAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new Y4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new Y4([]);config;currentThreadID=null;currentWsToken=null;constructor(J){this.config={baseURL:J.baseURL,threadId:J.threadId,apiKey:J.apiKey,wsToken:J.wsToken,wsTokenProvider:J.wsTokenProvider,reconnectDelayMs:J.reconnectDelayMs??Sc5,maxReconnectDelayMs:J.maxReconnectDelayMs??kc5,maxReconnectAttempts:J.maxReconnectAttempts??yc5,pingIntervalMs:J.pingIntervalMs??vc5,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${mc0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=xc5,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new T9("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",J.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let Z=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),Q=this.config.WebSocketClass??WebSocket,Y=yZ0(this.config),X;if(Y){let K=this.config.apiKey;if(!K)throw new T9("1-step flow requires apiKey");let V=this.currentThreadID??this.config.threadId;if(!V)V=(await this.fetchWsToken()).threadId;let z=`${Z}/threads`;if(V)z=`${z}?threadId=${encodeURIComponent(V)}`;X=new Q(z,{headers:{Authorization:`Bearer ${K}`}})}else{let{threadId:K,wsToken:V}=await this.ensureWsToken();this.currentThreadID=K,this.currentWsToken=V;let z=`${Z}/threads`;X=new Q(z,["amp",V])}try{X.binaryType="arraybuffer"}catch{}await this.waitForOpen(X),this.ws=X,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(X),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);if(this.recordLifecycleEvent("connect_failed",`mode=${J.fromReconnect?"reconnect":"initial"} error=${Q}`),!J.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q},this.scheduleReconnect();throw Z}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let J=this.ws;if(J)this.ws=null,this.intentionallyClosedSockets.add(J),J.close(1000,"Client disconnect");this.updateConnectionState("disconnected")}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(J){if(!this.hasOpenSocket())throw new T9("WebSocket is not connected");this.ws?.send(J)}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}updateConnectionState(J){if(J==="disconnected"||J==="reconnecting"){let Z={state:J,role:null,clientId:null,threadId:null};if(this.reconnectCause)Z.reconnectCause=this.reconnectCause;this.connectionInfo=Z}else if(this.connectionInfo.state=J,J==="connected")this.connectionInfo.threadId=this.currentThreadID,this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;this.connectionSubject.next({...this.connectionInfo}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${bc5(this.reconnectCause)}`)}async handleAuthExpired(){this.recordLifecycleEvent("auth_refresh_started");try{if(this.currentWsToken=null,this.config.wsTokenProvider){let J=await this.config.wsTokenProvider({forceRefresh:!0});this.currentThreadID=J.threadId,this.currentWsToken=J.wsToken}this.recordLifecycleEvent("auth_refresh_succeeded",`threadId=${this.currentThreadID??"none"}`)}catch{this.recordLifecycleEvent("auth_refresh_failed")}}onRawMessage(J){}onMaxReconnectExceeded(J){}async ensureWsToken(){let J=this.reconnectAttempts>0;if(!J&&this.currentWsToken&&this.currentThreadID)return{threadId:this.currentThreadID,wsToken:this.currentWsToken};if(this.config.wsTokenProvider){let Z=await this.config.wsTokenProvider(J?{forceRefresh:!0}:void 0);return this.currentThreadID=Z.threadId,this.currentWsToken=Z.wsToken,Z}if(!J&&this.config.wsToken&&this.config.threadId)return{threadId:this.config.threadId,wsToken:this.config.wsToken};return this.fetchWsToken()}async fetchWsToken(){let Z=`${this.config.baseURL.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}/threads`,Q={"Content-Type":"application/json"};if(this.config.apiKey)Q.Authorization=`Bearer ${this.config.apiKey}`;let Y=this.currentThreadID??this.config.threadId,X={};if(Y)X.threadId=Y;let K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(X)});if(!K.ok){let z=await K.text().catch(()=>"");throw new T9(`Failed to get wsToken: ${K.status} ${z}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new T9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let z="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new T9(`WebSocket connection failed: ${z}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new T9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K)})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(J){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!J?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Z=J?.immediate?0:this.getReconnectDelayMs();this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=zw4(),Z=hc0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=uc5();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=hc0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=zw4(),Z=hc0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of Kw4)J?.addEventListener(Y,Q);for(let Y of Vw4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of Kw4)J?.removeEventListener(Y,Q);for(let Y of Vw4)Z?.removeEventListener(Y,Q)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},fc5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function hc5(J){let Z=atob(J),Q=new Uint8Array(Z.length);for(let Y=0;Y<Z.length;Y++)Q[Y]=Z.charCodeAt(Y);return Q}class aF extends pc0{deltaSubject=new s1;errorSubject=new s1;errorEventSubject=new s1;cancelledSubject=new s1;agentStateSubject=new s1;messageAddedSubject=new s1;editRejectedSubject=new s1;messageEditedSubject=new s1;queuedMessagesSubject=new s1;retrySubject=new s1;toolLeaseSubject=new s1;toolLeaseRevokedSubject=new s1;toolApprovalQueueSubject=new s1;executorToolApprovalResponseSubject=new s1;toolProgressSubject=new s1;executorErrorSubject=new s1;executorConnectedSubject=new s1;executorRollbackRequestSubject=new s1;observersSubject=new s1;executorStatusSubject=new s1;environmentUpdateSubject=new s1;artifactsSubject=new s1;gitStatusSubject=new s1;threadTitleSubject=new s1;threadStatusSubject=new s1;threadRelationshipsSubject=new s1;compactionSubject=new s1;compactionRecordsSubject=new s1;pluginMessageSubject=new s1;fileSystemReadDirectoryRequestSubject=new s1;fileSystemReadFileRequestSubject=new s1;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}gitStatuses(){return this.gitStatusSubject}threadTitles(){return this.threadTitleSubject}threadStatuses(){return this.threadStatusSubject}threadRelationships(){return this.threadRelationshipsSubject}compactionEvents(){return this.compactionSubject}compactionRecords(){return this.compactionRecordsSubject}pluginMessages(){return this.pluginMessageSubject}fileSystemReadDirectoryRequests(){return this.fileSystemReadDirectoryRequestSubject}fileSystemReadFileRequests(){return this.fileSystemReadFileRequestSubject}dispose(){if(this.disposed)return;super.dispose(),this.rejectPendingFileSystemRequests("Transport disposed"),this.deltaSubject.complete(),this.errorSubject.complete(),this.errorEventSubject.complete(),this.cancelledSubject.complete(),this.agentStateSubject.complete(),this.messageAddedSubject.complete(),this.editRejectedSubject.complete(),this.messageEditedSubject.complete(),this.queuedMessagesSubject.complete(),this.retrySubject.complete(),this.toolLeaseSubject.complete(),this.toolLeaseRevokedSubject.complete(),this.toolApprovalQueueSubject.complete(),this.executorToolApprovalResponseSubject.complete(),this.toolProgressSubject.complete(),this.executorErrorSubject.complete(),this.executorConnectedSubject.complete(),this.executorRollbackRequestSubject.complete(),this.observersSubject.complete(),this.executorStatusSubject.complete(),this.environmentUpdateSubject.complete(),this.artifactsSubject.complete(),this.gitStatusSubject.complete(),this.threadTitleSubject.complete(),this.threadStatusSubject.complete(),this.threadRelationshipsSubject.complete(),this.compactionSubject.complete(),this.compactionRecordsSubject.complete(),this.pluginMessageSubject.complete(),this.fileSystemReadDirectoryRequestSubject.complete(),this.fileSystemReadFileRequestSubject.complete()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??iF();return this.send({type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState,discoveredGuidanceFiles:Q?.discoveredGuidanceFiles}),Y}removeQueuedMessage(J){this.send({type:"client_remove_queued_msg",queuedMessageId:J})}interruptQueuedMessage(J){this.send({type:"client_interrupt_queued_msg",queuedMessageId:J})}editUserMessage(J,Z,Q,Y){this.send({type:"client_edit_message",messageId:J,editId:Q,content:Z,agentMode:Y})}markMessageRead(J){this.send({type:"client_mark_message_read",messageId:J})}markMessageUnread(J){this.send({type:"client_mark_message_unread",messageId:J})}setThreadTitle(J){this.send({type:"client_set_thread_title",title:J})}upsertNotificationSubscription(J,Z){this.send({type:"client_upsert_notification_subscription",subscription:J,threadURL:Z})}readDirectory(J){return this.requestReadDirectory(J)}readFile(J){return this.requestReadFile(J)}resumeFromVersion(J){this.send({type:"client_resume",version:J})}retryAgentLoop(){this.send({type:"client_retry"})}cancelAgentLoop(){if(!this.hasOpenSocket())return;this.send({type:"client_cancel"})}appendManualBashInvocation(J){this.send({type:"client_append_manual_bash_invocation",args:J.args,run:J.run,hidden:J.hidden})}resolveToolApproval(J,Z,Q){this.send({type:"client_tool_approval_response",toolCallId:J,accepted:Z,input:Q})}requestExecutorSpawn(J,Z){this.send({type:"client_spawn_executor",requestId:J,repositoryURL:Z?.repositoryURL,projectID:Z?.projectID,additionalRepositories:Z?.additionalRepositories})}executePluginCommand(J,Z,Q,Y){this.sendPluginMessage({type:"request",id:J,method:"command.execute",params:{pluginName:Z,commandId:Q,threadID:Y}})}async executorHandshake(J,Z,Q){if(this.disposed)throw new T9("Transport is disposed");if(!this.hasOpenSocket())throw new T9("WebSocket is not connected. Call connect() first.");return new Promise((Y,X)=>{let K=!1,V=null,z=(q)=>{if(K)return;if(K=!0,V)clearTimeout(V),V=null;G.unsubscribe(),F.unsubscribe(),q()},G=this.executorConnectedSubject.subscribe({next:(q)=>{this.connectionInfo.clientId=q.executorId,this.connectionInfo.role="executor",this.updateConnectionState("connected"),z(()=>Y(q))},error:(q)=>{z(()=>X(q))}}),F=this.executorErrorSubject.subscribe({next:(q)=>{z(()=>X(Error(q.message)))}});this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),V=setTimeout(()=>{z(()=>X(Error("Executor connect timeout")))},1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=jl(Z,"snapshot");this.send({type:"tool_progress",toolCallId:J,progress:Q})}sendExecutorToolResult(J,Z){this.send({type:"executor_tool_result",toolCallId:J,run:Z})}sendExecutorFileSystemReadDirectoryResult(J,Z){this.send({type:"executor_filesystem_read_directory_result",requestId:J,...Z})}sendExecutorFileSystemReadFileResult(J,Z){this.send({type:"executor_filesystem_read_file_result",requestId:J,...Z})}sendExecutorToolApprovalRequest(J){this.send({type:"executor_tool_approval_request",approval:J})}sendPluginMessage(J){this.send({type:"executor_plugin_message",message:J})}sendRevocationAck(J){this.send({type:"executor_revocation_ack",toolCallId:J})}sendExecutorGuidanceSnapshot(J){this.send({type:"executor_guidance_snapshot",...J})}sendExecutorGuidanceDiscovery(J){this.send({type:"executor_guidance_discovery",...J})}sendExecutorSkillSnapshot(J){this.send({type:"executor_skill_snapshot",...J})}sendExecutorSettingsUpdate(J){this.send({type:"executor_settings_update",settings:J})}sendExecutorRollbackAck(J,Z,Q){this.send({type:"executor_rollback_ack",editId:J,ok:Z,error:Q})}registerTools(J){this.send({type:"executor_tools_register",tools:J})}sendExecutorToolsBootstrapComplete(J,Z){this.send({type:"executor_tools_bootstrap_complete",ok:J,error:Z})}sendEnvironmentSnapshot(J){this.send({type:"executor_environment_snapshot",environment:J})}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J})}sendExecutorArtifactUpsert(J,Z){this.send({type:"executor_artifact_upsert",artifact:J,toolCallId:Z})}sendExecutorArtifactDelete(J){this.send({type:"executor_artifact_delete",key:J})}sendExecutorGitStatus(J,Z){this.send({type:"executor_git_status",status:J,toolCallId:Z})}unregisterTools(J){this.send({type:"executor_tools_unregister",toolNames:J})}updateConnectionState(J){if(super.updateConnectionState(J),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}requestReadDirectory(J){let Z=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Z,()=>{this.send({type:"client_filesystem_read_directory",requestId:Z,uri:J})})}requestReadFile(J){let Z=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Z,()=>{this.send({type:"client_filesystem_read_file",requestId:Z,uri:J})})}createPendingReadRequest(J,Z,Q){if(!this.hasOpenSocket())return Promise.reject(new T9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new T9(`Filesystem request timed out: ${Z}`))},mN4);J.set(Z,{resolve:Y,reject:X,timeoutID:K});try{Q()}catch(V){clearTimeout(K),J.delete(Z),X(V instanceof Error?V:Error(String(V)))}})}nextFileSystemRequestID(J){let Z=this.fileSystemRequestCounter++;return`${J}-${Date.now()}-${Z}`}handleReadDirectoryResult(J){let Z=this.pendingReadDirectoryRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadDirectoryRequests.delete(J.requestId),J.ok&&J.entries){Z.resolve(J.entries);return}if(J.ok){Z.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!J.error){Z.reject(Error("Invalid filesystem read_directory response: missing error"));return}Z.reject(this.createFileSystemError(J.error))}handleReadFileResult(J){let Z=this.pendingReadFileRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadFileRequests.delete(J.requestId),!J.ok&&J.error){Z.reject(this.createFileSystemError(J.error));return}if(!J.ok){Z.reject(Error("Invalid filesystem read_file response: missing error"));return}if(J.contentBase64===void 0){Z.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Z.resolve(hc5(J.contentBase64))}catch{Z.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(J){return Error(`Filesystem error (${J.code}): ${J.message}`)}rejectPendingFileSystemRequests(J){for(let[Z,Q]of this.pendingReadDirectoryRequests)clearTimeout(Q.timeoutID),Q.reject(new T9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new T9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=rN4.safeDecode(J);if(!Z.success){let Y=oN4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:Xw4(J,X),code:"PARSE_ERROR"});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}handleServerMessage(J){switch(J.type){case"agent_state":this.agentStateSubject.next(J);break;case"error":this.errorSubject.next(J);break;case"error_set":case"error_cleared":this.errorEventSubject.next(J);break;case"cancelled":this.cancelledSubject.next(J);break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.retrySubject.next(J);break;case"delta":this.deltaSubject.next(J);break;case"message_added":this.messageAddedSubject.next(J);break;case"edit_rejected":this.editRejectedSubject.next(J);break;case"message_edited":this.messageEditedSubject.next(J);break;case"queued_messages":case"queued_message_added":case"queued_message_removed":this.queuedMessagesSubject.next(J);break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.executorConnectedSubject.next(J);break;case"tool_lease":this.toolLeaseSubject.next(J);break;case"executor_filesystem_read_directory":this.fileSystemReadDirectoryRequestSubject.next(J);break;case"executor_filesystem_read_file":this.fileSystemReadFileRequestSubject.next(J);break;case"executor_rollback_request":this.executorRollbackRequestSubject.next(J);break;case"executor_tool_lease_revoked":this.toolLeaseRevokedSubject.next(J);break;case"tool_approval_queue":this.toolApprovalQueueSubject.next(J);break;case"plugin_message":this.pluginMessageSubject.next(J);break;case"executor_tool_approval_response":this.executorToolApprovalResponseSubject.next(J);break;case"tool_progress":this.toolProgressSubject.next(J);break;case"executor_error":this.executorErrorSubject.next(J);break;case"cf_agent_state":case"cf_agent_mcp_servers":case"cf_agent_identity":break;case"observers":this.observersSubject.next(J);break;case"executor_status":this.executorStatusSubject.next(J);break;case"environment_update":this.environmentUpdateSubject.next(J);break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.artifactsSubject.next(J);break;case"git_status":this.gitStatusSubject.next(J);break;case"thread_title":this.threadTitleSubject.next(J);break;case"thread_status":this.threadStatusSubject.next(J);break;case"thread_relationships":this.threadRelationshipsSubject.next(J);break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(J);break;case"client_filesystem_read_file_result":this.handleReadFileResult(J);break;case"compaction_started":case"compaction_complete":this.compactionSubject.next(J);break;case"compaction_records":this.compactionRecordsSubject.next(J);break}}onMaxReconnectExceeded(J){this.errorSubject.next({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})}send(J){try{this.sendRaw(aN4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new T9(`Failed to encode DTW client message "${J.type}": ${Q}`)}}}function gc5(J){if(!J||typeof J!=="object")return!1;let Z=J.queuedMessage;if(!Z||typeof Z!=="object")return!1;return typeof Z.messageId==="string"}function mc5(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function pc5(J){if(gc5(J))return J.queuedMessage.messageId;if(mc5(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function dc0(J,Z,Q={}){let Y=Q.getQueuedMessageId??pc5;if(Z.type==="queued_messages")return[...Z.messages];if(Z.type==="queued_message_added"){if(Q.dedupeAdded&&J.some((X)=>Y(X)===Y(Z.message)))return[...J];return[...J,Z.message]}if(!J.some((X)=>Y(X)===Z.queuedMessageId))return[...J];return J.filter((X)=>Y(X)!==Z.queuedMessageId)}var dc5=15000;function cc5(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let G of K)G.unsubscribe()};return{promise:new Promise((G,F)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),G(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),F(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),F(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function cc0(J){let Z=J.workerUrl??h7(J.ampURL),Q=new aF({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??dc5;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=cc5(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as lc5}from"node:fs";import{mkdir as ic5,readdir as nc5,readFile as ac5}from"node:fs/promises";import{createServer as oc5}from"node:http";import lc0 from"node:path";function Fw4(J){return J instanceof Error?J.message:String(J)}function aA(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function rc5(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function qw4(J,Z){let Q=lc0.basename(Z),Y=Q.endsWith(".json")?lc0.join(J,Q):lc0.join(J,`${Q}.json`),X=await ac5(Y,"utf-8");return JSON.parse(X)}async function sc5(J){let Z=await nc5(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await qw4(J,Y.name);Q.push({sessionID:X.sessionID,createdAt:X.createdAt,runtimeMode:X.runtimeMode,traceName:X.traceName,threadId:X.threadId,protocolEvents:X.protocolEvents.length,providerStates:X.providerStateEvents.length,adapterStates:X.adapterStateEvents.length,commands:X.commandEvents.length})}catch{}}return Q.sort((Y,X)=>X.createdAt-Y.createdAt)}function tc5(){return`<!doctype html>
4633
+ `].join("");return Error(Y)}function rm5(J,Z){return Z.includes(J)}function sm5(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function kN4(J,Z,Q){if(J===void 0||J===null)return;let Y=am5(Z);if(typeof J!=="string")return _N4(Q,Y);if(J==="group"&&!Y.includes("group"))return om5(Z);if(rm5(J,Y))return J;return _N4(Q,Y)}async function tm5(J,Z,Q){let Y=await SN4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return kN4(K,Q,Y)}async function PZ0(J,Z,Q,Y){if(Y)return Y;if(!sm5(Q))return TN4(Q);let X=await tm5(J,Z,Q);if(X instanceof Error)return X;return X??TN4(Q)}function yN4(J,Z){return kN4(J,Z)}async function vN4(J,Z,Q){let Y=await SN4(Z);if(!Y)return Error("No git origin remote found for this repository.");let K={...await J.get("defaultVisibility","global")??{},[Y]:Q};return await J.set("defaultVisibility",K,"global"),{repoKey:Y}}t$();function CZ0(J){let Z=J.replace(/-/g,"");if(Z.length!==32)throw Error(`Invalid UUID hex length: ${Z.length}`);let Q=BigInt("0x"+Z),Y="";while(Q>0n)Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(Q%62n)]+Y,Q=Q/62n;return Y.padStart(22,"0")}U4();uj0();t$();var G8=y.string().min(1),Mc0=y.string().regex(/^[0-9A-Za-z]{22}$/),em5=y.templateLiteral([y.string().regex(/^[0-9a-f]{8}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{12}$/)]),Ol=y.templateLiteral(["T-",em5]),$p5=y.enum(["fork","handoff","mention"]),Jp5=y.enum(["parent","child"]),xN4=y.object({threadID:Ol,type:$p5,role:Jp5,messageIndex:y.number().int().nonnegative().optional(),blockIndex:y.number().int().nonnegative().optional(),createdAt:y.number().int().nonnegative(),comment:y.string().optional()}),q5=y.templateLiteral(["M-",Mc0]);function iF(){return`M-${CZ0(ZE())}`}var j8=y.templateLiteral(["TU-",Mc0]);function fN4(){return`TU-${CZ0(ZE())}`}var Ll=y.templateLiteral(["E-",Mc0]);function Ac0(){return`E-${CZ0(ZE())}`}var Zp5=y.looseObject({type:y.literal("object"),properties:y.record(y.string(),y.unknown()),required:y.array(y.string()).optional(),additionalProperties:y.boolean().optional()}),Qp5=y.union([y.literal("builtin"),y.object({toolbox:G8}).strict(),y.object({mcp:G8,target:y.enum(["global","workspace","flag","default"]).optional()}).strict(),y.object({plugin:G8}).strict(),y.object({remote:G8}).strict()]),Yp5=y.object({serial:y.boolean().optional(),deferred:y.boolean().optional(),skillNames:y.array(G8).optional()}),uN4=y.looseObject({name:G8,description:y.string(),inputSchema:Zp5,source:Qp5,meta:Yp5.optional()}),ut8=y.object({id:G8,category:G8,title:G8,description:y.string().optional(),pluginName:G8}),jc0=y.strictObject({"agent.deepReasoningEffort":y.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":y.array(y.string()).optional(),"anthropic.thinking.enabled":y.boolean().optional(),"anthropic.interleavedThinking.enabled":y.boolean().optional(),"anthropic.temperature":y.number().optional(),"anthropic.effort":y.enum(["low","medium","high","max"]).optional(),"anthropic.speed":y.enum(["standard","fast"]).optional(),"anthropic.provider":y.enum(["anthropic","vertex"]).optional(),"openai.speed":y.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":y.number().min(0).max(100).optional(),"internal.model":y.union([y.string(),y.record(y.string(),y.string())]).optional(),"internal.openai.websocket.enabled":y.boolean().optional(),"internal.oracleReasoningEffort":y.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":y.enum(["minimal","low","medium","high"]).optional(),"tools.disable":y.array(y.string()).optional(),"tools.enable":y.array(y.string()).optional()}),bN4=y.object({settings:jc0,workspaceId:y.string(),workingDirectory:y.string(),environment:y.object({os:y.enum(["darwin","linux","windows"]),hasDocker:y.boolean().optional(),hasBrowser:y.boolean().optional()}).strict(),tags:y.array(y.string())}).strict(),hN4=y.enum(["sandbox","local-client"]),El=y.any().and(y.object({status:y.string()})),gN4=y.discriminatedUnion("type",[y.object({type:y.literal("delta"),blocks:y.array(y.unknown()).optional(),state:y.enum(["start","generating","tool_use","complete","error"])}),y.object({type:y.literal("snapshot"),value:y.unknown()})]),nF=G8,mN4=30000,Bk=CG,Xp5=y.enum(["file","directory"]),Kp5=y.object({mtimeMs:y.number().nonnegative().optional()}),Ml=y.tuple([y.string(),Xp5,Kp5.optional()]),Vp5=y.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),sN=y.object({code:Vp5,message:y.string()}),zp5=y.object({ok:y.literal(!0),entries:y.array(Ml)}),Gp5=y.object({ok:y.literal(!1),error:sN}),bt8=y.discriminatedUnion("ok",[zp5,Gp5]),Fp5=y.object({ok:y.literal(!0),contentBase64:y.string()}),qp5=y.object({ok:y.literal(!1),error:sN}),ht8=y.discriminatedUnion("ok",[Fp5,qp5]),Wp5=G8,Rc0=y.object({key:G8,dataType:Wp5,contentBase64:y.string()}),Ic0=Rc0.extend({toolCallId:j8.optional(),updatedAt:y.string()}),Nk=y.looseObject({uri:CG,content:y.string().optional(),lineCount:y.int().optional(),hash:y.string().optional()}),pN4=y.object({name:G8,description:y.string(),baseDir:CG,frontmatter:y.object({name:G8,description:y.string()}).catchall(y.unknown()),files:y.array(y.string()).optional()}),Pc0=y.object({type:y.literal("text"),text:y.string(),hidden:y.boolean().optional()}),dN4=y.looseObject({type:y.literal("image"),source:y.discriminatedUnion("type",[y.object({type:y.literal("base64"),mediaType:y.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()}),y.object({type:y.literal("url"),url:y.string()})]),sourcePath:y.string()}),wk=y.array(y.discriminatedUnion("type",[Pc0,dN4])),Hk=y.record(y.string(),y.unknown()),cN4=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),normalizedName:y.string().optional(),metadata:y.record(y.string(),y.unknown()).optional()}),Up5=cN4.extend({complete:y.literal(!0),input:Hk,normalizedInput:Hk.optional()}),Dp5=cN4.extend({complete:y.literal(!1),input:Hk,inputIncomplete:Hk,inputPartialJSON:y.object({json:y.string()}),normalizedInput:Hk.optional()}),Hp5=y.object({accepted:y.boolean(),askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}),Bp5=y.object({type:y.literal("tool_result"),toolUseID:y.string().min(1),run:El,userInput:Hp5.optional()}),Np5=y.object({type:y.literal("thinking"),thinking:y.string(),signature:y.string()}),wp5=y.object({type:y.literal("redacted_thinking"),data:y.string()}),Op5=y.object({type:y.literal("server_tool_use"),id:y.string().min(1),name:y.string().min(1),input:Hk}),Lp5=y.object({type:y.literal("manual_bash_invocation"),args:y.object({cmd:y.string(),args:y.array(y.string()).readonly().optional(),cwd:y.string().optional()}),toolRun:El,hidden:y.boolean().optional()}),Ep5=y.object({sentAt:y.number().int().nonnegative().optional(),fromAggman:y.boolean().optional(),fromExecutorThreadID:Ol.optional()}),Mp5=y.object({uri:CG,lineCount:y.number().int().nonnegative(),content:y.string().optional()}),Ap5=y.union([Pc0,dN4,Bp5]),jp5=y.union([Pc0,Np5,wp5,Up5,Dp5,Op5]),Cc0=y.array(Ap5),Tc0=y.array(jp5),Rp5=y.array(Lp5),Ec0=y.looseObject({line:y.number().int(),column:y.number().int()}),Ip5=y.looseObject({start:Ec0,end:Ec0}),Pp5=y.looseObject({name:y.string(),repositoryURL:y.string()}),Cp5=y.looseObject({currentURL:y.string(),availableProjects:y.array(Pp5).optional()}),Tp5=y.object({treeOID:y.string(),repoRoot:y.string()}),_c0=y.looseObject({currentlyVisibleFiles:y.array(CG),runningTerminalCommands:y.array(y.string()).optional(),activeEditor:y.any().optional(),cursorLocation:Ec0.optional(),cursorLocationLine:y.string().optional(),selectionRange:Ip5.optional(),snapshotOIDs:y.array(Tp5).optional(),aggmanContext:Cp5.optional()}),_p5=y.object({threadId:Ol,role:y.literal("user"),content:Cc0,discoveredGuidanceFiles:y.array(Mp5).optional(),meta:Ep5.optional(),userState:_c0.optional(),readAt:y.string().nullable().optional(),messageId:q5,createdAt:y.string().optional()}),Sc0=y.object({model:y.string().optional(),maxInputTokens:y.number(),inputTokens:y.number(),outputTokens:y.number(),cacheCreationInputTokens:y.number().nullable(),cacheReadInputTokens:y.number().nullable(),totalInputTokens:y.number(),thinkingBudget:y.number().optional(),timestamp:y.string().optional()}),Sp5=y.union([y.object({type:y.literal("complete")}),y.object({type:y.literal("cancelled")})]),kp5=y.object({threadId:Ol,role:y.literal("assistant"),content:Tc0,state:Sp5.optional(),usage:Sc0.optional(),readAt:y.string().nullable().optional(),messageId:q5,createdAt:y.string().optional()}),yp5=y.object({threadId:Ol,role:y.literal("info"),content:Rp5,messageId:q5,createdAt:y.string().optional()}),lN4=y.discriminatedUnion("role",[_p5,kp5,yp5]),Al=y.object({workspaceRoot:CG.optional(),workingDirectory:CG.optional(),rootDirectoryListing:y.string().nullable().optional(),trees:y.array(y.any()).optional(),platform:y.any().optional(),tags:y.array(y.string()).optional(),updatedAt:y.string().optional()}),vp5=y.object({added:y.number().int().nonnegative(),deleted:y.number().int().nonnegative(),changed:y.number().int().nonnegative()}),xp5=y.object({path:y.string(),previousPath:y.string().optional(),changeType:y.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:y.boolean(),diff:y.string(),fullFileDiff:y.string().optional(),diffStat:vp5}),fp5=y.object({hash:y.string(),shortHash:y.string(),subject:y.string()}),TZ0=y.object({provider:y.literal("git"),capturedAt:y.number(),available:y.boolean(),repositoryRoot:y.string().nullable(),repositoryName:y.string().nullable(),branch:y.string().nullable(),head:y.string().nullable(),baseRef:y.string().nullable().optional(),baseRefHead:y.string().nullable().optional(),aheadCount:y.number().int().nonnegative().optional(),behindCount:y.number().int().nonnegative().optional(),aheadCommits:y.array(fp5).optional(),files:y.array(xp5),unavailableReason:y.string().optional(),unchanged:y.boolean().optional()}),_Z0=y.object({id:y.string(),toolCallId:j8,toolName:y.string(),args:y.record(y.string(),y.unknown()),reason:y.string().optional(),toAllow:y.array(y.string()).optional(),context:y.enum(["thread","subagent"]),subagentToolName:y.string().optional(),parentToolCallId:j8.optional(),timestamp:y.number(),matchedRule:y.object({tool:y.string(),action:y.string(),matches:y.record(y.string(),y.unknown()).optional()}).optional(),ruleSource:y.enum(["user","built-in"]).optional()}),up5=y.object({type:y.literal("request"),id:G8,method:G8,params:y.unknown()}),bp5=y.object({type:y.literal("response"),id:G8,result:y.unknown().optional(),error:y.string().optional()}),hp5=y.object({type:y.literal("event"),event:G8,data:y.unknown(),span:y.string().optional()}),SZ0=y.discriminatedUnion("type",[up5,bp5,hp5]);var gp5=y.object({type:y.literal("executor_connect"),clientId:G8,capabilities:bN4,executorType:hN4.optional()}),mp5=y.object({type:y.literal("executor_settings_update"),settings:jc0}),pp5=y.object({type:y.literal("executor_tools_register"),tools:y.array(uN4)}),dp5=y.object({type:y.literal("executor_tools_unregister"),toolNames:y.array(G8)}),cp5=y.object({type:y.literal("executor_tools_bootstrap_complete"),ok:y.boolean(),error:y.string().optional()}),lp5=y.object({type:y.literal("executor_tool_lease_ack"),toolCallId:j8}),kc0=y.object({type:y.literal("tool_progress"),toolCallId:j8,progress:y.union([gN4,y.unknown()]).optional(),parentToolCallId:j8.optional()}),ip5=y.object({type:y.literal("executor_tool_result"),toolCallId:j8,run:El}),np5=y.object({type:y.literal("executor_guidance_snapshot"),snapshotId:G8,files:y.array(Nk),isLast:y.boolean(),userConfigDir:y.any().optional()}),ap5=y.object({type:y.literal("executor_guidance_discovery"),toolCallId:j8,files:y.array(Nk),isLast:y.boolean()}),op5=y.object({type:y.literal("executor_skill_snapshot"),snapshotId:G8,skills:y.array(pN4),isLast:y.boolean()}),rp5=y.object({type:y.literal("executor_rollback_ack"),editId:Ll,ok:y.boolean(),error:y.string().optional()}),sp5=y.object({type:y.literal("executor_revocation_ack"),toolCallId:j8}),tp5=y.object({type:y.literal("executor_environment_snapshot"),environment:Al}),ep5=y.object({type:y.literal("executor_environment_update"),environment:Al}),$d5=y.object({type:y.literal("executor_artifact_upsert"),artifact:Rc0,toolCallId:j8.optional()}),Jd5=y.object({type:y.literal("executor_artifact_delete"),key:G8}),Zd5=y.object({type:y.literal("executor_git_status"),status:TZ0,toolCallId:j8.optional()}),Qd5=y.object({type:y.literal("executor_tool_approval_request"),approval:_Z0}),Yd5=y.object({type:y.literal("executor_plugin_message"),message:SZ0}),Xd5=y.object({type:y.literal("client_append_user_msg"),content:wk,userState:_c0.optional(),discoveredGuidanceFiles:y.array(Nk).optional(),agentMode:y.string().optional(),messageId:q5}),Kd5=y.object({type:y.literal("client_remove_queued_msg"),queuedMessageId:q5}),Vd5=y.object({type:y.literal("client_interrupt_queued_msg"),queuedMessageId:q5}),zd5=y.object({type:y.literal("client_edit_message"),messageId:q5,editId:Ll,content:wk,agentMode:y.string().optional()}),Gd5=y.object({type:y.literal("client_mark_message_read"),messageId:q5}),Fd5=y.object({type:y.literal("client_mark_message_unread"),messageId:q5}),qd5=y.object({type:y.literal("client_set_thread_title"),title:y.string().trim().min(1).max(256)}),Wd5=y.object({auth:y.string().min(1),p256dh:y.string().min(1)}),Ud5=y.object({endpoint:y.string().url(),keys:Wd5}),Dd5=y.object({type:y.literal("client_upsert_notification_subscription"),subscription:Ud5,threadURL:y.string().min(1)}),Hd5=y.object({type:y.literal("client_filesystem_read_directory"),requestId:nF,uri:Bk}),Bd5=y.object({type:y.literal("client_filesystem_read_file"),requestId:nF,uri:Bk}),Nd5=y.object({type:y.literal("executor_filesystem_read_directory_result"),requestId:nF,ok:y.boolean(),entries:y.array(Ml).optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),wd5=y.object({type:y.literal("executor_filesystem_read_file_result"),requestId:nF,ok:y.boolean(),contentBase64:y.string().optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),Od5=y.object({type:y.literal("client_resume"),version:y.number()}),Ld5=y.object({type:y.literal("client_retry")}),Ed5=y.object({type:y.literal("client_cancel")}),Md5=y.object({type:y.literal("client_append_manual_bash_invocation"),args:y.object({cmd:y.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:y.array(y.string()).optional(),cwd:y.string().optional()}),run:El,hidden:y.boolean().optional()}),Ad5=y.object({type:y.literal("client_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional()}).optional()}),jd5=y.object({type:y.literal("client_spawn_executor"),requestId:y.string().optional(),repositoryURL:y.string().optional(),projectID:y.uuid().optional(),additionalRepositories:y.array(y.object({name:y.string(),url:y.string()})).optional()}),dt8=y.enum(["agg-man"]),iN4=y.discriminatedUnion("type",[gp5,mp5,pp5,dp5,cp5,lp5,kc0,ip5,np5,ap5,op5,rp5,sp5,tp5,ep5,$d5,Jd5,Zd5,Qd5,Yd5,Xd5,Kd5,Vd5,zd5,Gd5,Fd5,qd5,Dd5,Hd5,Bd5,Nd5,wd5,Od5,Ld5,Ed5,Md5,Ad5,jd5]);t$();t$();var Rd5=y.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),Id5=y.enum(["start","generating","tool_use","complete","error"]),Pd5=y.object({message:y.string(),code:y.string().optional(),stack:y.string().optional(),retryAt:y.number().optional(),attempt:y.number().optional()}),Cd5=y.object({userId:y.string(),name:y.string(),avatarURL:y.string().optional()}),Td5=y.enum(["starting","running","failed"]),_d5=y.object({cutMessageId:q5,createdAt:y.string()}),nN4=y.object({interrupt:y.boolean(),queuedMessage:y.object({role:y.literal("user"),messageId:q5,content:wk,userState:y.any().optional(),discoveredGuidanceFiles:y.array(Nk).optional(),createdAt:y.string().optional()})}),Sd5=y.object({type:y.literal("agent_state"),state:Rd5,messageId:q5.optional()}),kd5=y.object({type:y.literal("error"),message:y.string(),code:y.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),yd5=y.object({type:y.literal("error_set"),seq:y.number(),error:Pd5}),vd5=y.object({type:y.literal("error_cleared"),seq:y.number()}),xd5=y.object({type:y.literal("cancelled"),seq:y.number(),messageId:q5.optional()}),fd5=y.object({type:y.literal("retry_scheduled"),retryAt:y.number(),attempt:y.number(),maxAttempts:y.number(),reason:y.string()}),ud5=y.object({type:y.literal("retry_started")}),bd5=y.object({type:y.literal("retry_cancelled")}),hd5=y.object({type:y.literal("executor_connected"),executorId:y.string(),registeredToolCount:y.number(),rejectedTools:y.array(y.object({name:y.string(),reason:y.string()})).optional()}),gd5=y.object({type:y.literal("tool_lease"),toolCallId:j8,toolName:y.string(),args:y.unknown(),messageId:q5,parentToolCallId:j8.optional()}),md5=y.object({type:y.literal("executor_filesystem_read_directory"),requestId:nF,uri:Bk}),pd5=y.object({type:y.literal("executor_filesystem_read_file"),requestId:nF,uri:Bk}),dd5=y.object({type:y.literal("client_filesystem_read_directory_result"),requestId:nF,ok:y.boolean(),entries:y.array(Ml).optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),cd5=y.object({type:y.literal("client_filesystem_read_file_result"),requestId:nF,ok:y.boolean(),contentBase64:y.string().optional(),error:sN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),ld5=y.object({type:y.literal("tool_approval_queue"),approvals:y.array(_Z0)}),id5=y.object({type:y.literal("executor_rollback_request"),editId:Ll,messageId:q5,reason:y.literal("message_edit"),toolUseIdsToRevert:y.array(j8)}),nd5=y.object({type:y.literal("executor_tool_lease_revoked"),toolCallId:j8,reason:y.enum(["executor_disconnected","reassigned","user_canceled"])}),ad5=y.object({type:y.literal("plugin_message"),message:SZ0}),od5=y.object({type:y.literal("executor_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional()}).optional()}),rd5=y.object({type:y.literal("executor_error"),message:y.string(),code:y.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),sd5=y.object({type:y.literal("delta"),messageId:q5,role:y.literal("assistant"),blocks:Tc0.optional(),state:Id5,usage:Sc0.optional(),parentToolCallId:j8.optional()}),td5=y.object({type:y.literal("delta"),messageId:q5,role:y.literal("user"),blocks:Cc0.optional(),state:y.literal("complete"),parentToolCallId:j8.optional()}),ed5=y.discriminatedUnion("role",[sd5,td5]),$c5=y.object({type:y.literal("queued_messages"),messages:y.array(nN4)}),Jc5=y.object({type:y.literal("queued_message_added"),message:nN4,seq:y.number()}),Zc5=y.object({type:y.literal("queued_message_removed"),queuedMessageId:q5,seq:y.number()}),Qc5=y.object({type:y.literal("message_added"),message:lN4,seq:y.number(),parentToolUseId:G8.optional()}),Yc5=y.object({type:y.literal("edit_rejected"),editId:y.string(),message:y.string()}),Xc5=y.object({type:y.literal("message_edited"),seq:y.number(),editId:y.string(),messageId:q5,content:wk,truncateToMessageId:q5,reason:y.literal("message_edit")}),Kc5=y.looseObject({type:y.literal("cf_agent_state")}),Vc5=y.looseObject({type:y.literal("cf_agent_mcp_servers")}),zc5=y.looseObject({type:y.literal("cf_agent_identity")}),Gc5=y.object({type:y.literal("observers"),count:y.number(),observers:y.array(Cd5),hasExecutor:y.boolean().optional()}),Fc5=y.object({type:y.literal("executor_status"),spawnId:y.string(),status:Td5,message:y.string().optional(),executorId:y.string().optional()}),qc5=y.object({type:y.literal("environment_update"),environment:Al}),Wc5=y.object({type:y.literal("artifacts_snapshot"),artifacts:y.array(Ic0)}),Uc5=y.object({type:y.literal("artifact_upserted"),artifact:Ic0}),Dc5=y.object({type:y.literal("artifact_deleted"),key:G8}),Hc5=y.object({type:y.literal("git_status"),status:TZ0,toolCallId:j8.optional()}),Bc5=y.object({type:y.literal("thread_title"),title:y.string().nullable()}),Nc5=y.object({type:y.literal("thread_status"),status:y.union([y.literal("merging"),y.literal("merged"),y.null()])}),wc5=y.object({type:y.literal("thread_relationships"),seq:y.number(),relationships:y.array(xN4)}),Oc5=y.object({type:y.literal("compaction_started")}),Lc5=y.object({type:y.literal("compaction_complete"),cutMessageId:q5}),Ec5=y.object({type:y.literal("compaction_records"),records:y.array(_d5)}),kZ0=y.discriminatedUnion("type",[Sd5,kd5,yd5,vd5,xd5,fd5,ud5,bd5,hd5,gd5,md5,pd5,dd5,cd5,ld5,id5,nd5,ad5,od5,kc0,rd5,ed5,$c5,Jc5,Zc5,Qc5,Yc5,Xc5,Kc5,Vc5,zc5,Gc5,Fc5,qc5,Wc5,Uc5,Dc5,Hc5,Bc5,Nc5,wc5,Oc5,Lc5,Ec5]);var yc0=(J)=>y.codec(y.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),y.NEVER}},encode:(Z)=>JSON.stringify(Z)}),aN4=yc0(iN4),Mc5=y.union([kZ0,y.array(kZ0)]),oN4=yc0(kZ0),rN4=yc0(Mc5);U4();function sN4(J,Z={}){let Y=(Z.mode??"lenient")==="strict";if(!Array.isArray(J))return Y?null:[];let X=[];for(let K of J){if(typeof K!=="object"||K===null){if(Y)return null;continue}let V=K;if(typeof V.uri!=="string"||V.uri.length===0){if(Y)return null;continue}let z;try{z=o1(X1.parse(V.uri))}catch{if(Y)return null;continue}let G={uri:z};if(typeof V.content==="string")G.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))G.lineCount=V.lineCount;if(typeof V.hash==="string")G.hash=V.hash;X.push(G)}return X}var tN4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function vc0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function Ac5(J){return J.replace(/\s+/g," ").trim()}function jc5(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function Rc5(J){if(J===void 0)return null;if(typeof J==="string")return JSON.stringify(J);if(typeof J==="number"||typeof J==="boolean"||J===null)return JSON.stringify(J);try{return vc0(JSON.stringify(J),120)}catch{return vc0(String(J),120)}}function eN4(J){if(!Array.isArray(J)||J.length===0)return null;let Z=J.map((Q)=>typeof Q==="number"?`[${Q}]`:String(Q)).join(".").replace(/\.\[/g,"[");return Z.length>0?Z:null}function Ic5(J){if(!J||typeof J!=="object")return null;let Z=J,Q=typeof Z.message==="string"?Z.message:null,Y=typeof Z.note==="string"?Z.note:null,X=eN4(Z.path);if(X&&Q&&Q!=="Invalid input")return`${X}: ${Q}`;if(X&&Y)return`${X}: ${Y}`;if(X&&Q)return`invalid value at ${X}`;return Y??Q}function $w4(J){for(let Z of J){let Q=Ic5(Z);if(Q)return Q}return null}function Pc5(J){return J.some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;return Q.code==="invalid_union"&&(Q.note==="No matching discriminator"||Q.discriminator==="type"||eN4(Q.path)==="type")})}function Cc5(J,Z){let Q=$w4(Z);if(J&&Q)return`type ${JSON.stringify(J)} failed validation: ${Q}`;if(J)return`type ${JSON.stringify(J)} failed validation`;if(Q)return`message payload failed validation: ${Q}`;return"message payload failed validation"}function Jw4(J,Z,Q){let Y=jc5(Z),X=(()=>{let F=Ac5(J);if(F.length===0)return null;return vc0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=$w4(Y);return{failureType:"invalid_json",summary:F?`malformed JSON: ${F}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let z=V.type,G=Rc5(z);if(typeof z!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${G??"unknown value"}`,messageType:null,typePreview:G,payloadPreview:X,issues:Y};if(Pc5(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(z)} (likely protocol version mismatch)`,messageType:z,typePreview:G,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:Cc5(z,Y),messageType:z,typePreview:G,payloadPreview:X,issues:Y}}function jl(J,Z){if(J&&typeof J==="object"&&"type"in J){let Y=J;if(Y.type==="delta"||Y.type==="snapshot")return Y}if(Z==="snapshot")return{type:"snapshot",value:J};let Q=typeof J==="string"?J:J!==void 0?JSON.stringify(J):"";return{type:"delta",blocks:Q?[{type:"text",text:Q}]:void 0,state:"generating"}}function Zw4(J){let Z=Number.isFinite(J)?J:0,Q=0,Y=Z;function X(V=Z){if(Number.isFinite(V))Z=V;return Q=0,Y=Z,Z}function K(V){if(!Number.isFinite(V)||V<1)return Z;if(V<=Q)return Z;if(Q===0)Y=Z-(V-1);return Z=Math.max(Z,Y+V),Q=V,Z}return{getVersion:()=>Z,reset:X,advanceFromSeq:K}}t$();var Qw4="[dtw-parse-error]",fc0="dtw-parse-error",Tc5=y.object({kind:y.literal(fc0),failureType:y.enum(tN4).nullable().optional(),source:y.string().nullable().optional(),direction:y.string().nullable().optional(),stage:y.string().nullable().optional(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),typePreview:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough(),_c5=y.object({source:y.string(),direction:y.string(),stage:y.string(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough();function xc0(J){return{kind:fc0,failureType:J.failureType??null,source:J.source??null,direction:J.direction??null,stage:J.stage??null,summary:J.summary??null,messageType:J.messageType??null,typePreview:J.typePreview??null,payloadPreview:J.payloadPreview??null,issues:J.issues??[]}}function Yw4(J){let Z=xc0(J);return JSON.stringify(Z)}function Xw4(J,Z){let Q=Jw4(J,Z);return Yw4({failureType:Q.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:Q.summary,messageType:Q.messageType,typePreview:Q.typePreview,payloadPreview:Q.payloadPreview,issues:Q.issues})}function uc0(J){let Z=J.startsWith(Qw4)?J.slice(Qw4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=Tc5.safeParse(Q);if(Y.success)return xc0(Y.data);let X=_c5.safeParse(Q);if(X.success)return xc0(X.data);return null}N1();class bc0 extends Error{constructor(J){super(J);this.name="DTWError"}}class T9 extends bc0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}N1();var Sc5=1000,kc5=30000,yc5=5,vc5=30000,xc5=200,fc5=30000,Kw4=["online","focus","pageshow","keydown","pointerdown"],Vw4=["visibilitychange"];function gc0(){return globalThis}function Gw4(J){if(!J||typeof J!=="object")return null;let Z=J;if(typeof Z.addEventListener!=="function"||typeof Z.removeEventListener!=="function")return null;return Z}function zw4(){return Gw4(gc0().window)}function hc0(){let J=gc0().document;if(!Gw4(J))return null;return J}function uc5(){let J=gc0().navigator;if(!J||typeof J!=="object")return null;return J}function bc5(J){if(!J)return"none";let Z=[J.type];if(J.code!==void 0)Z.push(`code=${J.code}`);if(J.reason!==void 0)Z.push(`reason=${J.reason}`);if(J.error!==void 0)Z.push(`error=${J.error}`);return Z.join(" ")}function yZ0(J){return!!(J.apiKey&&J.WebSocketClass)}function mc0(J){if(yZ0(J))return"one-step";return"two-step"}class pc0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null,threadId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;disposed=!1;lastPongAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new Y4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new Y4([]);config;currentThreadID=null;currentWsToken=null;constructor(J){this.config={baseURL:J.baseURL,threadId:J.threadId,apiKey:J.apiKey,wsToken:J.wsToken,wsTokenProvider:J.wsTokenProvider,reconnectDelayMs:J.reconnectDelayMs??Sc5,maxReconnectDelayMs:J.maxReconnectDelayMs??kc5,maxReconnectAttempts:J.maxReconnectAttempts??yc5,pingIntervalMs:J.pingIntervalMs??vc5,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${mc0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=xc5,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new T9("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",J.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let Z=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),Q=this.config.WebSocketClass??WebSocket,Y=yZ0(this.config),X;if(Y){let K=this.config.apiKey;if(!K)throw new T9("1-step flow requires apiKey");let V=this.currentThreadID??this.config.threadId;if(!V)V=(await this.fetchWsToken()).threadId;let z=`${Z}/threads`;if(V)z=`${z}?threadId=${encodeURIComponent(V)}`;X=new Q(z,{headers:{Authorization:`Bearer ${K}`}})}else{let{threadId:K,wsToken:V}=await this.ensureWsToken();this.currentThreadID=K,this.currentWsToken=V;let z=`${Z}/threads`;X=new Q(z,["amp",V])}try{X.binaryType="arraybuffer"}catch{}await this.waitForOpen(X),this.ws=X,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(X),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);if(this.recordLifecycleEvent("connect_failed",`mode=${J.fromReconnect?"reconnect":"initial"} error=${Q}`),!J.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q},this.scheduleReconnect();throw Z}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let J=this.ws;if(J)this.ws=null,this.intentionallyClosedSockets.add(J),J.close(1000,"Client disconnect");this.updateConnectionState("disconnected")}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(J){if(!this.hasOpenSocket())throw new T9("WebSocket is not connected");this.ws?.send(J)}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}updateConnectionState(J){if(J==="disconnected"||J==="reconnecting"){let Z={state:J,role:null,clientId:null,threadId:null};if(this.reconnectCause)Z.reconnectCause=this.reconnectCause;this.connectionInfo=Z}else if(this.connectionInfo.state=J,J==="connected")this.connectionInfo.threadId=this.currentThreadID,this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;this.connectionSubject.next({...this.connectionInfo}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${bc5(this.reconnectCause)}`)}async handleAuthExpired(){this.recordLifecycleEvent("auth_refresh_started");try{if(this.currentWsToken=null,this.config.wsTokenProvider){let J=await this.config.wsTokenProvider({forceRefresh:!0});this.currentThreadID=J.threadId,this.currentWsToken=J.wsToken}this.recordLifecycleEvent("auth_refresh_succeeded",`threadId=${this.currentThreadID??"none"}`)}catch{this.recordLifecycleEvent("auth_refresh_failed")}}onRawMessage(J){}onMaxReconnectExceeded(J){}async ensureWsToken(){let J=this.reconnectAttempts>0;if(!J&&this.currentWsToken&&this.currentThreadID)return{threadId:this.currentThreadID,wsToken:this.currentWsToken};if(this.config.wsTokenProvider){let Z=await this.config.wsTokenProvider(J?{forceRefresh:!0}:void 0);return this.currentThreadID=Z.threadId,this.currentWsToken=Z.wsToken,Z}if(!J&&this.config.wsToken&&this.config.threadId)return{threadId:this.config.threadId,wsToken:this.config.wsToken};return this.fetchWsToken()}async fetchWsToken(){let Z=`${this.config.baseURL.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}/threads`,Q={"Content-Type":"application/json"};if(this.config.apiKey)Q.Authorization=`Bearer ${this.config.apiKey}`;let Y=this.currentThreadID??this.config.threadId,X={};if(Y)X.threadId=Y;let K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(X)});if(!K.ok){let z=await K.text().catch(()=>"");throw new T9(`Failed to get wsToken: ${K.status} ${z}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new T9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let z="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new T9(`WebSocket connection failed: ${z}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new T9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K)})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(J){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!J?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Z=J?.immediate?0:this.getReconnectDelayMs();this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=zw4(),Z=hc0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=uc5();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=hc0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=zw4(),Z=hc0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of Kw4)J?.addEventListener(Y,Q);for(let Y of Vw4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of Kw4)J?.removeEventListener(Y,Q);for(let Y of Vw4)Z?.removeEventListener(Y,Q)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},fc5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function hc5(J){let Z=atob(J),Q=new Uint8Array(Z.length);for(let Y=0;Y<Z.length;Y++)Q[Y]=Z.charCodeAt(Y);return Q}class aF extends pc0{deltaSubject=new s1;errorSubject=new s1;errorEventSubject=new s1;cancelledSubject=new s1;agentStateSubject=new s1;messageAddedSubject=new s1;editRejectedSubject=new s1;messageEditedSubject=new s1;queuedMessagesSubject=new s1;retrySubject=new s1;toolLeaseSubject=new s1;toolLeaseRevokedSubject=new s1;toolApprovalQueueSubject=new s1;executorToolApprovalResponseSubject=new s1;toolProgressSubject=new s1;executorErrorSubject=new s1;executorConnectedSubject=new s1;executorRollbackRequestSubject=new s1;observersSubject=new s1;executorStatusSubject=new s1;environmentUpdateSubject=new s1;artifactsSubject=new s1;gitStatusSubject=new s1;threadTitleSubject=new s1;threadStatusSubject=new s1;threadRelationshipsSubject=new s1;compactionSubject=new s1;compactionRecordsSubject=new s1;pluginMessageSubject=new s1;fileSystemReadDirectoryRequestSubject=new s1;fileSystemReadFileRequestSubject=new s1;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}gitStatuses(){return this.gitStatusSubject}threadTitles(){return this.threadTitleSubject}threadStatuses(){return this.threadStatusSubject}threadRelationships(){return this.threadRelationshipsSubject}compactionEvents(){return this.compactionSubject}compactionRecords(){return this.compactionRecordsSubject}pluginMessages(){return this.pluginMessageSubject}fileSystemReadDirectoryRequests(){return this.fileSystemReadDirectoryRequestSubject}fileSystemReadFileRequests(){return this.fileSystemReadFileRequestSubject}dispose(){if(this.disposed)return;super.dispose(),this.rejectPendingFileSystemRequests("Transport disposed"),this.deltaSubject.complete(),this.errorSubject.complete(),this.errorEventSubject.complete(),this.cancelledSubject.complete(),this.agentStateSubject.complete(),this.messageAddedSubject.complete(),this.editRejectedSubject.complete(),this.messageEditedSubject.complete(),this.queuedMessagesSubject.complete(),this.retrySubject.complete(),this.toolLeaseSubject.complete(),this.toolLeaseRevokedSubject.complete(),this.toolApprovalQueueSubject.complete(),this.executorToolApprovalResponseSubject.complete(),this.toolProgressSubject.complete(),this.executorErrorSubject.complete(),this.executorConnectedSubject.complete(),this.executorRollbackRequestSubject.complete(),this.observersSubject.complete(),this.executorStatusSubject.complete(),this.environmentUpdateSubject.complete(),this.artifactsSubject.complete(),this.gitStatusSubject.complete(),this.threadTitleSubject.complete(),this.threadStatusSubject.complete(),this.threadRelationshipsSubject.complete(),this.compactionSubject.complete(),this.compactionRecordsSubject.complete(),this.pluginMessageSubject.complete(),this.fileSystemReadDirectoryRequestSubject.complete(),this.fileSystemReadFileRequestSubject.complete()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??iF();return this.send({type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState,discoveredGuidanceFiles:Q?.discoveredGuidanceFiles}),Y}removeQueuedMessage(J){this.send({type:"client_remove_queued_msg",queuedMessageId:J})}interruptQueuedMessage(J){this.send({type:"client_interrupt_queued_msg",queuedMessageId:J})}editUserMessage(J,Z,Q,Y){this.send({type:"client_edit_message",messageId:J,editId:Q,content:Z,agentMode:Y})}markMessageRead(J){this.send({type:"client_mark_message_read",messageId:J})}markMessageUnread(J){this.send({type:"client_mark_message_unread",messageId:J})}setThreadTitle(J){this.send({type:"client_set_thread_title",title:J})}upsertNotificationSubscription(J,Z){this.send({type:"client_upsert_notification_subscription",subscription:J,threadURL:Z})}readDirectory(J){return this.requestReadDirectory(J)}readFile(J){return this.requestReadFile(J)}resumeFromVersion(J){this.send({type:"client_resume",version:J})}retryAgentLoop(){this.send({type:"client_retry"})}cancelAgentLoop(){if(!this.hasOpenSocket())return;this.send({type:"client_cancel"})}appendManualBashInvocation(J){this.send({type:"client_append_manual_bash_invocation",args:J.args,run:J.run,hidden:J.hidden})}resolveToolApproval(J,Z,Q){this.send({type:"client_tool_approval_response",toolCallId:J,accepted:Z,input:Q})}requestExecutorSpawn(J,Z){this.send({type:"client_spawn_executor",requestId:J,repositoryURL:Z?.repositoryURL,projectID:Z?.projectID,additionalRepositories:Z?.additionalRepositories})}executePluginCommand(J,Z,Q,Y){this.sendPluginMessage({type:"request",id:J,method:"command.execute",params:{pluginName:Z,commandId:Q,threadID:Y}})}async executorHandshake(J,Z,Q){if(this.disposed)throw new T9("Transport is disposed");if(!this.hasOpenSocket())throw new T9("WebSocket is not connected. Call connect() first.");return new Promise((Y,X)=>{let K=!1,V=null,z=(q)=>{if(K)return;if(K=!0,V)clearTimeout(V),V=null;G.unsubscribe(),F.unsubscribe(),q()},G=this.executorConnectedSubject.subscribe({next:(q)=>{this.connectionInfo.clientId=q.executorId,this.connectionInfo.role="executor",this.updateConnectionState("connected"),z(()=>Y(q))},error:(q)=>{z(()=>X(q))}}),F=this.executorErrorSubject.subscribe({next:(q)=>{z(()=>X(Error(q.message)))}});this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),V=setTimeout(()=>{z(()=>X(Error("Executor connect timeout")))},1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=jl(Z,"snapshot");this.send({type:"tool_progress",toolCallId:J,progress:Q})}sendExecutorToolResult(J,Z){this.send({type:"executor_tool_result",toolCallId:J,run:Z})}sendExecutorFileSystemReadDirectoryResult(J,Z){this.send({type:"executor_filesystem_read_directory_result",requestId:J,...Z})}sendExecutorFileSystemReadFileResult(J,Z){this.send({type:"executor_filesystem_read_file_result",requestId:J,...Z})}sendExecutorToolApprovalRequest(J){this.send({type:"executor_tool_approval_request",approval:J})}sendPluginMessage(J){this.send({type:"executor_plugin_message",message:J})}sendRevocationAck(J){this.send({type:"executor_revocation_ack",toolCallId:J})}sendExecutorGuidanceSnapshot(J){this.send({type:"executor_guidance_snapshot",...J})}sendExecutorGuidanceDiscovery(J){this.send({type:"executor_guidance_discovery",...J})}sendExecutorSkillSnapshot(J){this.send({type:"executor_skill_snapshot",...J})}sendExecutorSettingsUpdate(J){this.send({type:"executor_settings_update",settings:J})}sendExecutorRollbackAck(J,Z,Q){this.send({type:"executor_rollback_ack",editId:J,ok:Z,error:Q})}registerTools(J){this.send({type:"executor_tools_register",tools:J})}sendExecutorToolsBootstrapComplete(J,Z){this.send({type:"executor_tools_bootstrap_complete",ok:J,error:Z})}sendEnvironmentSnapshot(J){this.send({type:"executor_environment_snapshot",environment:J})}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J})}sendExecutorArtifactUpsert(J,Z){this.send({type:"executor_artifact_upsert",artifact:J,toolCallId:Z})}sendExecutorArtifactDelete(J){this.send({type:"executor_artifact_delete",key:J})}sendExecutorGitStatus(J,Z){this.send({type:"executor_git_status",status:J,toolCallId:Z})}unregisterTools(J){this.send({type:"executor_tools_unregister",toolNames:J})}updateConnectionState(J){if(super.updateConnectionState(J),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}requestReadDirectory(J){let Z=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Z,()=>{this.send({type:"client_filesystem_read_directory",requestId:Z,uri:J})})}requestReadFile(J){let Z=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Z,()=>{this.send({type:"client_filesystem_read_file",requestId:Z,uri:J})})}createPendingReadRequest(J,Z,Q){if(!this.hasOpenSocket())return Promise.reject(new T9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new T9(`Filesystem request timed out: ${Z}`))},mN4);J.set(Z,{resolve:Y,reject:X,timeoutID:K});try{Q()}catch(V){clearTimeout(K),J.delete(Z),X(V instanceof Error?V:Error(String(V)))}})}nextFileSystemRequestID(J){let Z=this.fileSystemRequestCounter++;return`${J}-${Date.now()}-${Z}`}handleReadDirectoryResult(J){let Z=this.pendingReadDirectoryRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadDirectoryRequests.delete(J.requestId),J.ok&&J.entries){Z.resolve(J.entries);return}if(J.ok){Z.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!J.error){Z.reject(Error("Invalid filesystem read_directory response: missing error"));return}Z.reject(this.createFileSystemError(J.error))}handleReadFileResult(J){let Z=this.pendingReadFileRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadFileRequests.delete(J.requestId),!J.ok&&J.error){Z.reject(this.createFileSystemError(J.error));return}if(!J.ok){Z.reject(Error("Invalid filesystem read_file response: missing error"));return}if(J.contentBase64===void 0){Z.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Z.resolve(hc5(J.contentBase64))}catch{Z.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(J){return Error(`Filesystem error (${J.code}): ${J.message}`)}rejectPendingFileSystemRequests(J){for(let[Z,Q]of this.pendingReadDirectoryRequests)clearTimeout(Q.timeoutID),Q.reject(new T9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new T9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=rN4.safeDecode(J);if(!Z.success){let Y=oN4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:Xw4(J,X),code:"PARSE_ERROR"});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}handleServerMessage(J){switch(J.type){case"agent_state":this.agentStateSubject.next(J);break;case"error":this.errorSubject.next(J);break;case"error_set":case"error_cleared":this.errorEventSubject.next(J);break;case"cancelled":this.cancelledSubject.next(J);break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.retrySubject.next(J);break;case"delta":this.deltaSubject.next(J);break;case"message_added":this.messageAddedSubject.next(J);break;case"edit_rejected":this.editRejectedSubject.next(J);break;case"message_edited":this.messageEditedSubject.next(J);break;case"queued_messages":case"queued_message_added":case"queued_message_removed":this.queuedMessagesSubject.next(J);break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.executorConnectedSubject.next(J);break;case"tool_lease":this.toolLeaseSubject.next(J);break;case"executor_filesystem_read_directory":this.fileSystemReadDirectoryRequestSubject.next(J);break;case"executor_filesystem_read_file":this.fileSystemReadFileRequestSubject.next(J);break;case"executor_rollback_request":this.executorRollbackRequestSubject.next(J);break;case"executor_tool_lease_revoked":this.toolLeaseRevokedSubject.next(J);break;case"tool_approval_queue":this.toolApprovalQueueSubject.next(J);break;case"plugin_message":this.pluginMessageSubject.next(J);break;case"executor_tool_approval_response":this.executorToolApprovalResponseSubject.next(J);break;case"tool_progress":this.toolProgressSubject.next(J);break;case"executor_error":this.executorErrorSubject.next(J);break;case"cf_agent_state":case"cf_agent_mcp_servers":case"cf_agent_identity":break;case"observers":this.observersSubject.next(J);break;case"executor_status":this.executorStatusSubject.next(J);break;case"environment_update":this.environmentUpdateSubject.next(J);break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.artifactsSubject.next(J);break;case"git_status":this.gitStatusSubject.next(J);break;case"thread_title":this.threadTitleSubject.next(J);break;case"thread_status":this.threadStatusSubject.next(J);break;case"thread_relationships":this.threadRelationshipsSubject.next(J);break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(J);break;case"client_filesystem_read_file_result":this.handleReadFileResult(J);break;case"compaction_started":case"compaction_complete":this.compactionSubject.next(J);break;case"compaction_records":this.compactionRecordsSubject.next(J);break}}onMaxReconnectExceeded(J){this.errorSubject.next({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})}send(J){try{this.sendRaw(aN4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new T9(`Failed to encode DTW client message "${J.type}": ${Q}`)}}}function gc5(J){if(!J||typeof J!=="object")return!1;let Z=J.queuedMessage;if(!Z||typeof Z!=="object")return!1;return typeof Z.messageId==="string"}function mc5(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function pc5(J){if(gc5(J))return J.queuedMessage.messageId;if(mc5(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function dc0(J,Z,Q={}){let Y=Q.getQueuedMessageId??pc5;if(Z.type==="queued_messages")return[...Z.messages];if(Z.type==="queued_message_added"){if(Q.dedupeAdded&&J.some((X)=>Y(X)===Y(Z.message)))return[...J];return[...J,Z.message]}if(!J.some((X)=>Y(X)===Z.queuedMessageId))return[...J];return J.filter((X)=>Y(X)!==Z.queuedMessageId)}var dc5=15000;function cc5(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let G of K)G.unsubscribe()};return{promise:new Promise((G,F)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),G(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),F(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),F(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function cc0(J){let Z=J.workerUrl??h7(J.ampURL),Q=new aF({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??dc5;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=cc5(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as lc5}from"node:fs";import{mkdir as ic5,readdir as nc5,readFile as ac5}from"node:fs/promises";import{createServer as oc5}from"node:http";import lc0 from"node:path";function Fw4(J){return J instanceof Error?J.message:String(J)}function aA(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function rc5(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function qw4(J,Z){let Q=lc0.basename(Z),Y=Q.endsWith(".json")?lc0.join(J,Q):lc0.join(J,`${Q}.json`),X=await ac5(Y,"utf-8");return JSON.parse(X)}async function sc5(J){let Z=await nc5(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await qw4(J,Y.name);Q.push({sessionID:X.sessionID,createdAt:X.createdAt,runtimeMode:X.runtimeMode,traceName:X.traceName,threadId:X.threadId,protocolEvents:X.protocolEvents.length,providerStates:X.providerStateEvents.length,adapterStates:X.adapterStateEvents.length,commands:X.commandEvents.length})}catch{}}return Q.sort((Y,X)=>X.createdAt-Y.createdAt)}function tc5(){return`<!doctype html>
4634
4634
  <html lang="en">
4635
4635
  <head>
4636
4636
  <meta charset="utf-8" />
@@ -6159,11 +6159,11 @@ ${D}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
6159
6159
  ${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))H+=`
6160
6160
 
6161
6161
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6162
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();rM();async function WQ0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=PL4(J,F),W=q<0,U,D;if(G.time){let H=G.time[J],B=G.time[F],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:D}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:D,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var Ba5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function UQ0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${Ba5}?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 K=PL4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var Na5=604800000;function IL4(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>Na5)return{ageMs:Q};return null}function PL4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||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 _l0(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?AF(Q):void 0;return{sha:Y,age:X}}catch{return null}}N1();function Sl0(J,Z,Q={}){let Y=new s1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await qQ0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await UQ0(J):await WQ0(J,Zj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let D=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==jl0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await nl(U.latestVersion,q);let H=await Jw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}rM();import{stderr as sF}from"node:process";function CL4(J){let Z=new cN().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 Ll0(Y.force||!1,Y.verbose||!1,"0.0.1774195348-g48946d"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new cN("update").alias("up").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 wa5(Y.targetVersion)});J.addCommand(Q)}async function wa5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")sF.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6162
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();rM();async function WQ0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=PL4(J,F),W=q<0,U,D;if(G.time){let H=G.time[J],B=G.time[F],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:D}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:D,source:"npm"}}catch(z){return P.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var Ba5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function UQ0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${Ba5}?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 K=PL4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var Na5=604800000;function IL4(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>Na5)return{ageMs:Q};return null}function PL4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||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 _l0(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?AF(Q):void 0;return{sha:Y,age:X}}catch{return null}}N1();function Sl0(J,Z,Q={}){let Y=new s1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await JF(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await qQ0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await UQ0(J):await WQ0(J,Zj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let D=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==jl0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await nl(U.latestVersion,q);let H=await Jw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await JF(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}rM();import{stderr as sF}from"node:process";function CL4(J){let Z=new cN().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 Ll0(Y.force||!1,Y.verbose||!1,"0.0.1774240952-g432b79"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new cN("update").alias("up").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 wa5(Y.targetVersion)});J.addCommand(Q)}async function wa5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")sF.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6163
6163
 
6164
6164
  `));try{if(!J){sF.write(c0.blue(`Checking for updates...
6165
- `));let{hasUpdate:Y,latestVersion:X}=El0()?await UQ0("0.0.1774195348-g48946d"):await WQ0("0.0.1774195348-g48946d",Zj());if(!Y){let K=_l0("0.0.1774195348-g48946d"),V=K?.age?`released ${K.age} ago`:`built ${AF(new Date("2026-03-22T16:06:01.558Z"))} ago`;sF.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774195348-g48946d"} (${V})
6166
- `));let z=await Jw("0.0.1774195348-g48946d");if(z.warning)sF.write(`
6165
+ `));let{hasUpdate:Y,latestVersion:X}=El0()?await UQ0("0.0.1774240952-g432b79"):await WQ0("0.0.1774240952-g432b79",Zj());if(!Y){let K=_l0("0.0.1774240952-g432b79"),V=K?.age?`released ${K.age} ago`:`built ${AF(new Date("2026-03-23T04:46:09.725Z"))} ago`;sF.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774240952-g432b79"} (${V})
6166
+ `));let z=await Jw("0.0.1774240952-g432b79");if(z.warning)sF.write(`
6167
6167
  `+c0.yellow(z.warning)+`
6168
6168
  `);process.exit(0)}if(!X)sF.write(c0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}sF.write(c0.blue(`Updating to version ${J}...
6169
6169
  `)),await nl(J,void 0,(Y)=>{sF.write(c0.dim(`Running: ${Y}
@@ -7371,7 +7371,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
7371
7371
  `),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new m({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new m({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7372
7372
  `))}return new i0({decoration:{color:Q.colorScheme.background,border:c1.all(new h1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,K)})})})}}class x01 extends y${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=GG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new y01({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 Fg4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?k9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?k9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function aR3(J,Z,Q,Y,X,K,V,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 F=K?k9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),D=F+Z*U+Math.floor(U/2),H=z>0?V/z:0,B=Math.round((1-H)*(W-1));return{x:D,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?k9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),D=z>0?V/z:0,H=Math.round((1-D)*(W-1));return{x:U,y:H}}default:return null}}function oR3(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 rR3(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 K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function sR3(J,Z,Q,Y,X,K,V){let z;try{let H=_1.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 m({color:z.foreground,bold:!0}),F=new m({color:z.foreground}),q=new m({color:z.foreground,dim:!0}),W=[],U=new m({color:z.foreground,underline:!0}),D=(H,B)=>new C(B,U,void 0,jQ0(H),()=>{t3(J,H)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,G)),Z.link)W.push(D(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
7373
7373
  `,G));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],O=w.points[Q];if(!O)continue;B+=O.value;let L=w.color??X[N%X.length]??z.foreground;if(W.push(new C("● ",new m({color:L}))),W.push(new C(`${w.name}: `,q)),O.link)W.push(D(O.link,K(O.value)));else W.push(new C(K(O.value),F));if(N<Y.length-1||H)W.push(new C(`
7374
- `))}if(H)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:z.background,border:c1.all(new h1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,W)})})}VE();g0();P2();import{execSync as RI3}from"node:child_process";WE();N$();n3();P7();md();rM();MV();L$();sJ();qY();CA();f4();eg();eu();N1();var Fm4=z4(ZU(),1);import{writeFile as Xm4}from"fs/promises";import Km4 from"path";g0();L$();class f01{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.1774195348-g48946d"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await g40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class FO extends l0{props;constructor(J){super();this.props=J}createState(){return new qg4}}class qg4 extends d0{_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 Wg4 extends d0{controller=new Z$;focusNode=new W6({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,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new h1(Q.foreground,1,"solid")),G=new TZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new m({color:Q.foreground}))})}),new k1({child:G})]}),q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new m({color:Q.foreground})),new C(this.widget.props.commandName,new m({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new m({color:Y.keybind}))),W.push(new C(" to submit, ",new m({color:Q.foreground,dim:!0})));W.push(new C("Esc",new m({color:Y.keybind}))),W.push(new C(" to cancel",new m({color:Q.foreground,dim:!0})));let U=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,W)})});return new i0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class na extends l0{props;constructor(J){super();this.props=J}createState(){return new Wg4}}import{isDeepStrictEqual as u01}from"node:util";var tR3=/[\\/_ +.#"@[({&]/,eR3=/[\\/_ +.#"@[({&]/g,$I3=/[\s-]/,Ug4=/[\s-]/g;function WG0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,D,H;while(F>=0){if(W=WG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if($I3.test(J.charAt(F-1))){if(W*=0.9,H=J.slice(X,F-1).match(Ug4),H&&X>0)W*=0.999**H.length}else if(tR3.test(J.charAt(F-1))){if(W*=0.8,D=J.slice(X,F-1).match(eR3),D&&X>0)W*=0.999**D.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=WG0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function qG0(J){return J.toLowerCase().replace(Ug4," ")}function Dg4(J,Z){let Q=WG0(J,Z,qG0(J),qG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=WG0(J,z,qG0(J),qG0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Av{}class jv{}class UG0{}class DG0{}class Hg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Bg4}}class Bg4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function JI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Dg4(Z,J);return{matches:Q>0.15,score:Q}}class a2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Ng4}}class Ng4 extends d0{textController;focusNode;scrollController=new A5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new Z$(this.widget.props.controller?.query??""),this.focusNode=new W6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.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)=>u01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!u01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>u01(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 Av){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof jv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof UG0){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 DG0)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,...JI3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.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;Nv(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(),C6.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=c1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new TZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Av],[new D4("ArrowUp"),new jv],[new D4("Tab"),new Av],[new D4("Tab",{shift:!0}),new jv],[new D4("n",{ctrl:!0}),new Av],[new D4("p",{ctrl:!0}),new jv],[new D4("Enter"),new UG0],[new D4("Escape"),new DG0]]),focusNode:this.focusNode,child:z}),F=new L2({actions:new Map([[Av,new U6(this.invoke)],[jv,new U6(this.invoke)],[UG0,new U6(this.invoke)],[DG0,new U6(this.invoke)]]),child:G}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new m({color:Q.foreground}))})}),new k1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new $4({child:new $0({text:new C(N,new m({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new $4({child:new $0({text:new C(this.widget.props.emptyStateText,new m({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,O)=>{let L=O===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,L,E,J);else{let A=L?Z.app.selectionBackground:void 0,j=L?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(w),new m({color:j,dim:E}))})})}return new Hg4(new e1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new e1({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new m({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new $4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:U}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function wg4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=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(K<7)return`${K}d ago`;return J.toLocaleDateString()}class b01 extends t1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>wg4(X.pubDate).length));return new a2({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,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,D=F.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new $0({text:new C(B,new m({color:D}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new $0({text:new C(X.title,new m({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(wg4(X.pubDate),Q)]})})}})}}class h01 extends l0{createState(){return new Og4}}class Og4 extends d0{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 m({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function ZI3(J){return MY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function QI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return lV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function g01(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new m({color:Q})),maxLines:1})}function YI3(J,Z,Q,Y){return[g01("+",J,Y.success),b3.horizontal(1),g01("~",Z,Y.warning),b3.horizontal(1),g01("-",Q,Y.destructive)]}function XI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class HG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Lg4}}class Lg4 extends d0{spinner=new M3;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}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((O)=>O.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((O,L)=>{if(G){if(O.id===G)return-1;if(L.id===G)return 1}let E=V.indexOf(O.id),M=V.indexOf(L.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=QI3(F),W=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),U=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new $4({child:new $0({text:new C("",new m({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new m({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new m({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(O)=>{if(O!==H)H=O,B=ZI3(O);return B};return new a2({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,L)=>{let E=N(L);if(E)return O.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(O)=>N(O)?"":O,onAccept:async(O,L)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(O.id,L);if(!XI3(E))return;this.setSwitchingThread(!0);try{await E}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:D,renderItem:(O,L,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,k=L?j.selectionBackground:void 0,S=L?j.selectionForeground:R.foreground,u=R.mutedForeground,g=(s,F0)=>new I0({width:F0,child:q1.end([new $0({text:new C(s,new m({color:u}))})])}),x=Z.threadViewStates[O.id],T=[],f=O.relationshipType==="handoff",p=new La({connectorColor:R.mutedForeground});if(O.depth>0){let s=[],F0=O.ancestorsAreLast.slice(1);for(let O0 of F0)s.push(new C(p.getAncestorPrefix(O0),new m({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,q0=p.getConnectorText(a);s.push(new C(q0,new m({color:p.connectorColor,dim:p.connectorDim}))),T.push(new $0({text:new C("",void 0,s)}))}let d=[],h=G===O.id?new C("(current) ",new m({color:R.success})):z.has(O.id)?new C("(visited) ",new m({color:R.foreground,dim:!0})):null;if(h)d.push(new $0({text:h}));if(MN(x))d.push(new h01),d.push(new I0({width:1}));let n=O.title;if(O.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new $0({text:new C("[fork] ",new m({color:R.primary}))}))}else if(f)d.push(new $0({text:new C("[handoff] ",new m({color:R.accent}))}));if(d.push(new k1({child:new $0({text:new C(n,new m({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=L?{success:u,warning:u,destructive:u}:R;d.push(...YI3(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(g(O.description.timeAgo,W)),new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...T,...d]})})}})}}function Eg4(J){return 1-(1-J)**3}function Mg4(J,Z,Q){return J+(Z-J)*Q}function aa(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),K=Eg4(Y),V=Eg4(X);return{x:Mg4(J.startOffset.x,J.targetOffset.x,K),y:Mg4(J.startOffset.y,J.targetOffset.y,V)}}var KI3={nodeWidth:3,horizontalSpacing:3};class Rv{options;constructor(J={}){this.options={...KI3,...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 K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),D=Math.max(...W),H=Math.floor((U+D)/2);return Y.push({node:q,position:{x:H,y:G}}),H};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var VI3={nodeWidth:3,nodeHeight:2};class Iv{options;constructor(J={}){this.options={...VI3,...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 K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,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,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var zI3={nodeWidth:3,nodeHeight:2},GI3={x:0,y:0};class NG0{options;constructor(J={}){this.options={...zI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=GI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new m({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,g)=>u.position.x-g.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let g=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;k.push(this.renderNode(g,x,T,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((T)=>T.position.y===j-1),g=R,x=this.renderConnectors(u,g,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=O+A.position.x+this.options.nodeWidth+1,S=L+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:k,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new uz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new $0({text:new C(V,new m({color:G,bold:F}))}),new $0({text:new C(z,new m({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new $0({text:new C(z,new m({color:F}))})];for(let U of X){let D=" ".repeat(K-U.length);W.push(new $0({text:new C("│ ",new m({color:F}),[new C(U+D,new m({color:q??F})),new C(" │",new m({color:F}))])}))}return W.push(new $0({text:new C(G,new m({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let D=U.position.x+z;if(D>=0&&D<Y)F[D]="▲"}V.push(new $0({text:new C(F.join(""),new m({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let D=Z.filter((O)=>O.node.parentID===U.node.id);if(D.length===0)continue;let H=U.position.x+z,B=D.map((O)=>O.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let O=N;O<=w;O++)if(O>=0&&O<Y){if(O===H)if(D.length===1&&B[0]===H)q[O]="│";else if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┬";else if(B.includes(O))if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┴";else if(q[O]===" ")q[O]="─"}}V.push(new $0({text:new C(q.join(""),new m({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)W[H]="│"}return V.push(new $0({text:new C(W.join(""),new m({color:G}))})),V}}var FI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},qI3={x:0,y:0};class m01{options;constructor(J={}){this.options={...FI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=qI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new m({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,g)=>u.position.x-g.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let g=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1;k.push(this.renderNode(g,x,T,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((T)=>T.position.y===j-1),g=R,x=this.renderConnectors(u,g,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=O+A.position.x+this.options.nodeWidth+1,S=L+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:k,top:S,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new uz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new $0({text:new C(K,new m({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new $0({text:new C(V,new m({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,D=W.map((N)=>N.position.x+z),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,O=D.includes(N);if(w&&O)if(W.length===1)F[N]="│";else if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(O)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new $0({text:new C(F.join(""),new m({color:G}))})),V}}class oa extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Ag4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Ag4 extends v4{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 CR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Ig4}}var jg4=400,Rg4=300,WI3=16;class Ig4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Rv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Iv;renderer=new m01;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,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==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:jg4,durationY:Rg4};let Z=Math.max(jg4,Rg4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=aa(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},WI3)}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),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new oa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({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 Cg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Tg4}}class Tg4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var Pg4=30,UI3=30;class Pv{}class Cv{}class wG0{}class OG0{}class p01 extends l0{props;constructor(J){super();this.props=J}createState(){return new _g4}}class _g4 extends d0{highlightedIndex=0;controller=new Z$;focusNode;scrollController=new A5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new W6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.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;Nv(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 Pv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Cv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof wG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof OG0)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(),C6.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=K4.of(J).size.width>=UI3+Pg4,G=c1.all(new h1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new m({color:X.command,bold:!0}))})}),W=new TZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Pv],[new D4("ArrowUp"),new Cv],[new D4("Tab"),new Pv],[new D4("Tab",{shift:!0}),new Cv],[new D4("n",{ctrl:!0}),new Pv],[new D4("p",{ctrl:!0}),new Cv],[new D4("Enter"),new wG0],[new D4("Escape"),new OG0]]),focusNode:this.focusNode,child:W}),D=new L2({actions:new Map([[Pv,new U6(this.invoke)],[Cv,new U6(this.invoke)],[wG0,new U6(this.invoke)],[OG0,new U6(this.invoke)]]),child:U}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new $0({text:new C(">",new m({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((g)=>g.id===Z):!1,k=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new m({color:S})),new C(` (${M.threads.length})`,new m({color:S,dim:!0}))];if(R)u.push(new C(" (current)",new m({color:j?X.selectionForeground:Y.success})));return new Cg4(new e1({onClick:(g)=>this.handleItemClick(A,g.clickCount),child:new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,u)})})}),(g)=>{this.itemContexts[A]=g})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],L=F?new i0({padding:C0.all(1),child:new CR({threads:O,autofocus:!1,offsetY:2})}):null,E;if(z){let M=L?new k1({child:L}):new I0({width:Pg4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(L)M.push(new k1({child:L}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class yJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yJ._instance)yJ._instance=new yJ;return yJ._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()}}g0();class Sg4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.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(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new a2({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(F,q,W,U)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new m({color:H})),new C(N,new m({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new m({color:H}))})})},filterItem:(F,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(q);let U=q.trim().toLowerCase();return U.length===0||F.name.includes(U)},sortItems:(F,q,W)=>{let U="__isCreateMarker"in F.item&&F.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!D)return-1;if(!U&&D)return 1;return q.score-F.score}})}}class d01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Sg4}}class lz extends l0{props;constructor(J){super();this.props=J}createState(){return new kg4}}class kg4 extends d0{_spinner=new M3;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=c1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new $0({textAlign:"center",text:new C("",void 0,[new C(K,new m({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new m({color:Q.foreground}))])}),G=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)G.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new m({dim:!0}),[new C("Press ",new m({color:Q.foreground})),new C("Esc",new m({color:Q.info})),new C(" to cancel",new m({color:Q.foreground}))])})})}));let F=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ra={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"}},LG0=["workspace","global","flag","default","external","skill","other"];function DI3(J){return Array.from(new Set(J))}function yg4(J){return DI3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function Tv(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 yg4(J).length>0?"skill":"other"}function c01(J){return Tv(J)==="skill"}function vg4(J){let Z=yg4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=Tv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ra[Y].description}: ${Q}`}function xg4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var fg4=process.platform==="win32"?" ":"█",ug4=process.platform==="win32"?"░":"█";class O9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=fg4,thumbChar:K=ug4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createState(){return new bg4}}class bg4 extends d0{_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 K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),z=Math.max(1,X*V),G=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-z,q=Math.max(0,F*G),W=q+z;return J>=q&&J<=W}_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(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,K*z),F=K-G;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,D=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,V*z),F=Q-Y,q=V-G,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),D=U+G;if(Z>=U&&Z<=D)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new e1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?b5.POINTER:b5.DEFAULT,child:new hg4({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 hg4 extends Ck{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=fg4,thumbChar:K=ug4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new gg4(this)}updateRenderObject(J){J.updateWidget(this)}}class gg4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!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:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,z=this._widget.thumbColor,G=process.platform==="win32",F=Y,q=Y+X;if(!G){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let D="█",H=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);D=W[N]||"█",H=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);D=W[N]||"█"}else if(U>F&&U<q)H=!1;J.setChar(Z,Q+U,D,{fg:z,bg:V,reverse:H},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,D=U>=F&&U<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,H,{fg:D?z:V,bg:V,reverse:!1},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))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class TR extends l0{props;constructor(J){super();this.props=J}createState(){return new mg4}}class mg4 extends d0{scrollController=new A5;scrollAreaKey=new d7("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 n2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=az0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new m({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new m({color:Z.colors.foreground})),selectable:!0}),G=new k1({child:new m$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new T6({controller:this.scrollController,autofocus:!0,child:z})}),new O9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),D=q+U;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new m({color:Z.colors.foreground,dim:!0})),new C("R",new m({color:Z.app.keybind})),new C(" to retry, ",new m({color:Z.colors.foreground,dim:!0})),new C("Esc",new m({color:Z.app.keybind})),new C(" to cancel",new m({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new m({color:Z.colors.foreground,dim:!0}));if(q==="help"){let W=new m({color:Z.app.keybind}),U=new m({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",W),new C(" to close • Use ",U),new C("↑↓",W),new C(" or ",U),new C("j/k",W),new C(" to scroll",U)])}return new C("Press any key to close",new m({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),G,F]})})})}}P2();class pg4 extends l0{props;constructor(J){super();this.props=J}createState(){return new dg4}}class dg4 extends d0{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=_9.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 m({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((G)=>G.status==="active").length,V=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new m({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${z} ${d4(z,"tool")})`,new m({dim:!0})));Y.push(new C(`
7374
+ `))}if(H)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:z.background,border:c1.all(new h1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,W)})})}VE();g0();P2();import{execSync as RI3}from"node:child_process";WE();N$();n3();P7();md();rM();MV();L$();sJ();qY();CA();f4();eg();eu();N1();var Fm4=z4(ZU(),1);import{writeFile as Xm4}from"fs/promises";import Km4 from"path";g0();L$();class f01{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.1774240952-g432b79"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await g40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class FO extends l0{props;constructor(J){super();this.props=J}createState(){return new qg4}}class qg4 extends d0{_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 Wg4 extends d0{controller=new Z$;focusNode=new W6({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,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new h1(Q.foreground,1,"solid")),G=new TZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new m({color:Q.foreground}))})}),new k1({child:G})]}),q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new m({color:Q.foreground})),new C(this.widget.props.commandName,new m({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new m({color:Y.keybind}))),W.push(new C(" to submit, ",new m({color:Q.foreground,dim:!0})));W.push(new C("Esc",new m({color:Y.keybind}))),W.push(new C(" to cancel",new m({color:Q.foreground,dim:!0})));let U=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,W)})});return new i0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class na extends l0{props;constructor(J){super();this.props=J}createState(){return new Wg4}}import{isDeepStrictEqual as u01}from"node:util";var tR3=/[\\/_ +.#"@[({&]/,eR3=/[\\/_ +.#"@[({&]/g,$I3=/[\s-]/,Ug4=/[\s-]/g;function WG0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,D,H;while(F>=0){if(W=WG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if($I3.test(J.charAt(F-1))){if(W*=0.9,H=J.slice(X,F-1).match(Ug4),H&&X>0)W*=0.999**H.length}else if(tR3.test(J.charAt(F-1))){if(W*=0.8,D=J.slice(X,F-1).match(eR3),D&&X>0)W*=0.999**D.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=WG0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function qG0(J){return J.toLowerCase().replace(Ug4," ")}function Dg4(J,Z){let Q=WG0(J,Z,qG0(J),qG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=WG0(J,z,qG0(J),qG0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Av{}class jv{}class UG0{}class DG0{}class Hg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Bg4}}class Bg4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function JI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Dg4(Z,J);return{matches:Q>0.15,score:Q}}class a2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Ng4}}class Ng4 extends d0{textController;focusNode;scrollController=new A5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new Z$(this.widget.props.controller?.query??""),this.focusNode=new W6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.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)=>u01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!u01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>u01(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 Av){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof jv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof UG0){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 DG0)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,...JI3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.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;Nv(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(),C6.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=c1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new TZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Av],[new D4("ArrowUp"),new jv],[new D4("Tab"),new Av],[new D4("Tab",{shift:!0}),new jv],[new D4("n",{ctrl:!0}),new Av],[new D4("p",{ctrl:!0}),new jv],[new D4("Enter"),new UG0],[new D4("Escape"),new DG0]]),focusNode:this.focusNode,child:z}),F=new L2({actions:new Map([[Av,new U6(this.invoke)],[jv,new U6(this.invoke)],[UG0,new U6(this.invoke)],[DG0,new U6(this.invoke)]]),child:G}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new m({color:Q.foreground}))})}),new k1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new $4({child:new $0({text:new C(N,new m({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new $4({child:new $0({text:new C(this.widget.props.emptyStateText,new m({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,O)=>{let L=O===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,L,E,J);else{let A=L?Z.app.selectionBackground:void 0,j=L?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(w),new m({color:j,dim:E}))})})}return new Hg4(new e1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new e1({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new m({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new $4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:U}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function wg4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=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(K<7)return`${K}d ago`;return J.toLocaleDateString()}class b01 extends t1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>wg4(X.pubDate).length));return new a2({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,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,D=F.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new $0({text:new C(B,new m({color:D}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new $0({text:new C(X.title,new m({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(wg4(X.pubDate),Q)]})})}})}}class h01 extends l0{createState(){return new Og4}}class Og4 extends d0{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 m({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function ZI3(J){return MY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function QI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return lV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function g01(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new m({color:Q})),maxLines:1})}function YI3(J,Z,Q,Y){return[g01("+",J,Y.success),b3.horizontal(1),g01("~",Z,Y.warning),b3.horizontal(1),g01("-",Q,Y.destructive)]}function XI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class HG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Lg4}}class Lg4 extends d0{spinner=new M3;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}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((O)=>O.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((O,L)=>{if(G){if(O.id===G)return-1;if(L.id===G)return 1}let E=V.indexOf(O.id),M=V.indexOf(L.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=QI3(F),W=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),U=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new $4({child:new $0({text:new C("",new m({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new m({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new m({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(O)=>{if(O!==H)H=O,B=ZI3(O);return B};return new a2({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,L)=>{let E=N(L);if(E)return O.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(O)=>N(O)?"":O,onAccept:async(O,L)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(O.id,L);if(!XI3(E))return;this.setSwitchingThread(!0);try{await E}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:D,renderItem:(O,L,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,k=L?j.selectionBackground:void 0,S=L?j.selectionForeground:R.foreground,u=R.mutedForeground,g=(s,F0)=>new I0({width:F0,child:q1.end([new $0({text:new C(s,new m({color:u}))})])}),x=Z.threadViewStates[O.id],T=[],f=O.relationshipType==="handoff",p=new La({connectorColor:R.mutedForeground});if(O.depth>0){let s=[],F0=O.ancestorsAreLast.slice(1);for(let O0 of F0)s.push(new C(p.getAncestorPrefix(O0),new m({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,q0=p.getConnectorText(a);s.push(new C(q0,new m({color:p.connectorColor,dim:p.connectorDim}))),T.push(new $0({text:new C("",void 0,s)}))}let d=[],h=G===O.id?new C("(current) ",new m({color:R.success})):z.has(O.id)?new C("(visited) ",new m({color:R.foreground,dim:!0})):null;if(h)d.push(new $0({text:h}));if(MN(x))d.push(new h01),d.push(new I0({width:1}));let n=O.title;if(O.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new $0({text:new C("[fork] ",new m({color:R.primary}))}))}else if(f)d.push(new $0({text:new C("[handoff] ",new m({color:R.accent}))}));if(d.push(new k1({child:new $0({text:new C(n,new m({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=L?{success:u,warning:u,destructive:u}:R;d.push(...YI3(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(g(O.description.timeAgo,W)),new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...T,...d]})})}})}}function Eg4(J){return 1-(1-J)**3}function Mg4(J,Z,Q){return J+(Z-J)*Q}function aa(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),K=Eg4(Y),V=Eg4(X);return{x:Mg4(J.startOffset.x,J.targetOffset.x,K),y:Mg4(J.startOffset.y,J.targetOffset.y,V)}}var KI3={nodeWidth:3,horizontalSpacing:3};class Rv{options;constructor(J={}){this.options={...KI3,...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 K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),D=Math.max(...W),H=Math.floor((U+D)/2);return Y.push({node:q,position:{x:H,y:G}}),H};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var VI3={nodeWidth:3,nodeHeight:2};class Iv{options;constructor(J={}){this.options={...VI3,...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 K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,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,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var zI3={nodeWidth:3,nodeHeight:2},GI3={x:0,y:0};class NG0{options;constructor(J={}){this.options={...zI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=GI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new m({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,g)=>u.position.x-g.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let g=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;k.push(this.renderNode(g,x,T,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((T)=>T.position.y===j-1),g=R,x=this.renderConnectors(u,g,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=O+A.position.x+this.options.nodeWidth+1,S=L+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:k,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new uz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new $0({text:new C(V,new m({color:G,bold:F}))}),new $0({text:new C(z,new m({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new $0({text:new C(z,new m({color:F}))})];for(let U of X){let D=" ".repeat(K-U.length);W.push(new $0({text:new C("│ ",new m({color:F}),[new C(U+D,new m({color:q??F})),new C(" │",new m({color:F}))])}))}return W.push(new $0({text:new C(G,new m({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let D=U.position.x+z;if(D>=0&&D<Y)F[D]="▲"}V.push(new $0({text:new C(F.join(""),new m({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let D=Z.filter((O)=>O.node.parentID===U.node.id);if(D.length===0)continue;let H=U.position.x+z,B=D.map((O)=>O.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let O=N;O<=w;O++)if(O>=0&&O<Y){if(O===H)if(D.length===1&&B[0]===H)q[O]="│";else if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┬";else if(B.includes(O))if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┴";else if(q[O]===" ")q[O]="─"}}V.push(new $0({text:new C(q.join(""),new m({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)W[H]="│"}return V.push(new $0({text:new C(W.join(""),new m({color:G}))})),V}}var FI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},qI3={x:0,y:0};class m01{options;constructor(J={}){this.options={...FI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=qI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new m({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,g)=>u.position.x-g.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let g=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1;k.push(this.renderNode(g,x,T,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((T)=>T.position.y===j-1),g=R,x=this.renderConnectors(u,g,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=O+A.position.x+this.options.nodeWidth+1,S=L+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:k,top:S,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new uz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new $0({text:new C(K,new m({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new $0({text:new C(V,new m({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,D=W.map((N)=>N.position.x+z),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,O=D.includes(N);if(w&&O)if(W.length===1)F[N]="│";else if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(O)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new $0({text:new C(F.join(""),new m({color:G}))})),V}}class oa extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Ag4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Ag4 extends v4{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 CR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Ig4}}var jg4=400,Rg4=300,WI3=16;class Ig4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Rv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Iv;renderer=new m01;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,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==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:jg4,durationY:Rg4};let Z=Math.max(jg4,Rg4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=aa(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},WI3)}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),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new oa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({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 Cg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Tg4}}class Tg4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var Pg4=30,UI3=30;class Pv{}class Cv{}class wG0{}class OG0{}class p01 extends l0{props;constructor(J){super();this.props=J}createState(){return new _g4}}class _g4 extends d0{highlightedIndex=0;controller=new Z$;focusNode;scrollController=new A5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new W6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.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;Nv(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 Pv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Cv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof wG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof OG0)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(),C6.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=K4.of(J).size.width>=UI3+Pg4,G=c1.all(new h1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new m({color:X.command,bold:!0}))})}),W=new TZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new g$({shortcuts:new Map([[new D4("ArrowDown"),new Pv],[new D4("ArrowUp"),new Cv],[new D4("Tab"),new Pv],[new D4("Tab",{shift:!0}),new Cv],[new D4("n",{ctrl:!0}),new Pv],[new D4("p",{ctrl:!0}),new Cv],[new D4("Enter"),new wG0],[new D4("Escape"),new OG0]]),focusNode:this.focusNode,child:W}),D=new L2({actions:new Map([[Pv,new U6(this.invoke)],[Cv,new U6(this.invoke)],[wG0,new U6(this.invoke)],[OG0,new U6(this.invoke)]]),child:U}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new $0({text:new C(">",new m({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((g)=>g.id===Z):!1,k=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new m({color:S})),new C(` (${M.threads.length})`,new m({color:S,dim:!0}))];if(R)u.push(new C(" (current)",new m({color:j?X.selectionForeground:Y.success})));return new Cg4(new e1({onClick:(g)=>this.handleItemClick(A,g.clickCount),child:new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,u)})})}),(g)=>{this.itemContexts[A]=g})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],L=F?new i0({padding:C0.all(1),child:new CR({threads:O,autofocus:!1,offsetY:2})}):null,E;if(z){let M=L?new k1({child:L}):new I0({width:Pg4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(L)M.push(new k1({child:L}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class yJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yJ._instance)yJ._instance=new yJ;return yJ._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()}}g0();class Sg4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.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(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new a2({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(F,q,W,U)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new m({color:H})),new C(N,new m({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new m({color:H}))})})},filterItem:(F,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(q);let U=q.trim().toLowerCase();return U.length===0||F.name.includes(U)},sortItems:(F,q,W)=>{let U="__isCreateMarker"in F.item&&F.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!D)return-1;if(!U&&D)return 1;return q.score-F.score}})}}class d01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Sg4}}class lz extends l0{props;constructor(J){super();this.props=J}createState(){return new kg4}}class kg4 extends d0{_spinner=new M3;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=c1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new $0({textAlign:"center",text:new C("",void 0,[new C(K,new m({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new m({color:Q.foreground}))])}),G=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)G.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new m({dim:!0}),[new C("Press ",new m({color:Q.foreground})),new C("Esc",new m({color:Q.info})),new C(" to cancel",new m({color:Q.foreground}))])})})}));let F=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ra={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"}},LG0=["workspace","global","flag","default","external","skill","other"];function DI3(J){return Array.from(new Set(J))}function yg4(J){return DI3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function Tv(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 yg4(J).length>0?"skill":"other"}function c01(J){return Tv(J)==="skill"}function vg4(J){let Z=yg4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=Tv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ra[Y].description}: ${Q}`}function xg4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var fg4=process.platform==="win32"?" ":"█",ug4=process.platform==="win32"?"░":"█";class O9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=fg4,thumbChar:K=ug4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createState(){return new bg4}}class bg4 extends d0{_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 K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),z=Math.max(1,X*V),G=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-z,q=Math.max(0,F*G),W=q+z;return J>=q&&J<=W}_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(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,K*z),F=K-G;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,D=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,V*z),F=Q-Y,q=V-G,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),D=U+G;if(Z>=U&&Z<=D)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new e1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?b5.POINTER:b5.DEFAULT,child:new hg4({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 hg4 extends Ck{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=fg4,thumbChar:K=ug4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new gg4(this)}updateRenderObject(J){J.updateWidget(this)}}class gg4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!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:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,z=this._widget.thumbColor,G=process.platform==="win32",F=Y,q=Y+X;if(!G){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let D="█",H=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);D=W[N]||"█",H=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);D=W[N]||"█"}else if(U>F&&U<q)H=!1;J.setChar(Z,Q+U,D,{fg:z,bg:V,reverse:H},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,D=U>=F&&U<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,H,{fg:D?z:V,bg:V,reverse:!1},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))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class TR extends l0{props;constructor(J){super();this.props=J}createState(){return new mg4}}class mg4 extends d0{scrollController=new A5;scrollAreaKey=new d7("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 n2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=az0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new m({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new m({color:Z.colors.foreground})),selectable:!0}),G=new k1({child:new m$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new T6({controller:this.scrollController,autofocus:!0,child:z})}),new O9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),D=q+U;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new m({color:Z.colors.foreground,dim:!0})),new C("R",new m({color:Z.app.keybind})),new C(" to retry, ",new m({color:Z.colors.foreground,dim:!0})),new C("Esc",new m({color:Z.app.keybind})),new C(" to cancel",new m({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new m({color:Z.colors.foreground,dim:!0}));if(q==="help"){let W=new m({color:Z.app.keybind}),U=new m({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",W),new C(" to close • Use ",U),new C("↑↓",W),new C(" or ",U),new C("j/k",W),new C(" to scroll",U)])}return new C("Press any key to close",new m({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),G,F]})})})}}P2();class pg4 extends l0{props;constructor(J){super();this.props=J}createState(){return new dg4}}class dg4 extends d0{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=_9.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 m({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((G)=>G.status==="active").length,V=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new m({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${z} ${d4(z,"tool")})`,new m({dim:!0})));Y.push(new C(`
7375
7375
 
7376
7376
  `));for(let G of this.plugins){let{icon:F,color:q}=this.statusIcon(G.status),W=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${F} `,new m({color:q}))),Y.push(new C(W,new m({bold:!0}))),Y.push(new C(` ${G.status}`,new m({dim:!0}))),Y.push(new C(`
7377
7377
  `)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new m({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new m({color:Q.link}))),Y.push(new C(`
@@ -7600,7 +7600,7 @@ ${X0.content||""}`:X0.content||"",J1=[],H1=X0.baseDir.startsWith("file://")?YF0(
7600
7600
  `),process.exit(1)}process.stdout.write(await QS3(G.result.displayText)+`
7601
7601
  `),process.exit(0)})}rM();import{stdout as YS3}from"node:process";function XS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${AF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function kc4(J){YS3.write(`${XS3(J)}
7602
7602
  `)}function yc4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{kc4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{kc4(Z),process.exit(0)})}var Ix3=_O.join(rZ,"logs","headless.log"),N51=_O.join(Pk,"device-id.json");async function Px3(){for(let J of DE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => z4(Yx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){M7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7603
- `)}function Cx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function r2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")oJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")oJ("experimental.agentMode",Z.mode)}function qa4(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 Tx3(J){try{return await Ga4(J,"utf-8")}catch{return J}}async function w51(J,Z,Q){let Y=qa4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!A51(X,C7.HARNESS_SYSTEM_PROMPT)&&!Wa4(K))throw new I1("You are not allowed to do this.",1);oJ("systemPrompt",await Tx3(Y))}function Wa4(J){return!!(J&&x10(J))}function A51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function O51(J){return(J.userEmail?JJ(J.userEmail):!1)||A51(J.features,C7.DTW_TUI)}function Ja4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new I1("This TUI mode is not enabled for your user;",1)}function L51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return O51({userEmail:Z.user.email,features:Z.features})}function E51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function _x3(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 aF0(J){let Y=_x3(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 I1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Za4(J){if(!X5.write(J))await Mx3(X5,"drain")}var Qa4=[{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??AK,description:`Custom settings file path (overrides the default location ${AK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${nA})`},{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:b2(),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:fG.SMART.key,description:`Set the agent mode (${AV().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:AV().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{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:"threadActors",long:"thread-actors",type:"optional-option",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",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}],Ya4=(J)=>("deprecated"in J)&&J.deprecated===!0,Sx3=(J)=>("hidden"in J)&&J.hidden===!0,kx3=(J)=>("default"in J),yx3=(J)=>("default"in J)?J.default:void 0,Ua4=[{name:"toggle-skills-count",entryPoint:qi0}];function vx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new I1(L3.unknownCommand(Q),1,V)}}async function j51(J){return{...J,getThreadEnvironment:BZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new gV(J.fileSystem),generateThreadTitle:Z90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>JQ(J.configService),pluginService:J.pluginService}}function Da4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:BZ,filesystem:J.fileSystem,threadService:J.threadService}}var oF0=X1.file(Fa4.homedir()),M51=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(oF0,".config");function xx3(J){return IW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){RW4(Z);let Q=$Y0(),Y=Ii0();if((!Q||Y||kM4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(XD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(XD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve($Y0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function fx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function t9(J,Z,Q){let Y=Q?.deferAuth??!1;_f1("0.0.1774195348-g48946d");let X=a10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(X1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:oF0,userConfigDir:M51});SM4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
7603
+ `)}function Cx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function r2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")oJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")oJ("experimental.agentMode",Z.mode)}function qa4(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 Tx3(J){try{return await Ga4(J,"utf-8")}catch{return J}}async function w51(J,Z,Q){let Y=qa4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!A51(X,C7.HARNESS_SYSTEM_PROMPT)&&!Wa4(K))throw new I1("You are not allowed to do this.",1);oJ("systemPrompt",await Tx3(Y))}function Wa4(J){return!!(J&&x10(J))}function A51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function O51(J){return(J.userEmail?JJ(J.userEmail):!1)||A51(J.features,C7.DTW_TUI)}function Ja4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new I1("This TUI mode is not enabled for your user;",1)}function L51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return O51({userEmail:Z.user.email,features:Z.features})}function E51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function _x3(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 aF0(J){let Y=_x3(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 I1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Za4(J){if(!X5.write(J))await Mx3(X5,"drain")}var Qa4=[{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??AK,description:`Custom settings file path (overrides the default location ${AK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${nA})`},{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:b2(),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:fG.SMART.key,description:`Set the agent mode (${AV().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:AV().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{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:"threadActors",long:"thread-actors",type:"optional-option",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",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}],Ya4=(J)=>("deprecated"in J)&&J.deprecated===!0,Sx3=(J)=>("hidden"in J)&&J.hidden===!0,kx3=(J)=>("default"in J),yx3=(J)=>("default"in J)?J.default:void 0,Ua4=[{name:"toggle-skills-count",entryPoint:qi0}];function vx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new I1(L3.unknownCommand(Q),1,V)}}async function j51(J){return{...J,getThreadEnvironment:BZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new gV(J.fileSystem),generateThreadTitle:Z90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>JQ(J.configService),pluginService:J.pluginService}}function Da4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:BZ,filesystem:J.fileSystem,threadService:J.threadService}}var oF0=X1.file(Fa4.homedir()),M51=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(oF0,".config");function xx3(J){return IW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){RW4(Z);let Q=$Y0(),Y=Ii0();if((!Q||Y||kM4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(XD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(XD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve($Y0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function fx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function t9(J,Z,Q){let Y=Q?.deferAuth??!1;_f1("0.0.1774240952-g432b79");let X=a10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(X1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:oF0,userConfigDir:M51});SM4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
7604
7604
  `);let a=await ux3(J),q0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:a,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!a)await lF(),process.exit(1);V=!0}}{let F0=await X.getLatest(),a=F0.settings.url,q0=F0.secrets.isSet?.[a];P.info("Config secrets state after login",{configURL:a,apiKeySet:q0?.apiKey??!1})}let z=M1(JQ(X).pipe(L5((F0)=>F0!=="pending"))),G=Y?"pending":await z;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(G),isError:mW(G),errorMessage:mW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=LW4({configService:X}),W=new Map,U=()=>W.clear(),D=new P_0(X,J.settings.getWorkspaceRootPath()),H=Tt1({configService:X,filesystem:E8}),B=ja1({configService:X,trustStore:D,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(F0,a,q0)=>{let O0=`${F0}:${a}`,G0=W.get(O0);if(G0)return P.debug("Reusing existing OAuth provider for server",{serverName:F0,serverUrl:a}),G0;P.debug("Creating OAuth provider for server",{serverName:F0,serverUrl:a});let e=(async()=>{let U0=new AE(J.secrets),i=await U0.getClientInfo(F0,a),o=q0?.scopes??i?.scopes,t=qO4();P.info("OAuth headless mode check",{useHeadless:t,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:X5.isTTY});let Z0;if(t)Z0=J.executeMode?FO4():GO4(F0);let X0=new VI0({storage:U0,serverName:F0,serverUrl:a,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:o,headlessAuthHandler:Z0});return P.debug("OAuth provider created",{serverName:F0,serverUrl:a,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:o,headlessMode:t,executeMode:J.executeMode}),X0})();return W.set(O0,e),e}}),N=Tm0({configService:X,filesystem:E8,spawn:VJ0}),w;if(J.executeMode){let F0=await jG4({toolService:F,providers:[B,N],initialTimeout:15000});w=F0.registrations;for(let[a,q0]of F0.initErrors)P.warn(`${a} provider initialization slow or failed:`,q0)}else w=_m0({toolService:F,providers:[B,N]});if(Z.jetbrains)FE("JetBrains");else if(Z.ide&&oO4())FE("VS Code");else if(Z.ide&&rO4())FE("Neovim");else if(Z.ide){let F0=await Px3();if(F0){let a=Q40(F0.ideName);if(a)FE(a)}}if(J.executeMode)Sf1(!0);let O,L=w$.status.pipe(W1((F0)=>Boolean(F0.connected&&F0.authenticated&&F0.ideName&&Hu1(F0.ideName))),y4()).subscribe((F0)=>{if(F0){if(!O)O=F.registerTool(AG4)}else O?.dispose(),O=void 0}),E;if(!J.executeMode){let F0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new pZ0(process.cwd(),{alwaysIncludePaths:F0},!0)}else E=new class extends pZ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await xt1({isDevelopment:!1}),A=new Py0(M,X),j=new wk0(M,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=Z.takeMeBack?!1:void 0,k=L51(R,G),S=Boolean(k||Z.headless);if(S)P.info("DTW mode enabled: thread sync service disabled");let u=S?fx3():W04({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),g;w$.status.subscribe((F0)=>{g=F0});let x=new nj0({workspaceRoots:[X1.file(process.cwd())],fileSystem:E8,getCurrentFile:()=>{if(!g?.openFile)return;try{return X1.parse(g.openFile)}catch(F0){P.warn("Failed to parse current file URI",{uri:g.openFile,error:F0});return}},getOpenFiles:()=>{if(!g?.visibleFiles?.length)return[];let F0=g.openFile;return g.visibleFiles.filter((a)=>a!==F0).map((a)=>{try{return X1.parse(a)}catch(q0){return P.warn("Failed to parse visible file URI",{uri:a,error:q0}),null}}).filter((a)=>a!==null)}}),T=new Ti0,f=process.env.PLUGINS??"off",p=Z.headless?HM4():void 0,d=p??new aQ0({configService:X}),h=d instanceof aQ0?d:void 0;if(h)h.pluginExecutorKind=k?"local":"unknown";let n=d_0({configService:X,fileSystem:E8,platform:d,internalPlugins:Ua4,pluginFilter:f}),c=wo1({pluginService:n,toolService:F}),s={codebaseContextService:x,configService:X,toolService:F,mcpService:B,skillService:H,toolboxService:N,trustStore:D,threadService:A,threadHistoryService:j,threadSyncService:u,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:E8,terminal:T,pluginService:n,pluginPlatform:h,headlessPluginPlatform:p,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let F0 of w.values())F0.dispose();await s.mcpService.dispose(),U(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),q(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),L.unsubscribe(),O?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function ux3(J){if(!J.executeMode){if(!await lQ0("Would you like to log in to Amp? [(y)es, (n)o]: "))return X5.write(`Login cancelled. Run the command again to retry.
7605
7605
  `),!1}return await Ha4(J)}async function Ha4(J){let Z=Ex3(32).toString("hex"),Q=await fk(J.ampURL,Z),Y=new AbortController;try{await LV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await fk(J.ampURL,Z,!1);X5.write(`If your browser does not open automatically, visit:
7606
7606
 
@@ -7608,7 +7608,7 @@ ${c0.blue.bold(X)}
7608
7608
 
7609
7609
  `);try{return await aE4(J.ampURL,Z,J.secrets,Y),X5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),M7.write(`
7610
7610
  Login failed: ${K instanceof Error?K.message:String(K)}
7611
- `),!1}}function Xa4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function bx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new I1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!f9(Y.threadId))throw new I1("Create response did not include a valid thread ID",1);return Y.threadId}function hx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function gx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new I1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!hx3(Q))throw new I1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function mx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function px3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new I1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function dx3(){let J=new cN().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)oA(),process.exit(0);let B=H.originalError??H;Hw4(B)}),yc4(J,{version:"0.0.1774195348-g48946d",buildTimestamp:"2026-03-22T16:06:01.558Z",buildType:"'release'"}),J.addHelpText("after",iO4()),J.configureHelp({formatHelp:nO4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await rx3(w)}),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 N=B.optsWithGlobals(),w=await m3(N);await ox3(w,await ql0(N,w.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,N)=>{let w=N.optsWithGlobals(),O=await m3(w);await mw4(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 N=B.optsWithGlobals(),w=await m3(N);await pw4(w.ampURL,w.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",`
7611
+ `),!1}}function Xa4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function bx3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new I1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!f9(Y.threadId))throw new I1("Create response did not include a valid thread ID",1);return Y.threadId}function hx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function gx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new I1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!hx3(Q))throw new I1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function mx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function px3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new I1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function dx3(){let J=new cN().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)oA(),process.exit(0);let B=H.originalError??H;Hw4(B)}),yc4(J,{version:"0.0.1774240952-g432b79",buildTimestamp:"2026-03-23T04:46:09.725Z",buildType:"'release'"}),J.addHelpText("after",iO4()),J.configureHelp({formatHelp:nO4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await rx3(w)}),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 N=B.optsWithGlobals(),w=await m3(N);await ox3(w,await ql0(N,w.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,N)=>{let w=N.optsWithGlobals(),O=await m3(w);await mw4(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 N=B.optsWithGlobals(),w=await m3(N);await pw4(w.ampURL,w.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",`
7612
7612
  Actions:
7613
7613
  create Create a new DTW thread and print its ID
7614
7614
  add-message <message> Send a user message and wait for message_added
@@ -7672,8 +7672,8 @@ ${E}
7672
7672
 
7673
7673
  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 cx3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Rn({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:BZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new gV(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function lx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await mk()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await mk()).trimEnd(),stdinInput:null}}function ix3(J,Z,Q){if(J.remote&&!Z)throw new I1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new I1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new I1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new I1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new I1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new I1("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 I1("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"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new I1("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"
7674
7674
  Or pipe via stdin: echo "your message" | amp --execute`)}async function rF0(J,Z,Q){let Y=process.hrtime.bigint(),X=(G0,e)=>{let U0=Number(process.hrtime.bigint()-e)/1e6,i=HU4();P.info("Startup phase",{phase:G0,phaseMs:Math.round(U0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await lx3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;ix3({...Z,streamJson:z},J.executeMode,K),r2(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&!Z.threadActors&&F;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let W=await t9(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let U=await j51(W);X("runMainThread:createWorkerDeps",G);let{serverStatus:D}=W;if(!q&&mW(D)){let G0=Ok(Error(D.error.message));if(G0.message===L3.networkOffline||G0.message===L3.networkTimeout)throw aF0(J.ampURL);throw new I1(L3.invalidAPIKey,1)}let H=m6(D)?D:null,B=H?.user.email,N=Wa4(B),w=O51({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,L=H!==null&&L51(O,H);if(!q)await w51(Q,Z,D);let E=E51(D),M=E?.features??[],A=E?.team??null,j=iQ0(Z,E);if(j instanceof Error)p3(j.message);if((J.executeMode||z)&&w8(Z.mode)&&!N)throw new I1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!iH(Z.mode,B))throw new I1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await wM4(K,V,W.configService),await W.asyncDispose(),process.exit(0);if(Z.threadActors){if(!B||!JJ(B))throw new I1("Thread-actors mode is only available for Amp employees",1);let G0=await W.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new I1("API key required. Please run `amp login` first.",1);let e=typeof Z.threadActors==="string"&&Z.threadActors!=="true"?Z.threadActors:void 0;await g_4({configService:W.configService,apiKey:G0,threadId:e}),await W.asyncDispose(),await lF(),process.exit(0)}if(Z.headless){if(!B||!JJ(B))throw new I1("Headless DTW mode is only available for Amp employees",1);let G0=await W.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new I1("API key required for headless mode. Please run `amp login` first.",1);let e=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(e&&!f9(e))throw new I1(`Invalid thread ID: ${e}`,1);let U0=e??await Yf3({dependencies:W,visibility:j??void 0}),i=await HO4(U0);if(i.status==="already-running")await W.asyncDispose(),await lF(),process.exit(0);try{await zO4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:U0,initialToolDiscovery:Promise.all([W.mcpService.initialized,W.toolboxService.initialized]).then(()=>{return}),configService:W.configService,mcpService:W.mcpService,toolService:W.toolService,skillService:W.skillService,fileSystem:W.fileSystem,pluginService:W.pluginService,pluginPlatform:W.headlessPluginPlatform})}finally{await i.release(),await W.asyncDispose()}await lF(),process.exit(0)}let R=J.executeMode?void 0:async(G0)=>mo(G0,"interactive"),k={threadService:W.threadService,workerDeps:U,createThread:async()=>{let G0=q?await W.serverStatusPromise:D,e=await PZ0(J.settings,process.cwd(),E51(G0),j);if(e instanceof Error)p3(e.message);return Se0(U,{threadMeta:e?Ez(e):void 0,agentMode:Z.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(G0,e)=>{if(e?.nonBlockingOwnershipCheck){Ka4(G0,W.configService).catch((U0)=>{if(U0 instanceof I1){if(e.onOwnershipError){e.onOwnershipError(U0,G0);return}Lk(U0,G0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})});return}try{await Ka4(G0,W.configService)}catch(U0){if(U0 instanceof I1)throw U0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:R},S=async(G0)=>{try{if(G0==="dtw")return cx3({ampURL:J.ampURL,configService:W.configService,threadService:W.threadService,mcpService:W.mcpService,toolboxService:W.toolboxService,toolService:W.toolService,skillService:W.skillService,fileSystem:W.fileSystem,threadId:Z.threadId});return qu4(k,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(e){if(e instanceof I1)throw e;throw await Lk(e,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")M7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7675
- `),await lF(),process.exit(1);let u=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await W.configService.getLatest(),e=Ob(G0),U0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout(e)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),x=!J.executeMode?new Pr0:null,T,f=null;if(x)T=x,f=(async()=>{let G0=q?await W.serverStatusPromise:W.serverStatus;await w51(Q,Z,G0);let e=process.hrtime.bigint(),U0=L51(O,G0),i=m6(G0)?O51({userEmail:G0.user.email,features:G0.features}):!1;Ja4({dtwEnabled:U0,hasV2TUIAccess:i});let o=await S(U0?"dtw":"worker");if(X("runMainThread:createThreadPool",e),x.attach(o),K){let t=await M1(o.threadHandles$);if(!t)throw new I1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(G0)=>{let e=G0 instanceof Error?G0:Error(String(G0));x.setInitError(e),await Lk(G0,Z.threadId)});else G=process.hrtime.bigint(),Ja4({dtwEnabled:L,hasV2TUIAccess:w}),T=await S(L?"dtw":"worker"),X("runMainThread:createThreadPool",G);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),xx3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>T.threadHandles$.pipe(q4((G0)=>{if(!G0)return k0.of({});return V5(G0.thread$,G0.threadViewState$).pipe(W1(([e,U0])=>({[e.id]:U0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){KM4(W.mcpService,J.settings);let G0={userInput:K,stdinInput:V,dependencies:W,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},e=await Iw4({threadPool:T,...G0});if(await mo(e,"execute"),Z.archive)await g6.archiveThread({thread:e,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Eu1();let G0=await BE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let e=G0[0];if(e)w$.selectConfig(e)}else n=!0}G=process.hrtime.bigint();let c=Sl0("0.0.1774195348-g48946d",W.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let s=new Nk0(W.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let F0=new Fi0(W.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),K&&J.executeMode){let G0=await M1(T.threadHandles$);if(!G0)throw new I1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:K}]})}G=process.hrtime.bigint();let a=await rQ0();X("runMainThread:loadSessionState",G),P.info("Loaded session state:",a);let q0={...a,launchCount:a.launchCount+1};Gj((G0)=>({...G0,launchCount:G0.launchCount+1}));let O0=Z.threadId&&f9(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await $b4({codebaseContextService:W.codebaseContextService,history:new nc0,fuzzyServer:W.fuzzyServer,settingsStorage:W.settingsStorage,threadService:W.threadService,threadHistoryService:W.threadHistoryService,threadFuzzyIndexer:s,skillService:W.skillService,configService:W.configService,secretStorage:W.secretStorage,internalAPIClient:g6,threadPool:T,createSystemPromptDeps:async()=>Da4(W),ideClient:w$,mcpService:W.mcpService,toolboxService:W.toolboxService,mcpTrustHandler:F0,updateService:c,pluginPlatform:W.pluginPlatform,pluginService:W.pluginService},{initialServerStatus:W.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:W.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:O0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:u,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-22T16:06:01.558Z"},(G0)=>new ce0({...G0,threadPool:G0.threadPool},(e)=>new d41({...e,threadState:e.threadState}))),X("runMainThread:mountApp-returned",G),f)await f}finally{}await W.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)M7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7676
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Ta1({get:async(z)=>{if(z!==Ug)return;try{let G=await Ga4(N51,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Ug)return;await za4(_O.dirname(N51),{recursive:!0}),await Ax3(N51,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});kf1(Y);let X=await CO4({...J,workspaceTrust:{current:!0,changes:Jb},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 YM4(J.mcpConfig);X=XM4(X,z)}let K=_O.dirname(X.getSettingsFilePath());jW4(Pk,K);let V=await X.get("url","global");if(!V)V=V2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!EV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Mf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:AM4(await ql0(J,X))}}function nx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function ax3(){DU4();let J=nx3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));PN4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Ix3: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)c0.level=0;if(Cx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774195348-g48946d",buildTimestamp:"2026-03-22T16:06:01.558Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new I1(L3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await dx3().parseAsync(process.argv)}MW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ax3().catch(Lk)});async function ox3(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"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7675
+ `),await lF(),process.exit(1);let u=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await W.configService.getLatest(),e=Ob(G0),U0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout(e)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),x=!J.executeMode?new Pr0:null,T,f=null;if(x)T=x,f=(async()=>{let G0=q?await W.serverStatusPromise:W.serverStatus;await w51(Q,Z,G0);let e=process.hrtime.bigint(),U0=L51(O,G0),i=m6(G0)?O51({userEmail:G0.user.email,features:G0.features}):!1;Ja4({dtwEnabled:U0,hasV2TUIAccess:i});let o=await S(U0?"dtw":"worker");if(X("runMainThread:createThreadPool",e),x.attach(o),K){let t=await M1(o.threadHandles$);if(!t)throw new I1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(G0)=>{let e=G0 instanceof Error?G0:Error(String(G0));x.setInitError(e),await Lk(G0,Z.threadId)});else G=process.hrtime.bigint(),Ja4({dtwEnabled:L,hasV2TUIAccess:w}),T=await S(L?"dtw":"worker"),X("runMainThread:createThreadPool",G);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),xx3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>T.threadHandles$.pipe(q4((G0)=>{if(!G0)return k0.of({});return V5(G0.thread$,G0.threadViewState$).pipe(W1(([e,U0])=>({[e.id]:U0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){KM4(W.mcpService,J.settings);let G0={userInput:K,stdinInput:V,dependencies:W,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},e=await Iw4({threadPool:T,...G0});if(await mo(e,"execute"),Z.archive)await g6.archiveThread({thread:e,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Eu1();let G0=await BE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let e=G0[0];if(e)w$.selectConfig(e)}else n=!0}G=process.hrtime.bigint();let c=Sl0("0.0.1774240952-g432b79",W.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let s=new Nk0(W.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let F0=new Fi0(W.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),K&&J.executeMode){let G0=await M1(T.threadHandles$);if(!G0)throw new I1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:K}]})}G=process.hrtime.bigint();let a=await rQ0();X("runMainThread:loadSessionState",G),P.info("Loaded session state:",a);let q0={...a,launchCount:a.launchCount+1};Gj((G0)=>({...G0,launchCount:G0.launchCount+1}));let O0=Z.threadId&&f9(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await $b4({codebaseContextService:W.codebaseContextService,history:new nc0,fuzzyServer:W.fuzzyServer,settingsStorage:W.settingsStorage,threadService:W.threadService,threadHistoryService:W.threadHistoryService,threadFuzzyIndexer:s,skillService:W.skillService,configService:W.configService,secretStorage:W.secretStorage,internalAPIClient:g6,threadPool:T,createSystemPromptDeps:async()=>Da4(W),ideClient:w$,mcpService:W.mcpService,toolboxService:W.toolboxService,mcpTrustHandler:F0,updateService:c,pluginPlatform:W.pluginPlatform,pluginService:W.pluginService},{initialServerStatus:W.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:W.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:O0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:u,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-23T04:46:09.725Z"},(G0)=>new ce0({...G0,threadPool:G0.threadPool},(e)=>new d41({...e,threadState:e.threadState}))),X("runMainThread:mountApp-returned",G),f)await f}finally{}await W.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)M7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7676
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Ta1({get:async(z)=>{if(z!==Ug)return;try{let G=await Ga4(N51,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Ug)return;await za4(_O.dirname(N51),{recursive:!0}),await Ax3(N51,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:vG()});kf1(Y);let X=await CO4({...J,workspaceTrust:{current:!0,changes:Jb},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 YM4(J.mcpConfig);X=XM4(X,z)}let K=_O.dirname(X.getSettingsFilePath());jW4(Pk,K);let V=await X.get("url","global");if(!V)V=V2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!EV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Mf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:AM4(await ql0(J,X))}}function nx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function ax3(){DU4();let J=nx3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));PN4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Ix3: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)c0.level=0;if(Cx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774240952-g432b79",buildTimestamp:"2026-03-23T04:46:09.725Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new I1(L3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await dx3().parseAsync(process.argv)}MW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ax3().catch(Lk)});async function ox3(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"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7677
7677
  `);else if(!EV(J.ampURL))X5.write(`Logging in to ${new URL(J.ampURL).hostname}
7678
7678
  `);let Y=process.env.AMP_API_KEY;if(Y)X5.write(`API key found in environment variable, storing...
7679
7679
  `),await Z.set("apiKey",Y,J.ampURL),X5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1774195348-g48946d",
3
+ "version": "0.0.1774240952-g432b79",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {