@sourcegraph/amp 0.0.1778617350-g19dbc6 → 0.0.1778631508-g72c81a

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 +14 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -2677,7 +2677,9 @@ The file specified by \`path\` MUST exist, and it MUST be an absolute path. If y
2677
2677
 
2678
2678
  Set \`replace_all\` to true to replace all occurrences of \`old_str\` in the file. Else, \`old_str\` MUST be unique within the file or the edit will fail. Additional lines of context can be added to make the string more unique.
2679
2679
 
2680
- If you need to replace the entire contents of a file, use \`${v8}\` instead, since it requires less tokens for the same action (since you won't have to repeat the contents before replacing)
2680
+ If you need to replace the entire contents of a file, use \`${v8}\` instead, since it requires less tokens for the same action (since you won't have to repeat the contents before replacing).
2681
+
2682
+ If you see \`[REDACTED:_____]\` in your inputs and edits fail, Amp's secret redaction may have changed the text; ask the user to manually make the edit.
2681
2683
  `,kM4={spec:{name:z8,description:O15,inputSchema:b.toJSONSchema(gn0),source:"builtin",executionProfile:{resourceKeys:(A)=>{if(A&&typeof A==="object"&&"path"in A&&typeof A.path==="string")return[{key:A.path,mode:"write"}];return[]}}},fn:RM4}});function SM4(A){if(A.before===void 0&&A.after===void 0)throw Error("unreachable");if(A.before===null&&A.after===null)throw Error("unreachable")}function kY0(A,Q,B){let $=new Map,J=(Z)=>{let F;for(let[X,D]of $.entries())for(let[G,V]of D.entries()){if(!Z1.equalURIs(G,Z))continue;if(!F||V.timestamp<F.timestamp)F=V}return F},Y=async({filesFilter:Z,toolUsesToRevert:F,pruneRevertedToolUses:X})=>{let D=new n7,G=new Map;for(let[K,E]of $.entries()){let z=F?F.has(K):!0;for(let[W,H]of E.entries()){if(Z&&!Z(W))continue;if(H.reverted)continue;let q=D.get(W)||{changesAfterKeep:[]};if(!z){if(!q.latestKeepChange||H.timestamp>q.latestKeepChange.timestamp)q.latestKeepChange=H}else q.changesAfterKeep.push(H),G.set(H,K);D.set(W,q)}}let V=Array.from(D.entries()).filter(([,{changesAfterKeep:K}])=>K.length>0);if(await r70(V,R15,async([K,{latestKeepChange:E,changesAfterKeep:z}])=>{try{let W=z.reduce((q,N)=>N.timestamp<q.timestamp?N:q),H=E?E.after:W.isNewFile?null:W.before;await B(K,H);for(let q of z){q.reverted=!0;let N=G.get(q);if(N)try{let I={toolUseID:N,fileChangeID:q.id};await A.store(Q,I,q)}catch(I){j.error(`Error updating backup for file ${K}:`,I)}}}catch(W){j.error(`Error reverting file ${K}:`,W)}}),X&&F)for(let K of F)$.delete(K)};return{async getAllRecords(){return $},async record(Z){if(!Z.toolUse)return;let F=$.get(Z.toolUse);if(!F)F=new n7,$.set(Z.toolUse,F);let X=F.get(Z.uri),D=J(Z.uri),G=X?.before??Z.before??"",V=X?.isNewFile??Z.before===null,U=D?PD(D.before??"",Z.after??"",Z.uri):PD(G,Z.after??"",Z.uri),K=X?.id??crypto.randomUUID(),E={id:K,uri:u1(Z.uri),before:G,after:Z.after??"",diff:U,isNewFile:V,reverted:!1,timestamp:Date.now()};F.set(Z.uri,E),await A.store(Q,{toolUseID:Z.toolUse,fileChangeID:K},E),j.debug("Recorded file change",{isNewFile:V,isUpdate:!!X,filePath:Z.uri.toString(),toolUseID:Z.toolUse})},async restoreFromBackups(){let Z=await A.list(Q)??[];$.clear();for(let F of Z){let{toolUseID:X}=F,D=await A.load(Q,F);if(!D)continue;if(!$.has(X))$.set(X,new n7);$.get(X).set(D.uri,D)}return{totalBackups:Z.length}},async revertAll(Z){let F=new Set;for(let[X]of $.entries())F.add(X);await Y({filesFilter:Z?(X)=>Z1.equalURIs(X,Z):void 0,toolUsesToRevert:F,pruneRevertedToolUses:!1})},async revertChanges(Z){await Y({toolUsesToRevert:Z,pruneRevertedToolUses:!0})},getFilesForToolUses(Z){let F=new n7;for(let[X,D]of $.entries()){if(!Z.has(X))continue;for(let[G,V]of D.entries()){if(V.reverted)continue;F.set(G,!0)}}return Array.from(F.keys()).map(u1)},async cleanupBackups(){await A.cleanup(Q)},async getLastEdit(Z){let F,X,D=0;for(let[U,K]of $.entries()){let E=K.get(Z);if(E&&!E.reverted&&E.timestamp>=D)F=E,X=U,D=E.timestamp}if(!F||!X)return;let G=F,V=X;return{oldContent:G.before,newContent:G.after,revert:async()=>{G.reverted=!0,await A.store(Q,{toolUseID:V,fileChangeID:G.id},G)}}},dispose(){$.clear()}}}var R15=4;var mn0=r(()=>{e1();p0();QD();dO();s70()});function pn0(A,Q,B){async function $(J,Y){let Z={};Z.before=await pv0(A,J),await Y(),Z.after=await pv0(A,J),SM4(Z),await Q.record({toolUse:B,uri:J,...Z})}return{...A,async writeFile(J,Y,Z){await $(J,()=>A.writeFile(J,Y,Z))}}}function SY0(A,Q,B){async function $(Y,Z,F){if(Z!==null)await Q.writeFile(Y,Z,{signal:F});else await Q.delete(Y,{signal:F})}let J=kY0(A.fileChangeTrackerStorage,B,$);return{fileSystem:Q,trackedFileSystem:(Y)=>pn0(Q,J,Y),tracker:J}}var vY0=r(()=>{mn0();_Q()});function P15(A){if(A.action.type==="redact-tool-input"&&A.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(A.action.type==="send-user-message"&&A.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function dn0(A){if(!A||!Array.isArray(A))return[];return A.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let B=P15(Q);if(B)return j.warn(`Hook "${Q.id}" is invalid: ${B}`),!1;return!0})}var vM4=r(()=>{p0()});function yM4(A,Q){if(!A)return{action:null};A=dn0(A);for(let B of A){if(B.if===!1)continue;if(B.on.event==="tool:pre-execute"){if(!(Array.isArray(B.on.tool)?B.on.tool:[B.on.tool]).includes(Q.toolUse.name))continue;let J=JSON.stringify(Q.toolUse.input),Y=Array.isArray(B.on["input.contains"])?B.on["input.contains"]:[B.on["input.contains"]];for(let Z of Y)if(J.includes(Z)){if(j.debug(`Hook triggered: ${B.id}`,{hookID:B.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:Z,action:B.action}),B.action.type==="send-user-message")return{hookID:B.id,action:B.action}}}}return{action:null}}function xM4(A,Q){if(!A)return{action:null};A=dn0(A);for(let B of A){if(B.if===!1)continue;if(B.on.event==="tool:post-execute"){if(!(Array.isArray(B.on.tool)?B.on.tool:[B.on.tool]).includes(Q.toolUse.name))continue;if(j.debug(`Post-execution hook triggered: ${B.id}`,{hookID:B.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:B.action}),B.action.type==="redact-tool-input")return{hookID:B.id,action:B.action}}}return{action:null}}function fM4(A,Q){if(!A)return{action:null};try{return A(Q.thread)}catch(B){return j.error("Error processing assistant end-turn hook",B),{action:null}}}function vy(A,Q,B){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":{let $={type:"user:message",message:{messageId:0,content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}};return A.updateThread($),A.onThreadDelta($),{abortOp:!0}}case"redact-tool-input":{if(!B?.toolUseID)return j.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};let $={type:"tool:processed",toolUse:B.toolUseID,newArgs:Q.action.redactedInput};return A.updateThread($),A.onThreadDelta($),j.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:B.toolUseID}),{abortOp:!1}}case"handoff":return j.info("Handoff hook triggered",{hookID:Q.hookID,goal:Q.action.goal}),A.executeHandoff(Q.action.goal),{abortOp:!1}}}var cn0=r(()=>{p0();vM4()});function _15(A,Q,B){let $=B.getExecutionProfile(A.name),J=B.getExecutionProfile(Q.name);if(!$||!J)return!0;if($.serial||J.serial)return!0;let Y=$.resourceKeys(A.input??{}),Z=J.resourceKeys(Q.input??{});for(let F of Y)for(let X of Z)if(F.key===X.key){if(F.mode==="write"||X.mode==="write")return!0}return!1}function T15(A,Q,B){for(let $ of Q)if(_15(A,$,B))return!0;return!1}function bM4(A,Q){if(A.length===0)return[];let B=[],$=[];for(let J of A){if(T15(J,$,Q)){if($.length>0)B.push($),$=[]}$.push(J)}if($.length>0)B.push($);return B}class ln0{threadID;toolService;callbacks;processingMutex=new pY;runningTools=new Map;cancelledToolUses=new Set;toolMessages=new Map;toolCompletionResolvers=new Map;pendingApprovalsSubscription;writtenBlockedToolUseIds=new Set;disposed=!1;constructor(A,Q,B){this.threadID=A;this.toolService=Q;this.callbacks=B;this.pendingApprovalsSubscription=this.toolService.pendingApprovals$.subscribe(($)=>{this.syncPendingApprovalsToThreadState($)})}syncPendingApprovalsToThreadState(A){let Q=A.filter(($)=>$.threadId===this.threadID);for(let $ of Q)if(!this.writtenBlockedToolUseIds.has($.toolUseId))this.writtenBlockedToolUseIds.add($.toolUseId),j.debug("Writing blocked-on-user to thread state",{name:"syncPendingApprovalsToThreadState",threadID:this.threadID,toolUseId:$.toolUseId,toolName:$.toolName}),this.callbacks.updateThread({type:"tool:data",toolUse:$.toolUseId,data:{status:"blocked-on-user",reason:$.reason,toAllow:$.toAllow}});let B=new Set(Q.map(($)=>$.toolUseId));for(let $ of this.writtenBlockedToolUseIds)if(!B.has($))this.writtenBlockedToolUseIds.delete($)}async onResume(){await this.processingMutex.acquire();try{let A=this.callbacks.getThread(),Q=n2(A,"user");if(!Q)return;for(let B of Q.content){if(B.type!=="tool_result")continue;if(B.run.status==="blocked-on-user"){let Y=this.findToolUseById(B.toolUseID);if(!Y)continue;j.debug(`restoring blocked-on-user tool ${Y.name} to approval queue`,{name:"onResume",threadID:this.threadID,toolUseID:B.toolUseID}),this.toolService.restoreApproval({threadId:this.threadID,toolUseId:B.toolUseID,toolName:Y.name,args:Y.input??{},reason:B.run.reason,toAllow:B.run.toAllow,context:A.mainThreadID?"subagent":"thread"});continue}if(!(!y5(B.run.status)&&!this.runningTools.has(B.toolUseID)))continue;let J=this.findToolUseById(B.toolUseID);if(!J)continue;if(this.isDangerousToResume(J.name)){j.debug(`cancelling dangerous tool ${J.name} on resume`,{name:"onResume",threadID:this.threadID,toolUseID:B.toolUseID});let Y=sM(B.run);this.callbacks.updateThread({type:"tool:data",toolUse:B.toolUseID,data:{status:"cancelled",reason:"system:safety",progress:Y}});continue}j.debug(`re-invoking tool ${J.name} with ID ${B.toolUseID}`,{name:"onResume",threadID:this.threadID}),await this.invokeTool(J,B.userInput)}}finally{this.processingMutex.release()}await this.callbacks.updateFileChanges()}async onAssistantMessageComplete(A){let Q;await this.processingMutex.acquire();try{this.cancelledToolUses.clear(),Q=this.findToolUsesNeedingInvocation(A),j.debug(`saw ${Q.length} tool uses (${Q.map((B)=>B.name).join(", ")})`,{name:"onAssistantMessageComplete",threadID:this.threadID})}finally{this.processingMutex.release()}if(Q.length>0)await this.executeToolsWithPlan(Q)}async userProvideInput(A,Q){await this.processingMutex.acquire();try{let B=this.findToolUseById(A);if(B&&h3(B))await this.invokeTool(B,Q)}finally{this.processingMutex.release()}}async userCancel(A){await this.cancelTool(A,"user:cancelled")}async onNewUserMessage(){this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),await this.cancelAll("user:interrupted")}async cancelAll(A){await this.processingMutex.acquire();try{this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),this.cancelUnstartedTools(A),await this.cancelInProgressTools(A)}finally{this.processingMutex.release()}}async findAndCancelToolRun(A,Q){let B=this.callbacks.getThread();if(!a9(B,A))return;await this.cancelTool(A,"user:cancelled",Q)}async cancelToolOnly(A,Q){let B=this.callbacks.getThread();if(!a9(B,A))return;let J=this.getCancelDataForToolRun(A,"user:cancelled"),Y=this.toolMessages.get(A);if(Y){try{Y.next({type:"stop-command"})}catch(Z){j.warn("Failed to send stop-command",{toolUseID:A,error:Z})}Y.complete(),this.toolMessages.delete(A)}j.debug(`cancelToolOnly(${A})`),await this.callbacks.handle({type:"tool:data",toolUse:A,data:J},Q)}getRunningToolIds(){return Array.from(this.runningTools.keys())}hasRunningTools(){return this.runningTools.size>0}isCancelled(A){return this.cancelledToolUses.has(A)}markCancelled(A){this.cancelledToolUses.add(A)}clearCancelled(A){this.cancelledToolUses.delete(A)}sendToolMessage(A,Q){let B=this.toolMessages.get(A);if(B)return B.next(Q),!0;return!1}resolveToolCompletion(A,Q,B){let $=this.toolCompletionResolvers.get(A);if($){if(Q)$.resolve();else $.reject(B??Error(`Tool failed: ${A}`));this.toolCompletionResolvers.delete(A)}}dispose(){if(this.disposed)return;this.disposed=!0,this.pendingApprovalsSubscription.unsubscribe(),this.toolService.clearApprovalsForThread(this.threadID),this.writtenBlockedToolUseIds.clear();for(let[A,Q]of this.toolCompletionResolvers)try{Q.reject(Error("Orchestrator disposed"))}finally{this.toolCompletionResolvers.delete(A)}for(let[A,Q]of this.toolMessages)try{Q.next({type:"stop-command"}),Q.complete()}catch(B){j.warn("Failed to cleanup tool messages during disposal",{id:A,error:B})}this.toolMessages.clear();for(let A of this.runningTools.values())A.abort.abort();this.runningTools.clear(),this.cancelledToolUses.clear()}findToolUsesNeedingInvocation(A){if(A.content.some((F)=>F.type==="tool_use"&&!h3(F)))return[];if(!(A.state?.type==="complete"||A.state?.type==="cancelled"))return[];let $=this.callbacks.getThread(),J=n2($,"user"),Y=n2($,"assistant"),Z=new Set;if(J?.messageId!==void 0&&Y?.messageId!==void 0&&J.messageId>Y.messageId){for(let F of J.content)if(F.type==="tool_result")Z.add(F.toolUseID)}return A.content.filter((F)=>F.type==="tool_use").filter((F)=>!Z.has(F.id)&&!this.cancelledToolUses.has(F.id))}async executeToolsWithPlan(A){if(A.length===0)return;let Q=bM4(A,this.toolService);j.debug(`executing ${A.length} tools in ${Q.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Q.map((B)=>B.map(($)=>$.name))}),await this.executeToolBatchesSequentially(Q)}async executeToolBatchesSequentially(A){for(let Q of A){let $=(await Promise.allSettled(Q.map((J)=>this.invokeToolAndWait(J,void 0)))).filter((J)=>J.status==="rejected");if($.length>0)j.warn(`${$.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:$.map((J)=>J.reason)})}}async invokeToolAndWait(A,Q){let B=new Promise(($,J)=>{this.toolCompletionResolvers.set(A.id,{resolve:$,reject:J})});this.invokeTool(A,Q).catch(($)=>{let J=this.toolCompletionResolvers.get(A.id);if(J)j.debug(`Tool invocation setup failed for ${A.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String($)}),J.reject($),this.toolCompletionResolvers.delete(A.id)}),await B}async invokeTool(A,Q){if(this.runningTools.has(A.id))throw Error(`(bug) tool invocation already in progress: ${A.id}`);if(!h3(A))throw Error(`(bug) tool use is incomplete: ${A.id}`);let B=await this.callbacks.getConfig(),$=yM4(B.settings?.hooks,{threadID:this.threadID,toolUse:A}),{abortOp:J}=await this.callbacks.applyHookResult($);if(J){let X=this.toolCompletionResolvers.get(A.id);if(X)X.resolve(),this.toolCompletionResolvers.delete(A.id);return}let Y=A.input;if(this.callbacks.requestPluginToolCall){let X={thread:{id:this.threadID},toolUseID:A.id,tool:A.name,input:A.input??{}},D=await this.callbacks.requestPluginToolCall(X);if(D.action==="error"){j.warn("Plugin returned error action",{tool:A.name,message:D.message,toolUseID:A.id});let G=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"error",error:{message:`Plugin error: ${D.message}`,displayMessage:D.message}}}),G)G.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(D.action==="reject-and-continue"){let G=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"done",result:`Tool rejected by plugin: ${D.message}`,isFinal:!1}}),G)G.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(D.action==="synthesize"){let G=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"done",result:D.result.output,isFinal:!1}}),G)G.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(D.action==="modify")Y=D.input,await this.callbacks.handle({type:"tool:processed",toolUse:A.id,newArgs:D.input})}if(this.cancelledToolUses.has(A.id)){this.ensureCancelledToolResult(A.id,"user:interrupted"),this.resolveToolCompletion(A.id,!0);return}let Z=new AbortController,F={abort:Z};this.runningTools.set(A.id,F),this.callbacks.updateThread({type:"tool:data",toolUse:A.id,data:{status:"in-progress"}});try{let X=await this.callbacks.getToolRunEnvironment(A.id,Z.signal),D=new u0((N)=>{this.toolMessages.set(A.id,N)}),G={...X,toolMessages:D},V=this.toolService.preprocessArgs?.(A.name,Y,G);if(V)await this.callbacks.handle({type:"tool:processed",toolUse:A.id,newArgs:V});let U=V??Y,K=this.toolService.normalizeToolName(A.name),E=typeof U==="object"&&U!==null?this.toolService.normalizeToolArgs(A.name,U):U,z=typeof E==="object"&&E!==null&&"__isFinal"in E&&typeof E.__isFinal==="boolean"?E.__isFinal:void 0,W=z!==void 0?Object.fromEntries(Object.entries(E).filter(([N])=>N!=="__isFinal")):E,H=this.toolService.invokeTool(K,{args:W,userInput:Q},G).pipe(sK(this.callbacks.getDisposed$()),SH(()=>{this.runningTools.delete(A.id),this.toolMessages.get(A.id)?.complete(),this.toolMessages.delete(A.id)})).subscribe({next:async(N)=>{if(this.cancelledToolUses.has(A.id))return;if(j.debug(`${A.id}, ${N.status}`,{name:"invokeTool",threadID:this.threadID}),y5(N.status)){this.runningTools.delete(A.id),H.unsubscribe();let w=this.toolCompletionResolvers.get(A.id);if(w){if(N.status==="done")w.resolve();else w.reject(Error(`Tool ${N.status}: ${A.id}`));this.toolCompletionResolvers.delete(A.id)}if(N.status==="done"&&N.trackFiles?.length)this.callbacks.trackFiles(N.trackFiles);if(N.status==="done"&&A.name.toLowerCase()===x7.toLowerCase())this.callbacks.onSkillToolComplete(A);if(B.settings?.hooks){let L=xM4(B.settings.hooks,{threadID:this.threadID,toolUse:A});await this.callbacks.applyPostHookResult(L,{toolUseID:A.id})}if(this.callbacks.requestPluginToolResult){let L={thread:{id:this.threadID},toolUseID:A.id,tool:A.name,input:A.input??{},status:N.status,error:N.status==="error"?N.error?.message:void 0,output:N.status==="done"?N.result:void 0};try{let O=await this.callbacks.requestPluginToolResult(L);if(O)N={...N,status:O.status,error:O.status==="error"?{message:O.error??"Plugin error"}:void 0,result:O.output}}catch(O){j.debug("Failed to request plugin tool result",{error:O})}}}await this.callbacks.updateFileChanges();let I=z!==void 0&&N.status==="done"&&N.isFinal===void 0?{...N,isFinal:z}:N;await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:I},Z.signal)},error:async(N)=>{let I=this.toolCompletionResolvers.get(A.id);if(I)I.reject(N),this.toolCompletionResolvers.delete(A.id);await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"error",error:{message:"message"in N?N.message:String(N),displayMessage:"displayMessage"in N?N.displayMessage:void 0}}},Z.signal)},complete:()=>{let N=this.toolCompletionResolvers.get(A.id);if(!N)return;let I=this.callbacks.getThread(),w=nZ(I).get(A.id)?.run;if(w&&y5(w.status))return;let L;if(this.callbacks.isDisposed())L="Worker disposed";else if(Z.signal.aborted)L="Tool aborted";else if(this.cancelledToolUses.has(A.id))L="Tool cancelled";else L="Tool observable completed without terminal state";N.reject(Error(L)),this.toolCompletionResolvers.delete(A.id)}}),q=this.runningTools.get(A.id);if(q)q.subscription=H;eH(Z.signal,()=>H.unsubscribe())}catch(X){this.runningTools.delete(A.id);let D=this.toolCompletionResolvers.get(A.id);if(D)D.reject(X),this.toolCompletionResolvers.delete(A.id);throw X}}async cancelTool(A,Q,B){let $=this.getCancelDataForToolRun(A,Q),J=this.toolMessages.get(A);if(J){try{J.next({type:"stop-command"})}catch(Y){j.warn("Failed to send stop-command",{toolUseID:A,error:Y})}J.complete(),this.toolMessages.delete(A)}j.debug(`cancelTool(${A}, ${Q})`),await this.callbacks.handle({type:"tool:data",toolUse:A,data:$},B),this.resolveToolCompletion(A,!0)}ensureCancelledToolResult(A,Q){let B=this.callbacks.getThread(),$=nZ(B).get(A)?.run;if($&&y5($.status))return;this.callbacks.updateThread({type:"tool:data",toolUse:A,data:{status:"cancelled",reason:Q,progress:$?sM($):void 0}})}getCancelDataForToolRun(A,Q){let B=this.callbacks.getThread(),$=nZ(B).get(A)?.run;return{status:"cancelled",progress:$?sM($):void 0,reason:Q}}markAllActiveToolsCancelled(){let A=this.callbacks.getThread(),Q=n2(A,"assistant");if(Q){let B=n2(A,"user"),$=new Map;if(B){for(let J of B.content)if(J.type==="tool_result")$.set(J.toolUseID,J.run)}for(let J of Q.content)if(J.type==="tool_use"&&h3(J)){let Y=$.get(J.id);if(!(Y?y5(Y.status):!1))this.cancelledToolUses.add(J.id)}}}cancelUnstartedTools(A){let Q=this.callbacks.getThread(),B=nZ(Q),$=Q.messages.findLastIndex((Y)=>y30(Y)),J=$===-1?Q.messages:Q.messages.slice($+1);for(let Y of J){if(Y.role!=="assistant")continue;for(let Z of Y.content)if(Z.type==="tool_use"&&h3(Z)){let F=B.get(Z.id);if(F?.run.status==="blocked-on-user"&&A==="system:disposed")continue;if(!F||F.run.status==="blocked-on-user")this.callbacks.updateThread({type:"tool:data",toolUse:Z.id,data:{status:"cancelled",reason:A}})}}}async cancelInProgressTools(A){for(let[Q,B]of this.runningTools)B.abort.abort(),B.subscription?.unsubscribe(),await this.cancelTool(Q,A);this.runningTools.clear()}findToolUseById(A){let Q=this.callbacks.getThread(),B=n2(Q,"assistant");if(!B)return;for(let $ of B.content)if($.type==="tool_use"&&$.id===A)return $;return}isDangerousToResume(A){return A===tA||A===Vp||A===DY||A===E8||A===tT}abortToolOp(A){let Q=this.runningTools.get(A);if(Q)Q.abort.abort(),this.runningTools.delete(A)}abortAllTools(){for(let[A,Q]of this.runningTools){let B=this.toolMessages.get(A);if(B){try{B.next({type:"stop-command"}),B.complete()}catch($){j.warn("Failed to send stop-command during disposal",{toolId:A,error:$})}this.toolMessages.delete(A)}Q.abort.abort()}this.runningTools.clear()}}var uM4=r(()=>{L1();cX();p0();f4();Qq();cn0();i4()});function hM4(A){let Q=[],B=/@((?:[^\s@\\,;]|\\.)+)/g,$;while(($=B.exec(A))!==null){let J=$[1],Y=k15(J).replace(/[.,;:!?)}\]]+$/,"");Q.push(Y)}return{paths:Q}}function k15(A){if(A.match(/^[A-Za-z]:[\\]/))return A.replace(/\\(.)/g,(Q,B)=>{if(B===" "||B==="("||B===")"||B==="["||B==="]"||B==="?"||B==="*")return B;return Q});return A.replace(/\\(.)/g,"$1")}function yY0(A){if(!A.connected)return;return mM4(A)}async function gM4(){if(!await m3.isConnected())return;let Q=await T1(m3.status);return mM4(Q)}function mM4(A){let Q=A.selections?.[0],B=d30(Q),$=B&&Q?{line:Q.range.startLine+1,column:Q.range.startCharacter}:void 0;return{currentlyVisibleFiles:A.visibleFiles??[],activeEditor:A.openFile,cursorLocation:$,cursorLocationLine:void 0,selectionRange:!B&&Q?{start:{line:Q?.range.startLine+1,column:Q?.range.startCharacter},end:{line:Q?.range.endLine+1,column:Q?.range.endCharacter}}:void 0}}var xY0=r(()=>{L1();KE();gM()});function pM4(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B?.role==="user"&&B.userState!==void 0)return B.userState}return}async function dM4(A,{configService:Q,filesystem:B,previousUserState:$}){let J={sentAt:Date.now()},Y=W8(A.content),{paths:Z}=hM4(Y),F=await T1(Q.workspaceRoot);if(!F)return{message:{role:"user",messageId:0,content:A.content,source:A.source,fileMentions:void 0,userState:void 0,agentMode:A.agentMode,meta:J}};let X=await yQ0({fileSystem:B},Z,{searchPaths:[F],shouldIncludeImages:!A.agentMode||Ip(A.agentMode)}),D;if(X?.files&&X.files.length>0){let K=new Set,E=[];for(let z of X.files){let W=_A(z.uri),H=await XF(B,W,F,null,K,void 0);for(let q of H){if(!E.some((N)=>N.uri===q.uri))E.push(q);K.add(q.uri)}}if(E.length>0)D=E}let G={...await gM4()??qZ4},V=$!==void 0&&dZ(G,$)?void 0:G;return{message:{role:"user",messageId:0,content:X?.imageBlocks?.length?[...A.content,...X.imageBlocks]:A.content,source:A.source,fileMentions:X,userState:V,agentMode:A.agentMode,discoveredGuidanceFiles:D,meta:J}}}var cM4=r(()=>{e1();L1();x5();Q3();hE();i4();hq();xY0()});function S15(A,Q){let B=n2(A,"assistant");if(!B)return{updatedThread:A,uninvoked:[]};let $=B.content.filter((Z)=>Z.type==="tool_use"),J=Q.items.filter((Z)=>!Q.wasInvoked($,Z));if(J.length===0)return{updatedThread:A,uninvoked:[]};return{updatedThread:k2(A,(Z)=>{let F=Z.messages.findLast((X)=>X.role==="assistant");if(F&&F.role==="assistant"){for(let X of J){let D=iZ();F.content.push({type:"tool_use",complete:!0,id:D,name:Q.toolName,input:Q.toToolInput(X)})}if(F.state.type==="complete"&&F.state.stopReason==="end_turn")F.state={...F.state,stopReason:"tool_use"}}Z.v++}),uninvoked:J}}class yy{deps;threadID;trackFilesFromHistory(){j.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let A of this.thread.messages){if(A.role==="user"&&A.fileMentions?.files)this.trackFiles(A.fileMentions.files.map((Q)=>Q.uri).filter((Q)=>Q!==void 0));if(A.role==="user"){for(let Q of A.content)if(Q.type==="tool_result"&&Q.run?.status==="done")this.trackFiles(Q.run.trackFiles??[])}}}async getConfig(A){return T1(this.deps.configService.config,A)}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupEphemeralErrorLogging(){this.ephemeralError.pipe(sK(this.disposed$)).subscribe((A)=>{if(A)j.error("ephemeral error",{error:A})})}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(H1((A)=>({permissions:eK(A.settings?.permissions),dangerouslyAllowAll:A.settings?.dangerouslyAllowAll??!1})),_4((A,Q)=>A.dangerouslyAllowAll===Q.dangerouslyAllowAll&&A.permissions===Q.permissions),Hs1(1),sK(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){if(this.isDisposed)return;for(let A=this.thread.messages.length-1;A>=0;A--){let Q=this.thread.messages[A];if(!Q||Q.role!=="user")continue;let B=!1;for(let $ of Q.content)if($.type==="tool_result"&&$.run?.status==="blocked-on-user"&&$.toolUseID)B=!0,this.checkAndApproveBlockedTool($.toolUseID);if(!B)break}}async checkAndApproveBlockedTool(A){try{let Q=a9(this.thread,A);if(!Q){j.warn("Tool use block not found for blocked tool",{toolUseID:A});return}let B=await v80(Q.name,Q.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,A);if(B.permitted)j.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:A,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:A,value:{accepted:!0}});else j.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:A,reason:B.reason})}catch(Q){j.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:A})}}ops={tools:{},toolMessages:{},inference:null,titleGeneration:null};_state=new s1("initial");state=this._state.pipe(_4(),sA({shouldCountRefs:!0}));handleMutex=new pY;ephemeralError=new s1(void 0);ephemeralErrorRetryAttempt=0;retryCountdownSeconds=new s1(void 0);retryTimer=null;retrySession=0;_inferenceState=new s1("idle");_turnStartTime=new s1(void 0);_turnElapsedMs=new s1(void 0);fileChanges=new s1({files:[]});get inferenceState(){return this._inferenceState.getValue()}toolCallUpdates=new g4;trackedFiles=new vQ;discoveredGuidanceFileURIs=new Set;fs;cachedFileChanges=[];disposed$=new g4;isDisposed=!1;shouldContinueAfterRejection=!1;_pendingSkills=new s1([]);handoffState=new s1(void 0);pendingSkills=this._pendingSkills.pipe(_4(),sA({shouldCountRefs:!0}));_awaitingSkillInvocation=new s1([]);toolOrchestrator;currentAgentSpan=null;reasoningEffortOverride;currentSpan=null;traceStore;constructor(A,Q){this.deps=A;this.threadID=Q;this.fs=SY0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,Q),this.traceStore={startTrace:(B)=>{this.updateThread({type:"trace:start",span:B})},recordTraceEvent:(B,$)=>{this.updateThread({type:"trace:event",span:B,event:$})},recordTraceAttributes:(B,$)=>{this.updateThread({type:"trace:attributes",span:B,attributes:$})},endTrace:(B)=>{this.updateThread({type:"trace:end",span:B})}},this.toolOrchestrator=new ln0(Q,A.toolService,this.createOrchestratorCallbacks())}createTracer(A){return $b0(this.traceStore,A)}getPluginTracer(){let A=this.currentSpan?.id??this.currentAgentSpan?.span;if(!A)return;return this.createTracer(A)}createOrchestratorCallbacks(){return{getThread:()=>this.thread,updateThread:(A)=>this.updateThread(A),handle:(A,Q)=>this.handle(A,Q),getToolRunEnvironment:(A,Q)=>this.getToolRunEnvironment(A,Q),getHooks:async()=>(await this.getConfig()).settings?.hooks,getConfig:()=>this.getConfig(),updateFileChanges:()=>this.updateFileChanges(),trackFiles:(A)=>this.trackFiles(A),isDisposed:()=>this.isDisposed,getDisposed$:()=>this.disposed$,onSkillToolComplete:(A)=>this.onSkillToolComplete(A),applyHookResult:(A)=>Promise.resolve(vy(this,A)),applyPostHookResult:(A,Q)=>Promise.resolve(vy(this,A,Q)),requestPluginToolCall:this.deps.pluginService?(A)=>this.deps.pluginService.event.toolCall(A,this.getPluginTracer()):void 0,requestPluginToolResult:this.deps.pluginService?(A)=>this.deps.pluginService.event.toolResult(A,this.getPluginTracer()):void 0}}async getToolRunEnvironment(A,Q){let B=await this.getWorkspaceRoot(Q),$=$k(this.thread),J=a9(this.thread,A);return{...this.deps,dir:B,tool:J?.name??"",thread:this.thread,config:await this.getConfig(Q),trackedFiles:new vQ(this.trackedFiles),filesystem:this.fs.trackedFileSystem(A),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:A,todos:$,toolMessages:new u0(()=>{}),threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),agentMode:await this.getSelectedAgentMode(),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs}}onSkillToolComplete(A){let Q=A.input;this.thread=k2(this.thread,(B)=>{if(!B.activatedSkills)B.activatedSkills=[];if(!B.activatedSkills.some(($)=>$.name===Q.name))B.activatedSkills.push({name:Q.name,arguments:Q.arguments})})}status=this.state.pipe(x4((A)=>A==="active"?M6(this._inferenceState.pipe(_4()),this.fileChanges.pipe(_4()),this.ephemeralError,this.handoffState.pipe(_4()),this.retryCountdownSeconds.pipe(_4()),this._turnStartTime.pipe(_4()),this._turnElapsedMs.pipe(_4()),this.toolCallUpdates.pipe(B6(void 0))).pipe(H1(([Q,B,$,J,Y,Z,F])=>({state:A,inferenceState:Q,fileChanges:B,ephemeralError:$?{message:$.message,stack:"stack"in $?$.stack:void 0,error:"error"in $&&$.error&&typeof $.error==="object"&&"error"in $.error?$.error.error:void 0,retryCountdownSeconds:Y}:void 0,handoff:J,turnStartTime:Z,turnElapsedMs:F})),sK(this.disposed$)):u0.of({state:A})),sA({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(A){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(A),this.__testing__setThread(A)}updateThread(A){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(WZ4(A,new Date)),this.__testing__setThread(this.threadReadWriter.read())}repairMissingToolResultsForInference(){let A=!1,Q=k2(this.thread,(B)=>{for(let $=B.messages.length-1;$>=0;$--){let J=B.messages[$];if(J?.role!=="assistant")continue;if(!(J.state.type==="cancelled"||J.state.type==="complete"&&J.state.stopReason==="tool_use"))continue;if(J.content.some((K)=>K.type==="tool_use"&&!K.complete))continue;let F=J.content.filter((K)=>K.type==="tool_use"&&K.complete);if(F.length===0)continue;let X=B.messages[$+1];if(X?.role!=="user")continue;let D=new Map,G=[];for(let K of X.content)if(K.type==="tool_result"&&F.some((z)=>z.id===K.toolUseID))D.set(K.toolUseID,K);else G.push(K);let V=!1,U=[];for(let K of F){let E=D.get(K.id);if(E)U.push(J6(E));else U.push(J6({type:"tool_result",toolUseID:K.id,run:{status:"cancelled",reason:"user:interrupted"}})),V=!0,A=!0}if(V)X.content=[...U,...G]}if(A)B.v++});if(A)this.thread=Q}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(A){}__testing__getDeps(){return this.deps}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let A=this.thread.messages.at(-1);if(A?.role==="assistant"&&A.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),this.triggerTitleGeneration(),!this.shouldResumeFromLastMessage(A))return;await this.toolOrchestrator.onResume(),this.setupSettingsChangeHandlers(),this.setupEphemeralErrorLogging(),this.replayLastCompleteMessage()}resumed=!1;shouldResumeFromLastMessage(A){if(ue1(A)||he1(A)&&!this.shouldContinueAfterRejection||y30(A))return this._inferenceState.next("cancelled"),!1;return!0}replayLastCompleteMessage(){let A=this.thread.messages.findLastIndex((B)=>B.role==="user"?ge1(B):B.role==="assistant"&&B.state.type==="complete");if(A===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Q=this.thread.messages[A];switch(Q.role){case"user":if(!Q.interrupted)this.onThreadDelta({type:"user:message",message:Q});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Q});break}}async handle(A,Q){let B=A.type==="user:message"&&A.index!==void 0?A.index:void 0;await this.handleMutex.acquire();try{await this.innerHandle(A,Q)}finally{this.handleMutex.release()}if(B!==void 0)await this.performMessageEditCleanup()}async innerHandle(A,Q){if(this.isDisposed){j.debug(`Skipping ${A.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Q?.aborted){j.debug(`Skipping ${A.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),A.type==="pending-skills"){let J=this._pendingSkills.getValue();this._pendingSkills.next([...J,...A.skills]),j.info("Pending skills set for injection",{threadID:this.threadID,skillNames:A.skills.map((Y)=>Y.name)});return}let B=A,$=[];if(A.type==="user:message"){let J=pM4(this.thread.messages),Y=await dM4(A.message,{configService:this.deps.configService,filesystem:this.fs.fileSystem,previousUserState:J});if($=this._pendingSkills.getValue(),$.length>0)j.info("Pending skills will be injected as info message",{threadID:this.threadID,skillNames:$.map((Z)=>Z.name)}),this._pendingSkills.next([]);B=k2(A,(Z)=>{Z.message=J6(Y.message),Q?.throwIfAborted()})}if(B.type==="assistant:message"||B.type==="assistant:message-update")B=this.addNormalizedInputToToolUses(B);try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let J=this.thread;if(this.updateThread(B),this.onThreadDelta(B,J),$.length>0)await this.injectPendingSkills($,Q)}catch(J){if(!e8(J))j.error("Ephemeral error during handle processing",J,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(J instanceof Error?J:Error(String(J)));else j.debug(`AbortError caught during handle processing for ${B.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;addNormalizedInputToToolUses(A){let Q=this.thread.agentMode;if(!A.message.content.some(($)=>$.type==="tool_use"))return A;return k2(A,($)=>{for(let J of $.message.content)if(J.type==="tool_use"){if(!J.name){j.warn("Skipping tool_use normalization due to missing name",{threadID:this.threadID});continue}let Y=this.deps.toolService.normalizeToolName(J.name);if(Y!==J.name)J.normalizedName=Y;if(J.input&&typeof J.input==="object"){let F=this.deps.toolService.normalizeToolArgs(J.name,J.input,Q);if(JSON.stringify(F)!==JSON.stringify(J.input))J.normalizedInput=F}if((Y!==J.name?Y:J.name)===tT&&!J.metadata?.handoffThreadID)J.metadata={...J.metadata,handoffThreadID:i2()}}})}onThreadDelta(A,Q){switch(A.type){case"user:message":{if(this.resetRetryAttempts(),this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),A.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((J)=>{if(J.role==="user"){for(let Y of J.content)if(Y.type==="tool_result"&&Y.run?.status==="done"&&Y.run.trackFiles)this.trackFiles(Y.run.trackFiles);if(J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Y)=>Y.uri).filter((Y)=>Y!==void 0))}});else this.trackFiles(A.message.fileMentions?.files?.map((J)=>J.uri).filter((J)=>J!==void 0)??[]);let B=this.thread.messages.at(-1)?.messageId??0,$=W8(A.message.content);this.startAgentSpan(B),this.beginInference({agentStart:{messageId:B,messageText:$}});break}case"user:message-queue:dequeue":{let B=this.thread.messages.at(-1);if(!B)break;if(B.role!=="user")break;this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),this.trackFiles(B.fileMentions?.files?.map((Y)=>Y.uri).filter((Y)=>Y!==void 0)??[]);let $=B.messageId??0,J=W8(B.content);this.startAgentSpan($),this.beginInference({agentStart:{messageId:$,messageText:J}});break}case"user:tool-input":{this.toolOrchestrator.userProvideInput(A.toolUse,A.value).catch((B)=>{j.error("userProvideInput failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,toolUse:A.toolUse,error:B instanceof Error?B.message:String(B)})});break}case"tool:data":{if(this.toolOrchestrator.isCancelled(A.toolUse)){let $=nZ(this.thread).get(A.toolUse)?.run,J=$?sM($):void 0;this.updateThread({type:"tool:data",toolUse:A.toolUse,data:{status:"cancelled",reason:"user:interrupted",progress:J}});return}let B=a9(this.thread,A.toolUse);if(A.data.status==="done"&&B?.name===rT){let $=A.data.result;if("task"in $&&$.nextTask){let J=f7(this.thread),Y=this.deps.internalHooks?.onTaskCompleted?.({thread:this.thread,completedTask:$.task,nextTask:$.nextTask,usage:J?{totalInputTokens:J.totalInputTokens,maxInputTokens:J.maxInputTokens}:void 0});if(Y)vy(this,Y)}}if(y5(A.data.status))this.toolOrchestrator.clearCancelled(A.toolUse),this.toolOrchestrator.resolveToolCompletion(A.toolUse,A.data.status==="done",Error(`Tool ${A.data.status}: ${A.toolUse}`));if(B){let $=v15(this.thread,A.toolUse,this.shouldContinueAfterRejection);j.debug(`updated tool_result${$?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${A.type}, ${A.toolUse}, ${A.data.status})`,threadID:this.threadID});let J=this.shouldContinueAfterRejection||this._inferenceState.getValue()!=="cancelled";if($&&J)this.beginInference()}this.toolCallUpdates.next();break}case"assistant:message":{if(A.message.state.type==="complete"&&A.message.state.stopReason==="tool_use"){let $=this.thread.messages.at(-1);(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):wV).startActiveSpan("tools",{context:{messageId:$?.messageId}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(A.message)}).catch((Y)=>{j.error("onAssistantMessageComplete failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:A.message.state.type,error:Y instanceof Error?Y.message:String(Y)})})}break}case"assistant:message-update":break;case"user:message-queue:enqueue":{let B=this._inferenceState.getValue();if(Wl0(this.thread,B)!=="tool-running"){if(B==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(B==="idle"){let J=this.thread.messages.at(-1);if(J?.role==="assistant"){if(J.state.type==="cancelled"||J.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(J.state.type==="complete"&&J.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(J?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"cancelled":{if(this.resetRetryAttempts(),this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let B=this.currentAgentSpan.messageId,$=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:this.getMessageText(B),id:B,status:"cancelled",messages:n90(this.getMessagesSince(B))},$).then((J)=>this.handleAgentEndResult(J)).catch((J)=>j.debug("Failed to emit agent.end",{error:J}))}break}case"thread:truncate":{if(this.toolOrchestrator.cancelAll("system:edited").catch((B)=>{j.error("Failed to cancel tools on truncate",B,{name:"ThreadWorker",threadID:this.threadID})}),Q)this.cleanupFileChanges(A.fromIndex).catch((B)=>{j.error("Failed to cleanup file changes on truncate",B,{name:"ThreadWorker",threadID:this.threadID})});break}case"inference:completed":{this.resetRetryAttempts();let B=A.model?.includes("gpt-5")||A.model?.includes("codex"),$=!A.usage||A.usage.totalInputTokens===0||A.usage.outputTokens===0;if(B&&$)j.getChild("thread-worker").warn("Missing token counts in deep mode inference",{threadID:this.threadID,model:A.model,hasUsage:!!A.usage,inputTokens:A.usage?.inputTokens,outputTokens:A.usage?.outputTokens,totalInputTokens:A.usage?.totalInputTokens,cacheReadInputTokens:A.usage?.cacheReadInputTokens,cacheCreationInputTokens:A.usage?.cacheCreationInputTokens});let J=n2(this.thread,"assistant");if(J&&J.state.type==="complete"&&J.state.stopReason==="refusal"){this.ephemeralError.next(Error("The model refused to respond to this request. Please retry with a different prompt."));break}this.checkAndAppendAwaitedSkills();let Y=n2(this.thread,"assistant"),Z=Y?.state.type==="complete"&&Y.state.stopReason==="tool_use";if(Y&&Z){let X=this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):wV,D=Y.messageId;X.startActiveSpan("tools",{context:{messageId:D}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(Y)}).catch((G)=>{j.error("onAssistantMessageComplete failed after inference",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:Y.state.type,error:G instanceof Error?G.message:String(G)})})}if(Y&&Y.state.type==="complete"&&Y.state.stopReason==="end_turn"){let X=this._turnStartTime.getValue();if(X!==void 0){let D=Date.now()-X;this._turnElapsedMs.next(D),this.thread=k2(this.thread,(G)=>{let V=G.messages.findLast((U)=>U.role==="assistant");if(V&&V.role==="assistant")V.turnElapsedMs=D;G.v++})}if(this._turnStartTime.next(void 0),this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else{vy(this,fM4(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));let D=f7(this.thread);if(D&&this.deps.internalHooks?.onInferenceCompleted){let G=this.deps.internalHooks.onInferenceCompleted({thread:this.thread,usage:{totalInputTokens:D.totalInputTokens,maxInputTokens:D.maxInputTokens},isIdle:!0});vy(this,G)}if(this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let G=this.currentAgentSpan.messageId,V=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:this.getMessageText(G),id:G,status:"done",messages:n90(this.getMessagesSince(G))},V).then((U)=>this.handleAgentEndResult(U)).catch((U)=>j.debug("Failed to emit agent.end",{error:U}))}}}break}}}getMessageText(A){let Q=this.thread.messages.find((B)=>B.messageId===A);if(Q)return W8(Q.content);return""}getMessagesSince(A){let Q=this.thread.messages.findIndex((B)=>B.messageId===A);if(Q===-1)return[];return this.thread.messages.slice(Q)}startAgentSpan(A){let Q=Bb0();this.currentAgentSpan={span:Q,messageId:A},this.updateThread({type:"trace:start",span:{name:"agent",id:Q,startTime:new Date().toISOString(),context:{messageId:A}}})}stopAgentSpan(A){if(this.updateThread({type:"trace:end",span:{name:"agent",id:A,endTime:new Date().toISOString()}}),this.currentAgentSpan?.span===A)this.currentAgentSpan=null}handleAgentEndResult(A){if(A.action!=="continue"||!A.userMessage)return;this.handle({type:"user:message",message:{content:[{type:"text",text:A.userMessage}]}}).catch((Q)=>{j.debug("Failed to handle plugin agent.end continue",{error:Q})})}triggerTitleGeneration(){if(this.thread.mainThreadID!==void 0||this.thread.title)return;this.ops.titleGeneration?.abort(),this.ops.titleGeneration=new AbortController;let A=this.ops.titleGeneration.signal;this.getConfig(A).then((Q)=>{if(A.aborted)return;let B=Q.settings?.["agent.skipTitleGenerationIfMessageContains"],$=Array.isArray(B)?B.filter((Y)=>typeof Y==="string"):[],J=this.thread.messages.find((Y)=>{if(Y.role!=="user")return!1;let Z=W8(Y.content);if(!Z)return!1;if($.length===0)return!0;return!$.some((F)=>Z.includes(F))});if(j.debug("Checking for message to generate title for",{skipPatterns:$,rawSkipPatterns:B,hasFirstEligibleMessage:J!==void 0,firstEligibleMessageId:J?.messageId}),J)this.deps.generateThreadTitle(J,this.thread.id,this.deps.configService,A).then(({title:Y,usage:Z})=>{if(A.aborted||this.isDisposed)return;if(Y!==void 0&&this.thread.title!==Y)this.updateThread({type:"title",value:Y,usage:Z})}).catch((Y)=>{if(!e8(Y))j.error("generateThreadTitle error",Y,{name:"ThreadWorker",threadID:this.threadID})})}).catch((Q)=>{if(!e8(Q))j.error("ThreadWorker title generation config error",Q)})}setReasoningEffortOverride(A){this.reasoningEffortOverride=A}async getWorkspaceRoot(A){let Q=await T1(this.deps.configService.workspaceRoot,A);if(Q)return Q;let B=this.thread.env?.initial?.trees?.find(($)=>$.uri!==void 0)?.uri;return B?V8(B):null}beginInference(A){this.runInferenceAndUpdateThread(A).catch((Q)=>{if(this.isDisposed||e8(Q)||y80(Q))return;j.error("Failed to run inference",Q,{name:"ThreadWorker.runInferenceAndUpdateThread",threadID:this.threadID}),this.ephemeralError.next(Q instanceof Error?Q:Error(String(Q)))})}async runInferenceAndUpdateThread(A){this.abortInferenceOperation();let Q=new AbortController;if(this.ops.inference=Q,await this.deps.pluginService.event.sessionStart({thread:{id:this.threadID}}),Q.signal.aborted)return;if(A?.agentStart){let{messageId:B,messageText:$}=A.agentStart;try{let J=await this.deps.pluginService.event.agentStart({thread:{id:this.threadID},message:$,id:B},this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):void 0);if(Q.signal.aborted)return;if(J.message)this.updateThread({type:"user:message:append-content",messageId:B,content:[{type:"text",text:J.message.content}]})}catch(J){j.debug("Failed to emit agent.start",{error:J})}}if(Q.signal.aborted)return;return this.doRunInferenceSetup(Q)}async doRunInferenceSetup(A){if(j.debug("runInferenceAndUpdateThread: begin",{threadID:this.threadID,inferenceState:this._inferenceState.getValue(),messageCount:this.thread.messages.length}),A.signal.aborted||this.ops.inference!==A)return;if(this._inferenceState.getValue()==="cancelled")this._inferenceState.next("idle");let Q=this.currentAgentSpan?.span;if(await this.toolOrchestrator.onNewUserMessage(),A.signal.aborted||this.ops.inference!==A)return;await(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):wV).startActiveSpan("inference",{context:{messageId:this.currentAgentSpan?.messageId}},()=>this.doRunInferenceAndUpdateThread(A,Q))}async doRunInferenceAndUpdateThread(A,Q){try{await this.doRunInferenceAndUpdateThreadInner(A,Q)}catch(B){if(e8(B)||y80(B))return;throw B}}async doRunInferenceAndUpdateThreadInner(A,Q){let B=f7(this.thread);if(B&&B.totalInputTokens>=B.maxInputTokens){let z=Error("Context limit reached");this.ephemeralError.next(z);return}let $=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&$?.role==="user"&&this.thread.messages.filter((z)=>z.role==="user").length===1){if(this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(z)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...z}}})}).catch((z)=>{j.error("Failed to initialize thread environment",z,{threadID:this.threadID})})}this.triggerTitleGeneration(),this.repairMissingToolResultsForInference();let Y=await this.getConfig(),{model:Z,agentMode:F}=RY(Y.settings,this.thread),X=this.thread.messages.at(-1)?.messageId;j.debug("runInferenceAndUpdateThread: starting inference",{threadID:this.threadID,lastUserMessageId:X,selectedModel:Z,agentMode:F});let D=this.deps.getServerStatus?await T1(this.deps.getServerStatus().pipe(A5((z)=>z!=="pending")),A.signal):void 0,G=D&&lA(D)?D.user.email:void 0;if(!Fk(F,G))throw Error(`Agent mode '${F}' is only available for internal users`);let V={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,getEnvironmentData:this.deps.getEnvironmentData,filesystem:this.fs.fileSystem,threadService:this.deps.threadService,serverStatus:D},U,K=0,E=Date.now();try{let[z,W,H]=Z.match(/(.*?)\/(.*)/)??[],q=Xk({agentMode:F,model:H??"",serverStatus:D}),N=W&&q?`${W}/${q}`:Z,I=wM4(W??"",q),{systemPrompt:w,tools:L}=await TV(V,this.thread,{enableTask:!0,enableOracle:!0,enableChart:!1},{model:q,provider:W??"",agentMode:F??"smart"},A.signal),P=(this.reasoningEffortOverride!==void 0&&hX(F,this.reasoningEffortOverride)?this.reasoningEffortOverride:void 0)??RY0(N,Y.settings,F),S=I.stream({model:q,agentMode:F,thread:this.thread,systemPrompt:w,tools:L,configService:this.deps.configService,serverStatus:D,signal:A.signal,reasoningEffort:P});this._inferenceState.next("running"),E=Date.now(),j.debug("ThreadWorker inference stream started",{threadID:this.threadID,lastUserMessageId:X,selectedModel:N,agentMode:F});for await(let T of S){if(A.signal.aborted)return;K++,U=T,await this.handle({type:"assistant:message-update",message:T},A.signal)}if(A.signal.aborted)return;if(j.debug("ThreadWorker inference stream finished",{threadID:this.threadID,streamEventCount:K,durationMs:Date.now()-E,lastMessageState:U?.state.type,lastMessageId:U?.messageId}),U){let T=U.state.type==="streaming",x=U.content.some((h)=>h.type==="tool_use"&&h.complete&&Object.keys(h.input??{}).length===0);if(T||x)j.warn("Stream ended with incomplete message",{name:"ThreadWorker.runInference",threadID:this.threadID,streamEventCount:K,durationMs:Date.now()-E,messageState:U.state.type,stopReason:U.state.type==="complete"?U.state.stopReason:void 0,contentBlocks:U.content.map((h)=>({type:h.type,...h.type==="tool_use"?{name:h.name,complete:h.complete,inputKeys:Object.keys(h.input??{})}:{},...h.type==="text"?{textLength:h.text.length}:{}}))})}await this.handle({type:"inference:completed",model:U?.usage?.model??Z,usage:U?.usage},A.signal)}catch(z){if(j.debug("ThreadWorker inference stream error",{threadID:this.threadID,error:z instanceof Error?z.message:String(z),errorName:z instanceof Error?z.name:void 0,streamEventCount:K,durationMs:Date.now()-E,lastMessageState:U?.state.type,lastMessageId:U?.messageId}),!(e8(z)||y80(z))){let W=z instanceof Error?z:Error(String(z));if(rV({message:W.message})){this.ephemeralError.next(W);return}let H="status"in W&&typeof W.status==="number"?W.status:void 0;if($y({message:W.message,status:H})){let q=this.getRetryDelaySeconds();if(q!==void 0)this.startRetryCountdown(q)}this.ephemeralError.next(W)}if(U&&U.messageId){let W=await this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:W8(U.content),id:U.messageId,status:"error",messages:n90(this.getMessagesSince(U.messageId))},Q?this.createTracer(Q):void 0);if(Q)this.stopAgentSpan(Q);this.handleAgentEndResult(W)}else if(Q)this.stopAgentSpan(Q);return}finally{if(this.ops.inference===A)this.ops.inference=null,this._inferenceState.next("idle")}}async findAndCancelToolRun(A,Q){this.cancelInference(),await this.toolOrchestrator.findAndCancelToolRun(A,Q)}async cancelToolOnly(A,Q){await this.toolOrchestrator.cancelToolOnly(A,Q)}invokeBashTool(A,Q,B){return new u0(($)=>{let J,Y,Z,X=((G)=>{return eH(G,()=>{if(j.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),Z?.unsubscribe(),Y?.unsubscribe(),$?.complete(),J)this.handleManualBashInvocation(A,{status:"cancelled",progress:sM(J)},B)})})(Q);return(async()=>{try{if(Q.aborted){$.error(Error("Operation was aborted"));return}let G=await this.getWorkspaceRoot(Q),V=await this.getConfig(Q);if(this.isDisposed){$.complete();return}let U={...this.deps,dir:G,tool:tA,thread:this.thread,config:V,trackedFiles:new vQ(this.trackedFiles),filesystem:gA4(this.fs.fileSystem),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:iZ(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,userInitiated:!0};Y=this.deps.toolService.invokeTool(tA,{args:A,userInput:{accepted:!0}},U).subscribe({next:(K)=>{J=K,$.next(K)},error:(K)=>{$.error(K)},complete:()=>{if(J)this.handleManualBashInvocation(A,J,B);$.complete()}}),Z=this.disposed$.subscribe(()=>{X(),Y?.unsubscribe(),$?.complete()})}catch(G){$.error(G)}})(),()=>{X(),Y?.unsubscribe(),Z?.unsubscribe()}})}async handleManualBashInvocation(A,Q,B){await this.handle({type:"info:manual-bash-invocation",args:A,toolRun:Q,hidden:B})}async cleanupThreadBackups(A){try{await this.fs.tracker.cleanupBackups(),j.debug(`Cleaned up backup files for thread ${A}`,{threadID:A})}catch(Q){j.error("Error cleaning up thread backups",Q,{threadID:A})}}async cancel(){j.debug("cancel: aborting inference operation and tools"),this.cancelInference(),await this.toolOrchestrator.cancelAll("user:cancelled"),await this.handle({type:"cancelled"},void 0)}cancelInference(){this.abortInferenceOperation(),this._inferenceState.next("cancelled"),this._turnStartTime.next(void 0),this._turnElapsedMs.next(void 0)}abortInferenceOperation(){if(this.ops.inference)this.ops.inference.abort(Error(gv0.USER_CANCELLED)),this.ops.inference=null}static BASE_RETRY_SECONDS=5;static MAX_RETRY_SECONDS=60;static MAX_AUTO_RETRIES=5;getRetryDelaySeconds(){if(this.ephemeralErrorRetryAttempt>=yy.MAX_AUTO_RETRIES)return;let A=yy.BASE_RETRY_SECONDS*2**this.ephemeralErrorRetryAttempt;return Math.min(A,yy.MAX_RETRY_SECONDS)}async retry(){if(j.debug("retry: retrying inference operation"),this.clearRetryCountdown(),this.ephemeralError.getValue()!==void 0)this.ephemeralErrorRetryAttempt++,this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;let A=this.thread.messages.at(-1);if(A?.role==="assistant"&&(A.state.type!=="complete"||A.state.stopReason==="refusal"))this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});this._inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}resetRetryAttempts(){this.ephemeralErrorRetryAttempt=0}dismissEphemeralError(){this.clearRetryCountdown(),this.ephemeralError.next(void 0),this.ephemeralErrorRetryAttempt=0}clearRetryCountdown(){if(this.retrySession++,this.retryTimer!==null)clearInterval(this.retryTimer),this.retryTimer=null;this.retryCountdownSeconds.next(void 0)}startRetryCountdown(A){this.clearRetryCountdown();let Q=this.retrySession,B=Date.now()+A*1000;this.retryCountdownSeconds.next(A),this.retryTimer=setInterval(()=>{if(Q!==this.retrySession)return;let $=Math.max(0,Math.ceil((B-Date.now())/1000));if($<=0)this.clearRetryCountdown(),this.retry().catch((J)=>{j.error("Auto-retry failed",{error:J})});else this.retryCountdownSeconds.next($)},1000)}addPendingSkill(A){j.debug("addPendingSkill",{threadID:this.threadID,skillName:A.name});let Q=this._pendingSkills.getValue();if(!Q.some((B)=>B.name===A.name))this._pendingSkills.next([...Q,A])}removePendingSkill(A){j.debug("removePendingSkill",{threadID:this.threadID,skillName:A});let Q=this._pendingSkills.getValue();this._pendingSkills.next(Q.filter((B)=>B.name!==A))}clearPendingSkills(){j.debug("clearPendingSkills",{threadID:this.threadID}),this._pendingSkills.next([])}getPendingSkills(){return this._pendingSkills.getValue()}setTestEphemeralError(A){this.ephemeralError.next(A)}trackFiles(A){for(let Q of A)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let A=await this.fs.tracker.restoreFromBackups();j.debug(`Restored ${A.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(A){j.error("Error restoring file changes",A,{threadID:this.threadID})}}async revertFileChanges(A){await this.fs.tracker.revertAll(A),await this.updateFileChanges()}async getAllTrackedChanges(){return this.fs.tracker.getAllRecords()}async cleanupForkThreads(A=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:A})}async getToolUsesToRevert(A=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,A).forEach((J)=>{if(J.role==="user"){for(let Y of J.content)if(Y.type==="tool_result")Q.add(Y.toolUseID)}else for(let Y of J.content)if(Y.type==="tool_use")Q.add(Y.id)});let B=new Set,$=await this.fs.tracker.getAllRecords();for(let[J]of $.entries())if(!Q.has(J))B.add(J);return B}async getFilesAffectedByTruncation(A){let Q=await this.getToolUsesToRevert(A);return Q.size>0?this.fs.tracker.getFilesForToolUses(Q):[]}async cleanupFileChanges(A=this.thread.messages.length){let Q=await this.getToolUsesToRevert(A);if(Q.size===0)return;await this.fs.tracker.revertChanges(Q),await this.updateFileChanges()}async performMessageEditCleanup(){await this.toolOrchestrator.cancelAll("system:edited"),await this.cleanupFileChanges(),await this.cleanupForkThreads()}async updateFileChanges(){this.cachedFileChanges=await sJ4(this.fs.tracker),this.fileChanges.next({files:this.cachedFileChanges})}async injectPendingSkills(A,Q){let B=A.map(($)=>$.name);j.info("Adding info message to prompt skill invocation",{threadID:this.threadID,skillNames:B}),this._awaitingSkillInvocation.next(A),this.thread=k2(this.thread,($)=>{let J=$.nextMessageId??0;$.nextMessageId=J+1,$.messages.push({role:"info",messageId:J,content:[{type:"text",text:`You MUST call the ${x7} tool to load: ${B.join(", ")}. Do this immediately before responding.`}]}),$.v++})}checkAndAppendAwaitedSkills(){let A=this._awaitingSkillInvocation.getValue();if(A.length===0)return;this._awaitingSkillInvocation.next([]);let{updatedThread:Q,uninvoked:B}=S15(this.thread,{toolName:x7,items:A,wasInvoked:($,J)=>$.some((Y)=>Y.name===x7&&Y.input.name===J.name),toToolInput:($)=>({name:$.name,arguments:$.arguments})});if(B.length>0)j.info("Skills not invoked by model, appending tool_use blocks",{threadID:this.threadID,uninvokedSkills:B.map(($)=>$.name)}),this.thread=Q}async executeHandoff(A){j.info("Executing handoff",{threadID:this.threadID,goal:A}),this.handoffState.next({goal:A});try{let{threadWorkerService:Q}=await Promise.resolve().then(() => (xN(),iM4)),B={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,getEnvironmentData:this.deps.getEnvironmentData,filesystem:this.fs.fileSystem,threadService:this.deps.threadService},{threadID:$}=await Q.handoff(this.deps,{threadID:this.threadID,goal:A,images:[],mode:"initial",agentMode:this.thread.agentMode,queuedMessages:this.thread.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:B});j.info("Handoff thread created and running in background",{fromThreadID:this.threadID,newThreadID:$,goal:A}),this.handoffState.next({goal:A,result:{newThreadID:$}})}catch(Q){j.error("Handoff failed",Q,{threadID:this.threadID,goal:A}),this.handoffState.next({goal:A,result:{error:Q instanceof Error?Q.message:String(Q)}})}}continueInferenceAfterRejection(A=!0){this.shouldContinueAfterRejection=A}getTurnStartTime(){return this._turnStartTime.getValue()}setTurnStartTime(A){this._turnStartTime.next(A)}async asyncDispose(){if(this.isDisposed)return;if(j.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,activeToolCount:this.toolOrchestrator.getRunningToolIds().length}),this.isDisposed=!0,await this.toolOrchestrator.cancelAll("system:disposed"),this.disposed$.next(),this.disposed$.complete(),this.clearRetryCountdown(),this._state.complete(),this.ephemeralError.complete(),this._inferenceState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this.retryCountdownSeconds.complete(),this.toolOrchestrator.dispose(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.ops.titleGeneration)this.ops.titleGeneration.abort(),this.ops.titleGeneration=null;if(this.fs.tracker.dispose(),this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}async getSelectedAgentMode(){let A=await this.getConfig(),{agentMode:Q}=RY(A.settings,this.thread);return Q}}function v15(A,Q,B=!1){let $=n2(A,"assistant");if(!$||$.state.type!=="complete"||$.state.stopReason!=="tool_use")return!1;let J=$.content.filter((X)=>X.type==="tool_use").map((X)=>X.id);if(Q&&!J.includes(Q))return j.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:A.id}),!1;if(J.length===0)return!1;let Y=nZ(A);if(!J.every((X)=>{let D=Y.get(X);if(!D?.run||!y5(D.run.status))return!1;let G=D.run.status;if(G==="cancelled"){let V=D.run.reason;return V?!V.startsWith("user:"):!1}if(G==="rejected-by-user")return B;return!0}))return!1;if(J.every((X)=>{let D=Y.get(X);if(!D||D.run.status!=="done")return!1;return D.run.isFinal===!0}))return!1;return!0}var lM4=r(()=>{e1();L1();xQ();cX();p0();H8();fn0();ND();Q3();QD();Pk();AE();_Q();vY0();VY();f4();Qq();pu0();cn0();fL();kV();i4();lS();uM4();Jb0();cM4()});var iM4={};H2(iM4,{threadWorkerService:()=>B9});class aM4{threadWorkers=new $k0;async getOrCreateForThread(A,Q){let B=this.threadWorkers.get(Q);if(!B){if(B=new yy(A,Q),this.threadWorkers.set(Q,B),this.threadWorkers.size>25)j.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return in0.record(this.threadWorkers.size),B}async createThreadWorker(A,Q){let B=await this.getOrCreateForThread(A,Q);return await B.resume(),B}async seedThreadMessages(A,Q,B,$){let J=await A.threadService.exclusiveSyncReadWriter(Q),Y=$?B.map((X)=>X.role==="user"?{...X,agentMode:$}:X):[...B],Z=Y.length>0?Math.max(...Y.map((X)=>X.messageId))+1:0,F=J.read();J.write({...F,agentMode:$??F.agentMode,messages:Y,nextMessageId:Z,v:F.v+1}),await J.asyncDispose()}async applyParentRelationship(A,Q,B,$){let J=Date.now(),{threadID:Y,type:Z,messageIndex:F,blockIndex:X,comment:D}=$;await Q.handle({type:"relationship",relationship:{threadID:Y,type:Z,role:"child",messageIndex:F,blockIndex:X,createdAt:J,comment:D}});let G={threadID:B,type:Z,role:"parent",messageIndex:F,blockIndex:X,createdAt:J,comment:D},V=this.threadWorkers.get(Y);if(V)await V.handle({type:"relationship",relationship:G});else{let U=await A.threadService.exclusiveSyncReadWriter(Y);U.update((K)=>{if(!K.relationships)K.relationships=[];if(!K.relationships.some((z)=>z.threadID===G.threadID&&z.type===G.type&&z.role===G.role))K.relationships.push(G)}),await U.asyncDispose()}}async inheritVisibilityIfNeeded(A,Q,B){if(Q.type==="handoff")await Gq4(A.threadService,Q.threadID,B)}async sendInitialUserMessage(A,Q){let B=typeof Q==="string"?[{type:"text",text:Q}]:[...Q];await A.handle({type:"user:message",message:{content:B}})}async setDraftContent(A,Q){let B=typeof Q==="string"?Q:[...Q];await A.handle({type:"draft",content:B})}async setPendingNavigation(A,Q){let B=this.threadWorkers.get(A);if(B)await B.handle({type:"setPendingNavigation",threadID:Q})}async transferQueuedMessages(A,Q){for(let B of Q)await A.handle({type:"user:message-queue:enqueue",message:B.queuedMessage})}async createThread(A,Q){let B=Q?.newThreadID??i2(),$=Q?.agentMode,J=!1;if(Q?.seededMessages)await this.seedThreadMessages(A,B,Q.seededMessages,$),J=!0;let Y=await this.createThreadWorker(A,B);if(Y.thread.messages.length>0&&!J)return j.info("createThread called for existing thread, returning existing worker",{threadID:B,messageCount:Y.thread.messages.length}),{threadID:B,worker:Y};if($&&!J)await Y.handle({type:"agent-mode",mode:$});if(Q?.parent)await this.applyParentRelationship(A,Y,B,Q.parent),await this.inheritVisibilityIfNeeded(A,Q.parent,B);if(Q?.initialUserMessage){if(J)throw Error("initialUserMessage cannot be set when seededMessages is provided");await this.sendInitialUserMessage(Y,Q.initialUserMessage)}if(Q?.draftContent){if(J)throw Error("draftContent cannot be set when seededMessages is provided");await this.setDraftContent(Y,Q.draftContent)}if(Q?.navigate&&Q?.parent)await this.setPendingNavigation(Q.parent.threadID,B);if(Q?.queuedMessages)await this.transferQueuedMessages(Y,Q.queuedMessages);return{threadID:B,worker:Y}}async handoff(A,Q){let B=await this.createThreadWorker(A,Q.threadID),$=B.thread,J=Q.images??[],Y=Q.signal??new AbortController().signal,{content:Z}=await e$0({thread:$,goal:Q.goal,images:J,deps:{configService:A.configService,buildSystemPromptDeps:Q.buildSystemPromptDeps,signal:Y,filesystem:Q.filesystem,deadline:Q.deadline}}),F=typeof Z==="string"?Z:Z.filter((G)=>G.type==="text"||G.type==="image"),X={threadID:Q.threadID,type:"handoff",messageIndex:Q.messageIndex??($.messages.length?$.messages.length-1:void 0),blockIndex:Q.blockIndex,comment:Q.comment??Q.goal},D=await this.createThread(A,{newThreadID:Q.newThreadID,agentMode:Q.agentMode??$.agentMode,parent:X,navigate:Q.navigate,queuedMessages:Q.queuedMessages??$.queuedMessages,initialUserMessage:Q.mode==="initial"?F:void 0,draftContent:Q.mode==="draft"?F:void 0});if(Q.clearQueuedMessages&&$.queuedMessages?.length)await B.handle({type:"user:message-queue:discard"});return D}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(x4((A)=>A.size===0?u0.of({}):M6(...Array.from(A.values()).map((Q)=>Q.status.pipe(H1((B)=>[Q.threadID,Q.threadReadWriter?Fy(Q.thread,B):void 0])))).pipe(H1((Q)=>Object.fromEntries(Q)))),tK(25),sA())}get(A){return this.threadWorkers.get(A)}prettyPrintToolRun(A,Q){let B=this.threadWorkers.get(A);if(!B)throw Error(`No worker found for thread ${A}`);for(let $ of B.thread.messages)for(let J of $.content)if(J.type==="tool_result"&&J.toolUseID===Q)return CF4(J.run);throw Error(`Tool run not found for thread ${A} and tool use ${Q}`)}async cancelToolOnly(A,Q){await this.threadWorkers.get(A)?.cancelToolOnly(Q)}async cancel(A){await this.threadWorkers.get(A)?.cancel()}async dispose(A){let Q=this.threadWorkers.get(A);if(Q)await Q.cancel(),await Q.asyncDispose(),this.threadWorkers.delete(A),in0.record(this.threadWorkers.size)}async retry(A){let Q=this.threadWorkers.get(A);if(!Q)throw Error(`No active worker for thread ${A}`);await Q.retry()}async revertFileChanges(A,Q){let B=this.threadWorkers.get(A);if(!B)throw Error(`No active worker for thread ${A}`);await B.revertFileChanges(Q)}async getFilesAffectedByTruncation(A,Q){let B=this.threadWorkers.get(A);if(!B)throw Error(`No active worker for thread ${A}`);return B.getFilesAffectedByTruncation(Q)}async cleanupThreadBackups(A,Q){let B=this.threadWorkers.get(Q);if(B)await B.fs.tracker.cleanupBackups();else try{await new LL(A.osFileSystem).cleanup(Q),j.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch($){j.error("Error cleaning up thread backups",$,{threadID:Q})}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(A)=>await A.asyncDispose())),this.threadWorkers.clear(),in0.record(0)}}var nM4,y15,in0,B9;var xN=r(()=>{L1();p0();MF4();Dq4();Rc();i4();Vq4();lM4();nM4=v4(w4(),1),y15=nM4.metrics.getMeter("thread-worker-service"),in0=y15.createGauge("thread_worker_count",{description:"Number of active thread workers"});B9=new aM4});var an0=y((sM4)=>{Object.defineProperty(sM4,"__esModule",{value:!0});sM4.dynamicAnchor=void 0;var nn0=eA(),x15=BF(),oM4=Cd(),f15=S20(),b15={keyword:"$dynamicAnchor",schemaType:"string",code:(A)=>rM4(A,A.schema)};function rM4(A,Q){let{gen:B,it:$}=A;$.schemaEnv.root.dynamicAnchors[Q]=!0;let J=nn0._`${x15.default.dynamicAnchors}${(0,nn0.getProperty)(Q)}`,Y=$.errSchemaPath==="#"?$.validateName:u15(A);B.if(nn0._`!${J}`,()=>B.assign(J,Y))}sM4.dynamicAnchor=rM4;function u15(A){let{schemaEnv:Q,schema:B,self:$}=A.it,{root:J,baseId:Y,localRefs:Z,meta:F}=Q.root,{schemaId:X}=$.opts,D=new oM4.SchemaEnv({schema:B,schemaId:X,root:J,baseId:Y,localRefs:Z,meta:F});return oM4.compileSchema.call($,D),(0,f15.getValidate)(A,D)}sM4.default=b15});var on0=y((BL4)=>{Object.defineProperty(BL4,"__esModule",{value:!0});BL4.dynamicRef=void 0;var eM4=eA(),g15=BF(),AL4=S20(),m15={keyword:"$dynamicRef",schemaType:"string",code:(A)=>QL4(A,A.schema)};function QL4(A,Q){let{gen:B,keyword:$,it:J}=A;if(Q[0]!=="#")throw Error(`"${$}" only supports hash fragment reference`);let Y=Q.slice(1);if(J.allErrors)Z();else{let X=B.let("valid",!1);Z(X),A.ok(X)}function Z(X){if(J.schemaEnv.root.dynamicAnchors[Y]){let D=B.let("_v",eM4._`${g15.default.dynamicAnchors}${(0,eM4.getProperty)(Y)}`);B.if(D,F(D,X),F(J.validateName,X))}else F(J.validateName,X)()}function F(X,D){return D?()=>B.block(()=>{(0,AL4.callRef)(A,X),B.let(D,!0)}):()=>(0,AL4.callRef)(A,X)}}BL4.dynamicRef=QL4;BL4.default=m15});var YL4=y((JL4)=>{Object.defineProperty(JL4,"__esModule",{value:!0});var d15=an0(),c15=y6(),l15={keyword:"$recursiveAnchor",schemaType:"boolean",code(A){if(A.schema)(0,d15.dynamicAnchor)(A,"");else(0,c15.checkStrictMode)(A.it,"$recursiveAnchor: false is ignored")}};JL4.default=l15});var FL4=y((ZL4)=>{Object.defineProperty(ZL4,"__esModule",{value:!0});var n15=on0(),a15={keyword:"$recursiveRef",schemaType:"string",code:(A)=>(0,n15.dynamicRef)(A,A.schema)};ZL4.default=a15});var DL4=y((XL4)=>{Object.defineProperty(XL4,"__esModule",{value:!0});var r15=an0(),s15=on0(),t15=YL4(),e15=FL4(),A45=[r15.default,s15.default,t15.default,e15.default];XL4.default=A45});var UL4=y((VL4)=>{Object.defineProperty(VL4,"__esModule",{value:!0});var GL4=h20(),B45={keyword:"dependentRequired",type:"object",schemaType:"object",error:GL4.error,code:(A)=>(0,GL4.validatePropertyDeps)(A)};VL4.default=B45});var EL4=y((KL4)=>{Object.defineProperty(KL4,"__esModule",{value:!0});var J45=h20(),Y45={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(A)=>(0,J45.validateSchemaDeps)(A)};KL4.default=Y45});var WL4=y((zL4)=>{Object.defineProperty(zL4,"__esModule",{value:!0});var F45=y6(),X45={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:A,parentSchema:Q,it:B}){if(Q.contains===void 0)(0,F45.checkStrictMode)(B,`"${A}" without "contains" is ignored`)}};zL4.default=X45});var qL4=y((HL4)=>{Object.defineProperty(HL4,"__esModule",{value:!0});var G45=UL4(),V45=EL4(),U45=WL4(),K45=[G45.default,V45.default,U45.default];HL4.default=K45});var wL4=y((IL4)=>{Object.defineProperty(IL4,"__esModule",{value:!0});var fN=eA(),NL4=y6(),z45=BF(),W45={message:"must NOT have unevaluated properties",params:({params:A})=>fN._`{unevaluatedProperty: ${A.unevaluatedProperty}}`},H45={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:W45,code(A){let{gen:Q,schema:B,data:$,errsCount:J,it:Y}=A;if(!J)throw Error("ajv implementation error");let{allErrors:Z,props:F}=Y;if(F instanceof fN.Name)Q.if(fN._`${F} !== true`,()=>Q.forIn("key",$,(V)=>Q.if(D(F,V),()=>X(V))));else if(F!==!0)Q.forIn("key",$,(V)=>F===void 0?X(V):Q.if(G(F,V),()=>X(V)));Y.props=!0,A.ok(fN._`${J} === ${z45.default.errors}`);function X(V){if(B===!1){if(A.setParams({unevaluatedProperty:V}),A.error(),!Z)Q.break();return}if(!(0,NL4.alwaysValidSchema)(Y,B)){let U=Q.name("valid");if(A.subschema({keyword:"unevaluatedProperties",dataProp:V,dataPropType:NL4.Type.Str},U),!Z)Q.if((0,fN.not)(U),()=>Q.break())}}function D(V,U){return fN._`!${V} || !${V}[${U}]`}function G(V,U){let K=[];for(let E in V)if(V[E]===!0)K.push(fN._`${U} !== ${E}`);return(0,fN.and)(...K)}}};IL4.default=H45});var LL4=y((ML4)=>{Object.defineProperty(ML4,"__esModule",{value:!0});var lO=eA(),CL4=y6(),N45={message:({params:{len:A}})=>lO.str`must NOT have more than ${A} items`,params:({params:{len:A}})=>lO._`{limit: ${A}}`},I45={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:N45,code(A){let{gen:Q,schema:B,data:$,it:J}=A,Y=J.items||0;if(Y===!0)return;let Z=Q.const("len",lO._`${$}.length`);if(B===!1)A.setParams({len:Y}),A.fail(lO._`${Z} > ${Y}`);else if(typeof B=="object"&&!(0,CL4.alwaysValidSchema)(J,B)){let X=Q.var("valid",lO._`${Z} <= ${Y}`);Q.if((0,lO.not)(X),()=>F(X,Y)),A.ok(X)}J.items=!0;function F(X,D){Q.forRange("i",D,Z,(G)=>{if(A.subschema({keyword:"unevaluatedItems",dataProp:G,dataPropType:CL4.Type.Num},X),!J.allErrors)Q.if((0,lO.not)(X),()=>Q.break())})}}};ML4.default=I45});var jL4=y((OL4)=>{Object.defineProperty(OL4,"__esModule",{value:!0});var C45=wL4(),M45=LL4(),L45=[C45.default,M45.default];OL4.default=L45});var _L4=y((PL4)=>{Object.defineProperty(PL4,"__esModule",{value:!0});var j45=_x0(),R45=Sx0(),P45=hx0(),_45=DL4(),T45=qL4(),k45=jL4(),S45=gx0(),RL4=mx0(),v45=[_45.default,j45.default,R45.default,(0,P45.default)(!0),S45.default,RL4.metadataVocabulary,RL4.contentVocabulary,T45.default,k45.default];PL4.default=v45});var TL4=y((h68,x45)=>{x45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var kL4=y((g68,f45)=>{f45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var SL4=y((m68,b45)=>{b45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var vL4=y((p68,u45)=>{u45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var yL4=y((d68,h45)=>{h45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var xL4=y((c68,g45)=>{g45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var fL4=y((l68,m45)=>{m45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var bL4=y((i68,p45)=>{p45.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var hL4=y((uL4)=>{Object.defineProperty(uL4,"__esModule",{value:!0});var d45=TL4(),c45=kL4(),l45=SL4(),i45=vL4(),n45=yL4(),a45=xL4(),o45=fL4(),r45=bL4(),s45=["/properties"];function t45(A){return[d45,c45,l45,i45,n45,Q(this,a45),o45,Q(this,r45)].forEach((B)=>this.addMetaSchema(B,void 0,!1)),this;function Q(B,$){return A?B.$dataMetaSchema($,s45):$}}uL4.default=t45});var gL4=y((VJ,sn0)=>{Object.defineProperty(VJ,"__esModule",{value:!0});VJ.MissingRefError=VJ.ValidationError=VJ.CodeGen=VJ.Name=VJ.nil=VJ.stringify=VJ.str=VJ._=VJ.KeywordCxt=VJ.Ajv2020=void 0;var AA5=Px0(),QA5=_L4(),BA5=dx0(),$A5=hL4(),rn0="https://json-schema.org/draft/2020-12/schema";class Xa extends AA5.default{constructor(A={}){super({...A,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),QA5.default.forEach((A)=>this.addVocabulary(A)),this.opts.discriminator)this.addKeyword(BA5.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:A,meta:Q}=this.opts;if(!Q)return;$A5.default.call(this,A),this.refs["http://json-schema.org/schema"]=rn0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rn0)?rn0:void 0)}}VJ.Ajv2020=Xa;sn0.exports=VJ=Xa;sn0.exports.Ajv2020=Xa;Object.defineProperty(VJ,"__esModule",{value:!0});VJ.default=Xa;var JA5=gk();Object.defineProperty(VJ,"KeywordCxt",{enumerable:!0,get:function(){return JA5.KeywordCxt}});var xy=eA();Object.defineProperty(VJ,"_",{enumerable:!0,get:function(){return xy._}});Object.defineProperty(VJ,"str",{enumerable:!0,get:function(){return xy.str}});Object.defineProperty(VJ,"stringify",{enumerable:!0,get:function(){return xy.stringify}});Object.defineProperty(VJ,"nil",{enumerable:!0,get:function(){return xy.nil}});Object.defineProperty(VJ,"Name",{enumerable:!0,get:function(){return xy.Name}});Object.defineProperty(VJ,"CodeGen",{enumerable:!0,get:function(){return xy.CodeGen}});var YA5=Id();Object.defineProperty(VJ,"ValidationError",{enumerable:!0,get:function(){return YA5.default}});var ZA5=mk();Object.defineProperty(VJ,"MissingRefError",{enumerable:!0,get:function(){return ZA5.default}})});var pL4=y((mL4)=>{(()=>{var A={349:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.CircularList=void 0;let D=X(460),G=X(844);class V extends G.Disposable{constructor(U){super(),this._maxLength=U,this.onDeleteEmitter=this.register(new D.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new D.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new D.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(U){if(this._maxLength===U)return;let K=Array(U);for(let E=0;E<Math.min(U,this.length);E++)K[E]=this._array[this._getCyclicIndex(E)];this._array=K,this._maxLength=U,this._startIndex=0}get length(){return this._length}set length(U){if(U>this._length)for(let K=this._length;K<U;K++)this._array[K]=void 0;this._length=U}get(U){return this._array[this._getCyclicIndex(U)]}set(U,K){this._array[this._getCyclicIndex(U)]=K}push(U){this._array[this._getCyclicIndex(this._length)]=U,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(U,K,...E){if(K){for(let z=U;z<this._length-K;z++)this._array[this._getCyclicIndex(z)]=this._array[this._getCyclicIndex(z+K)];this._length-=K,this.onDeleteEmitter.fire({index:U,amount:K})}for(let z=this._length-1;z>=U;z--)this._array[this._getCyclicIndex(z+E.length)]=this._array[this._getCyclicIndex(z)];for(let z=0;z<E.length;z++)this._array[this._getCyclicIndex(U+z)]=E[z];if(E.length&&this.onInsertEmitter.fire({index:U,amount:E.length}),this._length+E.length>this._maxLength){let z=this._length+E.length-this._maxLength;this._startIndex+=z,this._length=this._maxLength,this.onTrimEmitter.fire(z)}else this._length+=E.length}trimStart(U){U>this._length&&(U=this._length),this._startIndex+=U,this._length-=U,this.onTrimEmitter.fire(U)}shiftElements(U,K,E){if(!(K<=0)){if(U<0||U>=this._length)throw Error("start argument out of range");if(U+E<0)throw Error("Cannot shift elements in list beyond index 0");if(E>0){for(let W=K-1;W>=0;W--)this.set(U+W+E,this.get(U+W));let z=U+K+E-this._length;if(z>0)for(this._length+=z;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let z=0;z<K;z++)this.set(U+z+E,this.get(U+z))}}_getCyclicIndex(U){return(this._startIndex+U)%this._maxLength}}F.CircularList=V},439:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.clone=void 0,F.clone=function X(D,G=5){if(typeof D!="object")return D;let V=Array.isArray(D)?[]:{};for(let U in D)V[U]=G<=1?D[U]:D[U]&&X(D[U],G-1);return V}},969:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.CoreTerminal=void 0;let D=X(844),G=X(585),V=X(348),U=X(866),K=X(744),E=X(302),z=X(83),W=X(460),H=X(753),q=X(480),N=X(994),I=X(282),w=X(435),L=X(981),O=X(660),P=!1;class S extends D.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new W.EventEmitter),this._onScroll.event((T)=>{this._onScrollApi?.fire(T.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(T){for(let x in T)this.optionsService.options[x]=T[x]}constructor(T){super(),this._windowsWrappingHeuristics=this.register(new D.MutableDisposable),this._onBinary=this.register(new W.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new W.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new W.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new W.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new W.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new W.EventEmitter),this._instantiationService=new V.InstantiationService,this.optionsService=this.register(new E.OptionsService(T)),this._instantiationService.setService(G.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(K.BufferService)),this._instantiationService.setService(G.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(U.LogService)),this._instantiationService.setService(G.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(z.CoreService)),this._instantiationService.setService(G.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(H.CoreMouseService)),this._instantiationService.setService(G.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(q.UnicodeService)),this._instantiationService.setService(G.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(N.CharsetService),this._instantiationService.setService(G.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(O.OscLinkService),this._instantiationService.setService(G.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new w.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,W.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,W.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,W.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,W.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll((x)=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll((x)=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new L.WriteBuffer((x,h)=>this._inputHandler.parse(x,h))),this.register((0,W.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(T,x){this._writeBuffer.write(T,x)}writeSync(T,x){this._logService.logLevel<=G.LogLevelEnum.WARN&&!P&&(this._logService.warn("writeSync is unreliable and will be removed soon."),P=!0),this._writeBuffer.writeSync(T,x)}input(T,x=!0){this.coreService.triggerDataEvent(T,x)}resize(T,x){isNaN(T)||isNaN(x)||(T=Math.max(T,K.MINIMUM_COLS),x=Math.max(x,K.MINIMUM_ROWS),this._bufferService.resize(T,x))}scroll(T,x=!1){this._bufferService.scroll(T,x)}scrollLines(T,x,h){this._bufferService.scrollLines(T,x,h)}scrollPages(T){this.scrollLines(T*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(T){let x=T-this._bufferService.buffer.ydisp;x!==0&&this.scrollLines(x)}registerEscHandler(T,x){return this._inputHandler.registerEscHandler(T,x)}registerDcsHandler(T,x){return this._inputHandler.registerDcsHandler(T,x)}registerCsiHandler(T,x){return this._inputHandler.registerCsiHandler(T,x)}registerOscHandler(T,x){return this._inputHandler.registerOscHandler(T,x)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let T=!1,x=this.optionsService.rawOptions.windowsPty;x&&x.buildNumber!==void 0&&x.buildNumber!==void 0?T=x.backend==="conpty"&&x.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(T=!0),T?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let T=[];T.push(this.onLineFeed(I.updateWindowsModeWrappedState.bind(null,this._bufferService))),T.push(this.registerCsiHandler({final:"H"},()=>((0,I.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,D.toDisposable)(()=>{for(let x of T)x.dispose()})}}}F.CoreTerminal=S},460:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.runAndSubscribe=F.forwardEvent=F.EventEmitter=void 0,F.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(X)=>{return this._listeners.push(X),{dispose:()=>{if(!this._disposed){for(let G=0;G<this._listeners.length;G++)if(this._listeners[G]===X)return void this._listeners.splice(G,1)}}}}),this._event}fire(X,D){let G=[];for(let V=0;V<this._listeners.length;V++)G.push(this._listeners[V]);for(let V=0;V<G.length;V++)G[V].call(void 0,X,D)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},F.forwardEvent=function(X,D){return X((G)=>D.fire(G))},F.runAndSubscribe=function(X,D){return D(void 0),X((G)=>D(G))}},435:function(Z,F,X){var D=this&&this.__decorate||function(g,l,a,t){var w0,V0=arguments.length,N0=V0<3?l:t===null?t=Object.getOwnPropertyDescriptor(l,a):t;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N0=Reflect.decorate(g,l,a,t);else for(var X0=g.length-1;X0>=0;X0--)(w0=g[X0])&&(N0=(V0<3?w0(N0):V0>3?w0(l,a,N0):w0(l,a))||N0);return V0>3&&N0&&Object.defineProperty(l,a,N0),N0},G=this&&this.__param||function(g,l){return function(a,t){l(a,t,g)}};Object.defineProperty(F,"__esModule",{value:!0}),F.InputHandler=F.WindowsOptionsReportType=void 0;let V=X(584),U=X(116),K=X(15),E=X(844),z=X(482),W=X(437),H=X(460),q=X(643),N=X(511),I=X(734),w=X(585),L=X(480),O=X(242),P=X(351),S=X(941),T={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function h(g,l){if(g>24)return l.setWinLines||!1;switch(g){case 1:return!!l.restoreWin;case 2:return!!l.minimizeWin;case 3:return!!l.setWinPosition;case 4:return!!l.setWinSizePixels;case 5:return!!l.raiseWin;case 6:return!!l.lowerWin;case 7:return!!l.refreshWin;case 8:return!!l.setWinSizeChars;case 9:return!!l.maximizeWin;case 10:return!!l.fullscreenWin;case 11:return!!l.getWinState;case 13:return!!l.getWinPosition;case 14:return!!l.getWinSizePixels;case 15:return!!l.getScreenSizePixels;case 16:return!!l.getCellSizePixels;case 18:return!!l.getWinSizeChars;case 19:return!!l.getScreenSizeChars;case 20:return!!l.getIconTitle;case 21:return!!l.getWinTitle;case 22:return!!l.pushTitle;case 23:return!!l.popTitle;case 24:return!!l.setWinLines}return!1}var u;(function(g){g[g.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",g[g.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(u||(F.WindowsOptionsReportType=u={}));let k=0;class f extends E.Disposable{getAttrData(){return this._curAttrData}constructor(g,l,a,t,w0,V0,N0,X0,j0=new K.EscapeSequenceParser){super(),this._bufferService=g,this._charsetService=l,this._coreService=a,this._logService=t,this._optionsService=w0,this._oscLinkService=V0,this._coreMouseService=N0,this._unicodeService=X0,this._parser=j0,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new z.StringToUtf32,this._utf8Decoder=new z.Utf8ToUtf32,this._workCell=new N.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=W.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=W.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new H.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new H.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new H.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new H.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new H.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new H.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new H.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new H.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new H.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new H.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new H.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new H.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new H.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new d(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((Q0)=>this._activeBuffer=Q0.activeBuffer)),this._parser.setCsiHandlerFallback((Q0,I0)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(Q0),params:I0.toArray()})}),this._parser.setEscHandlerFallback((Q0)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(Q0)})}),this._parser.setExecuteHandlerFallback((Q0)=>{this._logService.debug("Unknown EXECUTE code: ",{code:Q0})}),this._parser.setOscHandlerFallback((Q0,I0,n)=>{this._logService.debug("Unknown OSC code: ",{identifier:Q0,action:I0,data:n})}),this._parser.setDcsHandlerFallback((Q0,I0,n)=>{I0==="HOOK"&&(n=n.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(Q0),action:I0,payload:n})}),this._parser.setPrintHandler((Q0,I0,n)=>this.print(Q0,I0,n)),this._parser.registerCsiHandler({final:"@"},(Q0)=>this.insertChars(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(Q0)=>this.scrollLeft(Q0)),this._parser.registerCsiHandler({final:"A"},(Q0)=>this.cursorUp(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(Q0)=>this.scrollRight(Q0)),this._parser.registerCsiHandler({final:"B"},(Q0)=>this.cursorDown(Q0)),this._parser.registerCsiHandler({final:"C"},(Q0)=>this.cursorForward(Q0)),this._parser.registerCsiHandler({final:"D"},(Q0)=>this.cursorBackward(Q0)),this._parser.registerCsiHandler({final:"E"},(Q0)=>this.cursorNextLine(Q0)),this._parser.registerCsiHandler({final:"F"},(Q0)=>this.cursorPrecedingLine(Q0)),this._parser.registerCsiHandler({final:"G"},(Q0)=>this.cursorCharAbsolute(Q0)),this._parser.registerCsiHandler({final:"H"},(Q0)=>this.cursorPosition(Q0)),this._parser.registerCsiHandler({final:"I"},(Q0)=>this.cursorForwardTab(Q0)),this._parser.registerCsiHandler({final:"J"},(Q0)=>this.eraseInDisplay(Q0,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(Q0)=>this.eraseInDisplay(Q0,!0)),this._parser.registerCsiHandler({final:"K"},(Q0)=>this.eraseInLine(Q0,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(Q0)=>this.eraseInLine(Q0,!0)),this._parser.registerCsiHandler({final:"L"},(Q0)=>this.insertLines(Q0)),this._parser.registerCsiHandler({final:"M"},(Q0)=>this.deleteLines(Q0)),this._parser.registerCsiHandler({final:"P"},(Q0)=>this.deleteChars(Q0)),this._parser.registerCsiHandler({final:"S"},(Q0)=>this.scrollUp(Q0)),this._parser.registerCsiHandler({final:"T"},(Q0)=>this.scrollDown(Q0)),this._parser.registerCsiHandler({final:"X"},(Q0)=>this.eraseChars(Q0)),this._parser.registerCsiHandler({final:"Z"},(Q0)=>this.cursorBackwardTab(Q0)),this._parser.registerCsiHandler({final:"`"},(Q0)=>this.charPosAbsolute(Q0)),this._parser.registerCsiHandler({final:"a"},(Q0)=>this.hPositionRelative(Q0)),this._parser.registerCsiHandler({final:"b"},(Q0)=>this.repeatPrecedingCharacter(Q0)),this._parser.registerCsiHandler({final:"c"},(Q0)=>this.sendDeviceAttributesPrimary(Q0)),this._parser.registerCsiHandler({prefix:">",final:"c"},(Q0)=>this.sendDeviceAttributesSecondary(Q0)),this._parser.registerCsiHandler({final:"d"},(Q0)=>this.linePosAbsolute(Q0)),this._parser.registerCsiHandler({final:"e"},(Q0)=>this.vPositionRelative(Q0)),this._parser.registerCsiHandler({final:"f"},(Q0)=>this.hVPosition(Q0)),this._parser.registerCsiHandler({final:"g"},(Q0)=>this.tabClear(Q0)),this._parser.registerCsiHandler({final:"h"},(Q0)=>this.setMode(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(Q0)=>this.setModePrivate(Q0)),this._parser.registerCsiHandler({final:"l"},(Q0)=>this.resetMode(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(Q0)=>this.resetModePrivate(Q0)),this._parser.registerCsiHandler({final:"m"},(Q0)=>this.charAttributes(Q0)),this._parser.registerCsiHandler({final:"n"},(Q0)=>this.deviceStatus(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(Q0)=>this.deviceStatusPrivate(Q0)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(Q0)=>this.softReset(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(Q0)=>this.setCursorStyle(Q0)),this._parser.registerCsiHandler({final:"r"},(Q0)=>this.setScrollRegion(Q0)),this._parser.registerCsiHandler({final:"s"},(Q0)=>this.saveCursor(Q0)),this._parser.registerCsiHandler({final:"t"},(Q0)=>this.windowOptions(Q0)),this._parser.registerCsiHandler({final:"u"},(Q0)=>this.restoreCursor(Q0)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(Q0)=>this.insertColumns(Q0)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(Q0)=>this.deleteColumns(Q0)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(Q0)=>this.selectProtected(Q0)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(Q0)=>this.requestMode(Q0,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(Q0)=>this.requestMode(Q0,!1)),this._parser.setExecuteHandler(V.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(V.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(V.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(V.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(V.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(V.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(V.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(V.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(V.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(V.C1.IND,()=>this.index()),this._parser.setExecuteHandler(V.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(V.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new O.OscHandler((Q0)=>(this.setTitle(Q0),this.setIconName(Q0),!0))),this._parser.registerOscHandler(1,new O.OscHandler((Q0)=>this.setIconName(Q0))),this._parser.registerOscHandler(2,new O.OscHandler((Q0)=>this.setTitle(Q0))),this._parser.registerOscHandler(4,new O.OscHandler((Q0)=>this.setOrReportIndexedColor(Q0))),this._parser.registerOscHandler(8,new O.OscHandler((Q0)=>this.setHyperlink(Q0))),this._parser.registerOscHandler(10,new O.OscHandler((Q0)=>this.setOrReportFgColor(Q0))),this._parser.registerOscHandler(11,new O.OscHandler((Q0)=>this.setOrReportBgColor(Q0))),this._parser.registerOscHandler(12,new O.OscHandler((Q0)=>this.setOrReportCursorColor(Q0))),this._parser.registerOscHandler(104,new O.OscHandler((Q0)=>this.restoreIndexedColor(Q0))),this._parser.registerOscHandler(110,new O.OscHandler((Q0)=>this.restoreFgColor(Q0))),this._parser.registerOscHandler(111,new O.OscHandler((Q0)=>this.restoreBgColor(Q0))),this._parser.registerOscHandler(112,new O.OscHandler((Q0)=>this.restoreCursorColor(Q0))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let Q0 in U.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:Q0},()=>this.selectCharset("("+Q0)),this._parser.registerEscHandler({intermediates:")",final:Q0},()=>this.selectCharset(")"+Q0)),this._parser.registerEscHandler({intermediates:"*",final:Q0},()=>this.selectCharset("*"+Q0)),this._parser.registerEscHandler({intermediates:"+",final:Q0},()=>this.selectCharset("+"+Q0)),this._parser.registerEscHandler({intermediates:"-",final:Q0},()=>this.selectCharset("-"+Q0)),this._parser.registerEscHandler({intermediates:".",final:Q0},()=>this.selectCharset("."+Q0)),this._parser.registerEscHandler({intermediates:"/",final:Q0},()=>this.selectCharset("/"+Q0));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((Q0)=>(this._logService.error("Parsing error: ",Q0),Q0)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new P.DcsHandler((Q0,I0)=>this.requestStatusString(Q0,I0)))}_preserveStack(g,l,a,t){this._parseStack.paused=!0,this._parseStack.cursorStartX=g,this._parseStack.cursorStartY=l,this._parseStack.decodedLength=a,this._parseStack.position=t}_logSlowResolvingAsync(g){this._logService.logLevel<=w.LogLevelEnum.WARN&&Promise.race([g,new Promise((l,a)=>setTimeout(()=>a("#SLOW_TIMEOUT"),5000))]).catch((l)=>{if(l!=="#SLOW_TIMEOUT")throw l;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(g,l){let a,t=this._activeBuffer.x,w0=this._activeBuffer.y,V0=0,N0=this._parseStack.paused;if(N0){if(a=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,l))return this._logSlowResolvingAsync(a),a;t=this._parseStack.cursorStartX,w0=this._parseStack.cursorStartY,this._parseStack.paused=!1,g.length>x&&(V0=this._parseStack.position+x)}if(this._logService.logLevel<=w.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof g=="string"?` "${g}"`:` "${Array.prototype.map.call(g,(Q0)=>String.fromCharCode(Q0)).join("")}"`),typeof g=="string"?g.split("").map((Q0)=>Q0.charCodeAt(0)):g),this._parseBuffer.length<g.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(g.length,x))),N0||this._dirtyRowTracker.clearRange(),g.length>x)for(let Q0=V0;Q0<g.length;Q0+=x){let I0=Q0+x<g.length?Q0+x:g.length,n=typeof g=="string"?this._stringDecoder.decode(g.substring(Q0,I0),this._parseBuffer):this._utf8Decoder.decode(g.subarray(Q0,I0),this._parseBuffer);if(a=this._parser.parse(this._parseBuffer,n))return this._preserveStack(t,w0,n,Q0),this._logSlowResolvingAsync(a),a}else if(!N0){let Q0=typeof g=="string"?this._stringDecoder.decode(g,this._parseBuffer):this._utf8Decoder.decode(g,this._parseBuffer);if(a=this._parser.parse(this._parseBuffer,Q0))return this._preserveStack(t,w0,Q0,0),this._logSlowResolvingAsync(a),a}this._activeBuffer.x===t&&this._activeBuffer.y===w0||this._onCursorMove.fire();let X0=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),j0=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);j0<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(j0,this._bufferService.rows-1),Math.min(X0,this._bufferService.rows-1))}print(g,l,a){let t,w0,V0=this._charsetService.charset,N0=this._optionsService.rawOptions.screenReaderMode,X0=this._bufferService.cols,j0=this._coreService.decPrivateModes.wraparound,Q0=this._coreService.modes.insertMode,I0=this._curAttrData,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&a-l>0&&n.getWidth(this._activeBuffer.x-1)===2&&n.setCellFromCodepoint(this._activeBuffer.x-1,0,1,I0);let o=this._parser.precedingJoinState;for(let s=l;s<a;++s){if(t=g[s],t<127&&V0){let C0=V0[String.fromCharCode(t)];C0&&(t=C0.charCodeAt(0))}let A0=this._unicodeService.charProperties(t,o);w0=L.UnicodeService.extractWidth(A0);let F0=L.UnicodeService.extractShouldJoin(A0),J0=F0?L.UnicodeService.extractWidth(o):0;if(o=A0,N0&&this._onA11yChar.fire((0,z.stringFromCodePoint)(t)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+w0-J0>X0){if(j0){let C0=n,L0=this._activeBuffer.x-J0;for(this._activeBuffer.x=J0,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),J0>0&&n instanceof W.BufferLine&&n.copyCellsFrom(C0,L0,0,J0,!1);L0<X0;)C0.setCellFromCodepoint(L0++,0,1,I0)}else if(this._activeBuffer.x=X0-1,w0===2)continue}if(F0&&this._activeBuffer.x){let C0=n.getWidth(this._activeBuffer.x-1)?1:2;n.addCodepointToCell(this._activeBuffer.x-C0,t,w0);for(let L0=w0-J0;--L0>=0;)n.setCellFromCodepoint(this._activeBuffer.x++,0,0,I0)}else if(Q0&&(n.insertCells(this._activeBuffer.x,w0-J0,this._activeBuffer.getNullCell(I0)),n.getWidth(X0-1)===2&&n.setCellFromCodepoint(X0-1,q.NULL_CELL_CODE,q.NULL_CELL_WIDTH,I0)),n.setCellFromCodepoint(this._activeBuffer.x++,t,w0,I0),w0>0)for(;--w0;)n.setCellFromCodepoint(this._activeBuffer.x++,0,0,I0)}this._parser.precedingJoinState=o,this._activeBuffer.x<X0&&a-l>0&&n.getWidth(this._activeBuffer.x)===0&&!n.hasContent(this._activeBuffer.x)&&n.setCellFromCodepoint(this._activeBuffer.x,0,1,I0),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(g,l){return g.final!=="t"||g.prefix||g.intermediates?this._parser.registerCsiHandler(g,l):this._parser.registerCsiHandler(g,(a)=>!h(a.params[0],this._optionsService.rawOptions.windowOptions)||l(a))}registerDcsHandler(g,l){return this._parser.registerDcsHandler(g,new P.DcsHandler(l))}registerEscHandler(g,l){return this._parser.registerEscHandler(g,l)}registerOscHandler(g,l){return this._parser.registerOscHandler(g,new O.OscHandler(l))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let g=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);g.hasWidth(this._activeBuffer.x)&&!g.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let g=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-g),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(g=this._bufferService.cols-1){this._activeBuffer.x=Math.min(g,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(g,l){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=g,this._activeBuffer.y=this._activeBuffer.scrollTop+l):(this._activeBuffer.x=g,this._activeBuffer.y=l),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(g,l){this._restrictCursor(),this._setCursor(this._activeBuffer.x+g,this._activeBuffer.y+l)}cursorUp(g){let l=this._activeBuffer.y-this._activeBuffer.scrollTop;return l>=0?this._moveCursor(0,-Math.min(l,g.params[0]||1)):this._moveCursor(0,-(g.params[0]||1)),!0}cursorDown(g){let l=this._activeBuffer.scrollBottom-this._activeBuffer.y;return l>=0?this._moveCursor(0,Math.min(l,g.params[0]||1)):this._moveCursor(0,g.params[0]||1),!0}cursorForward(g){return this._moveCursor(g.params[0]||1,0),!0}cursorBackward(g){return this._moveCursor(-(g.params[0]||1),0),!0}cursorNextLine(g){return this.cursorDown(g),this._activeBuffer.x=0,!0}cursorPrecedingLine(g){return this.cursorUp(g),this._activeBuffer.x=0,!0}cursorCharAbsolute(g){return this._setCursor((g.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(g){return this._setCursor(g.length>=2?(g.params[1]||1)-1:0,(g.params[0]||1)-1),!0}charPosAbsolute(g){return this._setCursor((g.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(g){return this._moveCursor(g.params[0]||1,0),!0}linePosAbsolute(g){return this._setCursor(this._activeBuffer.x,(g.params[0]||1)-1),!0}vPositionRelative(g){return this._moveCursor(0,g.params[0]||1),!0}hVPosition(g){return this.cursorPosition(g),!0}tabClear(g){let l=g.params[0];return l===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:l===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(g){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let l=g.params[0]||1;for(;l--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(g){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let l=g.params[0]||1;for(;l--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(g){let l=g.params[0];return l===1&&(this._curAttrData.bg|=536870912),l!==2&&l!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(g,l,a,t=!1,w0=!1){let V0=this._activeBuffer.lines.get(this._activeBuffer.ybase+g);V0.replaceCells(l,a,this._activeBuffer.getNullCell(this._eraseAttrData()),w0),t&&(V0.isWrapped=!1)}_resetBufferLine(g,l=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+g);a&&(a.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),l),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+g),a.isWrapped=!1)}eraseInDisplay(g,l=!1){let a;switch(this._restrictCursor(this._bufferService.cols),g.params[0]){case 0:for(a=this._activeBuffer.y,this._dirtyRowTracker.markDirty(a),this._eraseInBufferLine(a++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,l);a<this._bufferService.rows;a++)this._resetBufferLine(a,l);this._dirtyRowTracker.markDirty(a);break;case 1:for(a=this._activeBuffer.y,this._dirtyRowTracker.markDirty(a),this._eraseInBufferLine(a,0,this._activeBuffer.x+1,!0,l),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(a+1).isWrapped=!1);a--;)this._resetBufferLine(a,l);this._dirtyRowTracker.markDirty(0);break;case 2:for(a=this._bufferService.rows,this._dirtyRowTracker.markDirty(a-1);a--;)this._resetBufferLine(a,l);this._dirtyRowTracker.markDirty(0);break;case 3:let t=this._activeBuffer.lines.length-this._bufferService.rows;t>0&&(this._activeBuffer.lines.trimStart(t),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-t,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-t,0),this._onScroll.fire(0))}return!0}eraseInLine(g,l=!1){switch(this._restrictCursor(this._bufferService.cols),g.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,l);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,l);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,l)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(g){this._restrictCursor();let l=g.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let a=this._activeBuffer.ybase+this._activeBuffer.y,t=this._bufferService.rows-1-this._activeBuffer.scrollBottom,w0=this._bufferService.rows-1+this._activeBuffer.ybase-t+1;for(;l--;)this._activeBuffer.lines.splice(w0-1,1),this._activeBuffer.lines.splice(a,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(g){this._restrictCursor();let l=g.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let a=this._activeBuffer.ybase+this._activeBuffer.y,t;for(t=this._bufferService.rows-1-this._activeBuffer.scrollBottom,t=this._bufferService.rows-1+this._activeBuffer.ybase-t;l--;)this._activeBuffer.lines.splice(a,1),this._activeBuffer.lines.splice(t,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(g){this._restrictCursor();let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return l&&(l.insertCells(this._activeBuffer.x,g.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(g){this._restrictCursor();let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return l&&(l.deleteCells(this._activeBuffer.x,g.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(g){let l=g.params[0]||1;for(;l--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(g){let l=g.params[0]||1;for(;l--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(W.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let l=g.params[0]||1;for(let a=this._activeBuffer.scrollTop;a<=this._activeBuffer.scrollBottom;++a){let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+a);t.deleteCells(0,l,this._activeBuffer.getNullCell(this._eraseAttrData())),t.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let l=g.params[0]||1;for(let a=this._activeBuffer.scrollTop;a<=this._activeBuffer.scrollBottom;++a){let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+a);t.insertCells(0,l,this._activeBuffer.getNullCell(this._eraseAttrData())),t.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let l=g.params[0]||1;for(let a=this._activeBuffer.scrollTop;a<=this._activeBuffer.scrollBottom;++a){let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+a);t.insertCells(this._activeBuffer.x,l,this._activeBuffer.getNullCell(this._eraseAttrData())),t.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let l=g.params[0]||1;for(let a=this._activeBuffer.scrollTop;a<=this._activeBuffer.scrollBottom;++a){let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+a);t.deleteCells(this._activeBuffer.x,l,this._activeBuffer.getNullCell(this._eraseAttrData())),t.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(g){this._restrictCursor();let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return l&&(l.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(g.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(g){let l=this._parser.precedingJoinState;if(!l)return!0;let a=g.params[0]||1,t=L.UnicodeService.extractWidth(l),w0=this._activeBuffer.x-t,V0=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(w0),N0=new Uint32Array(V0.length*a),X0=0;for(let Q0=0;Q0<V0.length;){let I0=V0.codePointAt(Q0)||0;N0[X0++]=I0,Q0+=I0>65535?2:1}let j0=X0;for(let Q0=1;Q0<a;++Q0)N0.copyWithin(j0,0,X0),j0+=X0;return this.print(N0,0,j0),!0}sendDeviceAttributesPrimary(g){return g.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(V.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(V.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(g){return g.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(V.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(V.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(g.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(V.C0.ESC+"[>83;40003;0c")),!0}_is(g){return(this._optionsService.rawOptions.termName+"").indexOf(g)===0}setMode(g){for(let l=0;l<g.length;l++)switch(g.params[l]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(g){for(let l=0;l<g.length;l++)switch(g.params[l]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,U.DEFAULT_CHARSET),this._charsetService.setgCharset(1,U.DEFAULT_CHARSET),this._charsetService.setgCharset(2,U.DEFAULT_CHARSET),this._charsetService.setgCharset(3,U.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1000:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(g){for(let l=0;l<g.length;l++)switch(g.params[l]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(g){for(let l=0;l<g.length;l++)switch(g.params[l]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1000:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),g.params[l]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(g,l){let a=this._coreService.decPrivateModes,{activeProtocol:t,activeEncoding:w0}=this._coreMouseService,V0=this._coreService,{buffers:N0,cols:X0}=this._bufferService,{active:j0,alt:Q0}=N0,I0=this._optionsService.rawOptions,n=(F0)=>F0?1:2,o=g.params[0];return s=o,A0=l?o===2?4:o===4?n(V0.modes.insertMode):o===12?3:o===20?n(I0.convertEol):0:o===1?n(a.applicationCursorKeys):o===3?I0.windowOptions.setWinLines?X0===80?2:X0===132?1:0:0:o===6?n(a.origin):o===7?n(a.wraparound):o===8?3:o===9?n(t==="X10"):o===12?n(I0.cursorBlink):o===25?n(!V0.isCursorHidden):o===45?n(a.reverseWraparound):o===66?n(a.applicationKeypad):o===67?4:o===1000?n(t==="VT200"):o===1002?n(t==="DRAG"):o===1003?n(t==="ANY"):o===1004?n(a.sendFocus):o===1005?4:o===1006?n(w0==="SGR"):o===1015?4:o===1016?n(w0==="SGR_PIXELS"):o===1048?1:o===47||o===1047||o===1049?n(j0===Q0):o===2004?n(a.bracketedPasteMode):0,V0.triggerDataEvent(`${V.C0.ESC}[${l?"":"?"}${s};${A0}$y`),!0;var s,A0}_updateAttrColor(g,l,a,t,w0){return l===2?(g|=50331648,g&=-16777216,g|=I.AttributeData.fromColorRGB([a,t,w0])):l===5&&(g&=-50331904,g|=33554432|255&a),g}_extractColor(g,l,a){let t=[0,0,-1,0,0,0],w0=0,V0=0;do{if(t[V0+w0]=g.params[l+V0],g.hasSubParams(l+V0)){let N0=g.getSubParams(l+V0),X0=0;do t[1]===5&&(w0=1),t[V0+X0+1+w0]=N0[X0];while(++X0<N0.length&&X0+V0+1+w0<t.length);break}if(t[1]===5&&V0+w0>=2||t[1]===2&&V0+w0>=5)break;t[1]&&(w0=1)}while(++V0+l<g.length&&V0+w0<t.length);for(let N0=2;N0<t.length;++N0)t[N0]===-1&&(t[N0]=0);switch(t[0]){case 38:a.fg=this._updateAttrColor(a.fg,t[1],t[3],t[4],t[5]);break;case 48:a.bg=this._updateAttrColor(a.bg,t[1],t[3],t[4],t[5]);break;case 58:a.extended=a.extended.clone(),a.extended.underlineColor=this._updateAttrColor(a.extended.underlineColor,t[1],t[3],t[4],t[5])}return V0}_processUnderline(g,l){l.extended=l.extended.clone(),(!~g||g>5)&&(g=1),l.extended.underlineStyle=g,l.fg|=268435456,g===0&&(l.fg&=-268435457),l.updateExtended()}_processSGR0(g){g.fg=W.DEFAULT_ATTR_DATA.fg,g.bg=W.DEFAULT_ATTR_DATA.bg,g.extended=g.extended.clone(),g.extended.underlineStyle=0,g.extended.underlineColor&=-67108864,g.updateExtended()}charAttributes(g){if(g.length===1&&g.params[0]===0)return this._processSGR0(this._curAttrData),!0;let l=g.length,a,t=this._curAttrData;for(let w0=0;w0<l;w0++)a=g.params[w0],a>=30&&a<=37?(t.fg&=-50331904,t.fg|=16777216|a-30):a>=40&&a<=47?(t.bg&=-50331904,t.bg|=16777216|a-40):a>=90&&a<=97?(t.fg&=-50331904,t.fg|=16777224|a-90):a>=100&&a<=107?(t.bg&=-50331904,t.bg|=16777224|a-100):a===0?this._processSGR0(t):a===1?t.fg|=134217728:a===3?t.bg|=67108864:a===4?(t.fg|=268435456,this._processUnderline(g.hasSubParams(w0)?g.getSubParams(w0)[0]:1,t)):a===5?t.fg|=536870912:a===7?t.fg|=67108864:a===8?t.fg|=1073741824:a===9?t.fg|=2147483648:a===2?t.bg|=134217728:a===21?this._processUnderline(2,t):a===22?(t.fg&=-134217729,t.bg&=-134217729):a===23?t.bg&=-67108865:a===24?(t.fg&=-268435457,this._processUnderline(0,t)):a===25?t.fg&=-536870913:a===27?t.fg&=-67108865:a===28?t.fg&=-1073741825:a===29?t.fg&=2147483647:a===39?(t.fg&=-67108864,t.fg|=16777215&W.DEFAULT_ATTR_DATA.fg):a===49?(t.bg&=-67108864,t.bg|=16777215&W.DEFAULT_ATTR_DATA.bg):a===38||a===48||a===58?w0+=this._extractColor(g,w0,t):a===53?t.bg|=1073741824:a===55?t.bg&=-1073741825:a===59?(t.extended=t.extended.clone(),t.extended.underlineColor=-1,t.updateExtended()):a===100?(t.fg&=-67108864,t.fg|=16777215&W.DEFAULT_ATTR_DATA.fg,t.bg&=-67108864,t.bg|=16777215&W.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",a);return!0}deviceStatus(g){switch(g.params[0]){case 5:this._coreService.triggerDataEvent(`${V.C0.ESC}[0n`);break;case 6:let l=this._activeBuffer.y+1,a=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.C0.ESC}[${l};${a}R`)}return!0}deviceStatusPrivate(g){if(g.params[0]===6){let l=this._activeBuffer.y+1,a=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.C0.ESC}[?${l};${a}R`)}return!0}softReset(g){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=W.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(g){let l=g.params[0]||1;switch(l){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}let a=l%2==1;return this._optionsService.options.cursorBlink=a,!0}setScrollRegion(g){let l=g.params[0]||1,a;return(g.length<2||(a=g.params[1])>this._bufferService.rows||a===0)&&(a=this._bufferService.rows),a>l&&(this._activeBuffer.scrollTop=l-1,this._activeBuffer.scrollBottom=a-1,this._setCursor(0,0)),!0}windowOptions(g){if(!h(g.params[0],this._optionsService.rawOptions.windowOptions))return!0;let l=g.length>1?g.params[1]:0;switch(g.params[0]){case 14:l!==2&&this._onRequestWindowsOptionsReport.fire(u.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(u.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${V.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:l!==0&&l!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),l!==0&&l!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:l!==0&&l!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),l!==0&&l!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(g){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(g){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(g){return this._windowTitle=g,this._onTitleChange.fire(g),!0}setIconName(g){return this._iconName=g,!0}setOrReportIndexedColor(g){let l=[],a=g.split(";");for(;a.length>1;){let t=a.shift(),w0=a.shift();if(/^\d+$/.exec(t)){let V0=parseInt(t);if(c(V0))if(w0==="?")l.push({type:0,index:V0});else{let N0=(0,S.parseColor)(w0);N0&&l.push({type:1,index:V0,color:N0})}}}return l.length&&this._onColor.fire(l),!0}setHyperlink(g){let l=g.split(";");return!(l.length<2)&&(l[1]?this._createHyperlink(l[0],l[1]):!l[0]&&this._finishHyperlink())}_createHyperlink(g,l){this._getCurrentLinkId()&&this._finishHyperlink();let a=g.split(":"),t,w0=a.findIndex((V0)=>V0.startsWith("id="));return w0!==-1&&(t=a[w0].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:t,uri:l}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(g,l){let a=g.split(";");for(let t=0;t<a.length&&!(l>=this._specialColors.length);++t,++l)if(a[t]==="?")this._onColor.fire([{type:0,index:this._specialColors[l]}]);else{let w0=(0,S.parseColor)(a[t]);w0&&this._onColor.fire([{type:1,index:this._specialColors[l],color:w0}])}return!0}setOrReportFgColor(g){return this._setOrReportSpecialColor(g,0)}setOrReportBgColor(g){return this._setOrReportSpecialColor(g,1)}setOrReportCursorColor(g){return this._setOrReportSpecialColor(g,2)}restoreIndexedColor(g){if(!g)return this._onColor.fire([{type:2}]),!0;let l=[],a=g.split(";");for(let t=0;t<a.length;++t)if(/^\d+$/.exec(a[t])){let w0=parseInt(a[t]);c(w0)&&l.push({type:2,index:w0})}return l.length&&this._onColor.fire(l),!0}restoreFgColor(g){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(g){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(g){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,U.DEFAULT_CHARSET),!0}selectCharset(g){return g.length!==2?(this.selectDefaultCharset(),!0):(g[0]==="/"||this._charsetService.setgCharset(T[g[0]],U.CHARSETS[g[1]]||U.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let g=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,g,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=W.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=W.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(g){return this._charsetService.setgLevel(g),!0}screenAlignmentPattern(){let g=new N.CellData;g.content=4194373,g.fg=this._curAttrData.fg,g.bg=this._curAttrData.bg,this._setCursor(0,0);for(let l=0;l<this._bufferService.rows;++l){let a=this._activeBuffer.ybase+this._activeBuffer.y+l,t=this._activeBuffer.lines.get(a);t&&(t.fill(g),t.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(g,l){let a=this._bufferService.buffer,t=this._optionsService.rawOptions;return((w0)=>(this._coreService.triggerDataEvent(`${V.C0.ESC}${w0}${V.C0.ESC}\\`),!0))(g==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:g==='"p'?'P1$r61;1"p':g==="r"?`P1$r${a.scrollTop+1};${a.scrollBottom+1}r`:g==="m"?"P1$r0m":g===" q"?`P1$r${{block:2,underline:4,bar:6}[t.cursorStyle]-(t.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(g,l){this._dirtyRowTracker.markRangeDirty(g,l)}}F.InputHandler=f;let d=class{constructor(g){this._bufferService=g,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(g){g<this.start?this.start=g:g>this.end&&(this.end=g)}markRangeDirty(g,l){g>l&&(k=g,g=l,l=k),g<this.start&&(this.start=g),l>this.end&&(this.end=l)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function c(g){return 0<=g&&g<256}d=D([G(0,w.IBufferService)],d)},844:(Z,F)=>{function X(D){for(let G of D)G.dispose();D.length=0}Object.defineProperty(F,"__esModule",{value:!0}),F.getDisposeArrayDisposable=F.disposeArray=F.toDisposable=F.MutableDisposable=F.Disposable=void 0,F.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let D of this._disposables)D.dispose();this._disposables.length=0}register(D){return this._disposables.push(D),D}unregister(D){let G=this._disposables.indexOf(D);G!==-1&&this._disposables.splice(G,1)}},F.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(D){this._isDisposed||D===this._value||(this._value?.dispose(),this._value=D)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},F.toDisposable=function(D){return{dispose:D}},F.disposeArray=X,F.getDisposeArrayDisposable=function(D){return{dispose:()=>X(D)}}},114:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.isChromeOS=F.isLinux=F.isWindows=F.isIphone=F.isIpad=F.isMac=F.getSafariVersion=F.isSafari=F.isLegacyEdge=F.isFirefox=F.isNode=void 0,F.isNode=typeof process<"u"&&"title"in process;let X=F.isNode?"node":navigator.userAgent,D=F.isNode?"node":navigator.platform;F.isFirefox=X.includes("Firefox"),F.isLegacyEdge=X.includes("Edge"),F.isSafari=/^((?!chrome|android).)*safari/i.test(X),F.getSafariVersion=function(){if(!F.isSafari)return 0;let G=X.match(/Version\/(\d+)/);return G===null||G.length<2?0:parseInt(G[1])},F.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(D),F.isIpad=D==="iPad",F.isIphone=D==="iPhone",F.isWindows=["Windows","Win16","Win32","WinCE"].includes(D),F.isLinux=D.indexOf("Linux")>=0,F.isChromeOS=/\bCrOS\b/.test(X)},226:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.DebouncedIdleTask=F.IdleTaskQueue=F.PriorityTaskQueue=void 0;let D=X(114);class G{constructor(){this._tasks=[],this._i=0}enqueue(U){this._tasks.push(U),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(U){this._idleCallback=void 0;let K=0,E=0,z=U.timeRemaining(),W=0;for(;this._i<this._tasks.length;){if(K=Date.now(),this._tasks[this._i]()||this._i++,K=Math.max(1,Date.now()-K),E=Math.max(K,E),W=U.timeRemaining(),1.5*E>W)return z-K<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(z-K))}ms`),void this._start();z=W}this.clear()}}class V extends G{_requestCallback(U){return setTimeout(()=>U(this._createDeadline(16)))}_cancelCallback(U){clearTimeout(U)}_createDeadline(U){let K=Date.now()+U;return{timeRemaining:()=>Math.max(0,K-Date.now())}}}F.PriorityTaskQueue=V,F.IdleTaskQueue=!D.isNode&&"requestIdleCallback"in window?class extends G{_requestCallback(U){return requestIdleCallback(U)}_cancelCallback(U){cancelIdleCallback(U)}}:V,F.DebouncedIdleTask=class{constructor(){this._queue=new F.IdleTaskQueue}set(U){this._queue.clear(),this._queue.enqueue(U)}flush(){this._queue.flush()}}},282:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.updateWindowsModeWrappedState=void 0;let D=X(643);F.updateWindowsModeWrappedState=function(G){let V=G.buffer.lines.get(G.buffer.ybase+G.buffer.y-1),U=V?.get(G.cols-1),K=G.buffer.lines.get(G.buffer.ybase+G.buffer.y);K&&U&&(K.isWrapped=U[D.CHAR_DATA_CODE_INDEX]!==D.NULL_CELL_CODE&&U[D.CHAR_DATA_CODE_INDEX]!==D.WHITESPACE_CELL_CODE)}},734:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.ExtendedAttrs=F.AttributeData=void 0;class X{constructor(){this.fg=0,this.bg=0,this.extended=new D}static toColorRGB(G){return[G>>>16&255,G>>>8&255,255&G]}static fromColorRGB(G){return(255&G[0])<<16|(255&G[1])<<8|255&G[2]}clone(){let G=new X;return G.fg=this.fg,G.bg=this.bg,G.extended=this.extended.clone(),G}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}F.AttributeData=X;class D{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(G){this._ext=G}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(G){this._ext&=-469762049,this._ext|=G<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(G){this._ext&=-67108864,this._ext|=67108863&G}get urlId(){return this._urlId}set urlId(G){this._urlId=G}get underlineVariantOffset(){let G=(3758096384&this._ext)>>29;return G<0?4294967288^G:G}set underlineVariantOffset(G){this._ext&=536870911,this._ext|=G<<29&3758096384}constructor(G=0,V=0){this._ext=0,this._urlId=0,this._ext=G,this._urlId=V}clone(){return new D(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}F.ExtendedAttrs=D},92:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.Buffer=F.MAX_BUFFER_SIZE=void 0;let D=X(349),G=X(226),V=X(734),U=X(437),K=X(634),E=X(511),z=X(643),W=X(863),H=X(116);F.MAX_BUFFER_SIZE=4294967295,F.Buffer=class{constructor(q,N,I){this._hasScrollback=q,this._optionsService=N,this._bufferService=I,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=U.DEFAULT_ATTR_DATA.clone(),this.savedCharset=H.DEFAULT_CHARSET,this.markers=[],this._nullCell=E.CellData.fromCharData([0,z.NULL_CELL_CHAR,z.NULL_CELL_WIDTH,z.NULL_CELL_CODE]),this._whitespaceCell=E.CellData.fromCharData([0,z.WHITESPACE_CELL_CHAR,z.WHITESPACE_CELL_WIDTH,z.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new G.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new D.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(q){return q?(this._nullCell.fg=q.fg,this._nullCell.bg=q.bg,this._nullCell.extended=q.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new V.ExtendedAttrs),this._nullCell}getWhitespaceCell(q){return q?(this._whitespaceCell.fg=q.fg,this._whitespaceCell.bg=q.bg,this._whitespaceCell.extended=q.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new V.ExtendedAttrs),this._whitespaceCell}getBlankLine(q,N){return new U.BufferLine(this._bufferService.cols,this.getNullCell(q),N)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let q=this.ybase+this.y-this.ydisp;return q>=0&&q<this._rows}_getCorrectBufferLength(q){if(!this._hasScrollback)return q;let N=q+this._optionsService.rawOptions.scrollback;return N>F.MAX_BUFFER_SIZE?F.MAX_BUFFER_SIZE:N}fillViewportRows(q){if(this.lines.length===0){q===void 0&&(q=U.DEFAULT_ATTR_DATA);let N=this._rows;for(;N--;)this.lines.push(this.getBlankLine(q))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new D.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(q,N){let I=this.getNullCell(U.DEFAULT_ATTR_DATA),w=0,L=this._getCorrectBufferLength(N);if(L>this.lines.maxLength&&(this.lines.maxLength=L),this.lines.length>0){if(this._cols<q)for(let P=0;P<this.lines.length;P++)w+=+this.lines.get(P).resize(q,I);let O=0;if(this._rows<N)for(let P=this._rows;P<N;P++)this.lines.length<N+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new U.BufferLine(q,I)):this.ybase>0&&this.lines.length<=this.ybase+this.y+O+1?(this.ybase--,O++,this.ydisp>0&&this.ydisp--):this.lines.push(new U.BufferLine(q,I)));else for(let P=this._rows;P>N;P--)this.lines.length>N+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(L<this.lines.maxLength){let P=this.lines.length-L;P>0&&(this.lines.trimStart(P),this.ybase=Math.max(this.ybase-P,0),this.ydisp=Math.max(this.ydisp-P,0),this.savedY=Math.max(this.savedY-P,0)),this.lines.maxLength=L}this.x=Math.min(this.x,q-1),this.y=Math.min(this.y,N-1),O&&(this.y+=O),this.savedX=Math.min(this.savedX,q-1),this.scrollTop=0}if(this.scrollBottom=N-1,this._isReflowEnabled&&(this._reflow(q,N),this._cols>q))for(let O=0;O<this.lines.length;O++)w+=+this.lines.get(O).resize(q,I);this._cols=q,this._rows=N,this._memoryCleanupQueue.clear(),w>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let q=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,q=!1);let N=0;for(;this._memoryCleanupPosition<this.lines.length;)if(N+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),N>100)return!0;return q}get _isReflowEnabled(){let q=this._optionsService.rawOptions.windowsPty;return q&&q.buildNumber?this._hasScrollback&&q.backend==="conpty"&&q.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(q,N){this._cols!==q&&(q>this._cols?this._reflowLarger(q,N):this._reflowSmaller(q,N))}_reflowLarger(q,N){let I=(0,K.reflowLargerGetLinesToRemove)(this.lines,this._cols,q,this.ybase+this.y,this.getNullCell(U.DEFAULT_ATTR_DATA));if(I.length>0){let w=(0,K.reflowLargerCreateNewLayout)(this.lines,I);(0,K.reflowLargerApplyNewLayout)(this.lines,w.layout),this._reflowLargerAdjustViewport(q,N,w.countRemoved)}}_reflowLargerAdjustViewport(q,N,I){let w=this.getNullCell(U.DEFAULT_ATTR_DATA),L=I;for(;L-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<N&&this.lines.push(new U.BufferLine(q,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-I,0)}_reflowSmaller(q,N){let I=this.getNullCell(U.DEFAULT_ATTR_DATA),w=[],L=0;for(let O=this.lines.length-1;O>=0;O--){let P=this.lines.get(O);if(!P||!P.isWrapped&&P.getTrimmedLength()<=q)continue;let S=[P];for(;P.isWrapped&&O>0;)P=this.lines.get(--O),S.unshift(P);let T=this.ybase+this.y;if(T>=O&&T<O+S.length)continue;let x=S[S.length-1].getTrimmedLength(),h=(0,K.reflowSmallerGetNewLineLengths)(S,this._cols,q),u=h.length-S.length,k;k=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+u):Math.max(0,this.lines.length-this.lines.maxLength+u);let f=[];for(let t=0;t<u;t++){let w0=this.getBlankLine(U.DEFAULT_ATTR_DATA,!0);f.push(w0)}f.length>0&&(w.push({start:O+S.length+L,newLines:f}),L+=f.length),S.push(...f);let d=h.length-1,c=h[d];c===0&&(d--,c=h[d]);let g=S.length-u-1,l=x;for(;g>=0;){let t=Math.min(l,c);if(S[d]===void 0)break;if(S[d].copyCellsFrom(S[g],l-t,c-t,t,!0),c-=t,c===0&&(d--,c=h[d]),l-=t,l===0){g--;let w0=Math.max(g,0);l=(0,K.getWrappedLineTrimmedLength)(S,w0,this._cols)}}for(let t=0;t<S.length;t++)h[t]<q&&S[t].setCell(h[t],I);let a=u-k;for(;a-- >0;)this.ybase===0?this.y<N-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+L)-N&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+u,this.ybase+N-1)}if(w.length>0){let O=[],P=[];for(let d=0;d<this.lines.length;d++)P.push(this.lines.get(d));let S=this.lines.length,T=S-1,x=0,h=w[x];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+L);let u=0;for(let d=Math.min(this.lines.maxLength-1,S+L-1);d>=0;d--)if(h&&h.start>T+u){for(let c=h.newLines.length-1;c>=0;c--)this.lines.set(d--,h.newLines[c]);d++,O.push({index:T+1,amount:h.newLines.length}),u+=h.newLines.length,h=w[++x]}else this.lines.set(d,P[T--]);let k=0;for(let d=O.length-1;d>=0;d--)O[d].index+=k,this.lines.onInsertEmitter.fire(O[d]),k+=O[d].amount;let f=Math.max(0,S+L-this.lines.maxLength);f>0&&this.lines.onTrimEmitter.fire(f)}}translateBufferLineToString(q,N,I=0,w){let L=this.lines.get(q);return L?L.translateToString(N,I,w):""}getWrappedRangeForLine(q){let N=q,I=q;for(;N>0&&this.lines.get(N).isWrapped;)N--;for(;I+1<this.lines.length&&this.lines.get(I+1).isWrapped;)I++;return{first:N,last:I}}setupTabStops(q){for(q!=null?this.tabs[q]||(q=this.prevStop(q)):(this.tabs={},q=0);q<this._cols;q+=this._optionsService.rawOptions.tabStopWidth)this.tabs[q]=!0}prevStop(q){for(q==null&&(q=this.x);!this.tabs[--q]&&q>0;);return q>=this._cols?this._cols-1:q<0?0:q}nextStop(q){for(q==null&&(q=this.x);!this.tabs[++q]&&q<this._cols;);return q>=this._cols?this._cols-1:q<0?0:q}clearMarkers(q){this._isClearing=!0;for(let N=0;N<this.markers.length;N++)this.markers[N].line===q&&(this.markers[N].dispose(),this.markers.splice(N--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let q=0;q<this.markers.length;q++)this.markers[q].dispose(),this.markers.splice(q--,1);this._isClearing=!1}addMarker(q){let N=new W.Marker(q);return this.markers.push(N),N.register(this.lines.onTrim((I)=>{N.line-=I,N.line<0&&N.dispose()})),N.register(this.lines.onInsert((I)=>{N.line>=I.index&&(N.line+=I.amount)})),N.register(this.lines.onDelete((I)=>{N.line>=I.index&&N.line<I.index+I.amount&&N.dispose(),N.line>I.index&&(N.line-=I.amount)})),N.register(N.onDispose(()=>this._removeMarker(N))),N}_removeMarker(q){this._isClearing||this.markers.splice(this.markers.indexOf(q),1)}}},437:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.BufferLine=F.DEFAULT_ATTR_DATA=void 0;let D=X(734),G=X(511),V=X(643),U=X(482);F.DEFAULT_ATTR_DATA=Object.freeze(new D.AttributeData);let K=0;class E{constructor(z,W,H=!1){this.isWrapped=H,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*z);let q=W||G.CellData.fromCharData([0,V.NULL_CELL_CHAR,V.NULL_CELL_WIDTH,V.NULL_CELL_CODE]);for(let N=0;N<z;++N)this.setCell(N,q);this.length=z}get(z){let W=this._data[3*z+0],H=2097151&W;return[this._data[3*z+1],2097152&W?this._combined[z]:H?(0,U.stringFromCodePoint)(H):"",W>>22,2097152&W?this._combined[z].charCodeAt(this._combined[z].length-1):H]}set(z,W){this._data[3*z+1]=W[V.CHAR_DATA_ATTR_INDEX],W[V.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[z]=W[1],this._data[3*z+0]=2097152|z|W[V.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*z+0]=W[V.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|W[V.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(z){return this._data[3*z+0]>>22}hasWidth(z){return 12582912&this._data[3*z+0]}getFg(z){return this._data[3*z+1]}getBg(z){return this._data[3*z+2]}hasContent(z){return 4194303&this._data[3*z+0]}getCodePoint(z){let W=this._data[3*z+0];return 2097152&W?this._combined[z].charCodeAt(this._combined[z].length-1):2097151&W}isCombined(z){return 2097152&this._data[3*z+0]}getString(z){let W=this._data[3*z+0];return 2097152&W?this._combined[z]:2097151&W?(0,U.stringFromCodePoint)(2097151&W):""}isProtected(z){return 536870912&this._data[3*z+2]}loadCell(z,W){return K=3*z,W.content=this._data[K+0],W.fg=this._data[K+1],W.bg=this._data[K+2],2097152&W.content&&(W.combinedData=this._combined[z]),268435456&W.bg&&(W.extended=this._extendedAttrs[z]),W}setCell(z,W){2097152&W.content&&(this._combined[z]=W.combinedData),268435456&W.bg&&(this._extendedAttrs[z]=W.extended),this._data[3*z+0]=W.content,this._data[3*z+1]=W.fg,this._data[3*z+2]=W.bg}setCellFromCodepoint(z,W,H,q){268435456&q.bg&&(this._extendedAttrs[z]=q.extended),this._data[3*z+0]=W|H<<22,this._data[3*z+1]=q.fg,this._data[3*z+2]=q.bg}addCodepointToCell(z,W,H){let q=this._data[3*z+0];2097152&q?this._combined[z]+=(0,U.stringFromCodePoint)(W):2097151&q?(this._combined[z]=(0,U.stringFromCodePoint)(2097151&q)+(0,U.stringFromCodePoint)(W),q&=-2097152,q|=2097152):q=W|4194304,H&&(q&=-12582913,q|=H<<22),this._data[3*z+0]=q}insertCells(z,W,H){if((z%=this.length)&&this.getWidth(z-1)===2&&this.setCellFromCodepoint(z-1,0,1,H),W<this.length-z){let q=new G.CellData;for(let N=this.length-z-W-1;N>=0;--N)this.setCell(z+W+N,this.loadCell(z+N,q));for(let N=0;N<W;++N)this.setCell(z+N,H)}else for(let q=z;q<this.length;++q)this.setCell(q,H);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,H)}deleteCells(z,W,H){if(z%=this.length,W<this.length-z){let q=new G.CellData;for(let N=0;N<this.length-z-W;++N)this.setCell(z+N,this.loadCell(z+W+N,q));for(let N=this.length-W;N<this.length;++N)this.setCell(N,H)}else for(let q=z;q<this.length;++q)this.setCell(q,H);z&&this.getWidth(z-1)===2&&this.setCellFromCodepoint(z-1,0,1,H),this.getWidth(z)!==0||this.hasContent(z)||this.setCellFromCodepoint(z,0,1,H)}replaceCells(z,W,H,q=!1){if(q)for(z&&this.getWidth(z-1)===2&&!this.isProtected(z-1)&&this.setCellFromCodepoint(z-1,0,1,H),W<this.length&&this.getWidth(W-1)===2&&!this.isProtected(W)&&this.setCellFromCodepoint(W,0,1,H);z<W&&z<this.length;)this.isProtected(z)||this.setCell(z,H),z++;else for(z&&this.getWidth(z-1)===2&&this.setCellFromCodepoint(z-1,0,1,H),W<this.length&&this.getWidth(W-1)===2&&this.setCellFromCodepoint(W,0,1,H);z<W&&z<this.length;)this.setCell(z++,H)}resize(z,W){if(z===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let H=3*z;if(z>this.length){if(this._data.buffer.byteLength>=4*H)this._data=new Uint32Array(this._data.buffer,0,H);else{let q=new Uint32Array(H);q.set(this._data),this._data=q}for(let q=this.length;q<z;++q)this.setCell(q,W)}else{this._data=this._data.subarray(0,H);let q=Object.keys(this._combined);for(let I=0;I<q.length;I++){let w=parseInt(q[I],10);w>=z&&delete this._combined[w]}let N=Object.keys(this._extendedAttrs);for(let I=0;I<N.length;I++){let w=parseInt(N[I],10);w>=z&&delete this._extendedAttrs[w]}}return this.length=z,4*H*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let z=new Uint32Array(this._data.length);return z.set(this._data),this._data=z,1}return 0}fill(z,W=!1){if(W)for(let H=0;H<this.length;++H)this.isProtected(H)||this.setCell(H,z);else{this._combined={},this._extendedAttrs={};for(let H=0;H<this.length;++H)this.setCell(H,z)}}copyFrom(z){this.length!==z.length?this._data=new Uint32Array(z._data):this._data.set(z._data),this.length=z.length,this._combined={};for(let W in z._combined)this._combined[W]=z._combined[W];this._extendedAttrs={};for(let W in z._extendedAttrs)this._extendedAttrs[W]=z._extendedAttrs[W];this.isWrapped=z.isWrapped}clone(){let z=new E(0);z._data=new Uint32Array(this._data),z.length=this.length;for(let W in this._combined)z._combined[W]=this._combined[W];for(let W in this._extendedAttrs)z._extendedAttrs[W]=this._extendedAttrs[W];return z.isWrapped=this.isWrapped,z}getTrimmedLength(){for(let z=this.length-1;z>=0;--z)if(4194303&this._data[3*z+0])return z+(this._data[3*z+0]>>22);return 0}getNoBgTrimmedLength(){for(let z=this.length-1;z>=0;--z)if(4194303&this._data[3*z+0]||50331648&this._data[3*z+2])return z+(this._data[3*z+0]>>22);return 0}copyCellsFrom(z,W,H,q,N){let I=z._data;if(N)for(let L=q-1;L>=0;L--){for(let O=0;O<3;O++)this._data[3*(H+L)+O]=I[3*(W+L)+O];268435456&I[3*(W+L)+2]&&(this._extendedAttrs[H+L]=z._extendedAttrs[W+L])}else for(let L=0;L<q;L++){for(let O=0;O<3;O++)this._data[3*(H+L)+O]=I[3*(W+L)+O];268435456&I[3*(W+L)+2]&&(this._extendedAttrs[H+L]=z._extendedAttrs[W+L])}let w=Object.keys(z._combined);for(let L=0;L<w.length;L++){let O=parseInt(w[L],10);O>=W&&(this._combined[O-W+H]=z._combined[O])}}translateToString(z,W,H,q){W=W??0,H=H??this.length,z&&(H=Math.min(H,this.getTrimmedLength())),q&&(q.length=0);let N="";for(;W<H;){let I=this._data[3*W+0],w=2097151&I,L=2097152&I?this._combined[W]:w?(0,U.stringFromCodePoint)(w):V.WHITESPACE_CELL_CHAR;if(N+=L,q)for(let O=0;O<L.length;++O)q.push(W);W+=I>>22||1}return q&&q.push(W),N}}F.BufferLine=E},634:(Z,F)=>{function X(D,G,V){if(G===D.length-1)return D[G].getTrimmedLength();let U=!D[G].hasContent(V-1)&&D[G].getWidth(V-1)===1,K=D[G+1].getWidth(0)===2;return U&&K?V-1:V}Object.defineProperty(F,"__esModule",{value:!0}),F.getWrappedLineTrimmedLength=F.reflowSmallerGetNewLineLengths=F.reflowLargerApplyNewLayout=F.reflowLargerCreateNewLayout=F.reflowLargerGetLinesToRemove=void 0,F.reflowLargerGetLinesToRemove=function(D,G,V,U,K){let E=[];for(let z=0;z<D.length-1;z++){let W=z,H=D.get(++W);if(!H.isWrapped)continue;let q=[D.get(z)];for(;W<D.length&&H.isWrapped;)q.push(H),H=D.get(++W);if(U>=z&&U<W){z+=q.length-1;continue}let N=0,I=X(q,N,G),w=1,L=0;for(;w<q.length;){let P=X(q,w,G),S=P-L,T=V-I,x=Math.min(S,T);q[N].copyCellsFrom(q[w],L,I,x,!1),I+=x,I===V&&(N++,I=0),L+=x,L===P&&(w++,L=0),I===0&&N!==0&&q[N-1].getWidth(V-1)===2&&(q[N].copyCellsFrom(q[N-1],V-1,I++,1,!1),q[N-1].setCell(V-1,K))}q[N].replaceCells(I,V,K);let O=0;for(let P=q.length-1;P>0&&(P>N||q[P].getTrimmedLength()===0);P--)O++;O>0&&(E.push(z+q.length-O),E.push(O)),z+=q.length-1}return E},F.reflowLargerCreateNewLayout=function(D,G){let V=[],U=0,K=G[U],E=0;for(let z=0;z<D.length;z++)if(K===z){let W=G[++U];D.onDeleteEmitter.fire({index:z-E,amount:W}),z+=W-1,E+=W,K=G[++U]}else V.push(z);return{layout:V,countRemoved:E}},F.reflowLargerApplyNewLayout=function(D,G){let V=[];for(let U=0;U<G.length;U++)V.push(D.get(G[U]));for(let U=0;U<V.length;U++)D.set(U,V[U]);D.length=G.length},F.reflowSmallerGetNewLineLengths=function(D,G,V){let U=[],K=D.map((H,q)=>X(D,q,G)).reduce((H,q)=>H+q),E=0,z=0,W=0;for(;W<K;){if(K-W<V){U.push(K-W);break}E+=V;let H=X(D,z,G);E>H&&(E-=H,z++);let q=D[z].getWidth(E-1)===2;q&&E--;let N=q?V-1:V;U.push(N),W+=N}return U},F.getWrappedLineTrimmedLength=X},295:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.BufferSet=void 0;let D=X(460),G=X(844),V=X(92);class U extends G.Disposable{constructor(K,E){super(),this._optionsService=K,this._bufferService=E,this._onBufferActivate=this.register(new D.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new V.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new V.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(K){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(K),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(K,E){this._normal.resize(K,E),this._alt.resize(K,E),this.setupTabStops(K)}setupTabStops(K){this._normal.setupTabStops(K),this._alt.setupTabStops(K)}}F.BufferSet=U},511:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.CellData=void 0;let D=X(482),G=X(643),V=X(734);class U extends V.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new V.ExtendedAttrs,this.combinedData=""}static fromCharData(K){let E=new U;return E.setFromCharData(K),E}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,D.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(K){this.fg=K[G.CHAR_DATA_ATTR_INDEX],this.bg=0;let E=!1;if(K[G.CHAR_DATA_CHAR_INDEX].length>2)E=!0;else if(K[G.CHAR_DATA_CHAR_INDEX].length===2){let z=K[G.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=z&&z<=56319){let W=K[G.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=W&&W<=57343?this.content=1024*(z-55296)+W-56320+65536|K[G.CHAR_DATA_WIDTH_INDEX]<<22:E=!0}else E=!0}else this.content=K[G.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|K[G.CHAR_DATA_WIDTH_INDEX]<<22;E&&(this.combinedData=K[G.CHAR_DATA_CHAR_INDEX],this.content=2097152|K[G.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}F.CellData=U},643:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.WHITESPACE_CELL_CODE=F.WHITESPACE_CELL_WIDTH=F.WHITESPACE_CELL_CHAR=F.NULL_CELL_CODE=F.NULL_CELL_WIDTH=F.NULL_CELL_CHAR=F.CHAR_DATA_CODE_INDEX=F.CHAR_DATA_WIDTH_INDEX=F.CHAR_DATA_CHAR_INDEX=F.CHAR_DATA_ATTR_INDEX=F.DEFAULT_EXT=F.DEFAULT_ATTR=F.DEFAULT_COLOR=void 0,F.DEFAULT_COLOR=0,F.DEFAULT_ATTR=256|F.DEFAULT_COLOR<<9,F.DEFAULT_EXT=0,F.CHAR_DATA_ATTR_INDEX=0,F.CHAR_DATA_CHAR_INDEX=1,F.CHAR_DATA_WIDTH_INDEX=2,F.CHAR_DATA_CODE_INDEX=3,F.NULL_CELL_CHAR="",F.NULL_CELL_WIDTH=1,F.NULL_CELL_CODE=0,F.WHITESPACE_CELL_CHAR=" ",F.WHITESPACE_CELL_WIDTH=1,F.WHITESPACE_CELL_CODE=32},863:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.Marker=void 0;let D=X(460),G=X(844);class V{get id(){return this._id}constructor(U){this.line=U,this.isDisposed=!1,this._disposables=[],this._id=V._nextId++,this._onDispose=this.register(new D.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,G.disposeArray)(this._disposables),this._disposables.length=0)}register(U){return this._disposables.push(U),U}}F.Marker=V,V._nextId=1},116:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.DEFAULT_CHARSET=F.CHARSETS=void 0,F.CHARSETS={},F.DEFAULT_CHARSET=F.CHARSETS.B,F.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},F.CHARSETS.A={"#":"£"},F.CHARSETS.B=void 0,F.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},F.CHARSETS.C=F.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},F.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},F.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},F.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},F.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},F.CHARSETS.E=F.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},F.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},F.CHARSETS.H=F.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},F.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},584:(Z,F)=>{var X,D,G;Object.defineProperty(F,"__esModule",{value:!0}),F.C1_ESCAPED=F.C1=F.C0=void 0,function(V){V.NUL="\x00",V.SOH="\x01",V.STX="\x02",V.ETX="\x03",V.EOT="\x04",V.ENQ="\x05",V.ACK="\x06",V.BEL="\x07",V.BS="\b",V.HT="\t",V.LF=`
2682
2684
  `,V.VT="\v",V.FF="\f",V.CR="\r",V.SO="\x0E",V.SI="\x0F",V.DLE="\x10",V.DC1="\x11",V.DC2="\x12",V.DC3="\x13",V.DC4="\x14",V.NAK="\x15",V.SYN="\x16",V.ETB="\x17",V.CAN="\x18",V.EM="\x19",V.SUB="\x1A",V.ESC="\x1B",V.FS="\x1C",V.GS="\x1D",V.RS="\x1E",V.US="\x1F",V.SP=" ",V.DEL=""}(X||(F.C0=X={})),function(V){V.PAD="€",V.HOP="",V.BPH="‚",V.NBH="ƒ",V.IND="„",V.NEL="…",V.SSA="†",V.ESA="‡",V.HTS="ˆ",V.HTJ="‰",V.VTS="Š",V.PLD="‹",V.PLU="Œ",V.RI="",V.SS2="Ž",V.SS3="",V.DCS="",V.PU1="‘",V.PU2="’",V.STS="“",V.CCH="”",V.MW="•",V.SPA="–",V.EPA="—",V.SOS="˜",V.SGCI="™",V.SCI="š",V.CSI="›",V.ST="œ",V.OSC="",V.PM="ž",V.APC="Ÿ"}(D||(F.C1=D={})),function(V){V.ST=`${X.ESC}\\`}(G||(F.C1_ESCAPED=G={}))},482:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.Utf8ToUtf32=F.StringToUtf32=F.utf32ToString=F.stringFromCodePoint=void 0,F.stringFromCodePoint=function(X){return X>65535?(X-=65536,String.fromCharCode(55296+(X>>10))+String.fromCharCode(X%1024+56320)):String.fromCharCode(X)},F.utf32ToString=function(X,D=0,G=X.length){let V="";for(let U=D;U<G;++U){let K=X[U];K>65535?(K-=65536,V+=String.fromCharCode(55296+(K>>10))+String.fromCharCode(K%1024+56320)):V+=String.fromCharCode(K)}return V},F.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(X,D){let G=X.length;if(!G)return 0;let V=0,U=0;if(this._interim){let K=X.charCodeAt(U++);56320<=K&&K<=57343?D[V++]=1024*(this._interim-55296)+K-56320+65536:(D[V++]=this._interim,D[V++]=K),this._interim=0}for(let K=U;K<G;++K){let E=X.charCodeAt(K);if(55296<=E&&E<=56319){if(++K>=G)return this._interim=E,V;let z=X.charCodeAt(K);56320<=z&&z<=57343?D[V++]=1024*(E-55296)+z-56320+65536:(D[V++]=E,D[V++]=z)}else E!==65279&&(D[V++]=E)}return V}},F.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(X,D){let G=X.length;if(!G)return 0;let V,U,K,E,z=0,W=0,H=0;if(this.interim[0]){let I=!1,w=this.interim[0];w&=(224&w)==192?31:(240&w)==224?15:7;let L,O=0;for(;(L=63&this.interim[++O])&&O<4;)w<<=6,w|=L;let P=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,S=P-O;for(;H<S;){if(H>=G)return 0;if(L=X[H++],(192&L)!=128){H--,I=!0;break}this.interim[O++]=L,w<<=6,w|=63&L}I||(P===2?w<128?H--:D[z++]=w:P===3?w<2048||w>=55296&&w<=57343||w===65279||(D[z++]=w):w<65536||w>1114111||(D[z++]=w)),this.interim.fill(0)}let q=G-4,N=H;for(;N<G;){for(;!(!(N<q)||128&(V=X[N])||128&(U=X[N+1])||128&(K=X[N+2])||128&(E=X[N+3]));)D[z++]=V,D[z++]=U,D[z++]=K,D[z++]=E,N+=4;if(V=X[N++],V<128)D[z++]=V;else if((224&V)==192){if(N>=G)return this.interim[0]=V,z;if(U=X[N++],(192&U)!=128){N--;continue}if(W=(31&V)<<6|63&U,W<128){N--;continue}D[z++]=W}else if((240&V)==224){if(N>=G)return this.interim[0]=V,z;if(U=X[N++],(192&U)!=128){N--;continue}if(N>=G)return this.interim[0]=V,this.interim[1]=U,z;if(K=X[N++],(192&K)!=128){N--;continue}if(W=(15&V)<<12|(63&U)<<6|63&K,W<2048||W>=55296&&W<=57343||W===65279)continue;D[z++]=W}else if((248&V)==240){if(N>=G)return this.interim[0]=V,z;if(U=X[N++],(192&U)!=128){N--;continue}if(N>=G)return this.interim[0]=V,this.interim[1]=U,z;if(K=X[N++],(192&K)!=128){N--;continue}if(N>=G)return this.interim[0]=V,this.interim[1]=U,this.interim[2]=K,z;if(E=X[N++],(192&E)!=128){N--;continue}if(W=(7&V)<<18|(63&U)<<12|(63&K)<<6|63&E,W<65536||W>1114111)continue;D[z++]=W}}return z}}},225:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.UnicodeV6=void 0;let D=X(480),G=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],V=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],U;F.UnicodeV6=class{constructor(){if(this.version="6",!U){U=new Uint8Array(65536),U.fill(1),U[0]=0,U.fill(0,1,32),U.fill(0,127,160),U.fill(2,4352,4448),U[9001]=2,U[9002]=2,U.fill(2,11904,42192),U[12351]=1,U.fill(2,44032,55204),U.fill(2,63744,64256),U.fill(2,65040,65050),U.fill(2,65072,65136),U.fill(2,65280,65377),U.fill(2,65504,65511);for(let K=0;K<G.length;++K)U.fill(0,G[K][0],G[K][1]+1)}}wcwidth(K){return K<32?0:K<127?1:K<65536?U[K]:function(E,z){let W,H=0,q=z.length-1;if(E<z[0][0]||E>z[q][1])return!1;for(;q>=H;)if(W=H+q>>1,E>z[W][1])H=W+1;else{if(!(E<z[W][0]))return!0;q=W-1}return!1}(K,V)?0:K>=131072&&K<=196605||K>=196608&&K<=262141?2:1}charProperties(K,E){let z=this.wcwidth(K),W=z===0&&E!==0;if(W){let H=D.UnicodeService.extractWidth(E);H===0?W=!1:H>z&&(z=H)}return D.UnicodeService.createPropertyValue(0,z,W)}}},981:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.WriteBuffer=void 0;let D=X(460),G=X(844);class V extends G.Disposable{constructor(U){super(),this._action=U,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new D.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(U,K){if(K!==void 0&&this._syncCalls>K)return void(this._syncCalls=0);if(this._pendingData+=U.length,this._writeBuffer.push(U),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let E;for(this._isSyncWriting=!0;E=this._writeBuffer.shift();){this._action(E);let z=this._callbacks.shift();z&&z()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(U,K){if(this._pendingData>50000000)throw Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=U.length,this._writeBuffer.push(U),this._callbacks.push(K),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=U.length,this._writeBuffer.push(U),this._callbacks.push(K)}_innerWrite(U=0,K=!0){let E=U||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){let z=this._writeBuffer[this._bufferOffset],W=this._action(z,K);if(W){let q=(N)=>Date.now()-E>=12?setTimeout(()=>this._innerWrite(0,N)):this._innerWrite(E,N);return void W.catch((N)=>(queueMicrotask(()=>{throw N}),Promise.resolve(!1))).then(q)}let H=this._callbacks[this._bufferOffset];if(H&&H(),this._bufferOffset++,this._pendingData-=z.length,Date.now()-E>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}F.WriteBuffer=V},941:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.toRgbString=F.parseColor=void 0;let X=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,D=/^[\da-f]+$/;function G(V,U){let K=V.toString(16),E=K.length<2?"0"+K:K;switch(U){case 4:return K[0];case 8:return E;case 12:return(E+E).slice(0,3);default:return E+E}}F.parseColor=function(V){if(!V)return;let U=V.toLowerCase();if(U.indexOf("rgb:")===0){U=U.slice(4);let K=X.exec(U);if(K){let E=K[1]?15:K[4]?255:K[7]?4095:65535;return[Math.round(parseInt(K[1]||K[4]||K[7]||K[10],16)/E*255),Math.round(parseInt(K[2]||K[5]||K[8]||K[11],16)/E*255),Math.round(parseInt(K[3]||K[6]||K[9]||K[12],16)/E*255)]}}else if(U.indexOf("#")===0&&(U=U.slice(1),D.exec(U)&&[3,6,9,12].includes(U.length))){let K=U.length/3,E=[0,0,0];for(let z=0;z<3;++z){let W=parseInt(U.slice(K*z,K*z+K),16);E[z]=K===1?W<<4:K===2?W:K===3?W>>4:W>>8}return E}},F.toRgbString=function(V,U=16){let[K,E,z]=V;return`rgb:${G(K,U)}/${G(E,U)}/${G(z,U)}`}},770:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.PAYLOAD_LIMIT=void 0,F.PAYLOAD_LIMIT=1e7},351:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.DcsHandler=F.DcsParser=void 0;let D=X(482),G=X(742),V=X(770),U=[];F.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=U,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=U}registerHandler(E,z){this._handlers[E]===void 0&&(this._handlers[E]=[]);let W=this._handlers[E];return W.push(z),{dispose:()=>{let H=W.indexOf(z);H!==-1&&W.splice(H,1)}}}clearHandler(E){this._handlers[E]&&delete this._handlers[E]}setHandlerFallback(E){this._handlerFb=E}reset(){if(this._active.length)for(let E=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;E>=0;--E)this._active[E].unhook(!1);this._stack.paused=!1,this._active=U,this._ident=0}hook(E,z){if(this.reset(),this._ident=E,this._active=this._handlers[E]||U,this._active.length)for(let W=this._active.length-1;W>=0;W--)this._active[W].hook(z);else this._handlerFb(this._ident,"HOOK",z)}put(E,z,W){if(this._active.length)for(let H=this._active.length-1;H>=0;H--)this._active[H].put(E,z,W);else this._handlerFb(this._ident,"PUT",(0,D.utf32ToString)(E,z,W))}unhook(E,z=!0){if(this._active.length){let W=!1,H=this._active.length-1,q=!1;if(this._stack.paused&&(H=this._stack.loopPosition-1,W=z,q=this._stack.fallThrough,this._stack.paused=!1),!q&&W===!1){for(;H>=0&&(W=this._active[H].unhook(E),W!==!0);H--)if(W instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=H,this._stack.fallThrough=!1,W;H--}for(;H>=0;H--)if(W=this._active[H].unhook(!1),W instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=H,this._stack.fallThrough=!0,W}else this._handlerFb(this._ident,"UNHOOK",E);this._active=U,this._ident=0}};let K=new G.Params;K.addParam(0),F.DcsHandler=class{constructor(E){this._handler=E,this._data="",this._params=K,this._hitLimit=!1}hook(E){this._params=E.length>1||E.params[0]?E.clone():K,this._data="",this._hitLimit=!1}put(E,z,W){this._hitLimit||(this._data+=(0,D.utf32ToString)(E,z,W),this._data.length>V.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(E){let z=!1;if(this._hitLimit)z=!1;else if(E&&(z=this._handler(this._data,this._params),z instanceof Promise))return z.then((W)=>(this._params=K,this._data="",this._hitLimit=!1,W));return this._params=K,this._data="",this._hitLimit=!1,z}}},15:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.EscapeSequenceParser=F.VT500_TRANSITION_TABLE=F.TransitionTable=void 0;let D=X(844),G=X(742),V=X(242),U=X(351);class K{constructor(W){this.table=new Uint8Array(W)}setDefault(W,H){this.table.fill(W<<4|H)}add(W,H,q,N){this.table[H<<8|W]=q<<4|N}addMany(W,H,q,N){for(let I=0;I<W.length;I++)this.table[H<<8|W[I]]=q<<4|N}}F.TransitionTable=K;let E=160;F.VT500_TRANSITION_TABLE=function(){let W=new K(4095),H=Array.apply(null,Array(256)).map((O,P)=>P),q=(O,P)=>H.slice(O,P),N=q(32,127),I=q(0,24);I.push(25),I.push.apply(I,q(28,32));let w=q(0,14),L;for(L in W.setDefault(1,0),W.addMany(N,0,2,0),w)W.addMany([24,26,153,154],L,3,0),W.addMany(q(128,144),L,3,0),W.addMany(q(144,152),L,3,0),W.add(156,L,0,0),W.add(27,L,11,1),W.add(157,L,4,8),W.addMany([152,158,159],L,0,7),W.add(155,L,11,3),W.add(144,L,11,9);return W.addMany(I,0,3,0),W.addMany(I,1,3,1),W.add(127,1,0,1),W.addMany(I,8,0,8),W.addMany(I,3,3,3),W.add(127,3,0,3),W.addMany(I,4,3,4),W.add(127,4,0,4),W.addMany(I,6,3,6),W.addMany(I,5,3,5),W.add(127,5,0,5),W.addMany(I,2,3,2),W.add(127,2,0,2),W.add(93,1,4,8),W.addMany(N,8,5,8),W.add(127,8,5,8),W.addMany([156,27,24,26,7],8,6,0),W.addMany(q(28,32),8,0,8),W.addMany([88,94,95],1,0,7),W.addMany(N,7,0,7),W.addMany(I,7,0,7),W.add(156,7,0,0),W.add(127,7,0,7),W.add(91,1,11,3),W.addMany(q(64,127),3,7,0),W.addMany(q(48,60),3,8,4),W.addMany([60,61,62,63],3,9,4),W.addMany(q(48,60),4,8,4),W.addMany(q(64,127),4,7,0),W.addMany([60,61,62,63],4,0,6),W.addMany(q(32,64),6,0,6),W.add(127,6,0,6),W.addMany(q(64,127),6,0,0),W.addMany(q(32,48),3,9,5),W.addMany(q(32,48),5,9,5),W.addMany(q(48,64),5,0,6),W.addMany(q(64,127),5,7,0),W.addMany(q(32,48),4,9,5),W.addMany(q(32,48),1,9,2),W.addMany(q(32,48),2,9,2),W.addMany(q(48,127),2,10,0),W.addMany(q(48,80),1,10,0),W.addMany(q(81,88),1,10,0),W.addMany([89,90,92],1,10,0),W.addMany(q(96,127),1,10,0),W.add(80,1,11,9),W.addMany(I,9,0,9),W.add(127,9,0,9),W.addMany(q(28,32),9,0,9),W.addMany(q(32,48),9,9,12),W.addMany(q(48,60),9,8,10),W.addMany([60,61,62,63],9,9,10),W.addMany(I,11,0,11),W.addMany(q(32,128),11,0,11),W.addMany(q(28,32),11,0,11),W.addMany(I,10,0,10),W.add(127,10,0,10),W.addMany(q(28,32),10,0,10),W.addMany(q(48,60),10,8,10),W.addMany([60,61,62,63],10,0,11),W.addMany(q(32,48),10,9,12),W.addMany(I,12,0,12),W.add(127,12,0,12),W.addMany(q(28,32),12,0,12),W.addMany(q(32,48),12,9,12),W.addMany(q(48,64),12,0,11),W.addMany(q(64,127),12,12,13),W.addMany(q(64,127),10,12,13),W.addMany(q(64,127),9,12,13),W.addMany(I,13,13,13),W.addMany(N,13,13,13),W.add(127,13,0,13),W.addMany([27,156,24,26],13,14,0),W.add(E,0,2,0),W.add(E,8,5,8),W.add(E,6,0,6),W.add(E,11,0,11),W.add(E,13,13,13),W}();class z extends D.Disposable{constructor(W=F.VT500_TRANSITION_TABLE){super(),this._transitions=W,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new G.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(H,q,N)=>{},this._executeHandlerFb=(H)=>{},this._csiHandlerFb=(H,q)=>{},this._escHandlerFb=(H)=>{},this._errorHandlerFb=(H)=>H,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,D.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new V.OscParser),this._dcsParser=this.register(new U.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(W,H=[64,126]){let q=0;if(W.prefix){if(W.prefix.length>1)throw Error("only one byte as prefix supported");if(q=W.prefix.charCodeAt(0),q&&60>q||q>63)throw Error("prefix must be in range 0x3c .. 0x3f")}if(W.intermediates){if(W.intermediates.length>2)throw Error("only two bytes as intermediates are supported");for(let I=0;I<W.intermediates.length;++I){let w=W.intermediates.charCodeAt(I);if(32>w||w>47)throw Error("intermediate must be in range 0x20 .. 0x2f");q<<=8,q|=w}}if(W.final.length!==1)throw Error("final must be a single byte");let N=W.final.charCodeAt(0);if(H[0]>N||N>H[1])throw Error(`final must be in range ${H[0]} .. ${H[1]}`);return q<<=8,q|=N,q}identToString(W){let H=[];for(;W;)H.push(String.fromCharCode(255&W)),W>>=8;return H.reverse().join("")}setPrintHandler(W){this._printHandler=W}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(W,H){let q=this._identifier(W,[48,126]);this._escHandlers[q]===void 0&&(this._escHandlers[q]=[]);let N=this._escHandlers[q];return N.push(H),{dispose:()=>{let I=N.indexOf(H);I!==-1&&N.splice(I,1)}}}clearEscHandler(W){this._escHandlers[this._identifier(W,[48,126])]&&delete this._escHandlers[this._identifier(W,[48,126])]}setEscHandlerFallback(W){this._escHandlerFb=W}setExecuteHandler(W,H){this._executeHandlers[W.charCodeAt(0)]=H}clearExecuteHandler(W){this._executeHandlers[W.charCodeAt(0)]&&delete this._executeHandlers[W.charCodeAt(0)]}setExecuteHandlerFallback(W){this._executeHandlerFb=W}registerCsiHandler(W,H){let q=this._identifier(W);this._csiHandlers[q]===void 0&&(this._csiHandlers[q]=[]);let N=this._csiHandlers[q];return N.push(H),{dispose:()=>{let I=N.indexOf(H);I!==-1&&N.splice(I,1)}}}clearCsiHandler(W){this._csiHandlers[this._identifier(W)]&&delete this._csiHandlers[this._identifier(W)]}setCsiHandlerFallback(W){this._csiHandlerFb=W}registerDcsHandler(W,H){return this._dcsParser.registerHandler(this._identifier(W),H)}clearDcsHandler(W){this._dcsParser.clearHandler(this._identifier(W))}setDcsHandlerFallback(W){this._dcsParser.setHandlerFallback(W)}registerOscHandler(W,H){return this._oscParser.registerHandler(W,H)}clearOscHandler(W){this._oscParser.clearHandler(W)}setOscHandlerFallback(W){this._oscParser.setHandlerFallback(W)}setErrorHandler(W){this._errorHandler=W}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(W,H,q,N,I){this._parseStack.state=W,this._parseStack.handlers=H,this._parseStack.handlerPos=q,this._parseStack.transition=N,this._parseStack.chunkPos=I}parse(W,H,q){let N,I=0,w=0,L=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,L=this._parseStack.chunkPos+1;else{if(q===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error("improper continuation due to previous async handler, giving up parsing");let O=this._parseStack.handlers,P=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(q===!1&&P>-1){for(;P>=0&&(N=O[P](this._params),N!==!0);P--)if(N instanceof Promise)return this._parseStack.handlerPos=P,N}this._parseStack.handlers=[];break;case 4:if(q===!1&&P>-1){for(;P>=0&&(N=O[P](),N!==!0);P--)if(N instanceof Promise)return this._parseStack.handlerPos=P,N}this._parseStack.handlers=[];break;case 6:if(I=W[this._parseStack.chunkPos],N=this._dcsParser.unhook(I!==24&&I!==26,q),N)return N;I===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(I=W[this._parseStack.chunkPos],N=this._oscParser.end(I!==24&&I!==26,q),N)return N;I===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,L=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let O=L;O<H;++O){switch(I=W[O],w=this._transitions.table[this.currentState<<8|(I<160?I:E)],w>>4){case 2:for(let h=O+1;;++h){if(h>=H||(I=W[h])<32||I>126&&I<E){this._printHandler(W,O,h),O=h-1;break}if(++h>=H||(I=W[h])<32||I>126&&I<E){this._printHandler(W,O,h),O=h-1;break}if(++h>=H||(I=W[h])<32||I>126&&I<E){this._printHandler(W,O,h),O=h-1;break}if(++h>=H||(I=W[h])<32||I>126&&I<E){this._printHandler(W,O,h),O=h-1;break}}break;case 3:this._executeHandlers[I]?this._executeHandlers[I]():this._executeHandlerFb(I),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:O,code:I,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let P=this._csiHandlers[this._collect<<8|I],S=P?P.length-1:-1;for(;S>=0&&(N=P[S](this._params),N!==!0);S--)if(N instanceof Promise)return this._preserveStack(3,P,S,w,O),N;S<0&&this._csiHandlerFb(this._collect<<8|I,this._params),this.precedingJoinState=0;break;case 8:do switch(I){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(I-48)}while(++O<H&&(I=W[O])>47&&I<60);O--;break;case 9:this._collect<<=8,this._collect|=I;break;case 10:let T=this._escHandlers[this._collect<<8|I],x=T?T.length-1:-1;for(;x>=0&&(N=T[x](),N!==!0);x--)if(N instanceof Promise)return this._preserveStack(4,T,x,w,O),N;x<0&&this._escHandlerFb(this._collect<<8|I),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|I,this._params);break;case 13:for(let h=O+1;;++h)if(h>=H||(I=W[h])===24||I===26||I===27||I>127&&I<E){this._dcsParser.put(W,O,h),O=h-1;break}break;case 14:if(N=this._dcsParser.unhook(I!==24&&I!==26),N)return this._preserveStack(6,[],0,w,O),N;I===27&&(w|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let h=O+1;;h++)if(h>=H||(I=W[h])<32||I>127&&I<E){this._oscParser.put(W,O,h),O=h-1;break}break;case 6:if(N=this._oscParser.end(I!==24&&I!==26),N)return this._preserveStack(5,[],0,w,O),N;I===27&&(w|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&w}}}F.EscapeSequenceParser=z},242:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.OscHandler=F.OscParser=void 0;let D=X(770),G=X(482),V=[];F.OscParser=class{constructor(){this._state=0,this._active=V,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(U,K){this._handlers[U]===void 0&&(this._handlers[U]=[]);let E=this._handlers[U];return E.push(K),{dispose:()=>{let z=E.indexOf(K);z!==-1&&E.splice(z,1)}}}clearHandler(U){this._handlers[U]&&delete this._handlers[U]}setHandlerFallback(U){this._handlerFb=U}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=V}reset(){if(this._state===2)for(let U=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;U>=0;--U)this._active[U].end(!1);this._stack.paused=!1,this._active=V,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||V,this._active.length)for(let U=this._active.length-1;U>=0;U--)this._active[U].start();else this._handlerFb(this._id,"START")}_put(U,K,E){if(this._active.length)for(let z=this._active.length-1;z>=0;z--)this._active[z].put(U,K,E);else this._handlerFb(this._id,"PUT",(0,G.utf32ToString)(U,K,E))}start(){this.reset(),this._state=1}put(U,K,E){if(this._state!==3){if(this._state===1)for(;K<E;){let z=U[K++];if(z===59){this._state=2,this._start();break}if(z<48||57<z)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+z-48}this._state===2&&E-K>0&&this._put(U,K,E)}}end(U,K=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let E=!1,z=this._active.length-1,W=!1;if(this._stack.paused&&(z=this._stack.loopPosition-1,E=K,W=this._stack.fallThrough,this._stack.paused=!1),!W&&E===!1){for(;z>=0&&(E=this._active[z].end(U),E!==!0);z--)if(E instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=z,this._stack.fallThrough=!1,E;z--}for(;z>=0;z--)if(E=this._active[z].end(!1),E instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=z,this._stack.fallThrough=!0,E}else this._handlerFb(this._id,"END",U);this._active=V,this._id=-1,this._state=0}}},F.OscHandler=class{constructor(U){this._handler=U,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(U,K,E){this._hitLimit||(this._data+=(0,G.utf32ToString)(U,K,E),this._data.length>D.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(U){let K=!1;if(this._hitLimit)K=!1;else if(U&&(K=this._handler(this._data),K instanceof Promise))return K.then((E)=>(this._data="",this._hitLimit=!1,E));return this._data="",this._hitLimit=!1,K}}},742:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.Params=void 0;let X=2147483647;class D{static fromArray(G){let V=new D;if(!G.length)return V;for(let U=Array.isArray(G[0])?1:0;U<G.length;++U){let K=G[U];if(Array.isArray(K))for(let E=0;E<K.length;++E)V.addSubParam(K[E]);else V.addParam(K)}return V}constructor(G=32,V=32){if(this.maxLength=G,this.maxSubParamsLength=V,V>256)throw Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(G),this.length=0,this._subParams=new Int32Array(V),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(G),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let G=new D(this.maxLength,this.maxSubParamsLength);return G.params.set(this.params),G.length=this.length,G._subParams.set(this._subParams),G._subParamsLength=this._subParamsLength,G._subParamsIdx.set(this._subParamsIdx),G._rejectDigits=this._rejectDigits,G._rejectSubDigits=this._rejectSubDigits,G._digitIsSub=this._digitIsSub,G}toArray(){let G=[];for(let V=0;V<this.length;++V){G.push(this.params[V]);let U=this._subParamsIdx[V]>>8,K=255&this._subParamsIdx[V];K-U>0&&G.push(Array.prototype.slice.call(this._subParams,U,K))}return G}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(G){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(G<-1)throw Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=G>X?X:G}}addSubParam(G){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(G<-1)throw Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=G>X?X:G,this._subParamsIdx[this.length-1]++}}hasSubParams(G){return(255&this._subParamsIdx[G])-(this._subParamsIdx[G]>>8)>0}getSubParams(G){let V=this._subParamsIdx[G]>>8,U=255&this._subParamsIdx[G];return U-V>0?this._subParams.subarray(V,U):null}getSubParamsAll(){let G={};for(let V=0;V<this.length;++V){let U=this._subParamsIdx[V]>>8,K=255&this._subParamsIdx[V];K-U>0&&(G[V]=this._subParams.slice(U,K))}return G}addDigit(G){let V;if(this._rejectDigits||!(V=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let U=this._digitIsSub?this._subParams:this.params,K=U[V-1];U[V-1]=~K?Math.min(10*K+G,X):G}}F.Params=D},741:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.AddonManager=void 0,F.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let X=this._addons.length-1;X>=0;X--)this._addons[X].instance.dispose()}loadAddon(X,D){let G={instance:D,dispose:D.dispose,isDisposed:!1};this._addons.push(G),D.dispose=()=>this._wrappedAddonDispose(G),D.activate(X)}_wrappedAddonDispose(X){if(X.isDisposed)return;let D=-1;for(let G=0;G<this._addons.length;G++)if(this._addons[G]===X){D=G;break}if(D===-1)throw Error("Could not dispose an addon that has not been loaded");X.isDisposed=!0,X.dispose.apply(X.instance),this._addons.splice(D,1)}}},771:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.BufferApiView=void 0;let D=X(785),G=X(511);F.BufferApiView=class{constructor(V,U){this._buffer=V,this.type=U}init(V){return this._buffer=V,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(V){let U=this._buffer.lines.get(V);if(U)return new D.BufferLineApiView(U)}getNullCell(){return new G.CellData}}},785:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.BufferLineApiView=void 0;let D=X(511);F.BufferLineApiView=class{constructor(G){this._line=G}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(G,V){if(!(G<0||G>=this._line.length))return V?(this._line.loadCell(G,V),V):this._line.loadCell(G,new D.CellData)}translateToString(G,V,U){return this._line.translateToString(G,V,U)}}},285:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.BufferNamespaceApi=void 0;let D=X(771),G=X(460),V=X(844);class U extends V.Disposable{constructor(K){super(),this._core=K,this._onBufferChange=this.register(new G.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new D.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new D.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}F.BufferNamespaceApi=U},975:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.ParserApi=void 0,F.ParserApi=class{constructor(X){this._core=X}registerCsiHandler(X,D){return this._core.registerCsiHandler(X,(G)=>D(G.toArray()))}addCsiHandler(X,D){return this.registerCsiHandler(X,D)}registerDcsHandler(X,D){return this._core.registerDcsHandler(X,(G,V)=>D(G,V.toArray()))}addDcsHandler(X,D){return this.registerDcsHandler(X,D)}registerEscHandler(X,D){return this._core.registerEscHandler(X,D)}addEscHandler(X,D){return this.registerEscHandler(X,D)}registerOscHandler(X,D){return this._core.registerOscHandler(X,D)}addOscHandler(X,D){return this.registerOscHandler(X,D)}}},90:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.UnicodeApi=void 0,F.UnicodeApi=class{constructor(X){this._core=X}register(X){this._core.unicodeService.register(X)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(X){this._core.unicodeService.activeVersion=X}}},744:function(Z,F,X){var D=this&&this.__decorate||function(W,H,q,N){var I,w=arguments.length,L=w<3?H:N===null?N=Object.getOwnPropertyDescriptor(H,q):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(W,H,q,N);else for(var O=W.length-1;O>=0;O--)(I=W[O])&&(L=(w<3?I(L):w>3?I(H,q,L):I(H,q))||L);return w>3&&L&&Object.defineProperty(H,q,L),L},G=this&&this.__param||function(W,H){return function(q,N){H(q,N,W)}};Object.defineProperty(F,"__esModule",{value:!0}),F.BufferService=F.MINIMUM_ROWS=F.MINIMUM_COLS=void 0;let V=X(460),U=X(844),K=X(295),E=X(585);F.MINIMUM_COLS=2,F.MINIMUM_ROWS=1;let z=F.BufferService=class extends U.Disposable{get buffer(){return this.buffers.active}constructor(W){super(),this.isUserScrolling=!1,this._onResize=this.register(new V.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new V.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(W.rawOptions.cols||0,F.MINIMUM_COLS),this.rows=Math.max(W.rawOptions.rows||0,F.MINIMUM_ROWS),this.buffers=this.register(new K.BufferSet(W,this))}resize(W,H){this.cols=W,this.rows=H,this.buffers.resize(W,H),this._onResize.fire({cols:W,rows:H})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(W,H=!1){let q=this.buffer,N;N=this._cachedBlankLine,N&&N.length===this.cols&&N.getFg(0)===W.fg&&N.getBg(0)===W.bg||(N=q.getBlankLine(W,H),this._cachedBlankLine=N),N.isWrapped=H;let I=q.ybase+q.scrollTop,w=q.ybase+q.scrollBottom;if(q.scrollTop===0){let L=q.lines.isFull;w===q.lines.length-1?L?q.lines.recycle().copyFrom(N):q.lines.push(N.clone()):q.lines.splice(w+1,0,N.clone()),L?this.isUserScrolling&&(q.ydisp=Math.max(q.ydisp-1,0)):(q.ybase++,this.isUserScrolling||q.ydisp++)}else{let L=w-I+1;q.lines.shiftElements(I+1,L-1,-1),q.lines.set(w,N.clone())}this.isUserScrolling||(q.ydisp=q.ybase),this._onScroll.fire(q.ydisp)}scrollLines(W,H,q){let N=this.buffer;if(W<0){if(N.ydisp===0)return;this.isUserScrolling=!0}else W+N.ydisp>=N.ybase&&(this.isUserScrolling=!1);let I=N.ydisp;N.ydisp=Math.max(Math.min(N.ydisp+W,N.ybase),0),I!==N.ydisp&&(H||this._onScroll.fire(N.ydisp))}};F.BufferService=z=D([G(0,E.IOptionsService)],z)},994:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.CharsetService=void 0,F.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(X){this.glevel=X,this.charset=this._charsets[X]}setgCharset(X,D){this._charsets[X]=D,this.glevel===X&&(this.charset=D)}}},753:function(Z,F,X){var D=this&&this.__decorate||function(N,I,w,L){var O,P=arguments.length,S=P<3?I:L===null?L=Object.getOwnPropertyDescriptor(I,w):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(N,I,w,L);else for(var T=N.length-1;T>=0;T--)(O=N[T])&&(S=(P<3?O(S):P>3?O(I,w,S):O(I,w))||S);return P>3&&S&&Object.defineProperty(I,w,S),S},G=this&&this.__param||function(N,I){return function(w,L){I(w,L,N)}};Object.defineProperty(F,"__esModule",{value:!0}),F.CoreMouseService=void 0;let V=X(585),U=X(460),K=X(844),E={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:(N)=>N.button!==4&&N.action===1&&(N.ctrl=!1,N.alt=!1,N.shift=!1,!0)},VT200:{events:19,restrict:(N)=>N.action!==32},DRAG:{events:23,restrict:(N)=>N.action!==32||N.button!==3},ANY:{events:31,restrict:(N)=>!0}};function z(N,I){let w=(N.ctrl?16:0)|(N.shift?4:0)|(N.alt?8:0);return N.button===4?(w|=64,w|=N.action):(w|=3&N.button,4&N.button&&(w|=64),8&N.button&&(w|=128),N.action===32?w|=32:N.action!==0||I||(w|=3)),w}let W=String.fromCharCode,H={DEFAULT:(N)=>{let I=[z(N,!1)+32,N.col+32,N.row+32];return I[0]>255||I[1]>255||I[2]>255?"":`\x1B[M${W(I[0])}${W(I[1])}${W(I[2])}`},SGR:(N)=>{let I=N.action===0&&N.button!==4?"m":"M";return`\x1B[<${z(N,!0)};${N.col};${N.row}${I}`},SGR_PIXELS:(N)=>{let I=N.action===0&&N.button!==4?"m":"M";return`\x1B[<${z(N,!0)};${N.x};${N.y}${I}`}},q=F.CoreMouseService=class extends K.Disposable{constructor(N,I){super(),this._bufferService=N,this._coreService=I,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new U.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(let w of Object.keys(E))this.addProtocol(w,E[w]);for(let w of Object.keys(H))this.addEncoding(w,H[w]);this.reset()}addProtocol(N,I){this._protocols[N]=I}addEncoding(N,I){this._encodings[N]=I}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(N){if(!this._protocols[N])throw Error(`unknown protocol "${N}"`);this._activeProtocol=N,this._onProtocolChange.fire(this._protocols[N].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(N){if(!this._encodings[N])throw Error(`unknown encoding "${N}"`);this._activeEncoding=N}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(N){if(N.col<0||N.col>=this._bufferService.cols||N.row<0||N.row>=this._bufferService.rows)return!1;if(N.button===4&&N.action===32)return!1;if(N.button===3&&N.action!==32)return!1;if(N.button!==4&&(N.action===2||N.action===3))return!1;if(N.col++,N.row++,N.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,N,this._activeEncoding==="SGR_PIXELS"))return!1;if(!this._protocols[this._activeProtocol].restrict(N))return!1;let I=this._encodings[this._activeEncoding](N);return I&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(I):this._coreService.triggerDataEvent(I,!0)),this._lastEvent=N,!0}explainEvents(N){return{down:!!(1&N),up:!!(2&N),drag:!!(4&N),move:!!(8&N),wheel:!!(16&N)}}_equalEvents(N,I,w){if(w){if(N.x!==I.x)return!1;if(N.y!==I.y)return!1}else{if(N.col!==I.col)return!1;if(N.row!==I.row)return!1}return N.button===I.button&&N.action===I.action&&N.ctrl===I.ctrl&&N.alt===I.alt&&N.shift===I.shift}};F.CoreMouseService=q=D([G(0,V.IBufferService),G(1,V.ICoreService)],q)},83:function(Z,F,X){var D=this&&this.__decorate||function(q,N,I,w){var L,O=arguments.length,P=O<3?N:w===null?w=Object.getOwnPropertyDescriptor(N,I):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(q,N,I,w);else for(var S=q.length-1;S>=0;S--)(L=q[S])&&(P=(O<3?L(P):O>3?L(N,I,P):L(N,I))||P);return O>3&&P&&Object.defineProperty(N,I,P),P},G=this&&this.__param||function(q,N){return function(I,w){N(I,w,q)}};Object.defineProperty(F,"__esModule",{value:!0}),F.CoreService=void 0;let V=X(439),U=X(460),K=X(844),E=X(585),z=Object.freeze({insertMode:!1}),W=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),H=F.CoreService=class extends K.Disposable{constructor(q,N,I){super(),this._bufferService=q,this._logService=N,this._optionsService=I,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new U.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new U.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new U.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new U.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,V.clone)(z),this.decPrivateModes=(0,V.clone)(W)}reset(){this.modes=(0,V.clone)(z),this.decPrivateModes=(0,V.clone)(W)}triggerDataEvent(q,N=!1){if(this._optionsService.rawOptions.disableStdin)return;let I=this._bufferService.buffer;N&&this._optionsService.rawOptions.scrollOnUserInput&&I.ybase!==I.ydisp&&this._onRequestScrollToBottom.fire(),N&&this._onUserInput.fire(),this._logService.debug(`sending data "${q}"`,()=>q.split("").map((w)=>w.charCodeAt(0))),this._onData.fire(q)}triggerBinaryEvent(q){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${q}"`,()=>q.split("").map((N)=>N.charCodeAt(0))),this._onBinary.fire(q))}};F.CoreService=H=D([G(0,E.IBufferService),G(1,E.ILogService),G(2,E.IOptionsService)],H)},348:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.InstantiationService=F.ServiceCollection=void 0;let D=X(585),G=X(343);class V{constructor(...U){this._entries=new Map;for(let[K,E]of U)this.set(K,E)}set(U,K){let E=this._entries.get(U);return this._entries.set(U,K),E}forEach(U){for(let[K,E]of this._entries.entries())U(K,E)}has(U){return this._entries.has(U)}get(U){return this._entries.get(U)}}F.ServiceCollection=V,F.InstantiationService=class{constructor(){this._services=new V,this._services.set(D.IInstantiationService,this)}setService(U,K){this._services.set(U,K)}getService(U){return this._services.get(U)}createInstance(U,...K){let E=(0,G.getServiceDependencies)(U).sort((H,q)=>H.index-q.index),z=[];for(let H of E){let q=this._services.get(H.id);if(!q)throw Error(`[createInstance] ${U.name} depends on UNKNOWN service ${H.id}.`);z.push(q)}let W=E.length>0?E[0].index:K.length;if(K.length!==W)throw Error(`[createInstance] First service dependency of ${U.name} at position ${W+1} conflicts with ${K.length} static arguments`);return new U(...[...K,...z])}}},866:function(Z,F,X){var D=this&&this.__decorate||function(W,H,q,N){var I,w=arguments.length,L=w<3?H:N===null?N=Object.getOwnPropertyDescriptor(H,q):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(W,H,q,N);else for(var O=W.length-1;O>=0;O--)(I=W[O])&&(L=(w<3?I(L):w>3?I(H,q,L):I(H,q))||L);return w>3&&L&&Object.defineProperty(H,q,L),L},G=this&&this.__param||function(W,H){return function(q,N){H(q,N,W)}};Object.defineProperty(F,"__esModule",{value:!0}),F.traceCall=F.setTraceLogger=F.LogService=void 0;let V=X(844),U=X(585),K={trace:U.LogLevelEnum.TRACE,debug:U.LogLevelEnum.DEBUG,info:U.LogLevelEnum.INFO,warn:U.LogLevelEnum.WARN,error:U.LogLevelEnum.ERROR,off:U.LogLevelEnum.OFF},E,z=F.LogService=class extends V.Disposable{get logLevel(){return this._logLevel}constructor(W){super(),this._optionsService=W,this._logLevel=U.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),E=this}_updateLogLevel(){this._logLevel=K[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(W){for(let H=0;H<W.length;H++)typeof W[H]=="function"&&(W[H]=W[H]())}_log(W,H,q){this._evalLazyOptionalParams(q),W.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+H,...q)}trace(W,...H){this._logLevel<=U.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,W,H)}debug(W,...H){this._logLevel<=U.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,W,H)}info(W,...H){this._logLevel<=U.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,W,H)}warn(W,...H){this._logLevel<=U.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,W,H)}error(W,...H){this._logLevel<=U.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,W,H)}};F.LogService=z=D([G(0,U.IOptionsService)],z),F.setTraceLogger=function(W){E=W},F.traceCall=function(W,H,q){if(typeof q.value!="function")throw Error("not supported");let N=q.value;q.value=function(...I){if(E.logLevel!==U.LogLevelEnum.TRACE)return N.apply(this,I);E.trace(`GlyphRenderer#${N.name}(${I.map((L)=>JSON.stringify(L)).join(", ")})`);let w=N.apply(this,I);return E.trace(`GlyphRenderer#${N.name} return`,w),w}}},302:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.OptionsService=F.DEFAULT_OPTIONS=void 0;let D=X(460),G=X(844),V=X(114);F.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1000,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:V.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};let U=["normal","bold","100","200","300","400","500","600","700","800","900"];class K extends G.Disposable{constructor(E){super(),this._onOptionChange=this.register(new D.EventEmitter),this.onOptionChange=this._onOptionChange.event;let z={...F.DEFAULT_OPTIONS};for(let W in E)if(W in z)try{let H=E[W];z[W]=this._sanitizeAndValidateOption(W,H)}catch(H){console.error(H)}this.rawOptions=z,this.options={...z},this._setupOptions(),this.register((0,G.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(E,z){return this.onOptionChange((W)=>{W===E&&z(this.rawOptions[E])})}onMultipleOptionChange(E,z){return this.onOptionChange((W)=>{E.indexOf(W)!==-1&&z()})}_setupOptions(){let E=(W)=>{if(!(W in F.DEFAULT_OPTIONS))throw Error(`No option with key "${W}"`);return this.rawOptions[W]},z=(W,H)=>{if(!(W in F.DEFAULT_OPTIONS))throw Error(`No option with key "${W}"`);H=this._sanitizeAndValidateOption(W,H),this.rawOptions[W]!==H&&(this.rawOptions[W]=H,this._onOptionChange.fire(W))};for(let W in this.rawOptions){let H={get:E.bind(this,W),set:z.bind(this,W)};Object.defineProperty(this.options,W,H)}}_sanitizeAndValidateOption(E,z){switch(E){case"cursorStyle":if(z||(z=F.DEFAULT_OPTIONS[E]),!function(W){return W==="block"||W==="underline"||W==="bar"}(z))throw Error(`"${z}" is not a valid value for ${E}`);break;case"wordSeparator":z||(z=F.DEFAULT_OPTIONS[E]);break;case"fontWeight":case"fontWeightBold":if(typeof z=="number"&&1<=z&&z<=1000)break;z=U.includes(z)?z:F.DEFAULT_OPTIONS[E];break;case"cursorWidth":z=Math.floor(z);case"lineHeight":case"tabStopWidth":if(z<1)throw Error(`${E} cannot be less than 1, value: ${z}`);break;case"minimumContrastRatio":z=Math.max(1,Math.min(21,Math.round(10*z)/10));break;case"scrollback":if((z=Math.min(z,4294967295))<0)throw Error(`${E} cannot be less than 0, value: ${z}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(z<=0)throw Error(`${E} cannot be less than or equal to 0, value: ${z}`);break;case"rows":case"cols":if(!z&&z!==0)throw Error(`${E} must be numeric, value: ${z}`);break;case"windowsPty":z=z??{}}return z}}F.OptionsService=K},660:function(Z,F,X){var D=this&&this.__decorate||function(K,E,z,W){var H,q=arguments.length,N=q<3?E:W===null?W=Object.getOwnPropertyDescriptor(E,z):W;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(K,E,z,W);else for(var I=K.length-1;I>=0;I--)(H=K[I])&&(N=(q<3?H(N):q>3?H(E,z,N):H(E,z))||N);return q>3&&N&&Object.defineProperty(E,z,N),N},G=this&&this.__param||function(K,E){return function(z,W){E(z,W,K)}};Object.defineProperty(F,"__esModule",{value:!0}),F.OscLinkService=void 0;let V=X(585),U=F.OscLinkService=class{constructor(K){this._bufferService=K,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(K){let E=this._bufferService.buffer;if(K.id===void 0){let I=E.addMarker(E.ybase+E.y),w={data:K,id:this._nextId++,lines:[I]};return I.onDispose(()=>this._removeMarkerFromLink(w,I)),this._dataByLinkId.set(w.id,w),w.id}let z=K,W=this._getEntryIdKey(z),H=this._entriesWithId.get(W);if(H)return this.addLineToLink(H.id,E.ybase+E.y),H.id;let q=E.addMarker(E.ybase+E.y),N={id:this._nextId++,key:this._getEntryIdKey(z),data:z,lines:[q]};return q.onDispose(()=>this._removeMarkerFromLink(N,q)),this._entriesWithId.set(N.key,N),this._dataByLinkId.set(N.id,N),N.id}addLineToLink(K,E){let z=this._dataByLinkId.get(K);if(z&&z.lines.every((W)=>W.line!==E)){let W=this._bufferService.buffer.addMarker(E);z.lines.push(W),W.onDispose(()=>this._removeMarkerFromLink(z,W))}}getLinkData(K){return this._dataByLinkId.get(K)?.data}_getEntryIdKey(K){return`${K.id};;${K.uri}`}_removeMarkerFromLink(K,E){let z=K.lines.indexOf(E);z!==-1&&(K.lines.splice(z,1),K.lines.length===0&&(K.data.id!==void 0&&this._entriesWithId.delete(K.key),this._dataByLinkId.delete(K.id)))}};F.OscLinkService=U=D([G(0,V.IBufferService)],U)},343:(Z,F)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.createDecorator=F.getServiceDependencies=F.serviceRegistry=void 0;let X="di$target",D="di$dependencies";F.serviceRegistry=new Map,F.getServiceDependencies=function(G){return G[D]||[]},F.createDecorator=function(G){if(F.serviceRegistry.has(G))return F.serviceRegistry.get(G);let V=function(U,K,E){if(arguments.length!==3)throw Error("@IServiceName-decorator can only be used to decorate a parameter");(function(z,W,H){W[X]===W?W[D].push({id:z,index:H}):(W[D]=[{id:z,index:H}],W[X]=W)})(V,U,E)};return V.toString=()=>G,F.serviceRegistry.set(G,V),V}},585:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.IDecorationService=F.IUnicodeService=F.IOscLinkService=F.IOptionsService=F.ILogService=F.LogLevelEnum=F.IInstantiationService=F.ICharsetService=F.ICoreService=F.ICoreMouseService=F.IBufferService=void 0;let D=X(343);var G;F.IBufferService=(0,D.createDecorator)("BufferService"),F.ICoreMouseService=(0,D.createDecorator)("CoreMouseService"),F.ICoreService=(0,D.createDecorator)("CoreService"),F.ICharsetService=(0,D.createDecorator)("CharsetService"),F.IInstantiationService=(0,D.createDecorator)("InstantiationService"),function(V){V[V.TRACE=0]="TRACE",V[V.DEBUG=1]="DEBUG",V[V.INFO=2]="INFO",V[V.WARN=3]="WARN",V[V.ERROR=4]="ERROR",V[V.OFF=5]="OFF"}(G||(F.LogLevelEnum=G={})),F.ILogService=(0,D.createDecorator)("LogService"),F.IOptionsService=(0,D.createDecorator)("OptionsService"),F.IOscLinkService=(0,D.createDecorator)("OscLinkService"),F.IUnicodeService=(0,D.createDecorator)("UnicodeService"),F.IDecorationService=(0,D.createDecorator)("DecorationService")},480:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.UnicodeService=void 0;let D=X(460),G=X(225);class V{static extractShouldJoin(U){return(1&U)!=0}static extractWidth(U){return U>>1&3}static extractCharKind(U){return U>>3}static createPropertyValue(U,K,E=!1){return(16777215&U)<<3|(3&K)<<1|(E?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new D.EventEmitter,this.onChange=this._onChange.event;let U=new G.UnicodeV6;this.register(U),this._active=U.version,this._activeProvider=U}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(U){if(!this._providers[U])throw Error(`unknown Unicode version "${U}"`);this._active=U,this._activeProvider=this._providers[U],this._onChange.fire(U)}register(U){this._providers[U.version]=U}wcwidth(U){return this._activeProvider.wcwidth(U)}getStringCellWidth(U){let K=0,E=0,z=U.length;for(let W=0;W<z;++W){let H=U.charCodeAt(W);if(55296<=H&&H<=56319){if(++W>=z)return K+this.wcwidth(H);let I=U.charCodeAt(W);56320<=I&&I<=57343?H=1024*(H-55296)+I-56320+65536:K+=this.wcwidth(I)}let q=this.charProperties(H,E),N=V.extractWidth(q);V.extractShouldJoin(q)&&(N-=V.extractWidth(E)),K+=N,E=q}return K}charProperties(U,K){return this._activeProvider.charProperties(U,K)}}F.UnicodeService=V},781:(Z,F,X)=>{Object.defineProperty(F,"__esModule",{value:!0}),F.Terminal=void 0;let D=X(437),G=X(969),V=X(460);class U extends G.CoreTerminal{constructor(K={}){super(K),this._onBell=this.register(new V.EventEmitter),this.onBell=this._onBell.event,this._onCursorMove=this.register(new V.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this.register(new V.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this.register(new V.EventEmitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this.register(new V.EventEmitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this.register(this._inputHandler.onRequestBell(()=>this.bell())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register((0,V.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,V.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,V.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,V.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(K){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+K)}bell(){this._onBell.fire()}input(K,E=!0){this.coreService.triggerDataEvent(K,E)}resize(K,E){K===this.cols&&E===this.rows||super.resize(K,E)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let K=1;K<this.rows;K++)this.buffer.lines.push(this.buffer.getBlankLine(D.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}F.Terminal=U}},Q={};function B(Z){var F=Q[Z];if(F!==void 0)return F.exports;var X=Q[Z]={exports:{}};return A[Z].call(X.exports,X,X.exports,B),X.exports}var $={};(()=>{var Z=$;Object.defineProperty(Z,"__esModule",{value:!0}),Z.Terminal=void 0;let F=B(285),X=B(975),D=B(90),G=B(781),V=B(741),U=B(844),K=["cols","rows"];class E extends U.Disposable{constructor(z){super(),this._core=this.register(new G.Terminal(z)),this._addonManager=this.register(new V.AddonManager),this._publicOptions={...this._core.options};let W=(q)=>this._core.options[q],H=(q,N)=>{this._checkReadonlyOptions(q),this._core.options[q]=N};for(let q in this._core.options){Object.defineProperty(this._publicOptions,q,{get:()=>this._core.options[q],set:(I)=>{this._checkReadonlyOptions(q),this._core.options[q]=I}});let N={get:W.bind(this,q),set:H.bind(this,q)};Object.defineProperty(this._publicOptions,q,N)}}_checkReadonlyOptions(z){if(K.includes(z))throw Error(`Option "${z}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get parser(){return this._checkProposedApi(),this._parser||(this._parser=new X.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new D.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||(this._buffer=this.register(new F.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let z=this._core.coreService.decPrivateModes,W="none";switch(this._core.coreMouseService.activeProtocol){case"X10":W="x10";break;case"VT200":W="vt200";break;case"DRAG":W="drag";break;case"ANY":W="any"}return{applicationCursorKeysMode:z.applicationCursorKeys,applicationKeypadMode:z.applicationKeypad,bracketedPasteMode:z.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:W,originMode:z.origin,reverseWraparoundMode:z.reverseWraparound,sendFocusMode:z.sendFocus,wraparoundMode:z.wraparound}}get options(){return this._publicOptions}set options(z){for(let W in z)this._publicOptions[W]=z[W]}input(z,W=!0){this._core.input(z,W)}resize(z,W){this._verifyIntegers(z,W),this._core.resize(z,W)}registerMarker(z=0){return this._checkProposedApi(),this._verifyIntegers(z),this._core.addMarker(z)}addMarker(z){return this.registerMarker(z)}dispose(){super.dispose()}scrollLines(z){this._verifyIntegers(z),this._core.scrollLines(z)}scrollPages(z){this._verifyIntegers(z),this._core.scrollPages(z)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(z){this._verifyIntegers(z),this._core.scrollToLine(z)}clear(){this._core.clear()}write(z,W){this._core.write(z,W)}writeln(z,W){this._core.write(z),this._core.write(`\r
2683
2685
  `,W)}reset(){this._core.reset()}loadAddon(z){this._addonManager.loadAddon(this,z)}_verifyIntegers(...z){for(let W of z)if(W===1/0||isNaN(W)||W%1!=0)throw Error("This API only accepts integers")}}Z.Terminal=E})();var J=mL4;for(var Y in $)J[Y]=$[Y];$.__esModule&&Object.defineProperty(J,"__esModule",{value:!0})})()});function oA5(A){return`${A.description}
@@ -3241,6 +3243,7 @@ HunkLine := (" " | "-" | "+") text NEWLINE
3241
3243
  - Ambiguous matches are worse than verbose hunks. Prefer a longer patch over a shorter patch that could apply in multiple places.
3242
3244
  - Whitespace drift: avoid changing internal spacing in context lines (e.g., \`get: () =>\` vs \`get: () =>\`). Copy context lines from the file.
3243
3245
  - CRLF files: keep line endings consistent with the file you're patching.
3246
+ - If you see \`[REDACTED:_____]\` in your inputs and edits fail, Amp's secret redaction may have changed the text; ask the user to manually make the edit.
3244
3247
 
3245
3248
  ${w8(B65)}
3246
3249
  `,MO4={spec:{name:bX,description:$65,inputSchema:b.toJSONSchema($a0),source:"builtin",executionProfile:{resourceKeys:(A)=>{return[]}}},preprocessArgs:(A,Q)=>{if(!Q.dir)return;let B=J65(A.patchText,Q.dir);return B===A.patchText?void 0:{...A,patchText:B}},fn:wO4};function J65(A,Q){return A.split(`
@@ -5288,12 +5291,12 @@ ${z}`))}},error:(E)=>{if(!K)K=!0,D(Error(`Failed to spawn brew: ${E.message}`))}
5288
5291
  ${z}`;if(Z==="pnpm"&&z.includes("Unable to find the global bin directory"))W+=`
5289
5292
 
5290
5293
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
5291
- npm install -g ${Y}`;D(Error(W))}},error:(E)=>{if(!U)U=!0,D(Error(`Failed to spawn ${Z}: ${E.message}`))},complete:()=>{if(!U)U=!0,X()}})})}p0();p0();EN();var tI5="@ampcode/cli";async function wX0(A,Q,B=tI5){let J=`${Q||"https://registry.npmjs.org"}/${B}/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=vo(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var eI5="https://static.ampcode.com/cli/cli-version.txt";async function CX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${eI5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=vo(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Aw5=604800000;function Xu4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Aw5)return{ageMs:B};return null}function vo(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function yo(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?oV(B):void 0;return{sha:$,timestamp:B,age:J}}catch{return null}}L1();p0();import{readFile as Qw5,realpath as Bw5}from"node:fs/promises";import{homedir as $w5}from"node:os";import{dirname as Du4,join as Ce0}from"node:path";async function Gu4(A){switch(A){case"binary":case"brew":return Jw5(_o());case"npm":case"pnpm":case"yarn":case"bun":return Yw5();case"bootstrap":return Zw5()}}async function Jw5(A){let Q=await fD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Yw5(){try{let A=process.argv[1];if(!A)return null;let Q=await Bw5(A),B=Du4(Du4(Q));return await Vu4(Ce0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Zw5(){try{let A=process.env.AMP_HOME??Ce0($w5(),".amp");return await Vu4(Ce0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Vu4(A){let Q=await Qw5(A,"utf8"),B=JSON.parse(Q);if(!B.name||!Ve0(B.name))return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Fw5=3600000,Xw5=5000;function MX0(A,Q,B={}){let $=new g4,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Fw5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await eV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await Dw5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(Xw5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await eV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function Dw5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await TU(),F=Z==="binary"||Z==="brew",X=F?void 0:await GI();B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F,npmPackageName:X});let D;if(F)D=await CX0(A);else{let U=await Pj();D=await wX0(A,U,X)}if(!(D.latestVersion&&D.hasUpdate))return B.debug("no update available"),J;let G=(U)=>{$.next(U),J.emittedVisibleState=!0};if(Z){let U=await Gu4(Z);if(U&&vo(U,D.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:U,latestVersion:D.latestVersion}),J.updatedTo=U,vo(A,U)<0){let K=await Sz(U),E={from:A,to:U,externallyUpdated:!0,...K};if(K.status==="same")B.info("on-disk already updated by another instance",E),G("updated");else B.warn("on-disk already updated by another instance, with PATH warning",E),G("updated-with-warning")}return J}}let V=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,K=0.5;if(Math.abs(U)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!V())G("update-available-brew");return J}if(Z==="binary"&&process.execPath!==_o()){if(B.debug("non-standard binary path, showing warning"),!V())G("update-available-unrecognized-path");return J}if(Y==="warn"){if(!V())G("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!V())G("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!V())G("update-available");return J}try{await So(D.latestVersion,Z),J.updatedTo=D.latestVersion;let U=await Sz(D.latestVersion),K={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")B.info("success",K),G("updated");else B.warn("success with warning",K),G("updated-with-warning")}catch(U){G("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}EN();import{stderr as bD}from"node:process";function Uu4(A){let Q=new pN().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($)=>{await De0($.force||!1,$.verbose||!1,"0.0.1778617350-g19dbc6"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new pN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await Vw5($.targetVersion)});A.addCommand(B)}function Gw5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5294
+ npm install -g ${Y}`;D(Error(W))}},error:(E)=>{if(!U)U=!0,D(Error(`Failed to spawn ${Z}: ${E.message}`))},complete:()=>{if(!U)U=!0,X()}})})}p0();p0();EN();var tI5="@ampcode/cli";async function wX0(A,Q,B=tI5){let J=`${Q||"https://registry.npmjs.org"}/${B}/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=vo(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var eI5="https://static.ampcode.com/cli/cli-version.txt";async function CX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${eI5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=vo(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Aw5=604800000;function Xu4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Aw5)return{ageMs:B};return null}function vo(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function yo(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?oV(B):void 0;return{sha:$,timestamp:B,age:J}}catch{return null}}L1();p0();import{readFile as Qw5,realpath as Bw5}from"node:fs/promises";import{homedir as $w5}from"node:os";import{dirname as Du4,join as Ce0}from"node:path";async function Gu4(A){switch(A){case"binary":case"brew":return Jw5(_o());case"npm":case"pnpm":case"yarn":case"bun":return Yw5();case"bootstrap":return Zw5()}}async function Jw5(A){let Q=await fD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Yw5(){try{let A=process.argv[1];if(!A)return null;let Q=await Bw5(A),B=Du4(Du4(Q));return await Vu4(Ce0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Zw5(){try{let A=process.env.AMP_HOME??Ce0($w5(),".amp");return await Vu4(Ce0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Vu4(A){let Q=await Qw5(A,"utf8"),B=JSON.parse(Q);if(!B.name||!Ve0(B.name))return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Fw5=3600000,Xw5=5000;function MX0(A,Q,B={}){let $=new g4,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Fw5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await eV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await Dw5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(Xw5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await eV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function Dw5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await TU(),F=Z==="binary"||Z==="brew",X=F?void 0:await GI();B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F,npmPackageName:X});let D;if(F)D=await CX0(A);else{let U=await Pj();D=await wX0(A,U,X)}if(!(D.latestVersion&&D.hasUpdate))return B.debug("no update available"),J;let G=(U)=>{$.next(U),J.emittedVisibleState=!0};if(Z){let U=await Gu4(Z);if(U&&vo(U,D.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:U,latestVersion:D.latestVersion}),J.updatedTo=U,vo(A,U)<0){let K=await Sz(U),E={from:A,to:U,externallyUpdated:!0,...K};if(K.status==="same")B.info("on-disk already updated by another instance",E),G("updated");else B.warn("on-disk already updated by another instance, with PATH warning",E),G("updated-with-warning")}return J}}let V=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,K=0.5;if(Math.abs(U)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!V())G("update-available-brew");return J}if(Z==="binary"&&process.execPath!==_o()){if(B.debug("non-standard binary path, showing warning"),!V())G("update-available-unrecognized-path");return J}if(Y==="warn"){if(!V())G("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!V())G("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!V())G("update-available");return J}try{await So(D.latestVersion,Z),J.updatedTo=D.latestVersion;let U=await Sz(D.latestVersion),K={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")B.info("success",K),G("updated");else B.warn("success with warning",K),G("updated-with-warning")}catch(U){G("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}EN();import{stderr as bD}from"node:process";function Uu4(A){let Q=new pN().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($)=>{await De0($.force||!1,$.verbose||!1,"0.0.1778631508-g72c81a"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new pN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await Vw5($.targetVersion)});A.addCommand(B)}function Gw5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5292
5295
  `),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function Vw5(A){let B=process.platform==="win32"&&Rj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=Gw5(bD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")bD.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
5293
5296
 
5294
5297
  `));try{if(!A){bD.write(n0.blue(`Checking for updates...
5295
- `));let F=!1,X;if(Rj()){let D=await CX0("0.0.1778617350-g19dbc6");F=D.hasUpdate,X=D.latestVersion}else{let D=await Pj(),G=await GI(),V=await wX0("0.0.1778617350-g19dbc6",D,G);F=V.hasUpdate,X=V.latestVersion}if(!F){let D=yo("0.0.1778617350-g19dbc6"),G=D?.age?`released ${D.age} ago`:`built ${oV(new Date("2026-05-12T20:26:19.685Z"))} ago`;bD.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1778617350-g19dbc6"} (${G})
5296
- `));let V=await Sz("0.0.1778617350-g19dbc6",B);if(V.warning)bD.write(`
5298
+ `));let F=!1,X;if(Rj()){let D=await CX0("0.0.1778631508-g72c81a");F=D.hasUpdate,X=D.latestVersion}else{let D=await Pj(),G=await GI(),V=await wX0("0.0.1778631508-g72c81a",D,G);F=V.hasUpdate,X=V.latestVersion}if(!F){let D=yo("0.0.1778631508-g72c81a"),G=D?.age?`released ${D.age} ago`:`built ${oV(new Date("2026-05-13T00:22:19.974Z"))} ago`;bD.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1778631508-g72c81a"} (${G})
5299
+ `));let V=await Sz("0.0.1778631508-g72c81a",B);if(V.warning)bD.write(`
5297
5300
  `+n0.yellow(V.warning)+`
5298
5301
  `);process.exit(0)}if(!X)bD.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}bD.write(n0.blue(`Updating to version ${A}...
5299
5302
  `)),await So(A,void 0,(F)=>{$(),bD.write(n0.dim(`Running: ${F}
@@ -5699,7 +5702,7 @@ ${$}`).join(`
5699
5702
  `).length,J=new p({text:new C(A,new v({color:B}))});if($<=fG0)return J;return new U0({width:1/0,height:fG0,child:new ZQ({autofocus:!1,controller:Q,child:J})})}function Yx5(){return new Map([[C1.key("PageUp"),new bG0],[C1.key("PageDown"),new o41],[C1.ctrl("u"),new bG0],[C1.shift("Home"),new r41],[C1.shift("End"),new s41]])}function Zx5(A,Q,B){return Math.max(Q,Math.min(A,B))}var t41=8,Wn4=1,Hn4=t41-1;class e41 extends P4{}class AA1 extends P4{}class uG0 extends P4{}class hG0 extends P4{}class QA1 extends P4{}class BA1 extends P4{}class $A1 extends T0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new qn4}}class qn4 extends _0{messageScroll=new vA;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,B=Fx5(Q,this.messageScroll),$=Xx5(Q.options.message),J=$?new l4({actions:this.buildScrollActions(),child:new Y5({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:Gx5(),child:B})}):B,Y=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if($)Y.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return Y.push({keys:["Esc"],label:"cancel"}),new xA({header:Q.options.title,minWidth:64,maxWidth:80,footer:Y,autofocus:!1,onDismiss:Q.onCancel,child:J})}buildScrollActions(){let A=(Q)=>{let B=Vx5(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo(B)};return new Map([[e41,new c1(()=>A(-Wn4))],[AA1,new c1(()=>A(Wn4))],[uG0,new c1(()=>A(-Hn4))],[hG0,new c1(()=>A(Hn4))],[QA1,new c1(()=>this.messageScroll.jumpTo(0))],[BA1,new c1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function Fx5(A,Q){let B=A.options.options.map((J)=>({value:J,label:J})),$=Math.max(0,B.findIndex((J)=>J.value===A.options.initialValue));return new V2({options:B,selectedIndex:$,body:Dx5(A.options.message,Q),onSelect:(J)=>{if(J===null){A.onCancel();return}A.onSelect(J)},padding:E0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}function Xx5(A){if(A===void 0)return!1;return A.split(`
5700
5703
  `).length>t41}function Dx5(A,Q){if(A===void 0)return;let B=A.split(`
5701
5704
  `).length,$=Math.min(B,t41);return new U0({width:1/0,height:$,child:new ZQ({autofocus:!1,controller:Q,child:new p({text:new C(A)})})})}function Gx5(){return new Map([[C1.key("PageUp"),new uG0],[C1.key("PageDown"),new hG0],[C1.ctrl("u"),new uG0],[C1.ctrl("d"),new hG0],[C1.ctrl("y"),new e41],[C1.ctrl("e"),new AA1],[C1.shift("Home"),new QA1],[C1.shift("End"),new BA1]])}function Vx5(A,Q,B){return Math.max(Q,Math.min(A,B))}class JA1{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];statusItems=new Map;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}hasBlockingDialog(){return this.activeDialog!==null}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];switch(A.kind){case"input":return[new Ns({key:new xz(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)})];case"confirm":return[new a41({key:new xz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)})];case"select":return[new $A1({key:new xz(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})]}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;if(sd(B.errorMessage))continue;let $=`${B.uri.toString()}
5702
- ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}wl();R2();import{readFile as Ux5}from"node:fs/promises";import YA1 from"node:os";function Kx5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Nn4(A,Q){try{return{path:Q,contents:th0(await Ux5(A,"utf8"))}}catch{return null}}async function gG0(A,Q){let B=[],$=Kx5(),J=await QA.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify(JJ(Y),null,2)});let Z=await Nn4(Kx(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await Nn4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await TU()??"unknown",D=await QA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778617350-g19dbc6",clientOS:`${YA1.platform()} ${YA1.release()} ${YA1.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class ZA1{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}class mG0 extends w5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new FA1(this.offstage)}updateRenderObject(A){if(A instanceof FA1)A.offstage=this.offstage}}class FA1 extends F4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class Is{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class XA1 extends T0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new In4}}class In4 extends _0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new yj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new yj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new mG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new n4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new mG0({key:$.key,offstage:!J,child:Y}))}return new BA({fit:"expand",children:Q})}}class GA1 extends q1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Ex5(Q);return new xA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:E0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new X5({items:Q,showBorder:!1,getLabel:($)=>{let J=DA1($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=ej($.item.verb.toLowerCase(),Y),F=ej(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=ej(DA1($.item),Y),D=ej(DA1(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=P0.of(J);return new p({text:new C($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new wn4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class wn4 extends q1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=P0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:zx5(Q.shortcut,Z,$)});return new Cn4({columns:z,padding:E0.horizontal(1),backgroundColor:D})}}function DA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Ex5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,y4(B.noun)):Q},0)}function zx5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Cn4 extends q1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new _1({child:X.child}));else Y.push(X.child)}let Z=new s0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new g0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class VA1{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let B=this.findByID(A);if(!B||B.status.type!=="enabled")return!1;return B.run(new Is,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class YB extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=YB.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(YB)?.commandRegistry??null}}class UA1 extends T0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Mn4}}class Mn4 extends _0{modalStack=new Is;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=YB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=YB.of(A).commands,B=new GA1({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new XA1({root:B,controller:this.modalStack})}}var KA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],EA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class pG0 extends q1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=A4.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new x0({padding:E0.only({left:4}),child:X})]});else D=new s0({crossAxisAlignment:"start",children:[new _1({flex:1,child:F}),new U0({width:1}),new _1({flex:1,child:X})]});Y.push(new x0({padding:E0.horizontal(6),child:D}))}return new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class zA1 extends T0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new Ln4}}class Ln4 extends _0{scrollController;initState(){this.scrollController=new vA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=R1.of(A).colorScheme,J=P0.of(A).app,Y=A4.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let P=O.noun?.toLowerCase();return P!=="dev"&&P!=="debug"&&!O.id.startsWith("debug-")&&!H.has(O.id)})].sort((O,P)=>{let S=(O.noun??"").toLowerCase(),T=(P.noun??"").toLowerCase(),x=S.localeCompare(T);if(x!==0)return x;let h=O.verb.toLowerCase(),u=P.verb.toLowerCase(),k=h.localeCompare(u);if(k!==0)return k;return O.id.localeCompare(P.id)}),I=new yA({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new I1(W,W,0,Number.POSITIVE_INFINITY),child:new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new t1({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5705
+ ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}wl();R2();import{readFile as Ux5}from"node:fs/promises";import YA1 from"node:os";function Kx5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Nn4(A,Q){try{return{path:Q,contents:th0(await Ux5(A,"utf8"))}}catch{return null}}async function gG0(A,Q){let B=[],$=Kx5(),J=await QA.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify(JJ(Y),null,2)});let Z=await Nn4(Kx(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await Nn4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await TU()??"unknown",D=await QA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778631508-g72c81a",clientOS:`${YA1.platform()} ${YA1.release()} ${YA1.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class ZA1{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}class mG0 extends w5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new FA1(this.offstage)}updateRenderObject(A){if(A instanceof FA1)A.offstage=this.offstage}}class FA1 extends F4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class Is{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class XA1 extends T0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new In4}}class In4 extends _0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new yj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new yj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new mG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new n4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new mG0({key:$.key,offstage:!J,child:Y}))}return new BA({fit:"expand",children:Q})}}class GA1 extends q1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Ex5(Q);return new xA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:E0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new X5({items:Q,showBorder:!1,getLabel:($)=>{let J=DA1($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=ej($.item.verb.toLowerCase(),Y),F=ej(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=ej(DA1($.item),Y),D=ej(DA1(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=P0.of(J);return new p({text:new C($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new wn4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class wn4 extends q1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=P0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:zx5(Q.shortcut,Z,$)});return new Cn4({columns:z,padding:E0.horizontal(1),backgroundColor:D})}}function DA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Ex5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,y4(B.noun)):Q},0)}function zx5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Cn4 extends q1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new _1({child:X.child}));else Y.push(X.child)}let Z=new s0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new g0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class VA1{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let B=this.findByID(A);if(!B||B.status.type!=="enabled")return!1;return B.run(new Is,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class YB extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=YB.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(YB)?.commandRegistry??null}}class UA1 extends T0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Mn4}}class Mn4 extends _0{modalStack=new Is;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=YB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=YB.of(A).commands,B=new GA1({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new XA1({root:B,controller:this.modalStack})}}var KA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],EA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class pG0 extends q1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=A4.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new x0({padding:E0.only({left:4}),child:X})]});else D=new s0({crossAxisAlignment:"start",children:[new _1({flex:1,child:F}),new U0({width:1}),new _1({flex:1,child:X})]});Y.push(new x0({padding:E0.horizontal(6),child:D}))}return new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class zA1 extends T0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new Ln4}}class Ln4 extends _0{scrollController;initState(){this.scrollController=new vA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=R1.of(A).colorScheme,J=P0.of(A).app,Y=A4.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let P=O.noun?.toLowerCase();return P!=="dev"&&P!=="debug"&&!O.id.startsWith("debug-")&&!H.has(O.id)})].sort((O,P)=>{let S=(O.noun??"").toLowerCase(),T=(P.noun??"").toLowerCase(),x=S.localeCompare(T);if(x!==0)return x;let h=O.verb.toLowerCase(),u=P.verb.toLowerCase(),k=h.localeCompare(u);if(k!==0)return k;return O.id.localeCompare(P.id)}),I=new yA({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new I1(W,W,0,Number.POSITIVE_INFINITY),child:new y0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new t1({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5703
5706
  `,Z)})}),new U0({height:1}),new x0({padding:E0.horizontal(2),child:new p({text:new C(`Editor Shortcuts
5704
5707
  `,F)})}),new pG0({items:KA1.filter((O)=>O.submitOnEnterOnly===void 0||O.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(O)=>{let P=[];for(let T of O.methods){let x=this.buildCleanKeyCombination(T);P.push(x)}let S=P.join(", ");return[new p({text:new C(S,X)}),new p({text:new C(O.description,G)})]}}),new U0({height:1}),new x0({padding:E0.horizontal(2),child:new p({text:new C(`Scrolling & Navigation
5705
5708
  `,F)})}),new pG0({items:EA1,renderRow:(O)=>{let P=[];for(let T of O.methods){let x=this.buildCleanKeyCombination(T);P.push(x)}let S=P.join(", ");return[new p({text:new C(S,X)}),new p({text:new C(O.description,G)})]}}),new U0({height:1}),new x0({padding:E0.horizontal(2),child:new p({text:new C(`Command Palette Commands
@@ -5796,7 +5799,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let V0=G.text.replace(/`([^`]+)`/g,"$1")+`
5796
5799
  `))}function jg5(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function sr4(A,Q){let B=A.replace(/\s+/g," ").trim();if(y4(B)<=Q)return B;let $="...",J=y4($);if(Q<=J)return WJ($,Q);return`${WJ(B,Q-J,!0,"")}${$}`}var o61="https://ampcode.com/news/neo",r61=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:o61,href:o61},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function Rg5(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:o61,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function Pg5(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var gf=50,WR=40,n61=1000,_g5=420,Tg5=760,kg5=-250,Sg5=1100,IV0=33,Qs4=0.999,vg5=2.1,yg5=720,xg5=420,Ds4="Meet the new",Gs4="Amp",Vs4="CLI",s61=M4(Ds4).length,fg5=M4(Gs4).length,bg5=M4(Vs4).length,wV0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},Bs4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},$s4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},Js4=[wV0,Bs4,$s4,wV0,Bs4,$s4,wV0],ug5=wV0;class t61 extends T0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??Pg5(),this.introStages=this.variant==="npm-migration"?Rg5(this.binaryInstallCommand):r61,this.dismissible=this.variant!=="npm-migration"}createState(){return new Us4}}class Us4 extends _0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=n61;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new v9(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=$Z(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=Qs4,this.firstStageHintVisible=this.animationProgress>=Qs4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:n61,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=$Z(A/Tg5);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},IV0)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let B=performance.now()-this.stageTransitionStartedAt,$=$Z(B/_g5);if(this.setState(()=>{if(this.stageTransitionProgress=$,$>=1)this.previousIntroStage=null}),$>=1)this.stopStageTransitionTimer()},IV0)}startProgressAnimation({from:A,to:Q,durationMs:B,onComplete:$}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=B,this.onAnimationComplete=$,this.animationProgress=A,this.animationTimer=setInterval(()=>{let J=performance.now()-this.startedAt,Y=$Z(J/this.animationDurationMs),Z=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*mf(Y);if(this.setState(()=>{this.animationProgress=Z}),Y>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},IV0)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,n61+kg5),Q=A+Sg5;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?$Z((A-this.firstStageTitleRevealStartedAt)/yg5):this.firstStageTitleRevealProgress,B=this.firstStageHintRevealStartedAt?$Z((A-this.firstStageHintRevealStartedAt)/xg5):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=B}),Q>=1&&B>=1)this.stopFirstStageRevealTimer()},IV0)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Ys4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:Zs4(Ys4(this.previousIntroStage),A,mf(this.stageTransitionProgress));return this.dismissProgress>0?Zs4(Q,ug5,mf(this.dismissProgress)):Q}build(A){let Q=R1.of(A).colorScheme,B=P0.of(A),$=this.currentOrbPalette(),J=eQ(1,"frontier",$),Y=A4.of(A).size,F=this.widget.animationProgress??this.animationProgress,X=Math.max(Y.width/gf,Y.height/WR)*vg5,D=X+(1-X)*F,G=mf(this.dismissProgress),V=Math.max(gf,Math.round(gf*D)),U=Math.max(WR,Math.round(WR*D)),K=Math.round((Y.width-V)/2),E=Math.round((Y.height-U)/2),z=Math.max(0,Math.floor((Y.width-gf)/2)),W=-Math.floor(WR/2),H=Math.round(K+(z-K)*F),q=Math.round(E+(W-E)*F),N=H+V/2,I=q+U/2,w=hg5({dismissProgress:this.dismissProgress,easedDismissProgress:G,introOrbScale:D,normalOrbCenterX:N,normalOrbCenterY:I,size:Y}),L=Math.max(gf,Math.round(gf*w.orbScale)),O=Math.max(WR,Math.round(WR*w.orbScale)),P=w.orbCenterX,S=w.orbCenterY,T=Math.round(P-L/2),x=Math.round(S-O/2),h=Math.max(3,Math.min(Y.height-5,Math.floor(WR/2)+2)),u=Math.max(h+3,Y.height-3),k=w.textDissolveProgress,f=this.isFinalIntroStage()?w.backdropDissolveProgress:0,d=this.firstStageTitleVisible&&k<1,c=d&&this.firstStageHintVisible,g=c&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),l=this.introStage===0?this.firstStageTitleRevealProgress:1,a=this.introStage===0?this.firstStageHintRevealProgress:1,t=Math.max(24,Math.min(74,Y.width-4)),w0=Math.min(12,Math.max(8,Y.height-h-6)),V0=Math.max(0,Math.floor((Y.width-t)/2)),N0=Math.max(0,Math.min(Y.height-w0,Math.floor(Y.height*0.55-w0/2))),j0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new bx({width:L,height:O,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new bx({width:L,height:O,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new n4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(Q0)=>{if(Q0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&Q0.key==="c"&&Q0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&Q0.key==="q")return this.widget.onQuit?.(),"handled";if((Q0.key===" "||Q0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(Q0.key==="Escape"||Q0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(Q0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(Q0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new BA({fit:"expand",children:[new Ks4({color:Q.background,dissolveProgress:f}),new BA({fit:"expand",children:[new k1({onClick:()=>{},child:U0.expand()}),new IA({left:T,top:x,width:L,height:O,child:j0}),...d?[new IA({left:V0,top:N0,width:t,height:w0,child:mg5({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:t,height:w0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:J,link:B.app.link,keybind:B.app.keybind,titleRevealProgress:l,dissolveProgress:k,context:A})})]:[],...c?[...g?[new IA({left:V0,top:Math.max(0,u-1),width:t,height:1,child:new p({text:ng5({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:k}),textAlign:"center"})})]:[],new IA({left:V0,top:u,width:t,height:1,child:og5({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:B.app.keybind,revealProgress:a,dissolveProgress:k,context:A})})]:[]]})]})})}}class Ks4 extends F8{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Es4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Es4 extends F4{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height),F={bg:this.color},X=$Z(this.dissolveProgress);if(X<=0){A.fill($,J,Y,Z," ",F);return}if(X>=1)return;for(let D=0;D<Z;D++)for(let G=0;G<Y;G++)if(!gg5(G,D,Y,Z,X))A.fill($+G,J+D,1,1," ",F)}}function $Z(A){return Math.min(1,Math.max(0,A))}function mf(A){return 1-(1-A)**3}function Ys4(A){return Js4[A]??Js4[0]}function Zs4(A,Q,B){return{primary:xj(A.primary,Q.primary,B),secondary:xj(A.secondary,Q.secondary,B)}}function hg5({dismissProgress:A,easedDismissProgress:Q,introOrbScale:B,normalOrbCenterX:$,normalOrbCenterY:J,size:Y}){return{orbScale:B+(B*0.86-B)*Q,orbCenterX:$+(Y.width*0.54-$)*Q,orbCenterY:J-Y.height*0.44*Q,textDissolveProgress:$Z(A/0.52),backdropDissolveProgress:mf($Z((A-0.12)/0.88))}}function gg5(A,Q,B,$,J){let Y=$<=1?0:Q/($-1),Z=zs4(A+Q*Math.max(1,B));return(1-Y)*0.72+Z*0.28<J}function mg5({introStages:A,stage:Q,previousStage:B,progress:$,direction:J,width:Y,height:Z,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E}){if(B===null||$>=1)return a61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E});let z=mf($),W=J*Math.round((1-z)*Y),H=-J*Math.round(z*Y);return new hz(new BA({fit:"expand",children:[new IA({left:H,top:0,width:Y,height:Z,child:a61({introStages:A,stage:B,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:B===0?1:U,dissolveProgress:K,context:E})}),new IA({left:W,top:0,width:Y,height:Z,child:a61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E})})]}))}function a61({introStages:A,stage:Q,foreground:B,mutedForeground:$,accent:J,link:Y,keybind:Z,titleRevealProgress:F,dissolveProgress:X,context:D}){let G=A[Q]??A[0]??r61[0],V=new v({color:J,bold:!0}),U=new v({color:B}),K=A===r61&&Q===0,E=[...G.title===null?[]:[new p({text:K?CV0(cg5({progress:F,foreground:J,pulseColor:J}),X):new C(Y$(G.title,X),V),textAlign:"center"})],...G.body.length>0?[pg5()]:[],...G.body.map((z)=>dg5(z,U,$,Y,Z,X,D))];return new t1({child:new x0({padding:E0.horizontal(1),child:new y0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:E})})})}function pg5(){return U0.height(1)}function dg5(A,Q,B,$,J,Y,Z){if(typeof A==="string")return new p({text:new C(Y$(A,Y),Q),textAlign:"center"});if("codeBlock"in A)return new J3({onCopy:(F,X)=>{if(X)Y3.success(Z,"Copied to clipboard",2000)},child:new y0({mainAxisSize:"min",children:A.codeBlock.map((F)=>new p({text:new C(Y$(F,Y),new v({color:J})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let F=new p({text:new C("",void 0,[new C(Y$(A.text,Y),new v({color:B,dim:!0})),new C(Y$(A.keybind,Y,M4(A.text).length),new v({color:J}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new t1({child:new J3({child:F})});return F}if("highlightText"in A){let F=XA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=tD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(A.highlightText,new v({color:J})),new C(A.textAfterHighlight,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{nA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:CV0(D,Y),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new y0({mainAxisSize:"min",children:[new p({text:new C(Y$(A.text,Y),Q),textAlign:"center"}),new t1({child:new s0({mainAxisSize:"min",children:[XA.createWidget(Z,A.href,Y$(A.linkText,Y),new v({color:$,underline:!0})),new p({text:new C(Y$(A.textAfter,Y),Q)})]})})]});let F=XA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=tD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{nA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:CV0(D,Y),textAlign:"center"})}if(Y>0)return new p({text:new C(Y$(A.text,Y),new v({color:$,underline:!0})),textAlign:"center"});return new t1({child:XA.createWidget(Z,A.href,A.text,new v({color:$,underline:!0}))})}function cg5({progress:A,foreground:Q,pulseColor:B}){let $=new v({color:Q,bold:!0}),J=new v({color:ig5({progress:A,foreground:Q,pulseColor:B}),bold:!0});return new C("",void 0,[new C(lg5(A).padEnd(s61," "),$),new C(" ",$),new C(Fs4(Gs4,fg5,A,0.72),$),new C(" ",$),new C(Fs4(Vs4,bg5,A,0.88),J)])}function lg5(A){let Q=M4(Ds4),B=Math.min(s61,Math.ceil($Z(A/0.62)*s61));return Q.slice(0,B).join("")}function Fs4(A,Q,B,$){return B>=$?A:"".padEnd(Q," ")}function ig5({progress:A,foreground:Q,pulseColor:B}){if(A<0.88||A>=1)return Q;let $=$Z((A-0.88)/0.12);return Math.cos($*Math.PI*4)*(1-$)>0.12?B:Q}function ng5({stage:A,featureStageCount:Q,foreground:B,dissolveProgress:$}){return new C(Y$(`${A}/${Q}`,$),new v({color:B,dim:!0}))}function ag5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}){let Z=new v({color:$}),F=new v({color:B,dim:!0}),X=Q?A?"Enter":"Space":"Esc",D=Q?A?" to get started":" to continue":" to quit, or use ",G=Q?"":"amp --take-me-back",V=Q?"":" to use the old version",U=`${D}${G}${V}`;if(!Q)return new C("",void 0,[new C(X,Z),new C(D,F),new C(G,Z),new C(V,F)]);let K=Xs4(X,J),E=Xs4(U,$Z((J*(M4(X).length+M4(U).length)-M4(X).length)/M4(U).length));return new C("",void 0,[new C(Y$(K,Y),Z),new C(Y$(E.slice(0,D.length),Y),F),new C(Y$(E.slice(D.length,D.length+G.length),Y),Z),new C(Y$(E.slice(D.length+G.length),Y),F)])}function og5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y,context:Z}){if(Q)return new p({text:ag5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}),textAlign:"center"});let F=new v({color:$}),X=new v({color:B,dim:!0});return new J3({onCopy:(D,G)=>{if(G)Y3.success(Z,"Copied to clipboard",2000)},child:new p({text:new C("",void 0,[new C("q",F),new C(" to quit, or use ",X),new C("amp --take-me-back",F),new C(" to use the old version",X)]),textAlign:"center",selectable:!0})})}function Xs4(A,Q){let B=M4(A),$=Math.min(B.length,Math.ceil($Z(Q)*B.length));return B.slice(0,$).join("").padEnd(B.length," ")}function CV0(A,Q,B=0){if(Q<=0)return A;let $=B+M4(A.text??"").length,J=A.children?.map((Y)=>{let Z=CV0(Y,Q,$);return $+=M4(Y.toPlainText()).length,Z});return new C(A.text?Y$(A.text,Q,B):A.text,A.style,J,A.hyperlink,A.onClick)}function Y$(A,Q,B=0){if(Q<=0)return A;return M4(A).map((J,Y)=>{if(J.trim()==="")return J;return zs4(B+Y)<Q?" ":J}).join("")}function zs4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}p0();R2();function oI(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,F=Y?.paidUSD??0;if(Z===0&&F===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(F===0)J.push(new C(aU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new C(" (free)",new v({color:B.foreground,dim:$})));else if(Z>0)J.push(new C(aU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new C(" (free)",new v({color:B.foreground,dim:$}))),J.push(new C(" + ",new v({color:B.foreground,dim:$}))),J.push(new C(aU(F,D),new v({color:B.foreground,dim:$,bold:!$})));else J.push(new C(aU(F,D),new v({color:B.foreground,dim:$,bold:!$})));return J}class e61 extends P4{}class A51 extends P4{}function rg5(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function sg5(A,Q){let B=P0.of(Q),{colors:$}=B,J=oI(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new C("Total: ",new v({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new C("Usage information is currently unavailable."));else Y.push(new C("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new C(`
5797
5800
 
5798
5801
  `)),Y.push(new C("Details: ",new v({color:$.mutedForeground}))),Y.push(new C(A.costBreakdownURL,new v({color:B.app.link})));return new p({text:new C("",void 0,Y)})}function tg5(A,Q,B){let $=sg5(A,Q);if(!A.costBreakdownURL)return new xA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new c1(()=>{return l4.maybeInvoke(Q,new b9(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new c1(()=>{return nA(Q,J),"handled"});return new xA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new l4({actions:new Map([[e61,Y],[A51,Z]]),child:new Y5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[C1.key("o"),new A51],[C1.key("y"),new e61]]),child:new d4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function Ws4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await QA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(rg5(J,Y.error),"error",5000),$();return}Q.push(tg5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}function eg5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${GY(new URL(A),Q).toString()} (cli log: ${B}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
5799
- `)}class Q51 extends T0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;onThreadArchived;onActiveThreadChange;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new qs4}}class qs4 extends _0{editorController=new j8;commandPalette=new Wr(this);commandRegistry=new VA1;toastController=new v01;exitHintTimer=new zr(this,1000);ideStatus=new G2(this,{});threadNavigationHistory=new ZA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;activeThreadIDSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new H6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>gG0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await Gc4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await Vc4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await Uc4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(tB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(g30(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new JA1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=L4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Un4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((F)=>rA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},Ws4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new LA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new i61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await nA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{CJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new CA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new WA1({commands:YB.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new xA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(KD0({version:"0.0.1778617350-g19dbc6",buildTimestamp:"2026-05-12T20:26:19.685Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{l4.maybeInvoke(Y,new Rf)}},...Q,...An4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new l61({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B,statusItems:this.pluginIntegration?.getStatusItems()??[]}),J=A4.of(A),Y=J.capabilities.animationSupport!=="disabled",F=[new g0({constraints:I1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())F.push(new n4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new UA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)F.push(rA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)F.push(new n4({debugLabel:"NeoWelcomeDialogOverlay",child:new t61({onDismiss:this.dismissNeoWelcome,onQuit:()=>L4.instance.stop(),animationsEnabled:Y,variant:this.widget.neoWelcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new n4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new IA1({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)F.push(new NA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:ms.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new wA1);return new S3({neoContext:this.widget.neoContext,child:new YB({commandRegistry:this.commandRegistry,child:new hI({completionBuilder:this.widget.completionBuilder,child:new Y3({controller:this.toastController,child:new l4({actions:this.buildActions(),child:new Y5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[C1.ctrl("c"),new _G0],[C1.ctrl("o"),new TG0],[C1.alt("i"),new SG0],[C1.alt("p"),new MI],[C1.ctrl("t"),new vG0]]),child:new d4({debugLabel:"AppShellFocus",child:new y01({controller:this.toastController,child:new HA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new BA({children:F})})})})})})})})})})}buildActions(){let A=new c1(()=>{if(wJ.hasAnyCopyableSelection())return wJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new c1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new c1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new c1(()=>{return this.startNewDraftThread(),"handled"}),J=new c1(()=>{return L4.instance.stop(),"handled"}),Y=new c1((U)=>{if(!U.text)return"ignored";return L4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new c1(()=>{return L4.instance.toggleFrameStatsOverlay(),"handled"}),F=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Kx(U);return L4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await L4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new c1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[_G0,A],[Gs,$],[Rf,J],[b9,Y],[Ks,B],[TG0,Q],[SG0,F],[Es,X],[zs,D],[Ws,G],[MI,Z],[vG0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:eg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Kx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await cx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=eB(Q),J=QD0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return AD0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Hs4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Hs4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(uI);if(this.exitHintTimer.isActive())A.add(Cf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),L4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:(B)=>{Q(B==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")L4.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((D)=>D.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,ms.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F??void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=eB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};NJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=yY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:(J)=>this.promptExecutorAlreadyConnected(J)});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)}),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=Q!=="idle"&&Q!=="error";if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=ms.cwd().replace(ms.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,ms.stdout.write(EI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Hs4(A,Q,B){let $={...A};for(let J of Am5(Q,B)){if(!dZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Am5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function Ns4(A,Q,B,$){let J=Bk(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new rY(G,V),K=new v9(42),E=new HI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),K);E.layout(I1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(z[P].some((S)=>S.char!==" ")){W=P;break}let H=V-1;for(let P=V-1;P>=0;P--)if(z[P].some((S)=>S.char!==" ")){H=P;break}function q(P,S){if(!P)return"";if(P.type==="rgb"){let{r:T,g:x,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${x};${h}m`;let u=Sj(T,x,h);return`\x1B[${S?38:48};5;${u}m`}return""}let N=[];if(H>=W)for(let P=W;P<=H;P++){let S="";for(let T=0;T<G;T++){let x=z[P][T],h=x.char,u=q(x.style.fg,!0);S+=u+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),L=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let S=" ".repeat(G);if(P>=L&&P<L+I)S=N[P-L];let T=" ",x="";if(P>=O&&P<O+D.length)x=D[P-O];B.write(S+T+x+`
5802
+ `)}class Q51 extends T0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;onThreadArchived;onActiveThreadChange;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new qs4}}class qs4 extends _0{editorController=new j8;commandPalette=new Wr(this);commandRegistry=new VA1;toastController=new v01;exitHintTimer=new zr(this,1000);ideStatus=new G2(this,{});threadNavigationHistory=new ZA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;activeThreadIDSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new H6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>gG0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await Gc4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await Vc4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await Uc4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(tB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(g30(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new JA1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=L4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Un4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((F)=>rA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},Ws4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new LA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new i61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await nA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{CJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new CA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new WA1({commands:YB.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new xA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(KD0({version:"0.0.1778631508-g72c81a",buildTimestamp:"2026-05-13T00:22:19.974Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{l4.maybeInvoke(Y,new Rf)}},...Q,...An4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new l61({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B,statusItems:this.pluginIntegration?.getStatusItems()??[]}),J=A4.of(A),Y=J.capabilities.animationSupport!=="disabled",F=[new g0({constraints:I1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())F.push(new n4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new UA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)F.push(rA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)F.push(new n4({debugLabel:"NeoWelcomeDialogOverlay",child:new t61({onDismiss:this.dismissNeoWelcome,onQuit:()=>L4.instance.stop(),animationsEnabled:Y,variant:this.widget.neoWelcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new n4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new IA1({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)F.push(new NA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:ms.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new wA1);return new S3({neoContext:this.widget.neoContext,child:new YB({commandRegistry:this.commandRegistry,child:new hI({completionBuilder:this.widget.completionBuilder,child:new Y3({controller:this.toastController,child:new l4({actions:this.buildActions(),child:new Y5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[C1.ctrl("c"),new _G0],[C1.ctrl("o"),new TG0],[C1.alt("i"),new SG0],[C1.alt("p"),new MI],[C1.ctrl("t"),new vG0]]),child:new d4({debugLabel:"AppShellFocus",child:new y01({controller:this.toastController,child:new HA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new BA({children:F})})})})})})})})})})}buildActions(){let A=new c1(()=>{if(wJ.hasAnyCopyableSelection())return wJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new c1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new c1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new c1(()=>{return this.startNewDraftThread(),"handled"}),J=new c1(()=>{return L4.instance.stop(),"handled"}),Y=new c1((U)=>{if(!U.text)return"ignored";return L4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new c1(()=>{return L4.instance.toggleFrameStatsOverlay(),"handled"}),F=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Kx(U);return L4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new c1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new c1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await L4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new c1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[_G0,A],[Gs,$],[Rf,J],[b9,Y],[Ks,B],[TG0,Q],[SG0,F],[Es,X],[zs,D],[Ws,G],[MI,Z],[vG0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:eg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Kx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await cx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=eB(Q),J=QD0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return AD0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Hs4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Hs4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(uI);if(this.exitHintTimer.isActive())A.add(Cf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),L4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:(B)=>{Q(B==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")L4.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((D)=>D.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,ms.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F??void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=eB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};NJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=yY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:(J)=>this.promptExecutorAlreadyConnected(J)});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)}),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=Q!=="idle"&&Q!=="error";if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=ms.cwd().replace(ms.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,ms.stdout.write(EI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Hs4(A,Q,B){let $={...A};for(let J of Am5(Q,B)){if(!dZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Am5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function Ns4(A,Q,B,$){let J=Bk(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new rY(G,V),K=new v9(42),E=new HI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),K);E.layout(I1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(z[P].some((S)=>S.char!==" ")){W=P;break}let H=V-1;for(let P=V-1;P>=0;P--)if(z[P].some((S)=>S.char!==" ")){H=P;break}function q(P,S){if(!P)return"";if(P.type==="rgb"){let{r:T,g:x,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${x};${h}m`;let u=Sj(T,x,h);return`\x1B[${S?38:48};5;${u}m`}return""}let N=[];if(H>=W)for(let P=W;P<=H;P++){let S="";for(let T=0;T<G;T++){let x=z[P][T],h=x.char,u=q(x.style.fg,!0);S+=u+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),L=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let S=" ".repeat(G);if(P>=L&&P<L+I)S=N[P-L];let T=" ",x="";if(P>=O&&P<O+D.length)x=D[P-O];B.write(S+T+x+`
5800
5803
  `)}if($)B.write(`
5801
5804
  \x1B[90m${$}\x1B[0m
5802
5805
  `)}p0();GD0();var Qm5=2000;function Is4(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<Qm5)return;if(J=U,hj())return;if(XX0())DX0();else NZ0(V)},Z=(V)=>{if(!Q||!B)return;if(hj()&&!Fr()&&!yx())return;process.stdout.write(hD(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&iQ(X),E=X==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){j.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}function Bm5({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:B,neoWelcomeVariant:$,neoWelcomeDismissed:J}){if(B)return{show:!1,markDismissedOnDismiss:!1};if($==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let Y=!A&&!J;return{show:Y,markDismissedOnDismiss:Y}}async function $m5(A){await NJ((Q)=>$D0(Q,A,"interactive"))}async function ws4(A,Q={}){let{initialThreadID:B,initialUserInput:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:Y=!1,observerOnly:Z=!1,initialAgentMode:F,initialReasoningEffort:X,showNeoWelcome:D=!1,hideNeoWelcome:G=!1,neoWelcomeVariant:V="intro"}=Q,U=V==="npm-migration",K=async(S)=>{let T=await A.getThreadFromServer(S);if(!T)return null;return nF0(T)},E=async(S)=>{let T=await A.getThreadFromServer(S);if(!T)throw Error(`Thread ${S} not found`);let x=await nY(S,A.configService,A.apiKey,{usesThreadActors:!0}),k=await OU({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([S],{params:{wsToken:x.wsToken},createWithInput:{threadId:x.threadId,threadVersion:x.threadVersion,ownerUserId:x.ownerUserId,...x.agentMode?{agentMode:x.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:vx4(T)}),skipReadyWait:!0});if(!k.ok&&k.status!==409)throw Error(`Thread import failed (${k.status}): ${await k.text()}`);try{await Ff4(S,A.configService,A.apiKey,{executorType:"local-client"})}catch(f){j.warn("failed to mark thread as imported on server",{threadID:S,error:f instanceof Error?f.message:String(f)})}},z=new Z01(A.rivetEndpoint,A.apiKey,A.configService,{clientID:QI.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(S)=>A.pluginService.event.toolCall(S),requestPluginToolResult:(S)=>A.pluginService.event.toolResult(S),pluginService:A.pluginService,invokeTool:async(S,T)=>{let x=typeof T.args==="object"&&T.args!==null?T.args:{},h=await YI({toolName:T.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:T.toolCallId,threadId:S});return A.toolService.invokeTool(T.toolName,{args:x},h)},persistLastThreadID:$m5,readFileSystemDirectory:A.readFileSystemDirectory},K,E),W=await wI(),H=Bm5({initialUserInput:$,showNeoWelcome:D,hideNeoWelcome:G,neoWelcomeVariant:V,neoWelcomeDismissed:W.neoWelcomeDismissed}),q={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(S)=>{let T=await A.getThreadFromServer(S);return T?SV(T):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:aa,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:U?!1:Z,sessionAgentMode:F??W.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:W.lastReasoningEffortByMode,lastSpeedByMode:W.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},N=(S,T)=>{return Dx({ampURL:A.ampURL,configService:A.configService,threadID:S,signal:T})},I=(S,T)=>{return Gg4({ampURL:A.ampURL,configService:A.configService,threadID:S,signal:T})},w=new j01,L=Is4({configService:A.configService}),O=await A.configService.getLatest();L4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:O.settings["terminal.animation"]===!1}});let P=new Set;try{await Xr(new Q51({clientPool:z,analyzeContextForThread:N,listSkillsForThread:I,completionBuilder:A.completionBuilder,history:new Wo,ideManager:w,configService:A.configService,initialThreadID:U?void 0:B,notificationService:L,initialUserInput:U?void 0:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:U?!1:Y,neoContext:q,showNeoWelcome:H.show,neoWelcomeVariant:V,onActiveThreadChange:A.setActiveThreadID,onNeoWelcomeDismissed:H.markDismissedOnDismiss?()=>{NJ(Eg4).catch((T)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:T})})}:void 0,onThreadArchived:(T)=>{P.add(T)}}));let S=z.lastActiveObservingClient;if(S){let{client:T,observer:x}=S,h=T.getThreadId();if(h){let u={id:h,title:x.title().getValue(),agentMode:x.agentMode,archived:P.has(h)},k=`${A.ampURL.replace(/\/$/,"")}/threads/${h}`;Ns4(u,k,process.stdout)}}}finally{process.stdout.write(EI("")),L.unsubscribe(),z.dispose(),await A.dispose?.()}process.exit(0)}E3();function pf(A){let Q=[],B={meta:{visibility:"private",sharedGroupIDs:[]}};if(A.workspace?.disablePrivateThreads)B.disabledReason="Disabled by workspace policy";if(Q.push(B),A.workspace?.groups&&A.workspace.groups.length>0){let Z={meta:{visibility:"private",shareWithAllCreatorGroups:!0}};if(A.creatorIsViewer===!1)Z.disabledReason="Can only be set by thread creator";Q.push(Z)}if(A.workspace)Q.push({meta:{visibility:"thread_workspace_shared"}});let $=A.workspace?.disablePublicSharing?"Disabled by workspace policy":void 0,J={meta:{visibility:"public_unlisted"}},Y={meta:{visibility:"public_discoverable"}};if($)J.disabledReason=$,Y.disabledReason=$;return Q.push(J,Y),Q}function Cs4(A){if(A.visibility!=="private")return!0;if("shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups)return!0;return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0}function HR(A,Q={}){switch(A.visibility){case"thread_workspace_shared":return{text:"Workspace",description:"Visible to all members of the workspace"};case"public_discoverable":return{text:"Public",description:"Visible on public profile & publicly searchable"};case"public_unlisted":return{text:"Unlisted",description:"Visible to anyone on the Internet who has the link"};case"private":{let B="shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups,J=(B?Q.workspace?.groups.map((Y)=>Y.id)??[]:("sharedGroupIDs"in A)?A.sharedGroupIDs:[]).reduce((Y,Z)=>{let F=Q.workspace?.groups.find((X)=>X.id===Z)?.name;if(F)Y.push(`'${F}'`);return Y},[]);if(J.length>0)return{text:"Group",description:`Shared with ${V4(J.length,"group")} ${J.join(", ")} and workspace admins`};if(B)return{text:"Group",description:"Shared with creator groups and workspace admins"};return{text:"Private",description:Q.workspace?"Only visible to you and workspace admins":"Only you can see this thread"}}}}function MV0(A){if(A.visibility==="private")return"shareWithAllCreatorGroups"in A?"group":"private";if(A.visibility==="thread_workspace_shared")return"workspace";if(A.visibility==="public_unlisted")return"unlisted";return"public"}function df(A,Q=null){let B=A!==null&&typeof A==="object"&&"visibility"in A?A.visibility:void 0;if(!B||typeof B!=="string")return;let J=pf({workspace:Q?.team??void 0}).filter((Y)=>!Y.disabledReason).map((Y)=>MV0(Y.meta));if(J.includes(B))return Jm5(B);if(B==="group"&&!J.includes("group")){if(Q?.team?.groups!==void 0)return Error(`Group visibility is not available. You are not a member of any group in this workspace.
@@ -7552,7 +7555,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
7552
7555
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].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 G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new C(G.slice(1,-1),new v({color:$.app.keybind,bold:!0})));else Y.push(new C(G,new v({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new C(`
7553
7556
  `))}return new g0({decoration:{color:B.colorScheme.background,border:l1.all(new i1($.app.keybind,1,"rounded"))},child:new x0({padding:E0.symmetric(0,1),child:new p({text:new C(void 0,void 0,Y)})})})}}class G31 extends F8{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=uU0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new X31({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function l0A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?l8:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?l8:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function Hn5(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?l8:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=F>0?Z/F:0,z=Math.round((1-E)*(V-1));return{x:K,y:z}}case"line":case"sparkline":case"stacked-area":{let D=Y?l8:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function qn5(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function Nn5(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function In5(A,Q,B,$,J,Y,Z){let F;try{let E=R1.of(A),z=P0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:z.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new v({color:F.foreground,bold:!0}),D=new v({color:F.foreground}),G=new v({color:F.foreground,dim:!0}),V=[],U=new v({color:F.foreground,underline:!0}),K=(E,z)=>new C(z,U,void 0,vz(E),()=>{nA(A,E)});if($.length<=1){if(V.push(new C(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new C(Y(Q.value),D));if(Q.meta)V.push(new C(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new C(`${Q.label}
7554
7557
  `,X));let z=0;for(let W=0;W<$.length;W++){let H=$[W],q=H.points[B];if(!q)continue;z+=q.value;let N=H.color??J[W%J.length]??F.foreground;if(V.push(new C("● ",new v({color:N}))),V.push(new C(`${H.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new C(Y(q.value),D));if(W<$.length-1||E)V.push(new C(`
7555
- `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new g0({decoration:{color:F.background,border:l1.all(new i1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}p0();function i0A(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}E3();H8();Q3();h7();S7();o9();R2();RQ();kV();i4();oS();wT();L1();p0();o9();class V31{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1778617350-g19dbc6"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await f30(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Xw extends T0{props;constructor(A){super();this.props=A}createState(){return new n0A}}class n0A extends _0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class a0A extends _0{controller=new j8;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.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(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=l1.all(new i1(B.foreground,1,"solid")),X=new A$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new s0({children:[new g0({decoration:{color:B.background},child:new p({text:new C(">",new v({color:B.foreground}))})}),new _1({child:X})]}),G=new g0({padding:E0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new v({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new v({color:$.keybind}))),V.push(new C(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new C("Esc",new v({color:$.keybind}))),V.push(new C(" to cancel",new v({color:B.foreground,dim:!0})));let U=new g0({padding:E0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new g0({decoration:{border:F,color:B.background},padding:E0.all(1),child:new y0({children:[G,new U0({height:1}),D,new Z5,U]})})}}class Yt extends T0{props;constructor(A){super();this.props=A}createState(){return new a0A}}RQ();class o0A extends _0{controller=new j8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=t9)return!1;let Q=await eF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,Y=A4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new AG({controller:this.controller,triggers:[new PJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:L4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new d4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new g0({constraints:new I1({maxHeight:Z}),padding:E0.symmetric(1,0),child:X}),G=new g0({padding:E0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new g0({padding:E0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new v({color:$.keybind})),new C(" again to clear input",new v({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new v({color:B.foreground,dim:!0})),new C("Enter",new v({color:$.keybind})),new C(" to submit, ",new v({color:B.foreground,dim:!0})),new C("Esc",new v({color:$.keybind})),new C(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new _1({child:D}),new U0({height:1}),V];return new g0({decoration:{border:l1.all(new i1(B.foreground,1,"solid")),color:B.background},padding:E0.all(1),child:new y0({children:U})})}}class U31 extends T0{props;constructor(A){super();this.props=A}createState(){return new o0A}}function r0A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class K31 extends q1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>r0A(J.pubDate).length));return new X5({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=P0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:s0.end([new p({text:new C(z,new v({color:K}))})])});return new g0({decoration:V?{color:V}:void 0,padding:E0.symmetric(2,0),child:new s0({children:[new _1({child:new p({text:new C(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(r0A(J.pubDate),B)]})})}})}}class UB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UB._instance)UB._instance=new UB;return UB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class s0A extends _0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=P0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new X5({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new g0({decoration:K?{color:K}:void 0,padding:E0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new v({color:E})),new C(W,new v({color:E,bold:!0}))])})})}return new g0({decoration:K?{color:K}:void 0,padding:E0.symmetric(2,0),child:new p({text:new C(D.name,new v({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class E31 extends T0{props;constructor(A){super();this.props=A}createState(){return new s0A}}class $G extends T0{props;constructor(A){super();this.props=A}createState(){return new t0A}}class t0A extends _0{_spinner=new H6;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(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=l1.all(new i1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new v({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new v({color:B.foreground}))])}),X=[new _1({child:new y0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new g0({padding:E0.symmetric(2,0),child:new p({text:new C("",new v({dim:!0}),[new C("Press ",new v({color:B.foreground})),new C("Esc",new v({color:B.info})),new C(" to cancel",new v({color:B.foreground}))])})})}));let D=new g0({decoration:new u4(B.background,J),child:new U0({width:60,height:7,child:new y0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new n4({debugLabel:"LoadingDialog",child:new d4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class sU extends T0{props;constructor(A){super();this.props=A}createState(){return new e0A}}class e0A extends _0{scrollController=new vA;scrollAreaKey=new X2("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(A){return A instanceof b2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=P0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=dD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=l1.all(new i1(Q.colors.border,1,"solid")),Z=new g0({padding:E0.symmetric(1,0),child:new p({text:new C($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new _1({child:new J3({child:new g0({padding:E0.symmetric(1,0),child:new s0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new yA({controller:this.scrollController,autofocus:!0,child:F})}),new K2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new g0({padding:E0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new v({color:Q.colors.foreground,dim:!0})),new C("R",new v({color:Q.app.keybind})),new C(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new C("Esc",new v({color:Q.app.keybind})),new C(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new n4({debugLabel:"MessageDialog",child:new BA({fit:"expand",children:[new k1({onClick:()=>{},child:new U0}),new d4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.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 g0({decoration:{border:Y,color:Q.colors.background},padding:E0.all(1),child:new y0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}E3();e1();class A1A extends T0{props;constructor(A){super();this.props=A}createState(){return new Q1A}}class Q1A extends _0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=o0.file(this.widget.props.cwd),B=Z1.relativePath(Q,_A(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return v5(A)}statusIcon(A){let Q=d8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=P0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new v({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new C(`${Y}/${J} ${V4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${V4(Z,"command")}, ${F} ${V4(F,"tool")})`,new v({dim:!0})));$.push(new C(`
7558
+ `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new g0({decoration:{color:F.background,border:l1.all(new i1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}p0();function i0A(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}E3();H8();Q3();h7();S7();o9();R2();RQ();kV();i4();oS();wT();L1();p0();o9();class V31{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1778631508-g72c81a"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await f30(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Xw extends T0{props;constructor(A){super();this.props=A}createState(){return new n0A}}class n0A extends _0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class a0A extends _0{controller=new j8;focusNode=new G6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.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(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=l1.all(new i1(B.foreground,1,"solid")),X=new A$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new s0({children:[new g0({decoration:{color:B.background},child:new p({text:new C(">",new v({color:B.foreground}))})}),new _1({child:X})]}),G=new g0({padding:E0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new v({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new v({color:$.keybind}))),V.push(new C(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new C("Esc",new v({color:$.keybind}))),V.push(new C(" to cancel",new v({color:B.foreground,dim:!0})));let U=new g0({padding:E0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new g0({decoration:{border:F,color:B.background},padding:E0.all(1),child:new y0({children:[G,new U0({height:1}),D,new Z5,U]})})}}class Yt extends T0{props;constructor(A){super();this.props=A}createState(){return new a0A}}RQ();class o0A extends _0{controller=new j8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new G6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=t9)return!1;let Q=await eF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,Y=A4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new AG({controller:this.controller,triggers:[new PJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:L4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new d4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new g0({constraints:new I1({maxHeight:Z}),padding:E0.symmetric(1,0),child:X}),G=new g0({padding:E0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new g0({padding:E0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new v({color:$.keybind})),new C(" again to clear input",new v({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new v({color:B.foreground,dim:!0})),new C("Enter",new v({color:$.keybind})),new C(" to submit, ",new v({color:B.foreground,dim:!0})),new C("Esc",new v({color:$.keybind})),new C(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new _1({child:D}),new U0({height:1}),V];return new g0({decoration:{border:l1.all(new i1(B.foreground,1,"solid")),color:B.background},padding:E0.all(1),child:new y0({children:U})})}}class U31 extends T0{props;constructor(A){super();this.props=A}createState(){return new o0A}}function r0A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class K31 extends q1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>r0A(J.pubDate).length));return new X5({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=P0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:s0.end([new p({text:new C(z,new v({color:K}))})])});return new g0({decoration:V?{color:V}:void 0,padding:E0.symmetric(2,0),child:new s0({children:[new _1({child:new p({text:new C(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(r0A(J.pubDate),B)]})})}})}}class UB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UB._instance)UB._instance=new UB;return UB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class s0A extends _0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=P0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new X5({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new g0({decoration:K?{color:K}:void 0,padding:E0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new v({color:E})),new C(W,new v({color:E,bold:!0}))])})})}return new g0({decoration:K?{color:K}:void 0,padding:E0.symmetric(2,0),child:new p({text:new C(D.name,new v({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class E31 extends T0{props;constructor(A){super();this.props=A}createState(){return new s0A}}class $G extends T0{props;constructor(A){super();this.props=A}createState(){return new t0A}}class t0A extends _0{_spinner=new H6;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(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=l1.all(new i1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new v({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new v({color:B.foreground}))])}),X=[new _1({child:new y0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new g0({padding:E0.symmetric(2,0),child:new p({text:new C("",new v({dim:!0}),[new C("Press ",new v({color:B.foreground})),new C("Esc",new v({color:B.info})),new C(" to cancel",new v({color:B.foreground}))])})})}));let D=new g0({decoration:new u4(B.background,J),child:new U0({width:60,height:7,child:new y0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new n4({debugLabel:"LoadingDialog",child:new d4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class sU extends T0{props;constructor(A){super();this.props=A}createState(){return new e0A}}class e0A extends _0{scrollController=new vA;scrollAreaKey=new X2("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(A){return A instanceof b2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=P0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=dD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=l1.all(new i1(Q.colors.border,1,"solid")),Z=new g0({padding:E0.symmetric(1,0),child:new p({text:new C($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new _1({child:new J3({child:new g0({padding:E0.symmetric(1,0),child:new s0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new yA({controller:this.scrollController,autofocus:!0,child:F})}),new K2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new g0({padding:E0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new v({color:Q.colors.foreground,dim:!0})),new C("R",new v({color:Q.app.keybind})),new C(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new C("Esc",new v({color:Q.app.keybind})),new C(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new n4({debugLabel:"MessageDialog",child:new BA({fit:"expand",children:[new k1({onClick:()=>{},child:new U0}),new d4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.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 g0({decoration:{border:Y,color:Q.colors.background},padding:E0.all(1),child:new y0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}E3();e1();class A1A extends T0{props;constructor(A){super();this.props=A}createState(){return new Q1A}}class Q1A extends _0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=o0.file(this.widget.props.cwd),B=Z1.relativePath(Q,_A(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return v5(A)}statusIcon(A){let Q=d8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=P0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new v({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new C(`${Y}/${J} ${V4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${V4(Z,"command")}, ${F} ${V4(F,"tool")})`,new v({dim:!0})));$.push(new C(`
7556
7559
 
7557
7560
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri);if($.push(new C(`${D} `,new v({color:G}))),$.push(new C(V,new v({bold:!0}))),$.push(new C(` ${X.status}`,new v({dim:!0}))),$.push(new C(`
7558
7561
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new C(" Events: ",new v({dim:!0}))),$.push(new C(X.registeredEvents.join(", "),new v({color:B.link}))),$.push(new C(`
@@ -7730,7 +7733,7 @@ ${s.content||""}`:s.content||"",f0=[],h0=s.baseDir.startsWith("file://")?KK0(s.b
7730
7733
  `)}function fAA(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),F=I04({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await QA.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.error.code==="auth-required")process.stderr.write(n0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(n0.red("Error: ")+X.error.message+`
7731
7734
  `),process.exit(1)}process.stdout.write(await ur5(X.result.displayText)+`
7732
7735
  `),process.exit(0)})}var Z13=dt.join(x$,"logs","headless.log"),H91=dt.join(kx,"device-id.json"),F13=`cli-tui-${G8A(16).toString("hex")}`;async function X13(){for(let A of mM)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => v4(vb(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){KB.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7733
- `)}function D13(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function W2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")ZY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")ZY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)ZY("internal.model",U13(Q.model))}function $8A(A){let Q=A.indexOf(":");if(Q===-1)throw new Z4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new Z4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function G13(A){if(A===void 0)return;let Q=A.trim();if(F04(Q))return Q;throw new Z4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function V13(A,Q){if(hX(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new Z4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function U13(A){if(!A.includes("="))return $8A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new Z4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new Z4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new Z4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);$8A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new Z4("No valid model overrides found in --model flag value.",1);return Q}function K13(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function E13(A){try{return await V8A(A,"utf-8")}catch{return A}}async function q91(A,Q,B){let $=K13(A,Q);if(!$)return;let J=lA(B)?B.features:[],Y=lA(B)?B.user.email:void 0;if(!YE0(J,f$.HARNESS_SYSTEM_PROMPT)&&!(Y&&T7(Y)))throw new Z4("You are not allowed to do this.",1);ZY("systemPrompt",await E13($))}function YE0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function z13(A){return A!=="pending"}function WW(A){if(!lA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function W13(A){let Q=WW(A);if(Q)return Q.id;if(uX(A))throw Error(A.error.message);throw Error("unreachable")}function H13(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function q13(A){let $=H13(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new Z4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function ct(A,Q){let B=Us0(Error(A.error.message));if(B.message===G7.networkOffline||B.message===G7.networkTimeout)return q13(Q);if(B.message!==G7.internalBug)return new Z4(B.message,1,B.suggestion);return new Z4(A.error.message.replace(/^Error: /,""),1)}async function N13(){if(process.versions.bun)return!1;try{return await TU()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var J8A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"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??dF,description:`Custom settings file path (overrides the default location ${dF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${aa})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:X9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"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:hM.SMART.key,description:`Set the agent mode (${m$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(m$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",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},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],Y8A=(A)=>("deprecated"in A)&&A.deprecated===!0,I13=(A)=>("hidden"in A)&&A.hidden===!0,w13=(A)=>("default"in A),C13=(A)=>("default"in A)?A.default:void 0;function BE0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=G13(Q.effort);if(B!==void 0)V13(Q.mode,B);return B}function M13(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new Z4(G7.unknownCommand(B),1,Z)}}async function ZE0(A){return{...A,getThreadEnvironment:wz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new LL(A.fileSystem),generateThreadTitle:IF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>OQ(A.configService),pluginService:A.pluginService}}function U8A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:wz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var $E0=o0.file(Y13.homedir()),N91=process.env.XDG_CONFIG_HOME?o0.file(process.env.XDG_CONFIG_HOME):Z1.joinPath($E0,".config");function L13(A){return aR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(XX0())DX0();else NZ0(Q);let B=hj(),$=Fr();if((!B||$||yx())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(hD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(hD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(hj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function k8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;te1("0.0.1778617350-g19dbc6");let Y=p30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:u0.of(o0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:$E0,userConfigDir:N91});ss4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let a=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(a),j.info("API key lookup before login",{found:Boolean(a),ampURL:A.ampURL,deferAuth:$}),!a)if($)j.info("No API key found, continuing startup with deferred auth");else{r6.write(`No API key found. Starting login flow...
7736
+ `)}function D13(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function W2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")ZY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")ZY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)ZY("internal.model",U13(Q.model))}function $8A(A){let Q=A.indexOf(":");if(Q===-1)throw new Z4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new Z4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function G13(A){if(A===void 0)return;let Q=A.trim();if(F04(Q))return Q;throw new Z4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function V13(A,Q){if(hX(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new Z4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function U13(A){if(!A.includes("="))return $8A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new Z4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new Z4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new Z4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);$8A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new Z4("No valid model overrides found in --model flag value.",1);return Q}function K13(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function E13(A){try{return await V8A(A,"utf-8")}catch{return A}}async function q91(A,Q,B){let $=K13(A,Q);if(!$)return;let J=lA(B)?B.features:[],Y=lA(B)?B.user.email:void 0;if(!YE0(J,f$.HARNESS_SYSTEM_PROMPT)&&!(Y&&T7(Y)))throw new Z4("You are not allowed to do this.",1);ZY("systemPrompt",await E13($))}function YE0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function z13(A){return A!=="pending"}function WW(A){if(!lA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function W13(A){let Q=WW(A);if(Q)return Q.id;if(uX(A))throw Error(A.error.message);throw Error("unreachable")}function H13(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function q13(A){let $=H13(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new Z4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function ct(A,Q){let B=Us0(Error(A.error.message));if(B.message===G7.networkOffline||B.message===G7.networkTimeout)return q13(Q);if(B.message!==G7.internalBug)return new Z4(B.message,1,B.suggestion);return new Z4(A.error.message.replace(/^Error: /,""),1)}async function N13(){if(process.versions.bun)return!1;try{return await TU()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var J8A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"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??dF,description:`Custom settings file path (overrides the default location ${dF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${aa})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:X9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"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:hM.SMART.key,description:`Set the agent mode (${m$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(m$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",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},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],Y8A=(A)=>("deprecated"in A)&&A.deprecated===!0,I13=(A)=>("hidden"in A)&&A.hidden===!0,w13=(A)=>("default"in A),C13=(A)=>("default"in A)?A.default:void 0;function BE0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=G13(Q.effort);if(B!==void 0)V13(Q.mode,B);return B}function M13(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new Z4(G7.unknownCommand(B),1,Z)}}async function ZE0(A){return{...A,getThreadEnvironment:wz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new LL(A.fileSystem),generateThreadTitle:IF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>OQ(A.configService),pluginService:A.pluginService}}function U8A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:wz,getEnvironmentData:(Q,B)=>YD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var $E0=o0.file(Y13.homedir()),N91=process.env.XDG_CONFIG_HOME?o0.file(process.env.XDG_CONFIG_HOME):Z1.joinPath($E0,".config");function L13(A){return aR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(XX0())DX0();else NZ0(Q);let B=hj(),$=Fr();if((!B||$||yx())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(hD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(hD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(hj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function k8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;te1("0.0.1778631508-g72c81a");let Y=p30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:u0.of(o0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:$E0,userConfigDir:N91});ss4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let a=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(a),j.info("API key lookup before login",{found:Boolean(a),ampURL:A.ampURL,deferAuth:$}),!a)if($)j.info("No API key found, continuing startup with deferred auth");else{r6.write(`No API key found. Starting login flow...
7734
7737
  `);let t=await O13(A),w0=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:t,storedKeyPresent:Boolean(w0),ampURL:A.ampURL}),!t)await Rz(),process.exit(1);F=!0}}{let a=await Y.getLatest(),t=a.settings.url,w0=a.secrets.isSet?.[t];j.info("Config secrets state after login",{configURL:t,apiKeySet:w0?.apiKey??!1})}let X=T1(OQ(Y).pipe(A5(z13))),D=$?"pending":await X;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:lA(D),isError:uX(D),errorMessage:uX(D)?D.error.message:void 0});let G=X.then((a)=>W13(a));G.catch(()=>{return});let V=!Q.takeMeBack&&lA(D)&&YE0(D.features,f$.THREAD_ACTORS_TUI),U=V?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=dR4({configService:Y}),z=new Map,W=()=>z.clear(),H=new sf0(Y,A.settings.getWorkspaceRootPath()),q=oJ4({configService:Y,filesystem:_3}),N=u74({configService:Y,trustStore:H,skillMCPServers:q.skillMCPServers,uploadImageAttachments:V,createOAuthProvider:async(a,t,w0)=>{let V0=`${a}:${t}`,N0=z.get(V0);if(N0)return j.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:t}),N0;j.debug("Creating OAuth provider for server",{serverName:a,serverUrl:t});let X0=(async()=>{let j0=new nM(A.secrets),Q0=await j0.getClientInfo(a,t),I0=w0?.scopes??Q0?.scopes,n=if4();j.info("OAuth headless mode check",{useHeadless:n,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:r6.isTTY});let o;if(n)o=A.executeMode?lf4():cf4(a);let s=new Fv0({storage:j0,serverName:a,serverUrl:t,clientId:w0?.clientId??Q0?.clientId,clientSecret:w0?.clientSecret??Q0?.clientSecret,authUrl:w0?.authUrl??Q0?.authUrl,tokenUrl:w0?.tokenUrl??Q0?.tokenUrl,scopes:I0,headlessAuthHandler:o});return j.debug("OAuth provider created",{serverName:a,serverUrl:t,hasManualClientId:!!(w0?.clientId??Q0?.clientId),willUseDCR:!(w0?.clientId??Q0?.clientId),scopes:I0,headlessMode:n,executeMode:A.executeMode}),s})();return z.set(V0,X0),X0}}),I=tn0({configService:Y,filesystem:_3,spawn:hY0}),w=Q.headless?_s4():void 0,L=w??new LV0({configService:Y}),O=L instanceof LV0?L:void 0;if(O)O.pluginExecutorKind="local";let P=new s1(null),S=V?[...Ss4(Z.settings)?[{name:"permissions",entryPoint:Y51}]:[],{name:"thread-visibility",entryPoint:xs4(Y,()=>X.then(WW)),alwaysLoad:!0}]:[],T=zb0({configService:Y,fileSystem:_3,platform:L,loadGlobalPlugins:dt0(Y),pluginFilter:U,activeThread$:P,internalPlugins:S}),x=uQ4(T),h=[N,I,x],u;if(J)u=new Map;else if(A.executeMode){let a=await NO4({toolService:K,providers:h,initialTimeout:15000});u=a.registrations;for(let[t,w0]of a.initErrors)j.warn(`${t} provider initialization slow or failed:`,w0)}else u=en0({toolService:K,providers:h});if(Q.jetbrains)xM("JetBrains");else if(Q.ide&&Sb4())xM("VS Code");else if(Q.ide&&vb4())xM("Neovim");else if(Q.ide){let a=await X13();if(a){let t=t30(a.ideName);if(t)xM(t)}}if(A.executeMode)ee1(!0);let k,f=m3.status.pipe(H1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&r04(a.ideName))),_4()).subscribe((a)=>{if(a){if(!k)k=K.registerTool(qO4)}else k?.dispose(),k=void 0}),d;if(!A.executeMode){let a=await A.settings.get("fuzzy.alwaysIncludePaths")??[];d=new YX0(process.cwd(),{alwaysIncludePaths:a},!0)}else d=new class extends YX0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let c=new Eg0(_l(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let g=new G51,l={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:H,threadService:c,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:d,fileSystem:_3,terminal:g,pluginService:T,pluginPlatform:O,headlessPluginPlatform:w,activeThread$:P,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...l,async asyncDispose(){if(l.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await l.mcpService.waitForAuthentication();for(let a of u.values())a.dispose();await l.mcpService.dispose(),W(),await l.threadService.asyncDispose(),l.configService.unsubscribe(),E(),l.fuzzyServer.dispose(),l.settingsStorage[Symbol.dispose](),f.unsubscribe(),k?.dispose(),await l.pluginService.dispose()}}}async function O13(A){if(!A.executeMode){if(!await tX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return r6.write(`Login cancelled. Run the command again to retry.
7735
7738
  `),!1}return await K8A(A)}async function K8A(A){let Q=G8A(32).toString("hex"),B=await dx(A.ampURL,Q),$=new AbortController;try{await xX(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await dx(A.ampURL,Q,!1);r6.write(`If your browser does not open automatically, visit:
7736
7739
 
@@ -7738,7 +7741,7 @@ ${n0.blue.bold(J)}
7738
7741
 
7739
7742
  `);try{return await sh4(A.ampURL,Q,A.secrets,$),r6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),KB.write(`
7740
7743
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
7741
- `),!1}}async function j13(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new Z4("No Amp API key found. Run `amp login` first.",1);let J=B13("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function R13(A){let Q=new pN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)Hj(),process.exit(0);let H=W.originalError??W;Pv4(H)}),Ym4(Q,{version:"0.0.1778617350-g19dbc6",buildTimestamp:"2026-05-12T20:26:19.685Z",buildType:"'release'"}),Q.addHelpText("after",_b4()),Q.configureHelp({formatHelp:Tb4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await f13(N)}),Q.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(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await x13(N,await Qe0(q,N.settings))}),Ov4(Q,m5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await m5(N);await j13(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.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(W,H,q)=>{let N=q.optsWithGlobals(),I=await m5(N);await ff4(W??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.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(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await bf4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(W)=>{await ru4({raw:W.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
7744
+ `),!1}}async function j13(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new Z4("No Amp API key found. Run `amp login` first.",1);let J=B13("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function R13(A){let Q=new pN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)Hj(),process.exit(0);let H=W.originalError??W;Pv4(H)}),Ym4(Q,{version:"0.0.1778631508-g72c81a",buildTimestamp:"2026-05-13T00:22:19.974Z",buildType:"'release'"}),Q.addHelpText("after",_b4()),Q.configureHelp({formatHelp:Tb4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await f13(N)}),Q.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(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await x13(N,await Qe0(q,N.settings))}),Ov4(Q,m5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await m5(N);await j13(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.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(W,H,q)=>{let N=q.optsWithGlobals(),I=await m5(N);await ff4(W??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.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(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await bf4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(W)=>{await ru4({raw:W.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
7742
7745
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(W,H,q)=>{if(W&&H.apply)throw new Z4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=H.apply??W;if(!N||N.trim().length===0)r6.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
7743
7746
 
7744
7747
  `),q.outputHelp(),process.exit(0);let I=s8(N)??aB(N),w=q.optsWithGlobals(),L=await m5(w);W2(q,w);let O=await k8(L,w),P=!1;try{if(H.checkout&&H.skipCheckout)throw new Z4("Choose either --checkout or --skip-checkout, not both.",1);if(uX(O.serverStatus))throw ct(O.serverStatus,L.ampURL);let S=lA(O.serverStatus)?O.serverStatus.features:void 0;if(!YE0(S,f$.V2))throw new Z4("live-sync is not enabled for your user",1);await gh4({ampURL:L.ampURL,threadId:I,configService:O.configService,threadService:O.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:tX0}),P=!0}finally{if(await O.asyncDispose(),P)process.exit(0)}});let J=async(W,H,q)=>{p30({storage:H.settings,secretStorage:H.secrets,workspaceRoot:u0.of(o0.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:$E0,userConfigDir:N91});let N={...H,executeMode:!1};await JE0(N,{...W,openThreadSwitcher:!0},q,A)},Y=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await D8A(q,N,H)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await a13(q,N,H)}),Y.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(W,H,q)=>{let N=q.optsWithGlobals(),I=await m5(N);if(H.pick)KB.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7771,8 +7774,8 @@ ${L}
7771
7774
  `))}),H.args.length>0)M13(N,H);await JE0(N,q,H,A)}),Uu4(Q),Q}async function yb(A,Q){await NJ((B)=>$D0(B,A,Q))}async function Z8A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([QA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new Z4(`Cannot resume thread created by another user.
7772
7775
 
7773
7776
  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 E8A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await PV0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await PV0()).trimEnd(),stdinInput:null}}function z8A(A,Q,B){if(A.streamJson&&!Q)throw new Z4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new Z4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new Z4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new Z4("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new Z4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new Z4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new Z4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new Z4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
7774
- Or pipe via stdin: echo "your message" | amp --execute`)}function P13(){bA4([e50.parse({tool:"*",action:"allow"})]),KA4({bypass:!0})}async function JE0(A,Q,B,$){if(Q.headless)return _13(A,Q,B);let J=await k8(A,Q),Y=await J.serverStatusPromise,Z=lA(Y)&&YE0(Y.features,f$.THREAD_ACTORS_TUI),F=Z&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new Z4("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!Z)throw await J.asyncDispose(),new Z4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F){let X=!A.executeMode&&await N13();return P13(),T13(A,Q,B,J,{showNpmMigrationWelcome:X})}else{if(Q.threadId&&z9(Q.threadId)){let X=await QA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(X?.ok&&X.result.usesThreadActors)throw await J.asyncDispose(),new Z4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return k13(A,Q,B,$,{dependencies:J})}}async function _13(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=$s0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};W2(B,Q);let J=process.hrtime.bigint(),Y=await k8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(uX(Z))throw ct(Z,A.ampURL);let F=lA(Z)?Z:null,X=F?.user.email;await q91(B,Q,Z);let D=WW(Z),G=df(Q,D);if(G instanceof Error)V5(G.message);if(F&&!Fk(Q.mode,X))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!T7(X)))throw new Z4("Headless executor mode is only available for Amp employees",1);CF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new Z4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!z9(K))throw new Z4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await i13({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new Z4("Failed to resolve headless thread ID",1);let W=await rf4(z);if(W.status==="already-running")await Y.asyncDispose(),await Rz(),process.exit(0);try{await mf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await Rz(),process.exit(0)}async function T13(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await E8A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;z8A({...Q,streamJson:F},A.executeMode,Y),W2(B,Q),qv4(),CF0();let X=Q.threadId&&z9(Q.threadId)?Q.threadId:void 0,D=Q.observe?s8(Q.observe)??aB(Q.observe):void 0,G=await $.serverStatusPromise;if(uX(G))throw ct(G,A.ampURL);let V=WW(G),U=df(Q,V);if(U instanceof Error)V5(U.message);let K=null,E=()=>{return K??=(async()=>{let H=await oa(A.settings,process.cwd(),V,U);if(H instanceof Error)V5(H.message);return H})(),K},z=await $.secretStorage.get("apiKey",A.ampURL);if(!z)throw new Z4("API key required. Please run `amp login` first.",1);let W=lA(G)&&T7(G.user.email);if(A.executeMode){B01($.mcpService,A.settings);try{let H=BE0(B,Q),q=await wI(),N=X?H:eX0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),I=X?void 0:AD0(await cx($.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=X?void 0:await E(),L=await Ef4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:X,initialThreadMeta:w,initialSettings:I});if(await yb(L,"execute"),Q.archive)await $.threadService.archive(L,!0)}finally{await $.asyncDispose()}await Rz(),process.exit(0)}else{let H=BE0(B,Q),q=J.showNpmMigrationWelcome?"npm-migration":"intro",N=MX0("0.0.1778617350-g19dbc6",$.settingsStorage,{startDelayMs:3000}),I=_l($.configService),w=new Zt($.fuzzyServer),L=process.cwd();await ws4({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??gF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:O})=>Cx({fileSystem:$.fileSystem,workspaceRoot:L},O),completionBuilder:w,workspaceRoot:L,listThreads:()=>I.listThreads(),getThreadFromServer:(O)=>I.getThread(O),toolboxes:$.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:$.settingsStorage.getSettingsFilePath(),setActiveThreadID:(O)=>$.activeThread$.next(O),dispose:()=>{return N.dispose(),$.asyncDispose()}},{initialThreadID:D??X,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function k13(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(X0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,I0=$s0();j.info("Startup phase",{phase:X0,phaseMs:Math.round(Q0),sinceMainMs:I0===null?void 0:Math.round(I0)})},{userInput:F,stdinInput:X}=await E8A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;z8A({...Q,streamJson:D},A.executeMode,F),W2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await k8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&uX(E))throw ct(E,A.ampURL);let z=lA(E)?E:null,W=z?.user.email,H=!!(W&&T7(W));if(H)CF0();if(!K)await q91(B,Q,E);let q=WW(E),N=q?.features??[],I=q?.team??null,w=df(Q,q);if(w instanceof Error)V5(w.message);if(z&&!Fk(Q.mode,W))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let L=Q.threadId&&z9(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await ZE0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(X0)=>yb(X0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(X0)=>{let j0=K?await V.serverStatusPromise:E,Q0=await oa(A.settings,process.cwd(),WW(j0),w);if(Q0 instanceof Error)V5(Q0.message);return c81(O,{threadMeta:Q0,agentMode:X0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(X0,j0)=>{if(j0?.nonBlockingOwnershipCheck){Z8A(X0,V.configService,V.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof Z4){if(j0.onOwnershipError){j0.onOwnershipError(Q0,X0);return}Pz(Q0,X0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await Z8A(X0,V.configService,V.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof Z4)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Pz},T=async()=>{try{return SAA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(X0){if(X0 instanceof Z4)throw X0;throw await Pz(X0,Q.threadId),Error("handleError should have called process.exit()")}},x=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let X0=await V.configService.getLatest(),j0=um(X0),Q0=await QA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(X0){j.error("Failed to fetch free tier status:",X0);return}})(),u=!A.executeMode?new z51:null,k,f=null;if(u)k=u,f=(async()=>{let X0=K?await V.serverStatusPromise:V.serverStatus;if(uX(X0))throw ct(X0,A.ampURL);await q91(B,Q,X0);let j0=process.hrtime.bigint(),Q0=await T();if(Z("runMainThread:createThreadPool",j0),u.attach(Q0),F){let I0=await T1(Q0.threadHandles$);if(!I0)throw new Z4("No active thread is available yet.",1);await I0.sendMessage({content:[{type:"text",text:F}]})}})(),f.catch(async(X0)=>{let j0=X0 instanceof Error?X0:Error(String(X0));u.setInitError(j0),await Pz(X0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let c=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),L13({configService:V.configService,threadService:V.threadService,config:c,useNotificationsForService:d,threadViewStates$:()=>k.threadHandles$.pipe(x4((X0)=>{if(!X0)return u0.of({});return M6(X0.thread$,X0.threadViewState$).pipe(H1(([j0,Q0])=>({[j0.id]:Q0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){B01(V.mcpService,A.settings);let X0=BE0(B,Q),j0=await wI(),Q0=L?X0:eX0({agentMode:Q.mode,explicitEffort:X0,sessionState:j0}),I0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await ov4({threadPool:k,...I0});if(await yb(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let g=!1,l=!1;if(Q.jetbrains||Q.ide){await e30();let X0=await mX({jetbrainsOnly:Q.jetbrains});if(X0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(X0.length===1){let j0=X0[0];if(j0)m3.selectConfig(j0)}else l=!0}G=process.hrtime.bigint();let a=MX0("0.0.1778617350-g19dbc6",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let t=new $01(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let X0=await T1(k.threadHandles$);if(!X0)throw new Z4("No active thread is available yet.",1);await X0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let w0=await wI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let V0=BE0(B,Q),N0={...w0,launchCount:w0.launchCount+1,lastReasoningEffortByMode:V0?{...w0.lastReasoningEffortByMode,[Q.mode]:V0}:w0.lastReasoningEffortByMode};NJ((X0)=>({...X0,launchCount:X0.launchCount+1}));try{if(G=process.hrtime.bigint(),await lt4({history:new Wo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:QA,threadPool:k,createSystemPromptDeps:async()=>U8A(V),ideClient:m3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:t,updateService:a,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:L,showJetBrainsInstaller:g,showIdePickerHint:l,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:F13,logFile:{path:$},sessionState:N0,freeTierStatusPromise:x,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-12T20:26:19.685Z"},(X0)=>new C51({...X0,threadPool:X0.threadPool},(j0)=>new p81({...j0,threadState:j0.threadState}))),Z("runMainThread:mountApp-returned",G),f)await f}finally{await k.dispose().catch((X0)=>{j.error("Failed to dispose thread pool during shutdown",X0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)KB.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7775
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await d74({get:async(F)=>{if(F!==pd)return;try{let X=await V8A(H91,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==pd)return;await $13(dt.dirname(H91),{recursive:!0}),await J13(H91,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:O90()});A04($);let J=await Vb4({...A,workspaceTrust:{current:!0,changes:hm},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await Fg4(A.mcpConfig);J=Xg4(J,F)}let Y=dt.dirname(J.getSettingsFilePath());nR4(kx,Y),J=Ss1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=k7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!yH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:ns4(await Qe0(A,J))}}function S13(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function v13(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=dt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Z13:aa));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function y13(){Uv4();let A=S13(process.argv),Q=v13(process.argv,A),B=Nv4(Q);iZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(D13(j),j.info("Starting Amp CLI.",{version:"0.0.1778617350-g19dbc6",buildTimestamp:"2026-05-12T20:26:19.685Z"}),process.platform==="win32"&&Rj())eb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Z4(G7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await R13(B).parseAsync(process.argv)}lR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await y13().catch(Pz)});async function x13(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),r6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7777
+ Or pipe via stdin: echo "your message" | amp --execute`)}function P13(){bA4([e50.parse({tool:"*",action:"allow"})]),KA4({bypass:!0})}async function JE0(A,Q,B,$){if(Q.headless)return _13(A,Q,B);let J=await k8(A,Q),Y=await J.serverStatusPromise,Z=lA(Y)&&YE0(Y.features,f$.THREAD_ACTORS_TUI),F=Z&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new Z4("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!Z)throw await J.asyncDispose(),new Z4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F){let X=!A.executeMode&&await N13();return P13(),T13(A,Q,B,J,{showNpmMigrationWelcome:X})}else{if(Q.threadId&&z9(Q.threadId)){let X=await QA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(X?.ok&&X.result.usesThreadActors)throw await J.asyncDispose(),new Z4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return k13(A,Q,B,$,{dependencies:J})}}async function _13(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=$s0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};W2(B,Q);let J=process.hrtime.bigint(),Y=await k8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(uX(Z))throw ct(Z,A.ampURL);let F=lA(Z)?Z:null,X=F?.user.email;await q91(B,Q,Z);let D=WW(Z),G=df(Q,D);if(G instanceof Error)V5(G.message);if(F&&!Fk(Q.mode,X))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!T7(X)))throw new Z4("Headless executor mode is only available for Amp employees",1);CF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new Z4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!z9(K))throw new Z4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await i13({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new Z4("Failed to resolve headless thread ID",1);let W=await rf4(z);if(W.status==="already-running")await Y.asyncDispose(),await Rz(),process.exit(0);try{await mf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await Rz(),process.exit(0)}async function T13(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await E8A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;z8A({...Q,streamJson:F},A.executeMode,Y),W2(B,Q),qv4(),CF0();let X=Q.threadId&&z9(Q.threadId)?Q.threadId:void 0,D=Q.observe?s8(Q.observe)??aB(Q.observe):void 0,G=await $.serverStatusPromise;if(uX(G))throw ct(G,A.ampURL);let V=WW(G),U=df(Q,V);if(U instanceof Error)V5(U.message);let K=null,E=()=>{return K??=(async()=>{let H=await oa(A.settings,process.cwd(),V,U);if(H instanceof Error)V5(H.message);return H})(),K},z=await $.secretStorage.get("apiKey",A.ampURL);if(!z)throw new Z4("API key required. Please run `amp login` first.",1);let W=lA(G)&&T7(G.user.email);if(A.executeMode){B01($.mcpService,A.settings);try{let H=BE0(B,Q),q=await wI(),N=X?H:eX0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),I=X?void 0:AD0(await cx($.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=X?void 0:await E(),L=await Ef4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:X,initialThreadMeta:w,initialSettings:I});if(await yb(L,"execute"),Q.archive)await $.threadService.archive(L,!0)}finally{await $.asyncDispose()}await Rz(),process.exit(0)}else{let H=BE0(B,Q),q=J.showNpmMigrationWelcome?"npm-migration":"intro",N=MX0("0.0.1778631508-g72c81a",$.settingsStorage,{startDelayMs:3000}),I=_l($.configService),w=new Zt($.fuzzyServer),L=process.cwd();await ws4({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??gF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:O})=>Cx({fileSystem:$.fileSystem,workspaceRoot:L},O),completionBuilder:w,workspaceRoot:L,listThreads:()=>I.listThreads(),getThreadFromServer:(O)=>I.getThread(O),toolboxes:$.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:$.settingsStorage.getSettingsFilePath(),setActiveThreadID:(O)=>$.activeThread$.next(O),dispose:()=>{return N.dispose(),$.asyncDispose()}},{initialThreadID:D??X,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function k13(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(X0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,I0=$s0();j.info("Startup phase",{phase:X0,phaseMs:Math.round(Q0),sinceMainMs:I0===null?void 0:Math.round(I0)})},{userInput:F,stdinInput:X}=await E8A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;z8A({...Q,streamJson:D},A.executeMode,F),W2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await k8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&uX(E))throw ct(E,A.ampURL);let z=lA(E)?E:null,W=z?.user.email,H=!!(W&&T7(W));if(H)CF0();if(!K)await q91(B,Q,E);let q=WW(E),N=q?.features??[],I=q?.team??null,w=df(Q,q);if(w instanceof Error)V5(w.message);if(z&&!Fk(Q.mode,W))throw new Z4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let L=Q.threadId&&z9(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await ZE0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(X0)=>yb(X0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(X0)=>{let j0=K?await V.serverStatusPromise:E,Q0=await oa(A.settings,process.cwd(),WW(j0),w);if(Q0 instanceof Error)V5(Q0.message);return c81(O,{threadMeta:Q0,agentMode:X0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(X0,j0)=>{if(j0?.nonBlockingOwnershipCheck){Z8A(X0,V.configService,V.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof Z4){if(j0.onOwnershipError){j0.onOwnershipError(Q0,X0);return}Pz(Q0,X0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await Z8A(X0,V.configService,V.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof Z4)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Pz},T=async()=>{try{return SAA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(X0){if(X0 instanceof Z4)throw X0;throw await Pz(X0,Q.threadId),Error("handleError should have called process.exit()")}},x=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let X0=await V.configService.getLatest(),j0=um(X0),Q0=await QA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(X0){j.error("Failed to fetch free tier status:",X0);return}})(),u=!A.executeMode?new z51:null,k,f=null;if(u)k=u,f=(async()=>{let X0=K?await V.serverStatusPromise:V.serverStatus;if(uX(X0))throw ct(X0,A.ampURL);await q91(B,Q,X0);let j0=process.hrtime.bigint(),Q0=await T();if(Z("runMainThread:createThreadPool",j0),u.attach(Q0),F){let I0=await T1(Q0.threadHandles$);if(!I0)throw new Z4("No active thread is available yet.",1);await I0.sendMessage({content:[{type:"text",text:F}]})}})(),f.catch(async(X0)=>{let j0=X0 instanceof Error?X0:Error(String(X0));u.setInitError(j0),await Pz(X0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let c=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),L13({configService:V.configService,threadService:V.threadService,config:c,useNotificationsForService:d,threadViewStates$:()=>k.threadHandles$.pipe(x4((X0)=>{if(!X0)return u0.of({});return M6(X0.thread$,X0.threadViewState$).pipe(H1(([j0,Q0])=>({[j0.id]:Q0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){B01(V.mcpService,A.settings);let X0=BE0(B,Q),j0=await wI(),Q0=L?X0:eX0({agentMode:Q.mode,explicitEffort:X0,sessionState:j0}),I0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await ov4({threadPool:k,...I0});if(await yb(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let g=!1,l=!1;if(Q.jetbrains||Q.ide){await e30();let X0=await mX({jetbrainsOnly:Q.jetbrains});if(X0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(X0.length===1){let j0=X0[0];if(j0)m3.selectConfig(j0)}else l=!0}G=process.hrtime.bigint();let a=MX0("0.0.1778631508-g72c81a",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let t=new $01(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let X0=await T1(k.threadHandles$);if(!X0)throw new Z4("No active thread is available yet.",1);await X0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let w0=await wI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let V0=BE0(B,Q),N0={...w0,launchCount:w0.launchCount+1,lastReasoningEffortByMode:V0?{...w0.lastReasoningEffortByMode,[Q.mode]:V0}:w0.lastReasoningEffortByMode};NJ((X0)=>({...X0,launchCount:X0.launchCount+1}));try{if(G=process.hrtime.bigint(),await lt4({history:new Wo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:QA,threadPool:k,createSystemPromptDeps:async()=>U8A(V),ideClient:m3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:t,updateService:a,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:L,showJetBrainsInstaller:g,showIdePickerHint:l,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:F13,logFile:{path:$},sessionState:N0,freeTierStatusPromise:x,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-13T00:22:19.974Z"},(X0)=>new C51({...X0,threadPool:X0.threadPool},(j0)=>new p81({...j0,threadState:j0.threadState}))),Z("runMainThread:mountApp-returned",G),f)await f}finally{await k.dispose().catch((X0)=>{j.error("Failed to dispose thread pool during shutdown",X0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)KB.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7778
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await d74({get:async(F)=>{if(F!==pd)return;try{let X=await V8A(H91,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==pd)return;await $13(dt.dirname(H91),{recursive:!0}),await J13(H91,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:O90()});A04($);let J=await Vb4({...A,workspaceTrust:{current:!0,changes:hm},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await Fg4(A.mcpConfig);J=Xg4(J,F)}let Y=dt.dirname(J.getSettingsFilePath());nR4(kx,Y),J=Ss1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=k7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!yH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:ns4(await Qe0(A,J))}}function S13(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function v13(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=dt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Z13:aa));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function y13(){Uv4();let A=S13(process.argv),Q=v13(process.argv,A),B=Nv4(Q);iZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(D13(j),j.info("Starting Amp CLI.",{version:"0.0.1778631508-g72c81a",buildTimestamp:"2026-05-13T00:22:19.974Z"}),process.platform==="win32"&&Rj())eb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Z4(G7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await R13(B).parseAsync(process.argv)}lR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await y13().catch(Pz)});async function x13(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),r6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7776
7779
  `);else if(!yH(A.ampURL))r6.write(`Logging in to ${new URL(A.ampURL).hostname}
7777
7780
  `);let $=process.env.AMP_API_KEY;if($)r6.write(`API key found in environment variable, storing...
7778
7781
  `),await Q.set("apiKey",$,A.ampURL),r6.write(`API key successfully stored.