@sourcegraph/amp 0.0.1772724405-g1c19f6 → 0.0.1772727221-g52e1a8

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
@@ -5882,11 +5882,11 @@ password=${U}
5882
5882
  `)}m0();b9();x50();mj();function _E(J){return J.toolUseId}function eO5(J){return J.parentToolUseId}function F80(J){let Z=_E(J);return{id:J.id||Z,toolCallId:Z,toolName:J.toolName,args:J.args,reason:J.reason,toAllow:J.toAllow,context:J.context,subagentToolName:J.subagentToolName,parentToolCallId:eO5(J),timestamp:J.timestamp,matchedRule:J.matchedRule,ruleSource:J.ruleSource}}tw();d5();f4();Y4();H1();VE();f4();async function tY4(J){let Z=await p$(),Q=v8(J)?J:Y8(),Y=await Dv0({filesystem:e6},Z,Q);return{...Z,...Y,updatedAt:new Date().toISOString()}}function $E5(J){return new TextEncoder().encode(JSON.stringify(J)).length}function Rm(J,Z,Q){if(J.length===0)return[];let Y=[],X=[];for(let U of J){let K=[...X,U],V=$E5(Q(K));if(X.length>0&&V>Z){Y.push(X),X=[U];continue}X=K}if(X.length>0)Y.push(X);return Y}var JE5=1048576;function ZE5(J){return{name:J.name,description:J.description??"",inputSchema:{type:"object",properties:J.inputSchema.properties??{},required:J.inputSchema.required,additionalProperties:J.inputSchema.additionalProperties},meta:{serial:J.executionProfile?.serial,disableTimeout:J.meta?.disableTimeout,hiddenFromDefaultListing:J.meta?.hiddenFromDefaultListing}}}function eY4(J){return J.map(ZE5)}function $X4(J,Z=JE5){return Rm(J,Z,(Q)=>({type:"executor_tools_register",tools:Q}))}import{execFile as QE5}from"node:child_process";import{basename as YE5}from"node:path";import YX4 from"node:process";import{promisify as XE5}from"node:util";var UE5=XE5(QE5),KE5=20971520,VE5=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],W80=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff","--binary"],DE5=999999,JX4="refs/remotes/origin/",zE5=20;function Pm(J){return J.replace(/\n+$/,"")}var hu0=YX4.platform==="win32"?"NUL":"/dev/null";function qE5(J=YX4.env,Z={}){let{isolateGitConfig:Q=!0}=Z,Y={...J};if(Q){for(let X of Object.keys(Y))if(VE5.includes(X)||X.startsWith("GIT_CONFIG_KEY_")||X.startsWith("GIT_CONFIG_VALUE_"))delete Y[X];Y.GIT_CONFIG_NOSYSTEM="1",Y.GIT_CONFIG_SYSTEM=hu0,Y.GIT_CONFIG_GLOBAL=hu0}return Y}function ZX4(J,Z){return{provider:"git",capturedAt:J,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,fullDiff:"",files:[],unavailableReason:Z}}function GE5(J){return J instanceof Error}async function Cm(J,Z,Q){try{let{stdout:Y}=await UE5("git",Z,{cwd:J,env:qE5(),maxBuffer:KE5});return Y}catch(Y){if(Q?.allowExitCodeOne&&GE5(Y)&&(Y.code===1||Y.code==="1")&&typeof Y.stdout==="string")return Y.stdout;throw Y}}async function $H(J,Z){try{return await Cm(J,Z)}catch{return null}}function FE5(J){if(J==="??")return"untracked";let Z=J[0]??" ",Q=J[1]??" ";if(Z==="U"||Q==="U"||J==="AA"||J==="DD")return"unmerged";if(Z==="R"||Q==="R")return"renamed";if(Z==="C"||Q==="C")return"copied";if(Z==="A"||Q==="A")return"added";if(Z==="D"||Q==="D")return"deleted";if(Z==="T"||Q==="T")return"type_changed";return"modified"}function WE5(J){let Z=[],Q=J.split("\x00");for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X||X.length<4)continue;let U=X.slice(0,2),K=X.slice(3);if(!K)continue;let V=FE5(U);if(V==="renamed"||V==="copied"){let D=Q[Y+1];if(D){Z.push({path:K,previousPath:D,changeType:V}),Y+=1;continue}}Z.push({path:K,changeType:V})}return Z.sort((Y,X)=>Y.path.localeCompare(X.path))}function HE5(J){let Z=0,Q=0,Y=0;for(let X of J.split(`
5883
5883
  `)){if(X.startsWith("+")&&!X.startsWith("+++"))Z+=1;if(X.startsWith("-")&&!X.startsWith("---"))Q+=1;if(X.startsWith("@@"))Y+=1}return{added:Z,deleted:Q,changed:Y}}async function QX4(J,Z,Q,Y){let X=Y!==void 0?[`--unified=${Y}`]:[];if(Q)return Cm(J,[...W80,...X,"HEAD","--",Z]);let[U,K]=await Promise.all([Cm(J,[...W80,...X,"--cached","--",Z]).catch(()=>""),Cm(J,[...W80,...X,"--",Z]).catch(()=>"")]);return[Pm(U),Pm(K)].filter(Boolean).join(`
5884
5884
  `)}async function BE5(J,Z){return Cm(J,[...W80,"--no-index","--",hu0,Z],{allowExitCodeOne:!0})}function wE5(J){let Z=Number.parseInt(J.trim(),10);if(!Number.isFinite(Z))return null;return Z}async function NE5(J){let Z=(await $H(J,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Z?.startsWith(JX4))return null;let Q=Z.slice(JX4.length);if(!Q)return null;let Y=`origin/${Q}`,U=(await $H(J,["rev-parse","--verify","--quiet",`${Y}^{commit}`]))?.trim();if(!U)return null;return{baseRef:Q,comparisonRef:Y,baseRefHead:U}}function OE5(J){let Z=J.split("\x00"),Q=[];for(let Y=0;Y+1<Z.length;Y+=2){let X=Z[Y],U=Z[Y+1]??"";if(!X)continue;Q.push({hash:X,shortHash:X.slice(0,12),subject:U})}return Q}async function EE5(J,Z){let Q=await $H(J,["log","-z",`--max-count=${zE5}`,"--format=%H%x00%s",`${Z}..HEAD`]);if(!Q)return[];return OE5(Q)}async function LE5(J,Z){if(!Z)return null;let Q=await NE5(J);if(!Q)return null;let Y=await $H(J,["rev-list","--count",`${Q.comparisonRef}..HEAD`]);if(!Y)return null;let X=wE5(Y);if(X===null)return null;return{baseRef:Q.baseRef,comparisonRef:Q.comparisonRef,baseRefHead:Q.baseRefHead,aheadCount:X}}async function H80(J){let Z=Date.now(),Q=await $H(J,["rev-parse","--show-toplevel"]);if(!Q)return ZX4(Z,"not a git repository");let Y=Q.trim(),X=YE5(Y),[U,K,V]=await Promise.all([$H(Y,["rev-parse","--verify","HEAD"]),$H(Y,["symbolic-ref","--short","HEAD"]),$H(Y,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(V===null)return ZX4(Z,"failed to read git status");let D=U?.trim()||null,z=K?.trim()||null,q=WE5(V),G=await LE5(Y,D),F=G?.aheadCount&&G.aheadCount>0?await EE5(Y,G.comparisonRef):[],W=[];for(let B of q){let w=Pm(B.changeType==="untracked"?await BE5(Y,B.path).catch(()=>""):await QX4(Y,B.path,D).catch(()=>"")),N=Pm(B.changeType==="modified"?await QX4(Y,B.path,D,DE5).catch(()=>""):w);W.push({path:B.path,previousPath:B.previousPath,changeType:B.changeType,created:B.changeType==="added"||B.changeType==="untracked",diff:w,fullFileDiff:N,diffStat:HE5(w)})}let H=W.map((B)=>Pm(B.diff)).filter(Boolean).join(`
5885
- `);return{provider:"git",capturedAt:Z,available:!0,repositoryRoot:Y,repositoryName:X,branch:z,head:D,baseRef:G?.baseRef??null,baseRefHead:G?.baseRefHead??null,aheadCount:G?.aheadCount??0,aheadCommits:F,fullDiff:H,files:W}}var XX4=1048576;function UX4(J,Z,Q,Y=XX4){return Rm(J,Y,(X)=>({type:"executor_guidance_snapshot",snapshotId:Z,files:X,isLast:!1,userConfigDir:Q}))}function B80(J,Z,Q=XX4){return Rm(J,Q,(Y)=>({type:"executor_guidance_discovery",toolCallId:Z,files:Y,isLast:!1}))}function IE5(J){if(J==="darwin")return"darwin";if(J==="win32")return"windows";return"linux"}async function ME5(J){let Z=await J.getLatest();return iB0(Z.settings)}async function w80(J){let{transport:Z,threadId:Q,configService:Y,skillService:X,logMessage:U}=J,K=J.fileSystem??e6,V=J.resumeFromVersion??0,D=await L1(J.toolService.tools),z=eY4(D.map((W)=>W.spec)),G={settings:await ME5(Y),workspaceId:J.workspaceRoot,workingDirectory:J.workspaceRoot,environment:{os:IE5(process.platform)},tags:[]};U?.("SEND",{type:"executor_connect",clientId:J.executorClientID,capabilities:G,executorType:J.executorType});let F=await Z.executorHandshake(J.executorClientID,G,{executorType:J.executorType});U?.("RECV",F);try{if(Q){let W=await tY4(Q);U?.("SEND",{type:"executor_environment_snapshot",environment:W}),Z.sendEnvironmentSnapshot(W);let H={trees:W.trees,platform:W.platform,tags:W.tags};await AE5(Z,K,Y,H,U)}await jE5(Z,X,U);for(let W of $X4(z))U?.("SEND",{type:"executor_tools_register",tools:W.map((H)=>H.name)}),Z.registerTools(W);if(U?.("SEND",{type:"client_resume",version:V}),Z.resumeFromVersion(V),J.sendGitSnapshot!==!1)try{let W=await H80(J.workspaceRoot);U?.("SEND",{type:"executor_git_status",available:W.available,fileCount:W.files.length,branch:W.branch,head:W.head}),Z.sendExecutorGitStatus(W)}catch{}U?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Z.sendExecutorToolsBootstrapComplete(!0)}catch(W){let H=W instanceof Error?W.message:String(W);throw U?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:H}),Z.sendExecutorToolsBootstrapComplete(!1,H),W}}function N80(J,Z,Q){let Y=iB0(Z.settings),X=JSON.stringify(Y);if(X===Q)return Q;let U=J.getConnectionInfo();if(U.state!=="connected"||U.role!=="executor")return Q;try{return J.sendExecutorSettingsUpdate(Y),X}catch{return Q}}async function AE5(J,Z,Q,Y,X){let K=(await tK({filesystem:Z,configService:Q,threadService:{observe:()=>v0.of({id:Y8(),created:Date.now(),v:0,messages:[],env:{initial:Y}})}},{messages:[],env:{initial:Y}})).filter((q)=>q.type!=="subtree").map((q)=>({uri:q.uri,content:q.content,lineCount:q.content.split(`
5885
+ `);return{provider:"git",capturedAt:Z,available:!0,repositoryRoot:Y,repositoryName:X,branch:z,head:D,baseRef:G?.baseRef??null,baseRefHead:G?.baseRefHead??null,aheadCount:G?.aheadCount??0,aheadCommits:F,fullDiff:H,files:W}}var XX4=1048576;function UX4(J,Z,Q,Y=XX4){return Rm(J,Y,(X)=>({type:"executor_guidance_snapshot",snapshotId:Z,files:X,isLast:!1,userConfigDir:Q}))}function B80(J,Z,Q=XX4){return Rm(J,Q,(Y)=>({type:"executor_guidance_discovery",toolCallId:Z,files:Y,isLast:!1}))}function IE5(J){if(J==="darwin")return"darwin";if(J==="win32")return"windows";return"linux"}async function ME5(J){let Z=await J.getLatest();return iB0(Z.settings)}async function w80(J){let{transport:Z,threadId:Q,configService:Y,skillService:X,logMessage:U}=J,K=J.fileSystem??e6,V=J.resumeFromVersion??0,D=await L1(J.toolService.tools),z=eY4(D.map((W)=>W.spec)),G={settings:await ME5(Y),workspaceId:J.workspaceRoot,workingDirectory:J.workspaceRoot,environment:{os:IE5(process.platform)},tags:[]};U?.("SEND",{type:"executor_connect",clientId:J.executorClientID,capabilities:G,executorType:J.executorType});let F=await Z.executorHandshake(J.executorClientID,G,{executorType:J.executorType});U?.("RECV",F);try{if(Q){let W=await tY4(Q);U?.("SEND",{type:"executor_environment_snapshot",environment:W}),Z.sendEnvironmentSnapshot(W);let H={trees:W.trees,platform:W.platform,tags:W.tags};await AE5(Z,K,Y,H,U)}await jE5(Z,X,U);for(let W of $X4(z))U?.("SEND",{type:"executor_tools_register",tools:W.map((H)=>H.name)}),Z.registerTools(W);if(J.subscribeToThreadEvents!==!1)U?.("SEND",{type:"client_resume",version:V}),Z.resumeFromVersion(V);if(J.sendGitSnapshot!==!1)try{let W=await H80(J.workspaceRoot);U?.("SEND",{type:"executor_git_status",available:W.available,fileCount:W.files.length,branch:W.branch,head:W.head}),Z.sendExecutorGitStatus(W)}catch{}U?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Z.sendExecutorToolsBootstrapComplete(!0)}catch(W){let H=W instanceof Error?W.message:String(W);throw U?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:H}),Z.sendExecutorToolsBootstrapComplete(!1,H),W}}function N80(J,Z,Q){let Y=iB0(Z.settings),X=JSON.stringify(Y);if(X===Q)return Q;let U=J.getConnectionInfo();if(U.state!=="connected"||U.role!=="executor")return Q;try{return J.sendExecutorSettingsUpdate(Y),X}catch{return Q}}async function AE5(J,Z,Q,Y,X){let K=(await tK({filesystem:Z,configService:Q,threadService:{observe:()=>v0.of({id:Y8(),created:Date.now(),v:0,messages:[],env:{initial:Y}})}},{messages:[],env:{initial:Y}})).filter((q)=>q.type!=="subtree").map((q)=>({uri:q.uri,content:q.content,lineCount:q.content.split(`
5886
5886
  `).length})),V=crypto.randomUUID(),D=Q.userConfigDir?d1(Q.userConfigDir):void 0;if(K.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:V,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:V,files:[],isLast:!0,userConfigDir:D});return}let z=UX4(K,V,D);for(let q=0;q<z.length;q++){let G=z[q];if(!G)continue;let F=q===z.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:V,fileCount:G.length,isLast:F}),J.sendExecutorGuidanceSnapshot({snapshotId:V,files:G,isLast:F,userConfigDir:D})}}async function jE5(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),U=20,K=Y.map((V)=>({name:V.name,description:V.description,baseDir:V.baseDir,frontmatter:V.frontmatter,files:V.files}));if(K.length===0){Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:0,isLast:!0}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:[],isLast:!0});return}for(let V=0;V<K.length;V+=20){let D=K.slice(V,V+20),z=V+20>=K.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:D.length,isLast:z}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:D,isLast:z})}}function RE5(){let J=()=>{return},Z=()=>{return};return{promise:new Promise((Y,X)=>{J=Y,Z=X}),resolve:J,reject:Z}}class Tm{options;inFlight=null;readyWaiter=null;retryTimer=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;constructor(J){this.options=J;this.baseDelayMs=J.baseDelayMs??1000,this.maxDelayMs=J.maxDelayMs??30000,this.maxAttempts=J.maxAttempts??5}ensureHandshake(J){return this.tryHandshake(J)}ensureReady(){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=RE5();return this.tryHandshake("connect"),this.readyWaiter.promise}handleConnectionChange(J){if(this.lastInfo=J,J.state!=="connected"){this.reset("disconnected");return}if(J.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){let J=this.readyWaiter;if(!J)return;this.readyWaiter=null,J.resolve()}rejectReadyWaiter(J){let Z=this.readyWaiter;if(!Z)return;this.readyWaiter=null,Z.reject(J)}reset(J){this.generation++,this.attempt=0,this.clearRetryTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}tryHandshake(J){if(this.disposed||this.inFlight)return this.inFlight;let Z=this.generation,Q=this.options.handshake(J);return this.inFlight=Q,Q.then(()=>{if(this.disposed||Z!==this.generation)return;this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch((Y)=>{if(this.disposed||Z!==this.generation)return;this.scheduleRetry(J,Y)}).finally(()=>{if(this.inFlight===Q)this.inFlight=null}),Q}scheduleRetry(J,Z){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;if(this.attempt+=1,this.attempt>=this.maxAttempts){this.clearRetryTimer(),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Z}),this.rejectReadyWaiter(Z instanceof Error?Z:Error("Executor handshake failed and exhausted retries"));return}let Q=Math.min(this.baseDelayMs*2**(this.attempt-1),this.maxDelayMs);this.clearRetryTimer(),this.options.onError?.({trigger:J,attempt:this.attempt,delayMs:Q,error:Z}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},Q)}}I$();import{createHash as PE5}from"node:crypto";class _m{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;lastGitStatusCapturedAt=0;lastGitStatusSignature=null;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(J){this.options=J;this.clientID=J.clientID,this.transport=J.transport}async handleToolLease(J){if(this.disposing)return;let{toolCallId:Z,toolName:Q,args:Y}=J;this.options.log.info(`${this.clientID} executing tool: ${Q}`,{toolCallId:Z}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Z}),this.transport.ackToolLease(Z);let X=this.options.executeBuiltinTool(Q,Y);if(X){let D=X.ok?{status:"done",result:X.content}:{status:"error",error:{message:X.content}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:D}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,D),{toolCallId:Z}),this.queueGitStatusSnapshot(Z);return}let U=new AbortController,K={subscription:{unsubscribe:()=>{}},abortController:U};this.activeTools.set(Z,K);let V=()=>{this.activeTools.delete(Z)};try{let z=(await this.options.invokeTool(J)).subscribe({next:(q)=>{if(U.signal.aborted)return;if(q.status==="in-progress"&&q.progress!==void 0)this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:q.progress}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,q.progress),{toolCallId:Z});if(F8(q))this.sendToolResult(Z,q),V(),z.unsubscribe();if(q.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(q)=>{if(U.signal.aborted){V();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,q);let G={status:"error",error:{message:q instanceof Error?q.message:"Unknown error"}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:G}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,G),{toolCallId:Z}),this.queueGitStatusSnapshot(Z),V()}});K.subscription=z}catch(D){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,D);let z={status:"error",error:{message:D instanceof Error?D.message:String(D)}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:z}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,z),{toolCallId:Z}),this.queueGitStatusSnapshot(Z),V()}}handleToolRevocation(J){if(this.disposing)return;let{toolCallId:Z,reason:Q}=J;this.options.log.info(`${this.clientID} lease revoked: ${Z}`,{reason:Q});let Y=this.activeTools.get(Z);if(Y)Y.abortController.abort(),Y.subscription.unsubscribe(),this.activeTools.delete(Z);this.sentApprovalRequests.delete(Z),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_revocation_ack",toolCallId:Z}),this.sendTransportMessage("executor_revocation_ack",()=>this.transport.sendRevocationAck(Z),{toolCallId:Z})}async handleRollbackRequest(J,Z,Q){if(this.disposing)return;try{if(Z.length>0)await Q(new Set(Z));this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!0}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!0),{editId:J}),this.queueGitStatusSnapshot()}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.options.log.error(`${this.clientID} rollback failed`,Y),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!1,error:X}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!1,X),{editId:J})}}triggerGitStatus(J){this.queueGitStatusSnapshot(J)}dispose(){this.disposing=!0;for(let[,J]of this.activeTools)J.abortController.abort(),J.subscription.unsubscribe();this.activeTools.clear()}sendToolResult(J,Z){let Q=this.toToolRun(Z),{run:Y,files:X}=this.extractGuidanceFromRun(Q);if(X.length>0)this.sendGuidanceDiscovery(J,X);this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:Y}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,Y),{toolCallId:J}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}sendGuidanceDiscovery(J,Z){let Q=this.options.batchGuidanceFiles(Z,J);for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X)continue;let U=Y===Q.length-1;if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:J,fileCount:X.length,isLast:U}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:J,files:X,isLast:U}),{toolCallId:J,isLast:U,fileCount:X.length}))return}}queueGitStatusSnapshot(J){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,J)this.gitStatusQueue.queuedToolCallId=J;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(J).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Z=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Z)})}async sendGitStatusSnapshot(J){try{if(!this.options.captureGitStatus)return;let Z=await this.options.captureGitStatus(),Q=Math.max(Z.capturedAt,this.lastGitStatusCapturedAt+1),Y=Q===Z.capturedAt?Z:{...Z,capturedAt:Q},X=this.buildGitStatusSignature(Y),U=X!==null&&X===this.lastGitStatusSignature&&Y.available;if(this.lastGitStatusCapturedAt=Y.capturedAt,U){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_git_status",available:Y.available,fileCount:Y.files.length,toolCallId:J,branch:Y.branch,head:Y.head,note:"unchanged"}),this.transport.sendExecutorGitStatus({...Y,unchanged:!0,fullDiff:"",files:Y.files.map((K)=>({...K,diff:"",fullFileDiff:""}))},J);return}this.lastGitStatusSignature=X,this.options.log.wsMessage("SEND",this.clientID,{type:"executor_git_status",available:Y.available,fileCount:Y.files.length,toolCallId:J,branch:Y.branch,head:Y.head}),this.transport.sendExecutorGitStatus(Y,J)}catch(Z){this.options.log.error("Failed to send git status snapshot",Z)}}buildGitStatusSignature(J){if(!J.available)return`unavailable:${J.unavailableReason??"unknown"}`;let Z=J.files.map((Y)=>[Y.path,Y.changeType,Y.previousPath??"",Y.diff.length,Y.fullFileDiff?.length??0]),Q=JSON.stringify({repositoryRoot:J.repositoryRoot,branch:J.branch,head:J.head,baseRef:J.baseRef??null,baseRefHead:J.baseRefHead??null,aheadCount:J.aheadCount??0,aheadCommitHashes:(J.aheadCommits??[]).map((Y)=>Y.hash),fullDiff:J.fullDiff,files:Z});return PE5("sha256").update(Q).digest("hex")}toToolRun(J){switch(J.status){case"done":return{status:"done",result:J.result,trackFiles:J.trackFiles?[...J.trackFiles]:void 0};case"error":return{status:"error",error:{message:J.error?this.options.renderToolRunError(J.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:J.reason};case"cancelled":return{status:"cancelled",reason:J.reason};default:return{status:"error",error:{message:`Unexpected status: ${J.status}`}}}}extractGuidanceFromRun(J){if(J.status!=="done")return{run:J,files:[]};if(!J.result||typeof J.result!=="object"||Array.isArray(J.result))return{run:J,files:[]};let Z=J.result;if(!("discoveredGuidanceFiles"in Z))return{run:J,files:[]};let Q=GY4(Z.discoveredGuidanceFiles),{discoveredGuidanceFiles:Y,...X}=Z;return{run:{...J,result:X},files:Q}}sendTransportMessage(J,Z,Q){try{return Z(),!0}catch(Y){if(Y instanceof o2)return this.options.log.info(`${this.clientID} dropped ${J} while reconnecting`,{messageType:J,...Q}),this.options.onTransportSendFailure?.(this.clientID,J,Y,Q),!1;return this.options.log.error(`${this.clientID} failed to send ${J}`,Y),!1}}}MX();Qv0();mj();y50();f4();Y4();H1();async function JH(J){let{toolName:Z,threadID:Q,configService:Y,toolService:X,mcpService:U,skillService:K,fsTracker:V,toolUseID:D,discoveredGuidanceFileURIs:z}=J,q={id:Q??Y8(),created:Date.now(),v:0,messages:[]},G=G1.file(process.cwd()),F=D??kK(),W=await Y.getLatest(),H,B;if(V)H=V.trackedFileSystem(F),B=V.tracker;else B=k50(WM0,q.id,async()=>{}),H=u50(e6,B,F);return{dir:G,dirs:[G],tool:Z,thread:q,trackedFiles:new LJ,toolUseID:F,todos:void 0,configService:Y,toolService:X,mcpService:U,config:W,filesystem:H,fileChangeTracker:B,getAllTrackedChanges:async()=>B.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>v0.of(q),get:()=>Promise.resolve(q)},threadSyncService:void 0,getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:e6,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:WM0,discoveredGuidanceFileURIs:z??new Set,skillService:K??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}function mu0(){return new Date().toISOString()}var gu0=process.stderr.isTTY;function CE5(J){let Z=J.trim();if(!(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")))return null;try{return JSON.parse(Z)}catch{return null}}function pu0(J){if(J instanceof Error)return J.stack??J.message;if(typeof J==="string"){let Z=CE5(J);if(Z!==null)return JSON.stringify(Z,null,2);return J}if(J===void 0)return"";try{return JSON.stringify(J,null,2)}catch{return String(J)}}function b8(J,Z,Q){if(P.info("[headless-dtw] websocket message",{direction:J,clientId:Z,...typeof Q==="object"&&Q!==null?Q:{message:Q}}),!gu0)return;let Y=J1.dim(`[${mu0()}]`),X=J1.magenta(`[${Z}]`),U=J==="SEND"?J1.green(">>>"):J1.yellow("<<<"),K=pu0(Q);process.stderr.write(`${Y} ${X} ${U} ${K}
5887
5887
  `)}function c$(J,Z){if(Z)P.info(`[headless-dtw] ${J}`,Z);else P.info(`[headless-dtw] ${J}`);if(!gu0)return;let Q=J1.dim(`[${mu0()}]`),Y=J1.cyan("[INFO]"),X=Z?` ${pu0(Z)}`:"";process.stderr.write(`${Q} ${Y} ${J}${X}
5888
5888
  `)}function jU(J,Z){if(Z!==void 0)P.error(`[headless-dtw] ${J}`,{error:Z});else P.error(`[headless-dtw] ${J}`);if(!gu0)return;let Q=J1.dim(`[${mu0()}]`),Y=J1.red("[ERROR]"),X=pu0(Z);process.stderr.write(`${Q} ${Y} ${J} ${X}
5889
- `)}function TE5(J){let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCode=J.code;if(J.reason)Z.reconnectReason=J.reason;if(J.error)Z.reconnectError=J.error;return Z}class KX4{options;clients=new Map;clientCounter=0;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;resolveRunLoop=null;constructor(J){this.options=J}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,c$(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{X.transport.disconnect(),await X.transport.connect();let U=X.transport.getThreadId();if(U)X.threadId=U;X.handshakeManager.ensureHandshake("retry")}catch(U){jU(`${J} transport recovery failed`,U)}finally{X.recoveringTransport=!1}}async start(){c$("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??Wq(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null});try{let J=await this.createClient(this.options.threadId);if(c$("Initial client created",{clientId:J.id,threadId:J.threadId}),J.threadId){let Q=new URL(this.options.ampURL);if(!Q.pathname.endsWith("/"))Q.pathname+="/";let Y=new URL(`threads/${J.threadId}`,Q).toString();c$(`Thread URL: ${J1.blue.underline(Y)}`)}let Z=await this.runLoop();if(Z!==0)throw Error(`Headless DTW harness exited with code ${Z}`)}catch(J){throw jU("Failed to start harness",J),J}}shutdown(J,Z){if(!this.disposed){if(J===0)c$(Z);else jU(Z);this.dispose()}if(this.resolveRunLoop){let Q=this.resolveRunLoop;this.resolveRunLoop=null,Q(J);return}if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:U}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:K,toolCallId:V,args:D}=Z,z=await JH({toolName:K,threadID:J.threadId??void 0,configService:Y,toolService:Q,mcpService:X,skillService:U,fsTracker:J.fsTracker??void 0,toolUseID:V,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs}),q=typeof D==="object"&&D!==null?D:{};return Q.invokeTool(K,{args:q},z)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??Wq(this.options.ampURL);c$(`Creating client ${Z}`,{threadId:J??"new",workerUrl:Y});let X=new tW({baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}),U,K=new _m({clientID:Z,transport:X,executeBuiltinTool:()=>null,invokeTool:(z)=>this.invokeToolForClient(U,z),captureGitStatus:()=>H80(this.options.workspaceRoot),batchGuidanceFiles:B80,renderToolRunError:ax,onTransportSendFailure:(z,q,G,F)=>{this.recoverTransport(z,q,G,F)},log:{info:c$,error:jU,wsMessage:b8}}),V=this.createHandshakeManager(()=>U,Z);U={id:Z,transport:X,threadId:J??null,executorClientId:Q,handshakeManager:V,toolRunner:K,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1},this.clients.set(Z,U),this.subscribeToTransportEvents(U),c$(`Connecting ${Z}...`),await X.connect();let D=X.getThreadId();if(U.threadId=D,c$(`Connected ${Z}`,{threadId:D}),D){let z=this.options.fileSystem??e6,q=new nX(z);U.fsTracker=iP({fileChangeTrackerStorage:q},z,D)}return U.handshakeManager.ensureHandshake("connect"),U}async connectAsExecutor(J,Z){c$(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null,await w80({transport:J.transport,executorClientID:J.executorClientId,workspaceRoot:this.options.workspaceRoot,threadId:J.threadId,resumeFromVersion:0,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,executorType:"sandbox",logMessage:(Q,Y)=>{b8(Q,J.id,Y)}}),this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw jU(`${J.id} executor bootstrap failed`,Q),Q}}setNotifyForwarder(J){let Z=this.options.pluginPlatform;if(!Z)return;Z.setNotifyForwarder(async(Q)=>{let Y={type:"event",event:"ui.notify",data:{message:Q}};try{b8("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){jU(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,c$(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Tm({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{jU(`${Z} executor handshake failed`,{error:Q,attempt:Y,delayMs:X})},onExhausted:({error:Q,maxAttempts:Y})=>{this.shutdown(1,`${Z} executor handshake failed after ${Y} attempts: ${Q instanceof Error?Q.message:String(Q)}`)}})}startSettingsSync(J){if(J.settingsSubscription)return;J.settingsSubscription=this.options.configService.config.subscribe({next:(Z)=>{J.lastSentSettingsJSON=N80(J.transport,Z,J.lastSentSettingsJSON)}})}syncApprovalRequests(J,Z){if(!J.threadId)return;let Q=Z.filter((X)=>X.threadId===J.threadId||X.mainThreadId===J.threadId),Y=new Set(Q.map(_E));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let U=_E(X);if(J.toolRunner.sentApprovalRequests.has(U))continue;let K=F80(X);b8("SEND",J.id,{type:"executor_tool_approval_request",toolCallId:K.toolCallId,toolName:K.toolName}),J.transport.sendExecutorToolApprovalRequest(K),J.toolRunner.sentApprovalRequests.add(U)}}handleExecutorToolApprovalResponse(J,Z){let{toolService:Q}=this.options;if(!Q){jU(`${J.id} received approval response without tool service`);return}c$(`${J.id} approval resolved`,{toolCallId:Z.toolCallId,accepted:Z.accepted}),Q.resolveApproval(Z.toolCallId,Z.accepted)}subscribeToTransportEvents(J){let{transport:Z,id:Q}=J;Z.deltas().subscribe({next:(X)=>b8("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.connectionChanges().subscribe({next:(X)=>{let K={role:X.role??"unclaimed"};if(X.state==="reconnecting"&&X.reconnectCause)Object.assign(K,TE5(X.reconnectCause));c$(`${Q} connection: ${X.state}`,K),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{b8("RECV",Q,X),jU(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.toolLeases().subscribe({next:(X)=>{b8("RECV",Q,X),J.toolRunner.handleToolLease(X)}}),Z.toolLeaseRevoked().subscribe({next:(X)=>{b8("RECV",Q,X),J.toolRunner.handleToolRevocation(X)}}),Z.toolApprovalQueue().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{b8("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{b8("RECV",Q,X),jU(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.executorRollbackRequests().subscribe({next:(X)=>{b8("RECV",Q,X),this.handleExecutorRollbackRequest(J,X)}}),Z.messageEdited().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>b8("RECV",Q,X)});let{toolService:Y}=this.options;if(Y)Y.pendingApprovals$.subscribe((X)=>{this.syncApprovalRequests(J,X)})}async handleExecutorRollbackRequest(J,Z){let{id:Q,fsTracker:Y}=J,{editId:X,toolUseIdsToRevert:U}=Z;if(!Y){jU(`${Q} rollback failed: no file tracker`),b8("SEND",Q,{type:"executor_rollback_ack",editId:X,ok:!1,error:"File tracker not initialized"}),J.transport.sendExecutorRollbackAck(X,!1,"File tracker not initialized");return}await J.toolRunner.handleRollbackRequest(X,U,(K)=>Y.tracker.revertChanges(K))}async runLoop(){if(c$("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((J)=>{let Z=!1,Q=(U)=>{if(Z){c$(`Received ${U} while shutdown is already in progress`);return}Z=!0,this.shutdown(0,`Received ${U}, shutting down harness...`)},Y=()=>Q("SIGINT"),X=()=>Q("SIGTERM");this.resolveRunLoop=(U)=>{process.off("SIGINT",Y),process.off("SIGTERM",X),J(U)},process.on("SIGINT",Y),process.on("SIGTERM",X)})}getClients(){return Array.from(this.clients.values())}dispose(){this.disposed=!0,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values())J.toolRunner.dispose(),J.settingsSubscription?.unsubscribe(),J.handshakeManager.dispose(),J.transport.dispose();this.clients.clear()}}async function VX4(J){await new KX4(J).start()}import{stderr as RU,stdin as vE5}from"node:process";import{createInterface as kE5}from"node:readline";import{stdout as _E5}from"node:process";function SE5(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function O80(){if(!_E5.isTTY)return!0;if(SE5())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var E80=[],du0=null;function cu0(J){if(du0=J,J&&E80.length>0){for(let Z of E80)J(Z);E80=[]}}function DX4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let U={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(du0)du0(U);else E80.push(U)})}}function zX4(){return async(J,Z)=>{return RU.write(`
5889
+ `)}function TE5(J){let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCode=J.code;if(J.reason)Z.reconnectReason=J.reason;if(J.error)Z.reconnectError=J.error;return Z}class KX4{options;clients=new Map;clientCounter=0;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;resolveRunLoop=null;constructor(J){this.options=J}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,c$(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{X.transport.disconnect(),await X.transport.connect();let U=X.transport.getThreadId();if(U)X.threadId=U;X.handshakeManager.ensureHandshake("retry")}catch(U){jU(`${J} transport recovery failed`,U)}finally{X.recoveringTransport=!1}}async start(){c$("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??Wq(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null});try{let J=await this.createClient(this.options.threadId);if(c$("Initial client created",{clientId:J.id,threadId:J.threadId}),J.threadId){let Q=new URL(this.options.ampURL);if(!Q.pathname.endsWith("/"))Q.pathname+="/";let Y=new URL(`threads/${J.threadId}`,Q).toString();c$(`Thread URL: ${J1.blue.underline(Y)}`)}let Z=await this.runLoop();if(Z!==0)throw Error(`Headless DTW harness exited with code ${Z}`)}catch(J){throw jU("Failed to start harness",J),J}}shutdown(J,Z){if(!this.disposed){if(J===0)c$(Z);else jU(Z);this.dispose()}if(this.resolveRunLoop){let Q=this.resolveRunLoop;this.resolveRunLoop=null,Q(J);return}if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:U}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:K,toolCallId:V,args:D}=Z,z=await JH({toolName:K,threadID:J.threadId??void 0,configService:Y,toolService:Q,mcpService:X,skillService:U,fsTracker:J.fsTracker??void 0,toolUseID:V,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs}),q=typeof D==="object"&&D!==null?D:{};return Q.invokeTool(K,{args:q},z)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??Wq(this.options.ampURL);c$(`Creating client ${Z}`,{threadId:J??"new",workerUrl:Y});let X=new tW({baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}),U,K=new _m({clientID:Z,transport:X,executeBuiltinTool:()=>null,invokeTool:(z)=>this.invokeToolForClient(U,z),captureGitStatus:()=>H80(this.options.workspaceRoot),batchGuidanceFiles:B80,renderToolRunError:ax,onTransportSendFailure:(z,q,G,F)=>{this.recoverTransport(z,q,G,F)},log:{info:c$,error:jU,wsMessage:b8}}),V=this.createHandshakeManager(()=>U,Z);U={id:Z,transport:X,threadId:J??null,executorClientId:Q,handshakeManager:V,toolRunner:K,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1},this.clients.set(Z,U),this.subscribeToTransportEvents(U),c$(`Connecting ${Z}...`),await X.connect();let D=X.getThreadId();if(U.threadId=D,c$(`Connected ${Z}`,{threadId:D}),D){let z=this.options.fileSystem??e6,q=new nX(z);U.fsTracker=iP({fileChangeTrackerStorage:q},z,D)}return U.handshakeManager.ensureHandshake("connect"),U}async connectAsExecutor(J,Z){c$(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null,await w80({transport:J.transport,executorClientID:J.executorClientId,workspaceRoot:this.options.workspaceRoot,threadId:J.threadId,resumeFromVersion:0,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,subscribeToThreadEvents:!1,executorType:"sandbox",logMessage:(Q,Y)=>{b8(Q,J.id,Y)}}),this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw jU(`${J.id} executor bootstrap failed`,Q),Q}}setNotifyForwarder(J){let Z=this.options.pluginPlatform;if(!Z)return;Z.setNotifyForwarder(async(Q)=>{let Y={type:"event",event:"ui.notify",data:{message:Q}};try{b8("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){jU(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,c$(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Tm({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{jU(`${Z} executor handshake failed`,{error:Q,attempt:Y,delayMs:X})},onExhausted:({error:Q,maxAttempts:Y})=>{this.shutdown(1,`${Z} executor handshake failed after ${Y} attempts: ${Q instanceof Error?Q.message:String(Q)}`)}})}startSettingsSync(J){if(J.settingsSubscription)return;J.settingsSubscription=this.options.configService.config.subscribe({next:(Z)=>{J.lastSentSettingsJSON=N80(J.transport,Z,J.lastSentSettingsJSON)}})}syncApprovalRequests(J,Z){if(!J.threadId)return;let Q=Z.filter((X)=>X.threadId===J.threadId||X.mainThreadId===J.threadId),Y=new Set(Q.map(_E));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let U=_E(X);if(J.toolRunner.sentApprovalRequests.has(U))continue;let K=F80(X);b8("SEND",J.id,{type:"executor_tool_approval_request",toolCallId:K.toolCallId,toolName:K.toolName}),J.transport.sendExecutorToolApprovalRequest(K),J.toolRunner.sentApprovalRequests.add(U)}}handleExecutorToolApprovalResponse(J,Z){let{toolService:Q}=this.options;if(!Q){jU(`${J.id} received approval response without tool service`);return}c$(`${J.id} approval resolved`,{toolCallId:Z.toolCallId,accepted:Z.accepted}),Q.resolveApproval(Z.toolCallId,Z.accepted)}subscribeToTransportEvents(J){let{transport:Z,id:Q}=J;Z.deltas().subscribe({next:(X)=>b8("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.connectionChanges().subscribe({next:(X)=>{let K={role:X.role??"unclaimed"};if(X.state==="reconnecting"&&X.reconnectCause)Object.assign(K,TE5(X.reconnectCause));c$(`${Q} connection: ${X.state}`,K),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{b8("RECV",Q,X),jU(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.toolLeases().subscribe({next:(X)=>{b8("RECV",Q,X),J.toolRunner.handleToolLease(X)}}),Z.toolLeaseRevoked().subscribe({next:(X)=>{b8("RECV",Q,X),J.toolRunner.handleToolRevocation(X)}}),Z.toolApprovalQueue().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{b8("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{b8("RECV",Q,X),jU(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.executorRollbackRequests().subscribe({next:(X)=>{b8("RECV",Q,X),this.handleExecutorRollbackRequest(J,X)}}),Z.messageEdited().subscribe({next:(X)=>b8("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>b8("RECV",Q,X)});let{toolService:Y}=this.options;if(Y)Y.pendingApprovals$.subscribe((X)=>{this.syncApprovalRequests(J,X)})}async handleExecutorRollbackRequest(J,Z){let{id:Q,fsTracker:Y}=J,{editId:X,toolUseIdsToRevert:U}=Z;if(!Y){jU(`${Q} rollback failed: no file tracker`),b8("SEND",Q,{type:"executor_rollback_ack",editId:X,ok:!1,error:"File tracker not initialized"}),J.transport.sendExecutorRollbackAck(X,!1,"File tracker not initialized");return}await J.toolRunner.handleRollbackRequest(X,U,(K)=>Y.tracker.revertChanges(K))}async runLoop(){if(c$("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((J)=>{let Z=!1,Q=(U)=>{if(Z){c$(`Received ${U} while shutdown is already in progress`);return}Z=!0,this.shutdown(0,`Received ${U}, shutting down harness...`)},Y=()=>Q("SIGINT"),X=()=>Q("SIGTERM");this.resolveRunLoop=(U)=>{process.off("SIGINT",Y),process.off("SIGTERM",X),J(U)},process.on("SIGINT",Y),process.on("SIGTERM",X)})}getClients(){return Array.from(this.clients.values())}dispose(){this.disposed=!0,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values())J.toolRunner.dispose(),J.settingsSubscription?.unsubscribe(),J.handshakeManager.dispose(),J.transport.dispose();this.clients.clear()}}async function VX4(J){await new KX4(J).start()}import{stderr as RU,stdin as vE5}from"node:process";import{createInterface as kE5}from"node:readline";import{stdout as _E5}from"node:process";function SE5(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function O80(){if(!_E5.isTTY)return!0;if(SE5())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var E80=[],du0=null;function cu0(J){if(du0=J,J&&E80.length>0){for(let Z of E80)J(Z);E80=[]}}function DX4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let U={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(du0)du0(U);else E80.push(U)})}}function zX4(){return async(J,Z)=>{return RU.write(`
5890
5890
  `),RU.write(J1.yellow.bold(`OAuth Authorization Required
5891
5891
  `)),RU.write(J1.dim("─".repeat(60)+`
5892
5892
  `)),RU.write(`
@@ -6014,11 +6014,11 @@ ${W}`))}},error:(F)=>{if(!G)G=!0,V(Error(`Failed to spawn brew: ${F.message}`))}
6014
6014
  ${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
6015
6015
 
6016
6016
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6017
- npm install -g @sourcegraph/amp`;V(Error(H))}},error:(F)=>{if(!q)q=!0,V(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!q)q=!0,K()}})})}m0();m0();Hj();async function C80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,U=new AbortController,K=setTimeout(()=>U.abort(),5000);try{let V=await fetch(X,{signal:U.signal});if(!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let D=await V.json(),z=D.version??D["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=WU4(J,z),G=q<0,F,W;if(D.time){let H=D.time[J],B=D.time[z],w=Date.now();if(H)F=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:G,currentVersionAge:F,latestVersionAge:W}),{hasUpdate:G,latestVersion:z,currentVersion:J,currentVersionAge:F,latestVersionAge:W,source:"npm"}}catch(V){return P.debug("Error checking npm version",{error:V}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var XI5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function T80(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${XI5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let U=WU4(J,X),K=U<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:U,hasUpdate:K}),{hasUpdate:K,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 UI5=604800000;function FU4(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>UI5)return{ageMs:Q};return null}function WU4(J,Z){let Q=(K)=>{let[V,D]=K.split("-");return{parts:V?.split(".").map(Number)||[],label:D}},Y=Q(J),X=Q(Z),U=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<U;K++){let V=Y.parts[K]||0,D=X.parts[K]||0;if(V<D)return-1;if(V>D)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function qx0(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?LF(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function Gx0(J,Z,Q={}){let Y=new X4,X=Y.pipe(L6({shouldCountRefs:!1}));return setImmediate(async()=>{let U=new MK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await $V(K);let V=X.subscribe({next:(D)=>{U.debug("emit new state",D)}});try{let D=process.env.AMP_TEST_UPDATE_STATUS;if(D){U.debug("using fake update status for testing",{status:D}),await $V(500),Y.next(D);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){U.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){U.debug("checking disabled");return}let q=await P80(),G=q==="binary"||q==="brew";U.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:G});let F=G?await T80(J):await C80(J,yE());if(!(F.latestVersion&&F.hasUpdate)){U.debug("no update available");return}let W=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let H=F.currentVersionAge-F.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return U.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",U.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!W())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Xx0()){if(U.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!W())Y.next("update-available");return}if(!q){if(U.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(U.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await hm(F.latestVersion,q);let H=await QH(F.latestVersion),B={from:F.currentVersion,to:F.latestVersion,...H};if(H.status==="same")U.info("success",B),Y.next("updated");else U.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(D){U.debug("check failed",{error:D})}finally{await $V(5000),Y.next("hidden"),V.unsubscribe(),Y.complete()}}),{state:X}}Hj();import{stderr as dV}from"node:process";function HU4(J){let Z=new lW().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 Jx0(Y.force||!1,Y.verbose||!1,"0.0.1772724405-g1c19f6"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new lW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await KI5(Y.targetVersion)});J.addCommand(Q)}async function KI5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")dV.write(J1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6017
+ npm install -g @sourcegraph/amp`;V(Error(H))}},error:(F)=>{if(!q)q=!0,V(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!q)q=!0,K()}})})}m0();m0();Hj();async function C80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,U=new AbortController,K=setTimeout(()=>U.abort(),5000);try{let V=await fetch(X,{signal:U.signal});if(!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let D=await V.json(),z=D.version??D["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=WU4(J,z),G=q<0,F,W;if(D.time){let H=D.time[J],B=D.time[z],w=Date.now();if(H)F=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:G,currentVersionAge:F,latestVersionAge:W}),{hasUpdate:G,latestVersion:z,currentVersion:J,currentVersionAge:F,latestVersionAge:W,source:"npm"}}catch(V){return P.debug("Error checking npm version",{error:V}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var XI5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function T80(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${XI5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let U=WU4(J,X),K=U<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:U,hasUpdate:K}),{hasUpdate:K,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 UI5=604800000;function FU4(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>UI5)return{ageMs:Q};return null}function WU4(J,Z){let Q=(K)=>{let[V,D]=K.split("-");return{parts:V?.split(".").map(Number)||[],label:D}},Y=Q(J),X=Q(Z),U=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<U;K++){let V=Y.parts[K]||0,D=X.parts[K]||0;if(V<D)return-1;if(V>D)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function qx0(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?LF(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function Gx0(J,Z,Q={}){let Y=new X4,X=Y.pipe(L6({shouldCountRefs:!1}));return setImmediate(async()=>{let U=new MK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await $V(K);let V=X.subscribe({next:(D)=>{U.debug("emit new state",D)}});try{let D=process.env.AMP_TEST_UPDATE_STATUS;if(D){U.debug("using fake update status for testing",{status:D}),await $V(500),Y.next(D);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){U.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){U.debug("checking disabled");return}let q=await P80(),G=q==="binary"||q==="brew";U.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:G});let F=G?await T80(J):await C80(J,yE());if(!(F.latestVersion&&F.hasUpdate)){U.debug("no update available");return}let W=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let H=F.currentVersionAge-F.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return U.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",U.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!W())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Xx0()){if(U.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!W())Y.next("update-available");return}if(!q){if(U.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(U.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await hm(F.latestVersion,q);let H=await QH(F.latestVersion),B={from:F.currentVersion,to:F.latestVersion,...H};if(H.status==="same")U.info("success",B),Y.next("updated");else U.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(D){U.debug("check failed",{error:D})}finally{await $V(5000),Y.next("hidden"),V.unsubscribe(),Y.complete()}}),{state:X}}Hj();import{stderr as dV}from"node:process";function HU4(J){let Z=new lW().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 Jx0(Y.force||!1,Y.verbose||!1,"0.0.1772727221-g52e1a8"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new lW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await KI5(Y.targetVersion)});J.addCommand(Q)}async function KI5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")dV.write(J1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6018
6018
 
6019
6019
  `));try{if(!J){dV.write(J1.blue(`Checking for updates...
6020
- `));let{hasUpdate:Y,latestVersion:X}=Zx0()?await T80("0.0.1772724405-g1c19f6"):await C80("0.0.1772724405-g1c19f6",yE());if(!Y){let U=qx0("0.0.1772724405-g1c19f6"),K=U?.age?`released ${U.age} ago`:`built ${LF(new Date("2026-03-05T15:32:53.284Z"))} ago`;dV.write(J1.green(`✓ Amp is already up to date on version ${"0.0.1772724405-g1c19f6"} (${K})
6021
- `));let V=await QH("0.0.1772724405-g1c19f6");if(V.warning)dV.write(`
6020
+ `));let{hasUpdate:Y,latestVersion:X}=Zx0()?await T80("0.0.1772727221-g52e1a8"):await C80("0.0.1772727221-g52e1a8",yE());if(!Y){let U=qx0("0.0.1772727221-g52e1a8"),K=U?.age?`released ${U.age} ago`:`built ${LF(new Date("2026-03-05T16:19:46.573Z"))} ago`;dV.write(J1.green(`✓ Amp is already up to date on version ${"0.0.1772727221-g52e1a8"} (${K})
6021
+ `));let V=await QH("0.0.1772727221-g52e1a8");if(V.warning)dV.write(`
6022
6022
  `+J1.yellow(V.warning)+`
6023
6023
  `);process.exit(0)}if(!X)dV.write(J1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}dV.write(J1.blue(`Updating to version ${J}...
6024
6024
  `)),await hm(J,void 0,(Y)=>{dV.write(J1.dim(`Running: ${Y}
@@ -7168,7 +7168,7 @@ Ctrl-X, Y, Z to unlock`;if(F){let f=z.text.replace(/`([^`]+)`/g,"$1")+`
7168
7168
  `),U=[];for(let K=0;K<X.length;K++){let z=X[K].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))U.push(new C(q.slice(1,-1),new b({color:Y.app.keybind,bold:!0})));else U.push(new C(q,new b({color:Q.colorScheme.foreground})));if(K<X.length-1)U.push(new C(`
7169
7169
  `))}return new l0({decoration:{color:Q.colorScheme.background,border:x1.all(new k1(Y.app.keybind,1,"rounded"))},child:new o0({padding:C0.symmetric(0,1),child:new Q0({text:new C(void 0,void 0,U)})})})}}class Kg0 extends W2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=l20}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Xg0({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 aB4(J,Z,Q,Y,X,U,K){if(U<=0)return null;switch(J){case"horizontal-bar":{let V=Q;return V>=0&&V<U?V:null}case"bar":case"stacked-bar":{let V=K?g8:0,D=Y-V;if(D<=0)return null;let z=Z-V;if(z<0||z>=D)return null;let q=Math.max(1,Math.floor(D/U)),G=Math.floor(z/q);return G>=0&&G<U?G:null}case"line":case"sparkline":case"stacked-area":{let V=K?g8:0,D=Y-V;if(D<=0)return null;let z=Math.max(0,Math.min(D-1,Z-V));if(U===1)return 0;let q=D/(U-1),G=Math.round(z/q);return Math.max(0,Math.min(U-1,G))}default:return null}}function ym5(J,Z,Q,Y,X,U,K,V){if(X<=0||Z<0||Z>=X)return null;let D=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=U?g8:0,q=Q-z,G=Y-(U?D:0);if(q<=0||G<=0)return null;let F=Math.max(1,Math.floor(q/X)),W=z+Z*F+Math.floor(F/2),H=V>0?K/V:0,B=Math.round((1-H)*(G-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let z=U?g8:0,q=Q-z,G=Y-(U?D:0);if(q<=0||G<=0)return null;let F=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),W=V>0?K/V:0,H=Math.round((1-W)*(G-1));return{x:F,y:H}}default:return null}}function um5(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 xm5(J,Z,Q,Y,X){if(Q.length<=1){let V=Y(J.value),D=J.meta?` (${J.meta})`:"";return J.label.length+2+V.length+D.length}let U=J.label.length,K=0;for(let V of Q){let D=V.points[Z];if(!D)continue;K+=D.value;let z=2+V.name.length+2+Y(D.value).length;U=Math.max(U,z)}if(X){let V=9+Y(K).length;U=Math.max(U,V)}return U}function fm5(J,Z,Q,Y,X,U,K){let V;try{let H=j1.of(J),B=f0.of(J);V={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{V={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let D=new b({color:V.foreground,bold:!0}),z=new b({color:V.foreground}),q=new b({color:V.foreground,dim:!0}),G=[],F=new b({color:V.foreground,underline:!0}),W=(H,B)=>new C(B,F,void 0,p80(H),()=>{D8(J,H)});if(Y.length<=1){if(G.push(new C(`${Z.label}: `,D)),Z.link)G.push(W(Z.link,U(Z.value)));else G.push(new C(U(Z.value),z));if(Z.meta)G.push(new C(` (${Z.meta})`,q))}else{let H=K==="stacked-bar"||K==="stacked-area";G.push(new C(`${Z.label}
7170
7170
  `,D));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??X[w%X.length]??V.foreground;if(G.push(new C("● ",new b({color:E}))),G.push(new C(`${N.name}: `,q)),O.link)G.push(W(O.link,U(O.value)));else G.push(new C(U(O.value),z));if(w<Y.length-1||H)G.push(new C(`
7171
- `))}if(H)G.push(new C(" ",q)),G.push(new C("Total: ",q)),G.push(new C(U(B),z))}return new l0({decoration:{color:V.background,border:x1.all(new k1(V.border,1,"rounded"))},child:new Q0({text:new C(void 0,void 0,G)})})}m0();a9();import{execSync as Kp5}from"node:child_process";HA();OJ();L3();N7();mw();TX();P$();uJ();jX();VE();f4();Zx();tv();H1();var XN4=q4(Lz(),1);import{writeFile as $N4}from"fs/promises";import JN4 from"path";m0();P$();class Vg0{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.1772724405-g1c19f6"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Dt(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 mH extends c0{props;constructor(J){super();this.props=J}createState(){return new oB4}}class oB4 extends p0{_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 rB4 extends p0{controller=new f7;focusNode=new n4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,U=this.controller.text.trim().length>0,K=!X||U,V=x1.all(new k1(Q.foreground,1,"solid")),D=new t$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new V1({children:[new l0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new _1({child:D})]}),q=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,[new C("Command: ",new b({color:Q.foreground})),new C(this.widget.props.commandName,new b({color:Y.command,bold:!0}))])})}),G=[];if(K)G.push(new C("Enter",new b({color:Y.keybind}))),G.push(new C(" to submit, ",new b({color:Q.foreground,dim:!0})));G.push(new C("Esc",new b({color:Y.keybind}))),G.push(new C(" to cancel",new b({color:Q.foreground,dim:!0})));let F=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,G)})});return new l0({decoration:{border:V,color:Q.background},padding:C0.all(1),child:new u0({children:[q,new P0({height:1}),z,new Q3,F]})})}}class Rp extends c0{props;constructor(J){super();this.props=J}createState(){return new rB4}}import{isDeepStrictEqual as Dg0}from"node:util";var bm5=/[\\/_ +.#"@[({&]/,hm5=/[\\/_ +.#"@[({&]/g,mm5=/[\s-]/,sB4=/[\s-]/g;function a20(J,Z,Q,Y,X,U,K){if(U===Z.length){if(X===J.length)return 1;return 0.99}let V=`${X},${U}`;if(K[V]!==void 0)return K[V];let D=Y.charAt(U),z=Q.indexOf(D,X),q=0,G,F,W,H;while(z>=0){if(G=a20(J,Z,Q,Y,z+1,U+1,K),G>q){if(z===X)G*=1;else if(mm5.test(J.charAt(z-1))){if(G*=0.9,H=J.slice(X,z-1).match(sB4),H&&X>0)G*=0.999**H.length}else if(bm5.test(J.charAt(z-1))){if(G*=0.8,W=J.slice(X,z-1).match(hm5),W&&X>0)G*=0.999**W.length}else if(G*=0.3,X>0)G*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(U))G*=0.9999}if(G<0.1&&(Q.charAt(z-1)===Y.charAt(U+1)||Y.charAt(U+1)===Y.charAt(U)&&Q.charAt(z-1)!==Y.charAt(U))){if(F=a20(J,Z,Q,Y,z+1,U+2,K),F*0.1>G)G=F*0.1}if(G>q)q=G;z=Q.indexOf(D,z+1)}return K[V]=q,q}function n20(J){return J.toLowerCase().replace(sB4," ")}function tB4(J,Z){let Q=a20(J,Z,n20(J),n20(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,U=0;for(let V of Y){let D=a20(J,V,n20(J),n20(V),0,0,{});if(D===0)return Q;X+=D,U+=V.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class MT{}class AT{}class o20{}class r20{}class eB4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new $w4}}class $w4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function gm5(J,Z){if(J==="")return{matches:!0,score:1};let Q=tB4(Z,J);return{matches:Q>0.15,score:Q}}class d9 extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Jw4}}class Jw4 extends p0{textController;focusNode;scrollController=new r6;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new f7(this.widget.props.controller?.query??""),this.focusNode=new n4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Dg0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Dg0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Dg0(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 MT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof AT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof o20){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 r20)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,...gm5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,U)=>this.widget.props.sortItems(X,U,J):(X,U)=>U.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;NT(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=x1.all(new k1(Q.foreground,1,"solid")),U=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,V=new t$({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),D=new N2({shortcuts:new Map([[new $4("ArrowDown"),new MT],[new $4("ArrowUp"),new AT],[new $4("Tab"),new MT],[new $4("Tab",{shift:!0}),new AT],[new $4("n",{ctrl:!0}),new MT],[new $4("p",{ctrl:!0}),new AT],[new $4("Enter"),new o20],[new $4("Escape"),new r20]]),focusNode:this.focusNode,child:V}),z=new P9({actions:new Map([[MT,new o4(this.invoke)],[AT,new o4(this.invoke)],[o20,new o4(this.invoke)],[r20,new o4(this.invoke)]]),child:D}),q=new V1({children:[new l0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new _1({child:z})]});this.itemContexts=[];let G;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";G=new P0({height:10,child:new n1({child:new Q0({text:new C(w,new b({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)G=new _1({child:new n1({child:new Q0({text:new C(this.widget.props.emptyStateText,new b({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,I;if(this.widget.props.renderItem)I=this.widget.props.renderItem(N,E,L,J);else{let M=E?Z.app.selectionBackground:void 0,A=E?Z.app.selectionForeground:Q.foreground;I=new l0({decoration:M?{color:M}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(this.widget.props.getLabel(N),new b({color:A,dim:L}))})})}return new eB4(new i1({onClick:(M)=>this.handleItemClick(O,M.clickCount),child:I}),(M)=>{this.itemContexts[O]=M})});G=new u0({children:w,crossAxisAlignment:"start"})}let F=new i1({onScroll:this.handleScroll,opaque:!1,child:new O6({controller:this.scrollController,autofocus:!1,child:G})}),W=[];if(this.widget.props.title){let w=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C(this.widget.props.title,new b({color:Z.app.command,bold:!0}))})});W.push(w)}if(!U)W.push(q,new P0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new _1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new _1({child:F}),new l0({padding:C0.only({top:1}),child:new n1({child:N??new P0({height:1})})})]})}))}else W.push(new _1({child:F}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new l0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function Zw4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),U=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(U<7)return`${U}d ago`;return J.toLocaleDateString()}class zg0 extends p1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,U)=>U.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Zw4(X.pubDate).length));return new d9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,U,K,V)=>{let D=f0.of(V),{colors:z}=D,q=D.app,G=U?q.selectionBackground:void 0,F=U?q.selectionForeground:z.foreground,W=z.mutedForeground,H=(B,w)=>new P0({width:w,child:V1.end([new Q0({text:new C(B,new b({color:W}))})])});return new l0({decoration:G?{color:G}:void 0,padding:C0.symmetric(2,0),child:new V1({children:[new _1({child:new Q0({text:new C(X.title,new b({color:F})),overflow:"ellipsis",maxLines:1})}),new P0({width:2}),H(Zw4(X.pubDate),Q)]})})}})}}f4();class qg0 extends c0{createState(){return new Qw4}}class Qw4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new Q0({text:new C("●",new b({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var pm5=/\/threads\/(T-[^/?#\s<>]+)/i;function dm5(J){let Z=J.trim(),Y=Z.match(pm5)?.[1];if(Y&&v8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(v8(X))return X;return null}function cm5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let V=K.relationships.find((D)=>D.role==="child"&&Z.has(D.threadID)&&(D.type==="fork"||D.type==="handoff"));if(V){Y.set(K.id,V.type);let D=V.threadID,z=Q.get(D)||[];z.push(K),Q.set(D,z)}else X.push(K)}return M70.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Gg0(J,Z,Q){return new Q0({text:new C(`${J}${Z}`,new b({color:Q})),maxLines:1})}function lm5(J,Z,Q,Y){return[Gg0("+",J,Y.success),Q3.horizontal(1),Gg0("~",Z,Y.warning),Q3.horizontal(1),Gg0("-",Q,Y.destructive)]}function im5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class s20 extends c0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Yw4}}class Yw4 extends p0{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}`,U=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)U=U.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],V=new Set(K),D=Z.currentThreadID,z=[...U].sort((O,E)=>{if(D){if(O.id===D)return-1;if(E.id===D)return 1}let L=K.indexOf(O.id),I=K.indexOf(E.id);if(L!==-1&&I!==-1)return L-I;if(L!==-1)return-1;if(I!==-1)return 1;return 0}),q=cm5(z),G=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),F=f0.of(J),W=new o0({padding:C0.symmetric(0,1),child:new n1({child:new Q0({text:new C("",new b({color:F.colors.foreground,dim:!0}),[new C("Ctrl+T",new b({color:F.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new b({color:F.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=dm5(O);return B};return new d9({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!im5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,I)=>{let M=f0.of(I),{app:A,colors:R}=M,_=E?A.selectionBackground:void 0,S=E?A.selectionForeground:R.foreground,y=R.mutedForeground,h=(e,q0)=>new P0({width:q0,child:V1.end([new Q0({text:new C(e,new b({color:y}))})])}),f=Z.threadViewStates[O.id],k=[],x=O.relationshipType==="handoff",d=new ng({connectorColor:R.mutedForeground});if(O.depth>0){let e=[],q0=O.ancestorsAreLast.slice(1);for(let z0 of q0)e.push(new C(d.getAncestorPrefix(z0),new b({color:d.connectorColor,dim:d.connectorDim})));let a=O.isLast?d.elbow:d.tee,K0=d.getConnectorText(a);e.push(new C(K0,new b({color:d.connectorColor,dim:d.connectorDim}))),k.push(new Q0({text:new C("",void 0,e)}))}let l=[],m=D===O.id?new C("(current) ",new b({color:R.success})):V.has(O.id)?new C("(visited) ",new b({color:R.foreground,dim:!0})):null;if(m)l.push(new Q0({text:m}));if(SO(f))l.push(new qg0),l.push(new P0({width:1}));let o=O.title;if(O.relationshipType==="fork"){let e=o.match(/^Forked\((\d+)\): /);if(e)o=o.slice(e[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);l.push(new Q0({text:new C("[fork] ",new b({color:R.primary}))}))}else if(x)l.push(new Q0({text:new C("[handoff] ",new b({color:R.accent}))}));if(l.push(new _1({child:new Q0({text:new C(o,new b({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new P0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let e=E?{success:y,warning:y,destructive:y}:R;l.push(...lm5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,e)),l.push(new P0({width:2}))}return l.push(h(O.description.timeAgo,G)),new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new V1({children:[...k,...l]})})}})}}function Xw4(J){return 1-(1-J)**3}function Uw4(J,Z,Q){return J+(Z-J)*Q}function Pp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),U=Xw4(Y),K=Xw4(X);return{x:Uw4(J.startOffset.x,J.targetOffset.x,U),y:Uw4(J.startOffset.y,J.targetOffset.y,K)}}var nm5={nodeWidth:3,horizontalSpacing:3};class jT{options;constructor(J={}){this.options={...nm5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let U=0,K=(V,D)=>{let z=Z.get(V.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...V,parentID:Q.get(V.id)};if(z.length===0){Y.push({node:q,position:{x:U,y:D}});let B=U;return U+=this.options.nodeWidth+this.options.horizontalSpacing,B}let G=[];for(let B of z)G.push(K(B,D+1));let F=Math.min(...G),W=Math.max(...G),H=Math.floor((F+W)/2);return Y.push({node:q,position:{x:H,y:D}}),H};for(let V of X)K(V,0);return Y}buildTree(J){let Z=new Set(J.map((U)=>U.id)),Q=[...J].sort((U,K)=>U.id.localeCompare(K.id)),Y=new Map;for(let U of Q){if(!U.parentID||!Z.has(U.parentID)){Y.set(U.id,void 0);continue}let K=!1,V=U.parentID;while(V){if(V===U.id){K=!0;break}V=Y.get(V)}Y.set(U.id,K?void 0:U.parentID)}let X=new Map;for(let U of J){let K=Y.get(U.id);if(!X.has(K))X.set(K,[]);X.get(K).push(U)}return{childrenMap:X,resolvedParent:Y}}}var am5={nodeWidth:3,nodeHeight:2};class RT{options;constructor(J={}){this.options={...am5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let U=this.calculateConnectorLine(X.position,Y.position);Z.push({points:U,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,U=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let V=K+1;if(Y.push({x:X,y:V}),X!==U)Y.push({x:U,y:V});let D=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:U,y:D}),Y}}var om5={nodeWidth:3,nodeHeight:2},rm5={x:0,y:0};class e20{options;constructor(J={}){this.options={...om5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=rm5,X,U,K,V){let D=V?f0.of(V):null,z=D?.colors,q=D?.app,G=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:G}))});let F=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let A=F;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new P0({width:y.position.x-S}));let h=y.node.id===Q,f=K?.(y.node.data)??!1,k=U?.activeFlashOn??!1,x=y.node.id===U?.copyFlashNodeId;_.push(this.renderNode(h,f,k,x,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new V1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(F+1)*B,I=[new P0({width:H,height:L}),new J5({left:O,top:E,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=F-M.position.y,_=O+M.position.x+this.options.nodeWidth+1,S=E+R*B+1,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new J5({left:_,top:S,child:this.renderInfoBox(A,y,z,q)}))}return new l0({padding:C0.horizontal(2),child:new zH(new z5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X,U){let K="┌─┐",V="└─┘",D=J?X?.threadGraphNodeSelected??U?.primary??U?.foreground:X?.threadGraphNode??U?.primary??U?.foreground,z=!1;if(Y)D=X?.threadGraphNodeSelected??U?.primary??D,K="┏━┓",V="┗━┛",z=!0;else if(Z&&Q)D=X?.toolSuccess??U?.primary??D,K="┏━┓",V="┗━┛";return new u0({crossAxisAlignment:"start",children:[new Q0({text:new C(K,new b({color:D,bold:z}))}),new Q0({text:new C(V,new b({color:D,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),U=Math.min(Z,Math.max(1,...X.map((F)=>F.length))),K=U+2,V="┌"+"─".repeat(K)+"┐",D="└"+"─".repeat(K)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,G=[new Q0({text:new C(V,new b({color:z}))})];for(let F of X){let W=" ".repeat(U-F.length);G.push(new Q0({text:new C("│ ",new b({color:z}),[new C(F+W,new b({color:q??z})),new C(" │",new b({color:z}))])}))}return G.push(new Q0({text:new C(D,new b({color:z}))})),new u0({crossAxisAlignment:"start",children:G})}renderConnectors(J,Z,Q,Y,X,U){let K=[],V=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let F of Z){let W=F.position.x+V;if(W>=0&&W<Y)z[W]="▲"}K.push(new Q0({text:new C(z.join(""),new b({color:D}))}));let q=Array(Y).fill(" ");for(let F of J){let W=Z.filter((O)=>O.node.parentID===F.node.id);if(W.length===0)continue;let H=F.position.x+V,B=W.map((O)=>O.position.x+V),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)q[O]="│";else if(O===w)q[O]="└";else if(O===N)q[O]="┘";else q[O]="┬";else if(B.includes(O))if(O===w)q[O]="└";else if(O===N)q[O]="┘";else q[O]="┴";else if(q[O]===" ")q[O]="─"}}K.push(new Q0({text:new C(q.join(""),new b({color:D}))}));let G=Array(Y).fill(" ");for(let F of J){if(Z.filter((B)=>B.node.parentID===F.node.id).length===0)continue;let H=F.position.x+V;if(H>=0&&H<Y)G[H]="│"}return K.push(new Q0({text:new C(G.join(""),new b({color:D}))})),K}}var sm5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},tm5={x:0,y:0};class Fg0{options;constructor(J={}){this.options={...sm5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=tm5,X,U,K,V){let D=V?f0.of(V):null,z=D?.colors,q=D?.app,G=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:G}))});let F=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let A=F;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new P0({width:y.position.x-S}));let h=y.node.id===Q,f=K?.(y.node.data)??!1,k=U?.activeFlashOn??!1;_.push(this.renderNode(h,f,k,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new V1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(F+1)*B,I=[new P0({width:H,height:L}),new J5({left:O,top:E,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=F-M.position.y,_=O+M.position.x+this.options.nodeWidth+1,S=E+R*B,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new J5({left:_,top:S,child:this.renderInfoBox(A,y,z)}))}return new l0({padding:C0.horizontal(2),child:new zH(new z5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X){let U=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,U="■";return new Q0({text:new C(U,new b({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,U=[];for(let K of Y)U.push(new Q0({text:new C(K,new b({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,U){let K=[],V=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let G=Z.filter((w)=>w.node.parentID===q.node.id);if(G.length===0)continue;let F=q.position.x+V,W=G.map((w)=>w.position.x+V),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===F,O=W.includes(w);if(N&&O)if(G.length===1)z[w]="│";else if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┼";else if(N)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┬";else if(O)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┴";else if(z[w]===" ")z[w]="─"}}return K.push(new Q0({text:new C(z.join(""),new b({color:D}))})),K}}class Cp extends z3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Kw4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Kw4 extends E4{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 IL extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new zw4}}var Vw4=400,Dw4=300,em5=16;class zw4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new jT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new RT;renderer=new Fg0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((D)=>D.id)),Q=new Set(this.widget.props.threads.map((D)=>D.id));if(Z.size!==Q.size||[...Z].some((D)=>!Q.has(D)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,U=this.widget.props.initialSelectedThreadID;if(X!==U&&U){let z=this.widget.props.threads.find((q)=>q.id===U);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((D)=>D.isActive),V=this.widget.props.threads.some((D)=>D.isActive);if(K!==V){if(this.stopActiveFlashTimer(),V)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Vw4,durationY:Dw4};let Z=Math.max(Vw4,Dw4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Pp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},em5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),U=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,V=2,D=Math.floor(this.viewportHeight/2),q=Math.floor(D/2)-K;return{x:U,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((U)=>U.node.parentID===Q.node.id);if(X.length>0){X.sort((K,V)=>K.position.x-V.position.x);let U=Math.floor(X.length/2);Y=X[U]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x<Q.position.x);if(X.length>0)X.sort((U,K)=>K.position.x-U.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x>Q.position.x);if(X.length>0)X.sort((U,K)=>U.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((G)=>G.node.id===this.selectedNodeId):null)??this.positionedNodes.find((G)=>!G.node.parentID);if(q){let G=Math.max(...this.positionedNodes.map((F)=>F.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,G)}}let X=this.widget.props.showTitle??!0,U=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+U},V=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),D=new Cp({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:V});return new _4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:D})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Gw4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Fw4}}class Fw4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var qw4=30,$g5=30;class PT{}class CT{}class $$0{}class J$0{}class Wg0 extends c0{props;constructor(J){super();this.props=J}createState(){return new Ww4}}class Ww4 extends p0{highlightedIndex=0;controller=new f7;focusNode;scrollController=new r6;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new n4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;NT(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 PT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof CT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof $$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof J$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,V=o1.of(J).size.width>=$g5+qw4,D=x1.all(new k1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C("Select a cluster",new b({color:X.command,bold:!0}))})}),G=new t$({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),F=new N2({shortcuts:new Map([[new $4("ArrowDown"),new PT],[new $4("ArrowUp"),new CT],[new $4("Tab"),new PT],[new $4("Tab",{shift:!0}),new CT],[new $4("n",{ctrl:!0}),new PT],[new $4("p",{ctrl:!0}),new CT],[new $4("Enter"),new $$0],[new $4("Escape"),new J$0]]),focusNode:this.focusNode,child:G}),W=new P9({actions:new Map([[PT,new o4(this.invoke)],[CT,new o4(this.invoke)],[$$0,new o4(this.invoke)],[J$0,new o4(this.invoke)]]),child:F}),H=new V1({children:[new l0({decoration:{color:Y.background},child:new Q0({text:new C(">",new b({color:Y.foreground}))})}),new _1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((I,M)=>{let A=M===this.highlightedIndex,R=Z?I.threads.some((h)=>h.id===Z):!1,_=A?X.selectionBackground:void 0,S=A?X.selectionForeground:Y.foreground,y=[new C(I.label,new b({color:S})),new C(` (${I.threads.length})`,new b({color:S,dim:!0}))];if(R)y.push(new C(" (current)",new b({color:A?X.selectionForeground:Y.success})));return new Gw4(new i1({onClick:(h)=>this.handleItemClick(M,h.clickCount),child:new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,y)})})}),(h)=>{this.itemContexts[M]=h})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new _1({child:new i1({onScroll:this.handleScroll,child:new O6({controller:this.scrollController,autofocus:!1,child:w})})}),O=z?z.threads.map((I)=>({id:I.id,title:I.title,parentID:I.parentID,updatedAt:I.updatedAt})):[],E=z?new l0({padding:C0.all(1),child:new IL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(V){let I=E?new _1({child:E}):new P0({width:qw4});L=new V1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,I]})}else{let I=[new _1({child:new i1({onScroll:this.handleScroll,child:new O6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)I.push(new _1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:I})}return new l0({decoration:{border:D,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[q,H,new P0({height:1}),new _1({child:L})]})})}}class e${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!e$._instance)e$._instance=new e$;return e$._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()}}m0();class Hw4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((U)=>U.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),U=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),D=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new d9({title:"Add Label",items:D,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:U||"Type to create a new label",renderItem:(z,q,G,F)=>{let W=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,[new C("Create new label: ",new b({color:H})),new C(w,new b({color:H,bold:!0}))])})})}return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(z.name,new b({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let F=q.trim().toLowerCase();return F.length===0||z.name.includes(F)},sortItems:(z,q,G)=>{let F="__isCreateMarker"in z.item&&z.item.__isCreateMarker,W="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(F&&!W)return-1;if(!F&&W)return 1;return q.score-z.score}})}}class Hg0 extends c0{props;constructor(J){super();this.props=J}createState(){return new Hw4}}class gH extends c0{props;constructor(J){super();this.props=J}createState(){return new Bw4}}class Bw4 extends p0{_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=x1.all(new k1(Q.foreground,1,"solid")),U=this._spinner.toBraille(),K=new Q0({textAlign:"center",text:new C("",void 0,[new C(U,new b({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new b({color:Q.foreground}))])}),D=[new _1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)D.push(new P0({height:2,child:new l0({padding:C0.symmetric(2,0),child:new Q0({text:new C("",new b({dim:!0}),[new C("Press ",new b({color:Q.foreground})),new C("Esc",new b({color:Q.info})),new C(" to cancel",new b({color:Q.foreground}))])})})}));let z=new l0({decoration:new T4(Q.background,X),child:new P0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new _4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class P8 extends c0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:K=!0,thumbColor:V,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=K,this.thumbColor=V,this.trackColor=D}createState(){return new ww4}}class ww4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let U=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),V=Math.max(1,X*K),D=Math.max(0,Math.min(1,U.scrollOffset/(Z-Q))),z=X-V,q=Math.max(0,z*D),G=q+V;return J>=q&&J<=G}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),U=this.context.findRenderObject()?.size.height??0;if(U===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,V=Math.min(1,Q/Z),D=Math.max(1,U*V),z=U-D;if(z<=0)return;let q=Z-Q,G=z/q,F=K/G,W=Math.max(0,Math.min(q,this._dragStartOffset+F));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let V=Math.min(1,Y/Q),D=Math.max(1,K*V),z=Q-Y,q=K-D,G=Math.max(0,Math.min(1,X/(Q-Y))),F=Math.max(0,q*G),W=F+D;if(Z>=F&&Z<=W)return;if(Z<F)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new i1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?B5.POINTER:B5.DEFAULT,child:new Nw4({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 Nw4 extends SC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:K=!0,thumbColor:V,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=K,this.thumbColor=V,this.trackColor=D}createRenderObject(){return new Ow4(this)}updateRenderObject(J){J.updateWidget(this)}}class Ow4 extends E4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;y4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:U}=this._calculateScrollbarMetrics();if(!U)return;let K=this._widget.trackColor,V=this._widget.thumbColor,D=["▁","▂","▃","▄","▅","▆","▇","█"],z=Y,q=Y+X;for(let G=0;G<this.size.height;G++){let F="█",W=!0;if(G===Math.floor(z)){let H=1-(z-G),B=Math.floor(H*8);F=D[B]||"█",W=!1}else if(G===Math.floor(q)){let H=1-(q-G),B=Math.floor(H*8);F=D[B]||"█"}else if(G>z&&G<q)W=!1;J.setChar(Z,Q+G,F,{fg:V,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),U=Math.min(1,Z/J),K=Math.max(1,Y*U),V=Y-K;return{thumbStartFloat:Math.max(0,V*X),thumbSizeFloat:K,showScrollbar:!0}}}class ML extends c0{props;constructor(J){super();this.props=J}createState(){return new Ew4}}class Ew4 extends p0{scrollController=new r6;scrollAreaKey=new v7("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 L2}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=S20(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,U=x1.all(new k1(Z.colors.border,1,"solid")),K=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C(Y.title,new b({color:X,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new Q0({text:new C(Y.description,new b({color:Z.colors.foreground})),selectable:!0}),D=new _1({child:new O2({child:new l0({padding:C0.symmetric(1,0),child:new V1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new O6({controller:this.scrollController,autofocus:!0,child:V})}),new P8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,G=this.scrollController.offset,F=this.getViewportHeight(),W=q+F;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(G,0)}}})]})})})}),z=new l0({padding:C0.symmetric(1,0),child:new Q0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new b({color:Z.colors.foreground,dim:!0})),new C("R",new b({color:Z.app.keybind})),new C(" to retry, ",new b({color:Z.colors.foreground,dim:!0})),new C("Esc",new b({color:Z.app.keybind})),new C(" to cancel",new b({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new b({color:Z.colors.foreground,dim:!0}));if(q==="help"){let G=new b({color:Z.app.keybind}),F=new b({color:Z.colors.foreground,dim:!0});return new C("",F,[new C("Press ",F),new C("Escape",G),new C(" to close • Use ",F),new C("↑↓",G),new C(" or ",F),new C("j/k",G),new C(" to scroll",F)])}return new C("Press any key to close",new b({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new _4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new l0({decoration:{border:U,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new P0({height:1}),D,z]})})})}}a9();class Lw4 extends c0{props;constructor(J){super();this.props=J}createState(){return new Iw4}}class Iw4 extends p0{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=h8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new Q0({text:new C("No plugins found.",new b({dim:!0}))});let Y=[],X=this.plugins.length,U=this.plugins.filter((D)=>D.status==="active").length,K=this.plugins.reduce((D,z)=>D+z.registeredCommands.length,0),V=this.plugins.reduce((D,z)=>D+z.registeredTools.length,0);if(Y.push(new C(`${U}/${X} ${g4(X,"plugin")} active`,new b({bold:!0}))),K>0||V>0)Y.push(new C(` (${K} ${g4(K,"command")}, ${V} ${g4(V,"tool")})`,new b({dim:!0})));Y.push(new C(`
7171
+ `))}if(H)G.push(new C(" ",q)),G.push(new C("Total: ",q)),G.push(new C(U(B),z))}return new l0({decoration:{color:V.background,border:x1.all(new k1(V.border,1,"rounded"))},child:new Q0({text:new C(void 0,void 0,G)})})}m0();a9();import{execSync as Kp5}from"node:child_process";HA();OJ();L3();N7();mw();TX();P$();uJ();jX();VE();f4();Zx();tv();H1();var XN4=q4(Lz(),1);import{writeFile as $N4}from"fs/promises";import JN4 from"path";m0();P$();class Vg0{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.1772727221-g52e1a8"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Dt(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 mH extends c0{props;constructor(J){super();this.props=J}createState(){return new oB4}}class oB4 extends p0{_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 rB4 extends p0{controller=new f7;focusNode=new n4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,U=this.controller.text.trim().length>0,K=!X||U,V=x1.all(new k1(Q.foreground,1,"solid")),D=new t$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new V1({children:[new l0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new _1({child:D})]}),q=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,[new C("Command: ",new b({color:Q.foreground})),new C(this.widget.props.commandName,new b({color:Y.command,bold:!0}))])})}),G=[];if(K)G.push(new C("Enter",new b({color:Y.keybind}))),G.push(new C(" to submit, ",new b({color:Q.foreground,dim:!0})));G.push(new C("Esc",new b({color:Y.keybind}))),G.push(new C(" to cancel",new b({color:Q.foreground,dim:!0})));let F=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C("",void 0,G)})});return new l0({decoration:{border:V,color:Q.background},padding:C0.all(1),child:new u0({children:[q,new P0({height:1}),z,new Q3,F]})})}}class Rp extends c0{props;constructor(J){super();this.props=J}createState(){return new rB4}}import{isDeepStrictEqual as Dg0}from"node:util";var bm5=/[\\/_ +.#"@[({&]/,hm5=/[\\/_ +.#"@[({&]/g,mm5=/[\s-]/,sB4=/[\s-]/g;function a20(J,Z,Q,Y,X,U,K){if(U===Z.length){if(X===J.length)return 1;return 0.99}let V=`${X},${U}`;if(K[V]!==void 0)return K[V];let D=Y.charAt(U),z=Q.indexOf(D,X),q=0,G,F,W,H;while(z>=0){if(G=a20(J,Z,Q,Y,z+1,U+1,K),G>q){if(z===X)G*=1;else if(mm5.test(J.charAt(z-1))){if(G*=0.9,H=J.slice(X,z-1).match(sB4),H&&X>0)G*=0.999**H.length}else if(bm5.test(J.charAt(z-1))){if(G*=0.8,W=J.slice(X,z-1).match(hm5),W&&X>0)G*=0.999**W.length}else if(G*=0.3,X>0)G*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(U))G*=0.9999}if(G<0.1&&(Q.charAt(z-1)===Y.charAt(U+1)||Y.charAt(U+1)===Y.charAt(U)&&Q.charAt(z-1)!==Y.charAt(U))){if(F=a20(J,Z,Q,Y,z+1,U+2,K),F*0.1>G)G=F*0.1}if(G>q)q=G;z=Q.indexOf(D,z+1)}return K[V]=q,q}function n20(J){return J.toLowerCase().replace(sB4," ")}function tB4(J,Z){let Q=a20(J,Z,n20(J),n20(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,U=0;for(let V of Y){let D=a20(J,V,n20(J),n20(V),0,0,{});if(D===0)return Q;X+=D,U+=V.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class MT{}class AT{}class o20{}class r20{}class eB4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new $w4}}class $w4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function gm5(J,Z){if(J==="")return{matches:!0,score:1};let Q=tB4(Z,J);return{matches:Q>0.15,score:Q}}class d9 extends c0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Jw4}}class Jw4 extends p0{textController;focusNode;scrollController=new r6;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new f7(this.widget.props.controller?.query??""),this.focusNode=new n4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Dg0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Dg0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Dg0(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 MT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof AT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof o20){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 r20)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,...gm5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,U)=>this.widget.props.sortItems(X,U,J):(X,U)=>U.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;NT(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=x1.all(new k1(Q.foreground,1,"solid")),U=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,V=new t$({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),D=new N2({shortcuts:new Map([[new $4("ArrowDown"),new MT],[new $4("ArrowUp"),new AT],[new $4("Tab"),new MT],[new $4("Tab",{shift:!0}),new AT],[new $4("n",{ctrl:!0}),new MT],[new $4("p",{ctrl:!0}),new AT],[new $4("Enter"),new o20],[new $4("Escape"),new r20]]),focusNode:this.focusNode,child:V}),z=new P9({actions:new Map([[MT,new o4(this.invoke)],[AT,new o4(this.invoke)],[o20,new o4(this.invoke)],[r20,new o4(this.invoke)]]),child:D}),q=new V1({children:[new l0({decoration:{color:Q.background},child:new Q0({text:new C(">",new b({color:Q.foreground}))})}),new _1({child:z})]});this.itemContexts=[];let G;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";G=new P0({height:10,child:new n1({child:new Q0({text:new C(w,new b({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)G=new _1({child:new n1({child:new Q0({text:new C(this.widget.props.emptyStateText,new b({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,I;if(this.widget.props.renderItem)I=this.widget.props.renderItem(N,E,L,J);else{let M=E?Z.app.selectionBackground:void 0,A=E?Z.app.selectionForeground:Q.foreground;I=new l0({decoration:M?{color:M}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(this.widget.props.getLabel(N),new b({color:A,dim:L}))})})}return new eB4(new i1({onClick:(M)=>this.handleItemClick(O,M.clickCount),child:I}),(M)=>{this.itemContexts[O]=M})});G=new u0({children:w,crossAxisAlignment:"start"})}let F=new i1({onScroll:this.handleScroll,opaque:!1,child:new O6({controller:this.scrollController,autofocus:!1,child:G})}),W=[];if(this.widget.props.title){let w=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C(this.widget.props.title,new b({color:Z.app.command,bold:!0}))})});W.push(w)}if(!U)W.push(q,new P0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new _1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new _1({child:F}),new l0({padding:C0.only({top:1}),child:new n1({child:N??new P0({height:1})})})]})}))}else W.push(new _1({child:F}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new l0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function Zw4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),U=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(U<7)return`${U}d ago`;return J.toLocaleDateString()}class zg0 extends p1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,U)=>U.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Zw4(X.pubDate).length));return new d9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,U,K,V)=>{let D=f0.of(V),{colors:z}=D,q=D.app,G=U?q.selectionBackground:void 0,F=U?q.selectionForeground:z.foreground,W=z.mutedForeground,H=(B,w)=>new P0({width:w,child:V1.end([new Q0({text:new C(B,new b({color:W}))})])});return new l0({decoration:G?{color:G}:void 0,padding:C0.symmetric(2,0),child:new V1({children:[new _1({child:new Q0({text:new C(X.title,new b({color:F})),overflow:"ellipsis",maxLines:1})}),new P0({width:2}),H(Zw4(X.pubDate),Q)]})})}})}}f4();class qg0 extends c0{createState(){return new Qw4}}class Qw4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new Q0({text:new C("●",new b({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var pm5=/\/threads\/(T-[^/?#\s<>]+)/i;function dm5(J){let Z=J.trim(),Y=Z.match(pm5)?.[1];if(Y&&v8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(v8(X))return X;return null}function cm5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let V=K.relationships.find((D)=>D.role==="child"&&Z.has(D.threadID)&&(D.type==="fork"||D.type==="handoff"));if(V){Y.set(K.id,V.type);let D=V.threadID,z=Q.get(D)||[];z.push(K),Q.set(D,z)}else X.push(K)}return M70.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Gg0(J,Z,Q){return new Q0({text:new C(`${J}${Z}`,new b({color:Q})),maxLines:1})}function lm5(J,Z,Q,Y){return[Gg0("+",J,Y.success),Q3.horizontal(1),Gg0("~",Z,Y.warning),Q3.horizontal(1),Gg0("-",Q,Y.destructive)]}function im5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class s20 extends c0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Yw4}}class Yw4 extends p0{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}`,U=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)U=U.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],V=new Set(K),D=Z.currentThreadID,z=[...U].sort((O,E)=>{if(D){if(O.id===D)return-1;if(E.id===D)return 1}let L=K.indexOf(O.id),I=K.indexOf(E.id);if(L!==-1&&I!==-1)return L-I;if(L!==-1)return-1;if(I!==-1)return 1;return 0}),q=cm5(z),G=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),F=f0.of(J),W=new o0({padding:C0.symmetric(0,1),child:new n1({child:new Q0({text:new C("",new b({color:F.colors.foreground,dim:!0}),[new C("Ctrl+T",new b({color:F.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new b({color:F.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=dm5(O);return B};return new d9({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!im5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,I)=>{let M=f0.of(I),{app:A,colors:R}=M,_=E?A.selectionBackground:void 0,S=E?A.selectionForeground:R.foreground,y=R.mutedForeground,h=(e,q0)=>new P0({width:q0,child:V1.end([new Q0({text:new C(e,new b({color:y}))})])}),f=Z.threadViewStates[O.id],k=[],x=O.relationshipType==="handoff",d=new ng({connectorColor:R.mutedForeground});if(O.depth>0){let e=[],q0=O.ancestorsAreLast.slice(1);for(let z0 of q0)e.push(new C(d.getAncestorPrefix(z0),new b({color:d.connectorColor,dim:d.connectorDim})));let a=O.isLast?d.elbow:d.tee,K0=d.getConnectorText(a);e.push(new C(K0,new b({color:d.connectorColor,dim:d.connectorDim}))),k.push(new Q0({text:new C("",void 0,e)}))}let l=[],m=D===O.id?new C("(current) ",new b({color:R.success})):V.has(O.id)?new C("(visited) ",new b({color:R.foreground,dim:!0})):null;if(m)l.push(new Q0({text:m}));if(SO(f))l.push(new qg0),l.push(new P0({width:1}));let o=O.title;if(O.relationshipType==="fork"){let e=o.match(/^Forked\((\d+)\): /);if(e)o=o.slice(e[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);l.push(new Q0({text:new C("[fork] ",new b({color:R.primary}))}))}else if(x)l.push(new Q0({text:new C("[handoff] ",new b({color:R.accent}))}));if(l.push(new _1({child:new Q0({text:new C(o,new b({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new P0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let e=E?{success:y,warning:y,destructive:y}:R;l.push(...lm5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,e)),l.push(new P0({width:2}))}return l.push(h(O.description.timeAgo,G)),new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new V1({children:[...k,...l]})})}})}}function Xw4(J){return 1-(1-J)**3}function Uw4(J,Z,Q){return J+(Z-J)*Q}function Pp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),U=Xw4(Y),K=Xw4(X);return{x:Uw4(J.startOffset.x,J.targetOffset.x,U),y:Uw4(J.startOffset.y,J.targetOffset.y,K)}}var nm5={nodeWidth:3,horizontalSpacing:3};class jT{options;constructor(J={}){this.options={...nm5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let U=0,K=(V,D)=>{let z=Z.get(V.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...V,parentID:Q.get(V.id)};if(z.length===0){Y.push({node:q,position:{x:U,y:D}});let B=U;return U+=this.options.nodeWidth+this.options.horizontalSpacing,B}let G=[];for(let B of z)G.push(K(B,D+1));let F=Math.min(...G),W=Math.max(...G),H=Math.floor((F+W)/2);return Y.push({node:q,position:{x:H,y:D}}),H};for(let V of X)K(V,0);return Y}buildTree(J){let Z=new Set(J.map((U)=>U.id)),Q=[...J].sort((U,K)=>U.id.localeCompare(K.id)),Y=new Map;for(let U of Q){if(!U.parentID||!Z.has(U.parentID)){Y.set(U.id,void 0);continue}let K=!1,V=U.parentID;while(V){if(V===U.id){K=!0;break}V=Y.get(V)}Y.set(U.id,K?void 0:U.parentID)}let X=new Map;for(let U of J){let K=Y.get(U.id);if(!X.has(K))X.set(K,[]);X.get(K).push(U)}return{childrenMap:X,resolvedParent:Y}}}var am5={nodeWidth:3,nodeHeight:2};class RT{options;constructor(J={}){this.options={...am5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let U=this.calculateConnectorLine(X.position,Y.position);Z.push({points:U,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,U=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let V=K+1;if(Y.push({x:X,y:V}),X!==U)Y.push({x:U,y:V});let D=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:U,y:D}),Y}}var om5={nodeWidth:3,nodeHeight:2},rm5={x:0,y:0};class e20{options;constructor(J={}){this.options={...om5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=rm5,X,U,K,V){let D=V?f0.of(V):null,z=D?.colors,q=D?.app,G=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:G}))});let F=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let A=F;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new P0({width:y.position.x-S}));let h=y.node.id===Q,f=K?.(y.node.data)??!1,k=U?.activeFlashOn??!1,x=y.node.id===U?.copyFlashNodeId;_.push(this.renderNode(h,f,k,x,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new V1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(F+1)*B,I=[new P0({width:H,height:L}),new J5({left:O,top:E,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=F-M.position.y,_=O+M.position.x+this.options.nodeWidth+1,S=E+R*B+1,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new J5({left:_,top:S,child:this.renderInfoBox(A,y,z,q)}))}return new l0({padding:C0.horizontal(2),child:new zH(new z5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X,U){let K="┌─┐",V="└─┘",D=J?X?.threadGraphNodeSelected??U?.primary??U?.foreground:X?.threadGraphNode??U?.primary??U?.foreground,z=!1;if(Y)D=X?.threadGraphNodeSelected??U?.primary??D,K="┏━┓",V="┗━┛",z=!0;else if(Z&&Q)D=X?.toolSuccess??U?.primary??D,K="┏━┓",V="┗━┛";return new u0({crossAxisAlignment:"start",children:[new Q0({text:new C(K,new b({color:D,bold:z}))}),new Q0({text:new C(V,new b({color:D,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),U=Math.min(Z,Math.max(1,...X.map((F)=>F.length))),K=U+2,V="┌"+"─".repeat(K)+"┐",D="└"+"─".repeat(K)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,G=[new Q0({text:new C(V,new b({color:z}))})];for(let F of X){let W=" ".repeat(U-F.length);G.push(new Q0({text:new C("│ ",new b({color:z}),[new C(F+W,new b({color:q??z})),new C(" │",new b({color:z}))])}))}return G.push(new Q0({text:new C(D,new b({color:z}))})),new u0({crossAxisAlignment:"start",children:G})}renderConnectors(J,Z,Q,Y,X,U){let K=[],V=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let F of Z){let W=F.position.x+V;if(W>=0&&W<Y)z[W]="▲"}K.push(new Q0({text:new C(z.join(""),new b({color:D}))}));let q=Array(Y).fill(" ");for(let F of J){let W=Z.filter((O)=>O.node.parentID===F.node.id);if(W.length===0)continue;let H=F.position.x+V,B=W.map((O)=>O.position.x+V),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)q[O]="│";else if(O===w)q[O]="└";else if(O===N)q[O]="┘";else q[O]="┬";else if(B.includes(O))if(O===w)q[O]="└";else if(O===N)q[O]="┘";else q[O]="┴";else if(q[O]===" ")q[O]="─"}}K.push(new Q0({text:new C(q.join(""),new b({color:D}))}));let G=Array(Y).fill(" ");for(let F of J){if(Z.filter((B)=>B.node.parentID===F.node.id).length===0)continue;let H=F.position.x+V;if(H>=0&&H<Y)G[H]="│"}return K.push(new Q0({text:new C(G.join(""),new b({color:D}))})),K}}var sm5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},tm5={x:0,y:0};class Fg0{options;constructor(J={}){this.options={...sm5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=tm5,X,U,K,V){let D=V?f0.of(V):null,z=D?.colors,q=D?.app,G=z?.mutedForeground??z?.foreground;if(J.length===0)return new Q0({text:new C("No nodes",new b({color:G}))});let F=Math.max(...J.map((A)=>A.position.y)),H=Math.max(...J.map((A)=>A.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let A=F;A>=0;A--){let R=J.filter((y)=>y.position.y===A);R.sort((y,h)=>y.position.x-h.position.x);let _=[],S=0;for(let y of R){if(y.position.x>S)_.push(new P0({width:y.position.x-S}));let h=y.node.id===Q,f=K?.(y.node.data)??!1,k=U?.activeFlashOn??!1;_.push(this.renderNode(h,f,k,q,z)),S=y.position.x+this.options.nodeWidth}if(w.push(new V1({crossAxisAlignment:"start",children:_})),A>0){let y=J.filter((k)=>k.position.y===A-1),h=R,f=this.renderConnectors(y,h,Z,H,z,q);w.push(...f)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(F+1)*B,I=[new P0({width:H,height:L}),new J5({left:O,top:E,child:N})],M=Q?J.find((A)=>A.node.id===Q):void 0;if(M&&X){let A=X(M.node.data),R=F-M.position.y,_=O+M.position.x+this.options.nodeWidth+1,S=E+R*B,y=30;if(U?.maxTitleWidthPercent&&U.viewportWidth)y=Math.floor(U.viewportWidth*U.maxTitleWidthPercent/100);I.push(new J5({left:_,top:S,child:this.renderInfoBox(A,y,z)}))}return new l0({padding:C0.horizontal(2),child:new zH(new z5({fit:"expand",children:I}))})}renderNode(J,Z,Q,Y,X){let U=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,U="■";return new Q0({text:new C(U,new b({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let U of Q){if(U.length>Z)U=U.slice(0,Z-1)+"…";if(X.length===0)X=U;else if(X.length+1+U.length<=Z)X+=" "+U;else Y.push(X),X=U}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,U=[];for(let K of Y)U.push(new Q0({text:new C(K,new b({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,U){let K=[],V=Math.floor(this.options.nodeWidth/2),D=U?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let G=Z.filter((w)=>w.node.parentID===q.node.id);if(G.length===0)continue;let F=q.position.x+V,W=G.map((w)=>w.position.x+V),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===F,O=W.includes(w);if(N&&O)if(G.length===1)z[w]="│";else if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┼";else if(N)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┬";else if(O)if(w===H)z[w]="└";else if(w===B)z[w]="┘";else z[w]="┴";else if(z[w]===" ")z[w]="─"}}return K.push(new Q0({text:new C(z.join(""),new b({color:D}))})),K}}class Cp extends z3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Kw4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Kw4 extends E4{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 IL extends c0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new zw4}}var Vw4=400,Dw4=300,em5=16;class zw4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new jT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new RT;renderer=new Fg0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((D)=>D.id)),Q=new Set(this.widget.props.threads.map((D)=>D.id));if(Z.size!==Q.size||[...Z].some((D)=>!Q.has(D)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,U=this.widget.props.initialSelectedThreadID;if(X!==U&&U){let z=this.widget.props.threads.find((q)=>q.id===U);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((D)=>D.isActive),V=this.widget.props.threads.some((D)=>D.isActive);if(K!==V){if(this.stopActiveFlashTimer(),V)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Vw4,durationY:Dw4};let Z=Math.max(Vw4,Dw4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Pp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},em5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),U=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,V=2,D=Math.floor(this.viewportHeight/2),q=Math.floor(D/2)-K;return{x:U,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((U)=>U.node.parentID===Q.node.id);if(X.length>0){X.sort((K,V)=>K.position.x-V.position.x);let U=Math.floor(X.length/2);Y=X[U]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x<Q.position.x);if(X.length>0)X.sort((U,K)=>K.position.x-U.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((U)=>U.position.y===Q.position.y&&U.position.x>Q.position.x);if(X.length>0)X.sort((U,K)=>U.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((G)=>G.node.id===this.selectedNodeId):null)??this.positionedNodes.find((G)=>!G.node.parentID);if(q){let G=Math.max(...this.positionedNodes.map((F)=>F.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,G)}}let X=this.widget.props.showTitle??!0,U=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+U},V=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),D=new Cp({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:V});return new _4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:D})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Gw4 extends c0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Fw4}}class Fw4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var qw4=30,$g5=30;class PT{}class CT{}class $$0{}class J$0{}class Wg0 extends c0{props;constructor(J){super();this.props=J}createState(){return new Ww4}}class Ww4 extends p0{highlightedIndex=0;controller=new f7;focusNode;scrollController=new r6;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new n4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;NT(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 PT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof CT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof $$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof J$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),q6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,V=o1.of(J).size.width>=$g5+qw4,D=x1.all(new k1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C("Select a cluster",new b({color:X.command,bold:!0}))})}),G=new t$({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),F=new N2({shortcuts:new Map([[new $4("ArrowDown"),new PT],[new $4("ArrowUp"),new CT],[new $4("Tab"),new PT],[new $4("Tab",{shift:!0}),new CT],[new $4("n",{ctrl:!0}),new PT],[new $4("p",{ctrl:!0}),new CT],[new $4("Enter"),new $$0],[new $4("Escape"),new J$0]]),focusNode:this.focusNode,child:G}),W=new P9({actions:new Map([[PT,new o4(this.invoke)],[CT,new o4(this.invoke)],[$$0,new o4(this.invoke)],[J$0,new o4(this.invoke)]]),child:F}),H=new V1({children:[new l0({decoration:{color:Y.background},child:new Q0({text:new C(">",new b({color:Y.foreground}))})}),new _1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((I,M)=>{let A=M===this.highlightedIndex,R=Z?I.threads.some((h)=>h.id===Z):!1,_=A?X.selectionBackground:void 0,S=A?X.selectionForeground:Y.foreground,y=[new C(I.label,new b({color:S})),new C(` (${I.threads.length})`,new b({color:S,dim:!0}))];if(R)y.push(new C(" (current)",new b({color:A?X.selectionForeground:Y.success})));return new Gw4(new i1({onClick:(h)=>this.handleItemClick(M,h.clickCount),child:new l0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,y)})})}),(h)=>{this.itemContexts[M]=h})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new _1({child:new i1({onScroll:this.handleScroll,child:new O6({controller:this.scrollController,autofocus:!1,child:w})})}),O=z?z.threads.map((I)=>({id:I.id,title:I.title,parentID:I.parentID,updatedAt:I.updatedAt})):[],E=z?new l0({padding:C0.all(1),child:new IL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(V){let I=E?new _1({child:E}):new P0({width:qw4});L=new V1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,I]})}else{let I=[new _1({child:new i1({onScroll:this.handleScroll,child:new O6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)I.push(new _1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:I})}return new l0({decoration:{border:D,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[q,H,new P0({height:1}),new _1({child:L})]})})}}class e${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!e$._instance)e$._instance=new e$;return e$._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()}}m0();class Hw4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((U)=>U.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),U=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),D=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new d9({title:"Add Label",items:D,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:U||"Type to create a new label",renderItem:(z,q,G,F)=>{let W=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C("",void 0,[new C("Create new label: ",new b({color:H})),new C(w,new b({color:H,bold:!0}))])})})}return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new Q0({text:new C(z.name,new b({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let F=q.trim().toLowerCase();return F.length===0||z.name.includes(F)},sortItems:(z,q,G)=>{let F="__isCreateMarker"in z.item&&z.item.__isCreateMarker,W="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(F&&!W)return-1;if(!F&&W)return 1;return q.score-z.score}})}}class Hg0 extends c0{props;constructor(J){super();this.props=J}createState(){return new Hw4}}class gH extends c0{props;constructor(J){super();this.props=J}createState(){return new Bw4}}class Bw4 extends p0{_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=x1.all(new k1(Q.foreground,1,"solid")),U=this._spinner.toBraille(),K=new Q0({textAlign:"center",text:new C("",void 0,[new C(U,new b({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new b({color:Q.foreground}))])}),D=[new _1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)D.push(new P0({height:2,child:new l0({padding:C0.symmetric(2,0),child:new Q0({text:new C("",new b({dim:!0}),[new C("Press ",new b({color:Q.foreground})),new C("Esc",new b({color:Q.info})),new C(" to cancel",new b({color:Q.foreground}))])})})}));let z=new l0({decoration:new T4(Q.background,X),child:new P0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:D})})});if(this.widget.props.onAbort)return new _4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}class P8 extends c0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:K=!0,thumbColor:V,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=K,this.thumbColor=V,this.trackColor=D}createState(){return new ww4}}class ww4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let U=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),V=Math.max(1,X*K),D=Math.max(0,Math.min(1,U.scrollOffset/(Z-Q))),z=X-V,q=Math.max(0,z*D),G=q+V;return J>=q&&J<=G}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),U=this.context.findRenderObject()?.size.height??0;if(U===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,V=Math.min(1,Q/Z),D=Math.max(1,U*V),z=U-D;if(z<=0)return;let q=Z-Q,G=z/q,F=K/G,W=Math.max(0,Math.min(q,this._dragStartOffset+F));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let V=Math.min(1,Y/Q),D=Math.max(1,K*V),z=Q-Y,q=K-D,G=Math.max(0,Math.min(1,X/(Q-Y))),F=Math.max(0,q*G),W=F+D;if(Z>=F&&Z<=W)return;if(Z<F)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new i1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?B5.POINTER:B5.DEFAULT,child:new Nw4({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 Nw4 extends SC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:U="█",showTrack:K=!0,thumbColor:V,trackColor:D}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=U,this.showTrack=K,this.thumbColor=V,this.trackColor=D}createRenderObject(){return new Ow4(this)}updateRenderObject(J){J.updateWidget(this)}}class Ow4 extends E4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;y4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:U}=this._calculateScrollbarMetrics();if(!U)return;let K=this._widget.trackColor,V=this._widget.thumbColor,D=["▁","▂","▃","▄","▅","▆","▇","█"],z=Y,q=Y+X;for(let G=0;G<this.size.height;G++){let F="█",W=!0;if(G===Math.floor(z)){let H=1-(z-G),B=Math.floor(H*8);F=D[B]||"█",W=!1}else if(G===Math.floor(q)){let H=1-(q-G),B=Math.floor(H*8);F=D[B]||"█"}else if(G>z&&G<q)W=!1;J.setChar(Z,Q+G,F,{fg:V,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),U=Math.min(1,Z/J),K=Math.max(1,Y*U),V=Y-K;return{thumbStartFloat:Math.max(0,V*X),thumbSizeFloat:K,showScrollbar:!0}}}class ML extends c0{props;constructor(J){super();this.props=J}createState(){return new Ew4}}class Ew4 extends p0{scrollController=new r6;scrollAreaKey=new v7("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 L2}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=S20(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,U=x1.all(new k1(Z.colors.border,1,"solid")),K=new l0({padding:C0.symmetric(1,0),child:new Q0({text:new C(Y.title,new b({color:X,bold:!0}))})}),V=this.isWidgetMessage(Q)?Q.widget:new Q0({text:new C(Y.description,new b({color:Z.colors.foreground})),selectable:!0}),D=new _1({child:new O2({child:new l0({padding:C0.symmetric(1,0),child:new V1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new O6({controller:this.scrollController,autofocus:!0,child:V})}),new P8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,G=this.scrollController.offset,F=this.getViewportHeight(),W=q+F;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(G,0)}}})]})})})}),z=new l0({padding:C0.symmetric(1,0),child:new Q0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new b({color:Z.colors.foreground,dim:!0})),new C("R",new b({color:Z.app.keybind})),new C(" to retry, ",new b({color:Z.colors.foreground,dim:!0})),new C("Esc",new b({color:Z.app.keybind})),new C(" to cancel",new b({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new b({color:Z.colors.foreground,dim:!0}));if(q==="help"){let G=new b({color:Z.app.keybind}),F=new b({color:Z.colors.foreground,dim:!0});return new C("",F,[new C("Press ",F),new C("Escape",G),new C(" to close • Use ",F),new C("↑↓",G),new C(" or ",F),new C("j/k",G),new C(" to scroll",F)])}return new C("Press any key to close",new b({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new _4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new l0({decoration:{border:U,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new P0({height:1}),D,z]})})})}}a9();class Lw4 extends c0{props;constructor(J){super();this.props=J}createState(){return new Iw4}}class Iw4 extends p0{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=h8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new Q0({text:new C("No plugins found.",new b({dim:!0}))});let Y=[],X=this.plugins.length,U=this.plugins.filter((D)=>D.status==="active").length,K=this.plugins.reduce((D,z)=>D+z.registeredCommands.length,0),V=this.plugins.reduce((D,z)=>D+z.registeredTools.length,0);if(Y.push(new C(`${U}/${X} ${g4(X,"plugin")} active`,new b({bold:!0}))),K>0||V>0)Y.push(new C(` (${K} ${g4(K,"command")}, ${V} ${g4(V,"tool")})`,new b({dim:!0})));Y.push(new C(`
7172
7172
 
7173
7173
  `));for(let D of this.plugins){let{icon:z,color:q}=this.statusIcon(D.status),G=this.getRelativePath(D.uri.toString());if(Y.push(new C(`${z} `,new b({color:q}))),Y.push(new C(G,new b({bold:!0}))),Y.push(new C(` ${D.status}`,new b({dim:!0}))),Y.push(new C(`
7174
7174
  `)),D.status==="active"&&D.registeredEvents.length>0)Y.push(new C(" Events: ",new b({dim:!0}))),Y.push(new C(D.registeredEvents.join(", "),new b({color:Q.link}))),Y.push(new C(`
@@ -7395,7 +7395,7 @@ ${r.content||""}`:r.content||"",D1=[],E1=r.baseDir.startsWith("file://")?n$0(r.b
7395
7395
  `)}function BL4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),U=await Z(X),K=await U.settings.get("proxy"),V=AA1({settings:{url:U.ampURL,proxy:K},secrets:{getToken:(z,q)=>U.secrets.get(z,q)}}),D=await T6.userDisplayBalanceInfo({},{config:V});if(!D.ok){if(D.error.code==="auth-required")process.stderr.write(J1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(J1.red("Error: ")+D.error.message+`
7396
7396
  `),process.exit(1)}process.stdout.write(await Mi5(D.result.displayText)+`
7397
7397
  `),process.exit(0)})}var dr5=Od.join(MZ,"logs","headless.log"),cc0=Od.join(LC,"device-id.json");function cr5(){return $z.some((J)=>J.listConfigs().length>0)}try{if(process.platform==="win32")await Promise.resolve().then(() => q4(Y_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){G7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7398
- `)}function lr5(J){process.emitWarning=(Z,Q,Y,X)=>{let U=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",V=!1;J.warn(U,{name:K,code:Y})}}function d7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")E7("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")E7("experimental.agentMode",Z.mode)}function dA4(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 ir5(J){try{return await pA4(J,"utf-8")}catch{return J}}async function lc0(J,Z,Q){let Y=dA4(J,Z);if(!Y)return;let X=S5(Q)?Q.features:[],U=S5(Q)?Q.user.email:void 0;if(!X.some((V)=>V.name===_X.HARNESS_SYSTEM_PROMPT&&V.enabled)&&!cA4(U))throw new H4("You are not allowed to do this.",1);E7("systemPrompt",await ir5(Y))}function cA4(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function ic0(J,Z){if(typeof J==="boolean")return J;if(!S5(Z))return!1;return nQ(Z.user.email)}function nc0(J){if(!S5(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function nr5(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 ac0(J){let Y=nr5(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 H4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var fA4=[{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??uY,description:`Custom settings file path (overrides the default location ${uY})`},{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 ${RE})`},{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:p9(),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:SK.SMART.key,description:`Set the agent mode (${gQ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gQ().map((J)=>J.mode).concat("large","deep")},{name:"dtw",long:"dtw",type:"flag",description:"Use the DTW-backed thread provider in the TUI (experimental)",hidden:!0,aliases:["deliver-me-to-agg"]},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],bA4=(J)=>("deprecated"in J)&&J.deprecated===!0,ar5=(J)=>("hidden"in J)&&J.hidden===!0,or5=(J)=>("default"in J),rr5=(J)=>("default"in J)?J.default:void 0,lA4=[{name:"toggle-skills-count",entryPoint:Bx0}];function sr5(J,Z){let Q=Z.args[0],Y=Z.commands.map((U)=>U.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let U=Y.filter((V)=>Q.includes(V)||V.includes(Q)),K="Run amp --help for a list of available commands.";if(U.length>0)K=`Did you mean: ${U.join(", ")}? Or run amp --help for all commands.`;throw new H4(V8.unknownCommand(Q),1,K)}}async function rc0(J){return{...J,getThreadEnvironment:p$,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new nX(J.fileSystem),generateThreadTitle:m00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xJ(J.configService),pluginService:J.pluginService}}function iA4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:p$,filesystem:J.fileSystem,threadService:J.threadService}}var fJ0=G1.file(pr5.homedir()),oc0=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(fJ0,".config");function tr5(J){return d74({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){p74(Z);let Q=r80(),Y=xx0();if((!Q||Y||QK4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wq("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wq("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(r80()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function er5(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function i9(J,Z,Q){let Y=Q?.deferAuth??!1;wA1("0.0.1772724405-g1c19f6");let X=to({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([G1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:fJ0,userConfigDir:oc0});tU4(X);let U=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(U.settings)});let{toolService:K,dispose:V}=f74({configService:X}),D=new Map,z=()=>D.clear(),q=new wL0(X,J.settings.getWorkspaceRootPath()),G=Ih1({configService:X,filesystem:e6}),F=ly1({configService:X,trustStore:q,skillMCPServers:G.skillMCPServers,createOAuthProvider:async(e,q0,a)=>{let K0=`${e}:${q0}`,z0=D.get(K0);if(z0)return P.debug("Reusing existing OAuth provider for server",{serverName:e,serverUrl:q0}),z0;P.debug("Creating OAuth provider for server",{serverName:e,serverUrl:q0});let O0=(async()=>{let X0=new ON(J.secrets),H0=await X0.getClientInfo(e,q0),i=a?.scopes??H0?.scopes,s=qX4();P.info("OAuth headless mode check",{useHeadless:s,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let J0;if(s)J0=J.executeMode?zX4():DX4(e);let c=new xE0({storage:X0,serverName:e,serverUrl:q0,clientId:a?.clientId??H0?.clientId,clientSecret:a?.clientSecret??H0?.clientSecret,authUrl:a?.authUrl??H0?.authUrl,tokenUrl:a?.tokenUrl??H0?.tokenUrl,scopes:i,headlessAuthHandler:J0});return P.debug("OAuth provider created",{serverName:e,serverUrl:q0,hasManualClientId:!!(a?.clientId??H0?.clientId),willUseDCR:!(a?.clientId??H0?.clientId),scopes:i,headlessMode:s,executeMode:J.executeMode}),c})();return D.set(K0,O0),O0}}),W=jv0({configService:X,filesystem:e6,spawn:h50}),H;if(J.executeMode){let e=await r34({toolService:K,providers:[F,W],initialTimeout:15000});H=e.registrations;for(let[q0,a]of e.initErrors)P.warn(`${q0} provider initialization slow or failed:`,a)}else H=Pv0({toolService:K,providers:[F,W]});if(Z.jetbrains)ow("JetBrains");else if(Z.ide&&nX4())ow("VS Code");else if(Z.ide&&aX4())ow("Neovim");else if(Z.ide&&cr5()){let e=$z.find((q0)=>q0.listConfigs().length>0);if(e){let q0=Zr(e.ideName);if(q0)ow(q0)}}if(J.executeMode)NA1(!0);let B,w=y8.status.pipe(W1((e)=>Boolean(e.connected&&e.authenticated&&e.ideName&&yA1(e.ideName))),M4()).subscribe((e)=>{if(e){if(!B)B=K.registerTool(o34)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let e=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new G80(process.cwd(),{alwaysIncludePaths:e},!0)}else N=new class extends G80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let e=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(e),P.info("API key lookup before login",{found:Boolean(e),ampURL:J.ampURL,deferAuth:Y}),!e)if(Y)P.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
7398
+ `)}function lr5(J){process.emitWarning=(Z,Q,Y,X)=>{let U=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",V=!1;J.warn(U,{name:K,code:Y})}}function d7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")E7("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")E7("experimental.agentMode",Z.mode)}function dA4(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 ir5(J){try{return await pA4(J,"utf-8")}catch{return J}}async function lc0(J,Z,Q){let Y=dA4(J,Z);if(!Y)return;let X=S5(Q)?Q.features:[],U=S5(Q)?Q.user.email:void 0;if(!X.some((V)=>V.name===_X.HARNESS_SYSTEM_PROMPT&&V.enabled)&&!cA4(U))throw new H4("You are not allowed to do this.",1);E7("systemPrompt",await ir5(Y))}function cA4(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}function ic0(J,Z){if(typeof J==="boolean")return J;if(!S5(Z))return!1;return nQ(Z.user.email)}function nc0(J){if(!S5(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function nr5(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 ac0(J){let Y=nr5(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 H4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var fA4=[{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??uY,description:`Custom settings file path (overrides the default location ${uY})`},{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 ${RE})`},{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:p9(),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:SK.SMART.key,description:`Set the agent mode (${gQ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gQ().map((J)=>J.mode).concat("large","deep")},{name:"dtw",long:"dtw",type:"flag",description:"Use the DTW-backed thread provider in the TUI (experimental)",hidden:!0,aliases:["deliver-me-to-agg"]},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],bA4=(J)=>("deprecated"in J)&&J.deprecated===!0,ar5=(J)=>("hidden"in J)&&J.hidden===!0,or5=(J)=>("default"in J),rr5=(J)=>("default"in J)?J.default:void 0,lA4=[{name:"toggle-skills-count",entryPoint:Bx0}];function sr5(J,Z){let Q=Z.args[0],Y=Z.commands.map((U)=>U.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let U=Y.filter((V)=>Q.includes(V)||V.includes(Q)),K="Run amp --help for a list of available commands.";if(U.length>0)K=`Did you mean: ${U.join(", ")}? Or run amp --help for all commands.`;throw new H4(V8.unknownCommand(Q),1,K)}}async function rc0(J){return{...J,getThreadEnvironment:p$,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new nX(J.fileSystem),generateThreadTitle:m00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xJ(J.configService),pluginService:J.pluginService}}function iA4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:p$,filesystem:J.fileSystem,threadService:J.threadService}}var fJ0=G1.file(pr5.homedir()),oc0=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(fJ0,".config");function tr5(J){return d74({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){p74(Z);let Q=r80(),Y=xx0();if((!Q||Y||QK4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(wq("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(wq("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(r80()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function er5(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function i9(J,Z,Q){let Y=Q?.deferAuth??!1;wA1("0.0.1772727221-g52e1a8");let X=to({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([G1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:fJ0,userConfigDir:oc0});tU4(X);let U=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(U.settings)});let{toolService:K,dispose:V}=f74({configService:X}),D=new Map,z=()=>D.clear(),q=new wL0(X,J.settings.getWorkspaceRootPath()),G=Ih1({configService:X,filesystem:e6}),F=ly1({configService:X,trustStore:q,skillMCPServers:G.skillMCPServers,createOAuthProvider:async(e,q0,a)=>{let K0=`${e}:${q0}`,z0=D.get(K0);if(z0)return P.debug("Reusing existing OAuth provider for server",{serverName:e,serverUrl:q0}),z0;P.debug("Creating OAuth provider for server",{serverName:e,serverUrl:q0});let O0=(async()=>{let X0=new ON(J.secrets),H0=await X0.getClientInfo(e,q0),i=a?.scopes??H0?.scopes,s=qX4();P.info("OAuth headless mode check",{useHeadless:s,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let J0;if(s)J0=J.executeMode?zX4():DX4(e);let c=new xE0({storage:X0,serverName:e,serverUrl:q0,clientId:a?.clientId??H0?.clientId,clientSecret:a?.clientSecret??H0?.clientSecret,authUrl:a?.authUrl??H0?.authUrl,tokenUrl:a?.tokenUrl??H0?.tokenUrl,scopes:i,headlessAuthHandler:J0});return P.debug("OAuth provider created",{serverName:e,serverUrl:q0,hasManualClientId:!!(a?.clientId??H0?.clientId),willUseDCR:!(a?.clientId??H0?.clientId),scopes:i,headlessMode:s,executeMode:J.executeMode}),c})();return D.set(K0,O0),O0}}),W=jv0({configService:X,filesystem:e6,spawn:h50}),H;if(J.executeMode){let e=await r34({toolService:K,providers:[F,W],initialTimeout:15000});H=e.registrations;for(let[q0,a]of e.initErrors)P.warn(`${q0} provider initialization slow or failed:`,a)}else H=Pv0({toolService:K,providers:[F,W]});if(Z.jetbrains)ow("JetBrains");else if(Z.ide&&nX4())ow("VS Code");else if(Z.ide&&aX4())ow("Neovim");else if(Z.ide&&cr5()){let e=$z.find((q0)=>q0.listConfigs().length>0);if(e){let q0=Zr(e.ideName);if(q0)ow(q0)}}if(J.executeMode)NA1(!0);let B,w=y8.status.pipe(W1((e)=>Boolean(e.connected&&e.authenticated&&e.ideName&&yA1(e.ideName))),M4()).subscribe((e)=>{if(e){if(!B)B=K.registerTool(o34)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let e=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new G80(process.cwd(),{alwaysIncludePaths:e},!0)}else N=new class extends G80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let e=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(e),P.info("API key lookup before login",{found:Boolean(e),ampURL:J.ampURL,deferAuth:Y}),!e)if(Y)P.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
7399
7399
  `);let q0=await $s5(J),a=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:q0,storedKeyPresent:Boolean(a),ampURL:J.ampURL}),!q0)await Fq(),process.exit(1);O=!0}}{let e=await X.getLatest(),q0=e.settings.url,a=e.secrets.isSet?.[q0];P.info("Config secrets state after login",{configURL:q0,apiKeySet:a?.apiKey??!1})}let E=L1(xJ(X).pipe(x5((e)=>e!=="pending"))),L=await Ch1({isDevelopment:!1}),I=Y?"pending":await E;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:S5(I),isError:EF(I),errorMessage:EF(I)?I.error.message:void 0});let M=new AA0(L,X),A=new BM0(L,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=ic0(Z.dtw,I),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let S=_?er5():$g1({threadService:M,threadHistoryService:A,configService:X,isExtensionDevelopment:!1}),y;y8.status.subscribe((e)=>{y=e});let h=new vB0({workspaceRoots:[G1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?Ht:e6,getCurrentFile:()=>{if(!y?.openFile)return;try{return G1.parse(y.openFile)}catch(e){P.warn("Failed to parse current file URI",{uri:y.openFile,error:e});return}},getOpenFiles:()=>{if(!y?.visibleFiles?.length)return[];let e=y.openFile;return y.visibleFiles.filter((q0)=>q0!==e).map((q0)=>{try{return G1.parse(q0)}catch(a){return P.warn("Failed to parse visible file URI",{uri:q0,error:a}),null}}).filter((q0)=>q0!==null)}}),f=new hx0,k=process.env.PLUGINS??"off",x=Z.headless?bU4():void 0,d=x??new v80({configService:X}),l=d instanceof v80?d:void 0;if(l)l.pluginExecutorKind=R?"local":"unknown";let m=YM0({configService:X,fileSystem:Z.jetbrains||Z.ide?Ht:e6,platform:d,internalPlugins:lA4,pluginFilter:k}),o=db1({pluginService:m,toolService:K}),p={codebaseContextService:h,configService:X,toolService:K,mcpService:F,skillService:G,toolboxService:W,trustStore:q,threadService:M,threadHistoryService:A,threadSyncService:S,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?Ht:e6,terminal:f,pluginService:m,pluginPlatform:l,headlessPluginPlatform:x,serverStatus:I,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...p,async asyncDispose(){if(p.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await p.mcpService.waitForAuthentication();for(let e of H.values())e.dispose();await p.mcpService.dispose(),z(),await p.threadService.asyncDispose(),p.configService.unsubscribe(),V(),p.fuzzyServer.dispose(),p.threadSyncService.dispose(),p.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),o.dispose(),p.pluginService.dispose()}}}async function $s5(J){if(!J.executeMode){if(!await Wx0("Would you like to log in to Amp? [(y)es, (n)o]: "))return s6.write(`Login cancelled. Run the command again to retry.
7400
7400
  `),!1}return await nA4(J)}async function nA4(J){let Z=hr5(32).toString("hex"),Q=await MC(J.ampURL,Z),Y=new AbortController;try{await PX(Q,Y.signal)}catch(U){P.error("Error opening browser",{error:U})}let X=await MC(J.ampURL,Z,!1);s6.write(`If your browser does not open automatically, visit:
7401
7401
 
@@ -7403,7 +7403,7 @@ ${J1.blue.bold(X)}
7403
7403
 
7404
7404
  `);try{return await wU4(J.ampURL,Z,J.secrets,Y),s6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(U){return P.error("Login failed",{error:U}),G7.write(`
7405
7405
  Login failed: ${U instanceof Error?U.message:String(U)}
7406
- `),!1}}function Js5(){let J=new lW().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)CE(),process.exit(0);let B=H.originalError??H;RY4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${LF(new Date("2026-03-05T15:32:53.284Z"))} ago`}catch{}s6.write(`0.0.1772724405-g1c19f6 (released 2026-03-05T15:32:53.284Z${B??""})
7406
+ `),!1}}function Js5(){let J=new lW().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)CE(),process.exit(0);let B=H.originalError??H;RY4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${LF(new Date("2026-03-05T16:19:46.573Z"))} ago`}catch{}s6.write(`0.0.1772727221-g52e1a8 (released 2026-03-05T16:19:46.573Z${B??""})
7407
7407
  `),process.exit(0)}),J.addHelpText("after",cX4()),J.configureHelp({formatHelp:lX4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await j3(w);await Vs5(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await j3(w);await Ks5(N,await au0(w,N.settings))}),J.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),O=await j3(N);await rY4(H??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let w=B.optsWithGlobals(),N=await j3(w);await sY4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7408
7408
  Actions:
7409
7409
  add-message <message> Send a user message and wait for message_added
@@ -7455,8 +7455,8 @@ ${L}
7455
7455
 
7456
7456
  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 Zs5(J){if(!J.userEmail||!nQ(J.userEmail))throw new H4("DTW TUI mode is only available for Amp employees",1);P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Zg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:p$,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new nX(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 Qs5(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await pm()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await pm()).trimEnd(),stdinInput:null}}function Ys5(J,Z,Q){if(J.remote&&!Z)throw new H4("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new H4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new H4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new H4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new H4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new H4("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 H4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new H4("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"
7457
7457
  Or pipe via stdin: echo "your message" | amp --execute`)}async function bJ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(q0,a)=>{let K0=Number(process.hrtime.bigint()-a)/1e6,z0=v24();P.info("Startup phase",{phase:q0,phaseMs:Math.round(K0),sinceMainMs:z0===null?void 0:Math.round(z0)})},{userInput:U,stdinInput:K}=await Qs5(Z),V=!!Z.streamJson||!!Z.streamJsonThinking;Ys5({...Z,streamJson:V},J.executeMode,U),d7(Q,Z);let D=process.hrtime.bigint(),z=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&z;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:z,executeMode:J.executeMode,headless:Boolean(Z.headless)});let G=await i9(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",D),D=process.hrtime.bigint();let F=await rc0(G);X("runMainThread:createWorkerDeps",D);let{serverStatus:W}=G;if(!q&&EF(W)){let q0=Om(Error(W.error.message));if(q0.message===V8.networkOffline||q0.message===V8.networkTimeout)throw ac0(J.ampURL);throw new H4(V8.invalidAPIKey,1)}let H=S5(W)?W:null,B=H?.user.email,w=cA4(B),N=!J.executeMode&&H!==null&&ic0(Z.dtw,H);if(!q)await lc0(Q,Z,W);let O=nc0(W),E=O?.features??[],L=O?.team??null,I=_80(Z,O);if(I instanceof Error)G3(I.message);if((J.executeMode||V)&&_8(Z.mode)&&!w)throw new H4(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(J.executeMode&&Z.remote)await gU4(U,K,G.configService),await G.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!nQ(B))throw new H4("Headless DTW mode is only available for Amp employees",1);let q0=await G.secretStorage.get("apiKey",J.ampURL);if(!q0)throw new H4("API key required for headless mode. Please run `amp login` first.",1);let a=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(a&&!v8(a))throw new H4(`Invalid thread ID: ${a}`,1);let K0=a??await Bs5({dependencies:G,visibility:I??void 0}),z0=await HX4(K0);if(z0.status==="already-running")await G.asyncDispose(),await Fq(),process.exit(0);try{await VX4({ampURL:J.ampURL,apiKey:q0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:K0,configService:G.configService,mcpService:G.mcpService,toolService:G.toolService,skillService:G.skillService,fileSystem:G.fileSystem,pluginService:G.pluginService,pluginPlatform:G.headlessPluginPlatform})}finally{await z0.release(),await G.asyncDispose()}await Fq(),process.exit(0)}let M={threadService:G.threadService,workerDeps:F,createThread:async()=>{let q0=q?await G.serverStatusPromise:W,a=await t30(J.settings,process.cwd(),nc0(q0),I);if(a instanceof Error)G3(a.message);return lh0(F,{threadMeta:a?PU(a):void 0,agentMode:Z.mode,onFirstAssistantMessage:hA4})},validateThreadOwnership:async(q0,a)=>{if(a?.nonBlockingOwnershipCheck){mA4(q0,G.configService).catch((K0)=>{if(K0 instanceof H4){if(a.onOwnershipError){a.onOwnershipError(K0,q0);return}NC(K0,q0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:K0})});return}try{await mA4(q0,G.configService)}catch(K0){if(K0 instanceof H4)throw K0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:K0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:hA4},A=async(q0,a)=>{try{if(q0==="dtw")return Zs5({userEmail:a?.dtwUserEmail??B,ampURL:J.ampURL,configService:G.configService,threadService:G.threadService,mcpService:G.mcpService,toolService:G.toolService,skillService:G.skillService,fileSystem:G.fileSystem,threadId:Z.threadId});return bF4(M,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(K0){if(K0 instanceof H4)throw K0;throw await NC(K0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")G7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7458
- `),await Fq(),process.exit(1);let R=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let q0=await G.configService.getLatest(),a=wk(q0),K0=await T6.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(a)});if(K0.ok)return P.info("User free tier status:",K0),K0.result;return}catch(q0){P.error("Failed to fetch free tier status:",q0);return}})(),S=!J.executeMode?new dx0:null,y,h=null;if(S)y=S,h=(async()=>{let q0=q?await G.serverStatusPromise:G.serverStatus;await lc0(Q,Z,q0);let a=process.hrtime.bigint(),K0=ic0(Z.dtw,q0),z0=S5(q0)?q0.user.email:void 0,O0=await A(K0?"dtw":"worker",{dtwUserEmail:z0});if(X("runMainThread:createThreadPool",a),S.attach(O0),U){let X0=await L1(O0.threadHandles$);if(!X0)throw new H4("No active thread is available yet.",1);await X0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(q0)=>{let a=q0 instanceof Error?q0:Error(String(q0));S.setInitError(a),await NC(q0,Z.threadId)});else D=process.hrtime.bigint(),y=await A(N?"dtw":"worker"),X("runMainThread:createThreadPool",D);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;D=process.hrtime.bigint();let k=await G.configService.getLatest();if(X("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),tr5({configService:G.configService,threadService:G.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(s1((q0)=>{if(!q0)return v0.of({});return t6(q0.thread$,q0.threadViewState$).pipe(W1(([a,K0])=>({[a.id]:K0})))}))}),X("runMainThread:createCliNotificationService",D),J.executeMode){if(TU4(G.mcpService,J.settings),!(y instanceof eC))throw new H4("Execute mode is not supported with the DTW thread pool",1);let q0=y.getWorkerForExecuteMode();if(await uY4({worker:q0,threadID:q0.threadID,userInput:U,stdinInput:K,dependencies:G,streamJson:V,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label}),Z.archive)await T6.archiveThread({thread:q0.threadID,archived:!0},{config:G.configService});await G.asyncDispose(),process.exit(0)}let x=!1,d=!1;if(Z.jetbrains||Z.ide){await mA1();let q0=JN({jetbrainsOnly:Z.jetbrains});if(q0.length===0){if(Z.jetbrains)x=!await G.configService.get("jetbrains.skipInstall")}else if(q0.length===1){let a=q0[0];if(a)y8.selectConfig(a)}else d=!0}D=process.hrtime.bigint();let l=Gx0("0.0.1772724405-g1c19f6",G.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let m=new HM0(G.threadStorage);X("runMainThread:createThreadFuzzyIndexer",D),D=process.hrtime.bigint();let o=new Hx0(G.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",D),U&&J.executeMode){let q0=await L1(y.threadHandles$);if(!q0)throw new H4("No active thread is available yet.",1);await q0.sendMessage({content:[{type:"text",text:U}]})}D=process.hrtime.bigint();let p=await cV();X("runMainThread:loadSessionState",D),P.info("Loaded session state:",p);let e={...p,launchCount:p.launchCount+1};lV(e);try{if(D=process.hrtime.bigint(),await iW4({codebaseContextService:G.codebaseContextService,history:new vu0,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadFuzzyIndexer:m,skillService:G.skillService,configService:G.configService,secretStorage:G.secretStorage,internalAPIClient:T6,threadPool:y,createSystemPromptDeps:async()=>iA4(G),ideClient:y8,mcpService:G.mcpService,toolboxService:G.toolboxService,mcpTrustHandler:o,updateService:l,pluginPlatform:G.pluginPlatform,pluginService:G.pluginService},{initialServerStatus:G.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:G.hasAPIKeyAtStartup,ampURL:J.ampURL,showJetBrainsInstaller:x,showIdePickerHint:d,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:e,freeTierStatusPromise:R,workspace:L??null,features:E,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-05T15:32:53.284Z"},(q0)=>new Nm0({...q0,threadPool:q0.threadPool},(a)=>new Bd0({...a,threadState:a.threadState}))),X("runMainThread:mountApp-returned",D),h)await h}finally{}await G.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function j3(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)G7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7459
- `);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 sy1({get:async(V)=>{if(V!==qu)return;try{let D=await pA4(cc0,"utf-8");return JSON.parse(D).installationID}catch{return}},set:async(V,D)=>{if(V!==qu)return;await mr5(Od.dirname(cc0),{recursive:!0}),await gr5(cc0,JSON.stringify({installationID:D},null,2),{mode:384})}},{clientType:"cli",platform:aQ()});OA1(Y);let X=await CX4({...J,workspaceTrust:{current:!0,changes:$k},getHook:process.env.AMP_URL?(V,D)=>{if(V==="url")return Promise.resolve(process.env.AMP_URL);return D()}:void 0});if(J.mcpConfig){let V=await PU4(J.mcpConfig);X=CU4(X,V)}let U=Od.dirname(X.getSettingsFilePath());g74(LC,U);let K=await X.get("url","global");if(!K)K=r9;if(P.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!sG(K))P.info("Targeting custom Amp server",{ampURL:K});return X=VA1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:iU4(await au0(J,X))}}function Xs5(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let U=Y.slice(2).replace(/-([a-z])/g,(V,D)=>D.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[U]=K,Q++}}return Z}async function Us5(){S24();let J=Xs5(process.argv),Z=process.argv.includes("--headless")||process.argv.some((U)=>U.startsWith("--headless="));cQ4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?dr5: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)J1.level=0;if(lr5(P),P.info("Starting Amp CLI.",{version:"0.0.1772724405-g1c19f6",buildTimestamp:"2026-03-05T15:32:53.284Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new H4(V8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Js5().parseAsync(process.argv)}h74().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Us5().catch(NC)});async function Ks5(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),s6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7458
+ `),await Fq(),process.exit(1);let R=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let q0=await G.configService.getLatest(),a=wk(q0),K0=await T6.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(a)});if(K0.ok)return P.info("User free tier status:",K0),K0.result;return}catch(q0){P.error("Failed to fetch free tier status:",q0);return}})(),S=!J.executeMode?new dx0:null,y,h=null;if(S)y=S,h=(async()=>{let q0=q?await G.serverStatusPromise:G.serverStatus;await lc0(Q,Z,q0);let a=process.hrtime.bigint(),K0=ic0(Z.dtw,q0),z0=S5(q0)?q0.user.email:void 0,O0=await A(K0?"dtw":"worker",{dtwUserEmail:z0});if(X("runMainThread:createThreadPool",a),S.attach(O0),U){let X0=await L1(O0.threadHandles$);if(!X0)throw new H4("No active thread is available yet.",1);await X0.sendMessage({content:[{type:"text",text:U}]})}})(),h.catch(async(q0)=>{let a=q0 instanceof Error?q0:Error(String(q0));S.setInitError(a),await NC(q0,Z.threadId)});else D=process.hrtime.bigint(),y=await A(N?"dtw":"worker"),X("runMainThread:createThreadPool",D);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;D=process.hrtime.bigint();let k=await G.configService.getLatest();if(X("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),tr5({configService:G.configService,threadService:G.threadService,config:k,useNotificationsForService:f,threadViewStates$:()=>y.threadHandles$.pipe(s1((q0)=>{if(!q0)return v0.of({});return t6(q0.thread$,q0.threadViewState$).pipe(W1(([a,K0])=>({[a.id]:K0})))}))}),X("runMainThread:createCliNotificationService",D),J.executeMode){if(TU4(G.mcpService,J.settings),!(y instanceof eC))throw new H4("Execute mode is not supported with the DTW thread pool",1);let q0=y.getWorkerForExecuteMode();if(await uY4({worker:q0,threadID:q0.threadID,userInput:U,stdinInput:K,dependencies:G,streamJson:V,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label}),Z.archive)await T6.archiveThread({thread:q0.threadID,archived:!0},{config:G.configService});await G.asyncDispose(),process.exit(0)}let x=!1,d=!1;if(Z.jetbrains||Z.ide){await mA1();let q0=JN({jetbrainsOnly:Z.jetbrains});if(q0.length===0){if(Z.jetbrains)x=!await G.configService.get("jetbrains.skipInstall")}else if(q0.length===1){let a=q0[0];if(a)y8.selectConfig(a)}else d=!0}D=process.hrtime.bigint();let l=Gx0("0.0.1772727221-g52e1a8",G.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let m=new HM0(G.threadStorage);X("runMainThread:createThreadFuzzyIndexer",D),D=process.hrtime.bigint();let o=new Hx0(G.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",D),U&&J.executeMode){let q0=await L1(y.threadHandles$);if(!q0)throw new H4("No active thread is available yet.",1);await q0.sendMessage({content:[{type:"text",text:U}]})}D=process.hrtime.bigint();let p=await cV();X("runMainThread:loadSessionState",D),P.info("Loaded session state:",p);let e={...p,launchCount:p.launchCount+1};lV(e);try{if(D=process.hrtime.bigint(),await iW4({codebaseContextService:G.codebaseContextService,history:new vu0,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadFuzzyIndexer:m,skillService:G.skillService,configService:G.configService,secretStorage:G.secretStorage,internalAPIClient:T6,threadPool:y,createSystemPromptDeps:async()=>iA4(G),ideClient:y8,mcpService:G.mcpService,toolboxService:G.toolboxService,mcpTrustHandler:o,updateService:l,pluginPlatform:G.pluginPlatform,pluginService:G.pluginService},{initialServerStatus:G.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:G.hasAPIKeyAtStartup,ampURL:J.ampURL,showJetBrainsInstaller:x,showIdePickerHint:d,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:e,freeTierStatusPromise:R,workspace:L??null,features:E,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-05T16:19:46.573Z"},(q0)=>new Nm0({...q0,threadPool:q0.threadPool},(a)=>new Bd0({...a,threadState:a.threadState}))),X("runMainThread:mountApp-returned",D),h)await h}finally{}await G.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function j3(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)G7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7459
+ `);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 sy1({get:async(V)=>{if(V!==qu)return;try{let D=await pA4(cc0,"utf-8");return JSON.parse(D).installationID}catch{return}},set:async(V,D)=>{if(V!==qu)return;await mr5(Od.dirname(cc0),{recursive:!0}),await gr5(cc0,JSON.stringify({installationID:D},null,2),{mode:384})}},{clientType:"cli",platform:aQ()});OA1(Y);let X=await CX4({...J,workspaceTrust:{current:!0,changes:$k},getHook:process.env.AMP_URL?(V,D)=>{if(V==="url")return Promise.resolve(process.env.AMP_URL);return D()}:void 0});if(J.mcpConfig){let V=await PU4(J.mcpConfig);X=CU4(X,V)}let U=Od.dirname(X.getSettingsFilePath());g74(LC,U);let K=await X.get("url","global");if(!K)K=r9;if(P.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!sG(K))P.info("Targeting custom Amp server",{ampURL:K});return X=VA1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:iU4(await au0(J,X))}}function Xs5(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let U=Y.slice(2).replace(/-([a-z])/g,(V,D)=>D.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[U]=K,Q++}}return Z}async function Us5(){S24();let J=Xs5(process.argv),Z=process.argv.includes("--headless")||process.argv.some((U)=>U.startsWith("--headless="));cQ4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?dr5: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)J1.level=0;if(lr5(P),P.info("Starting Amp CLI.",{version:"0.0.1772727221-g52e1a8",buildTimestamp:"2026-03-05T16:19:46.573Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new H4(V8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Js5().parseAsync(process.argv)}h74().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Us5().catch(NC)});async function Ks5(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),s6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7460
7460
  `);else if(!sG(J.ampURL))s6.write(`Logging in to ${new URL(J.ampURL).hostname}
7461
7461
  `);let Y=process.env.AMP_API_KEY;if(Y)s6.write(`API key found in environment variable, storing...
7462
7462
  `),await Z.set("apiKey",Y,J.ampURL),s6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1772724405-g1c19f6",
3
+ "version": "0.0.1772727221-g52e1a8",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {